PageRenderTime 85ms CodeModel.GetById 40ms app.highlight 18ms RepoModel.GetById 22ms app.codeStats 0ms

/sally/backend/lib/Controller/Mediapool/Base.php

https://bitbucket.org/SallyCMS/trunk
PHP | 324 lines | 240 code | 69 blank | 15 comment | 32 complexity | 8f63dd729875b91402e671f4021b3c1e MD5 | raw file
  1<?php
  2/*
  3 * Copyright (c) 2012, webvariants GbR, http://www.webvariants.de
  4 *
  5 * This file is released under the terms of the MIT license. You can find the
  6 * complete text in the attached LICENSE file or online at:
  7 *
  8 * http://www.opensource.org/licenses/mit-license.php
  9 */
 10
 11abstract class sly_Controller_Mediapool_Base extends sly_Controller_Backend implements sly_Controller_Interface {
 12	protected $args;
 13	protected $category;
 14	protected $selectBox;
 15	protected $categories;
 16
 17	private $init = false;
 18
 19	public function __construct() {
 20		// load our i18n stuff
 21		sly_Core::getI18N()->appendFile(SLY_SALLYFOLDER.'/backend/lang/pages/mediapool/');
 22	}
 23
 24	protected function init() {
 25		if ($this->init) return;
 26		$this->init = true;
 27
 28		$request          = $this->getRequest();
 29		$this->args       = $request->requestArray('args', 'string');
 30		$this->categories = array();
 31
 32		// init category filter
 33		if (isset($this->args['categories'])) {
 34			$cats             = array_map('intval', explode('|', $this->args['categories']));
 35			$this->categories = array_unique($cats);
 36		}
 37
 38		$this->getCurrentCategory();
 39
 40		// build navigation
 41
 42		$layout = sly_Core::getLayout();
 43		$nav    = $layout->getNavigation();
 44		$page   = $nav->find('mediapool');
 45
 46		if ($page) {
 47			$cur     = sly_Core::getCurrentControllerName();
 48			$subline = array(
 49				array('mediapool',        t('media_list')),
 50				array('mediapool_upload', t('upload_file'))
 51			);
 52
 53			if ($this->isMediaAdmin()) {
 54				$subline[] = array('mediapool_structure', t('categories'));
 55				$subline[] = array('mediapool_sync',      t('sync_files'));
 56			}
 57
 58			foreach ($subline as $item) {
 59				$sp = $page->addSubpage($item[0], $item[1]);
 60
 61				if (!empty($this->args)) {
 62					$sp->setExtraParams(array('args' => $this->args));
 63
 64					// ignore the extra params when detecting the current page
 65					if ($cur === $item[0]) $sp->forceStatus(true);
 66				}
 67			}
 68		}
 69
 70		$page = sly_Core::dispatcher()->filter('SLY_MEDIAPOOL_MENU', $page);
 71
 72		$layout->showNavigation(false);
 73		$layout->pageHeader(t('media_list'), $page);
 74		$layout->setBodyAttr('class', 'sly-popup sly-mediapool');
 75
 76		$this->render('mediapool/javascript.phtml', array(), false);
 77	}
 78
 79	protected function getArgumentString($separator = '&amp;') {
 80		$args = array();
 81
 82		foreach ($this->args as $name => $value) {
 83			$args['args['.$name.']'] = $value;
 84		}
 85
 86		return http_build_query($args, '', $separator);
 87	}
 88
 89	protected function getCurrentCategory() {
 90		if ($this->category === null) {
 91			$request  = $this->getRequest();
 92			$category = $request->request('category', 'int', -1);
 93			$service  = sly_Service_Factory::getMediaCategoryService();
 94			$session  = sly_Core::getSession();
 95
 96			if ($category === -1) {
 97				$category = $session->get('sly-media-category', 'int', 0);
 98			}
 99
100			// respect category filter
101			if (!empty($this->categories) && !in_array($category, $this->categories)) {
102				$category = reset($this->categories);
103			}
104
105			$category = $service->findById($category);
106			$category = $category ? $category->getId() : 0;
107
108			$session->set('sly-media-category', $category);
109			$this->category = $category;
110		}
111
112		return $this->category;
113	}
114
115	protected function getOpenerLink(sly_Model_Medium $file) {
116		$request  = $this->getRequest();
117		$callback = $request->request('callback', 'string');
118		$link     = '';
119
120		if (!empty($callback)) {
121			$filename = $file->getFilename();
122			$title    = $file->getTitle();
123			$link     = '<a href="#" data-filename="'.sly_html($filename).'" data-title="'.sly_html($title).'">'.t('apply_file').'</a>';
124		}
125
126		return $link;
127	}
128
129	protected function getFiles() {
130		$cat   = $this->getCurrentCategory();
131		$where = 'f.category_id = '.$cat;
132		$where = sly_Core::dispatcher()->filter('SLY_MEDIA_LIST_QUERY', $where, array('category_id' => $cat));
133		$where = '('.$where.')';
134
135		if (isset($this->args['types'])) {
136			$types = explode('|', preg_replace('#[^a-z0-9/+.-|]#i', '', $this->args['types']));
137
138			if (!empty($types)) {
139				$where .= ' AND filetype IN ("'.implode('","', $types).'")';
140			}
141		}
142
143		$db     = sly_DB_Persistence::getInstance();
144		$prefix = sly_Core::getTablePrefix();
145		$query  = 'SELECT f.id FROM '.$prefix.'file f LEFT JOIN '.$prefix.'file_category c ON f.category_id = c.id WHERE '.$where.' ORDER BY f.updatedate DESC';
146		$files  = array();
147
148		$db->query($query);
149
150		foreach ($db as $row) {
151			$files[$row['id']] = sly_Util_Medium::findById($row['id']);
152		}
153
154		return $files;
155	}
156
157	protected function deleteMedium(sly_Model_Medium $medium, sly_Util_FlashMessage $msg, $revalidate = true) {
158		$filename = $medium->getFileName();
159		$user     = sly_Util_User::getCurrentUser();
160		$service  = sly_Service_Factory::getMediumService();
161
162		if ($this->canAccessCategory($medium->getCategoryId())) {
163			$usages = $this->isInUse($medium);
164
165			if ($usages === false) {
166				try {
167					$service->deleteByMedium($medium);
168					if ($revalidate) $this->revalidate();
169					$msg->appendInfo($filename.': '.t('medium_deleted'));
170				}
171				catch (sly_Exception $e) {
172					$msg->appendWarning($filename.': '.$e->getMessage());
173				}
174			}
175			else {
176				$tmp   = array();
177				$tmp[] = t('file_is_in_use', $filename);
178				$tmp[] = '<ul>';
179
180				foreach ($usages as $usage) {
181					$title = sly_html($usage['title']);
182
183					if (!empty($usage['link'])) {
184						$tmp[] = '<li><a href="javascript:openPage('.json_encode($usage['link']).')">'.$title.'</a></li>';
185					}
186					else {
187						$tmp[] = '<li>'.$title.'</li>';
188					}
189				}
190
191				$tmp[] = '</ul>';
192				$flash->appendWarning(implode("\n", $tmp));
193			}
194		}
195		else {
196			$msg->appendWarning($filename.': '.t('no_permission'));
197		}
198	}
199
200	public function checkPermission($action) {
201		$user = sly_Util_User::getCurrentUser();
202
203		if (!$user || (!$user->isAdmin() && !$user->hasRight('pages', 'mediapool'))) {
204			return false;
205		}
206
207		if ($action === 'batch') {
208			sly_Util_Csrf::checkToken();
209		}
210
211		return true;
212	}
213
214	protected function isMediaAdmin() {
215		$user = sly_Util_User::getCurrentUser();
216		return $user->isAdmin() || $user->hasRight('mediacategory', 'access', sly_Authorisation_ListProvider::ALL);
217	}
218
219	protected function canAccessFile(sly_Model_Medium $medium) {
220		return $this->canAccessCategory($medium->getCategoryId());
221	}
222
223	protected function canAccessCategory($cat) {
224		$user = sly_Util_User::getCurrentUser();
225		return $this->isMediaAdmin() || $user->hasRight('mediacategory', 'access', intval($cat));
226	}
227
228	protected function getCategorySelect() {
229		$user = sly_Util_User::getCurrentUser();
230
231		if ($this->selectBox === null) {
232			$this->selectBox = sly_Form_Helper::getMediaCategorySelect('category', null, $user);
233			$this->selectBox->setLabel(t('categories'));
234			$this->selectBox->setMultiple(false);
235			$this->selectBox->setAttribute('value', $this->getCurrentCategory());
236
237			// filter categories if args[categories] is set
238			if (isset($this->args['categories'])) {
239				$cats = array_map('intval', explode('|', $this->args['categories']));
240				$cats = array_unique($cats);
241
242				if (!empty($cats)) {
243					$values = array_keys($this->selectBox->getValues());
244
245					foreach ($values as $catID) {
246						if (!in_array($catID, $cats)) $this->selectBox->removeValue($catID);
247					}
248				}
249			}
250		}
251
252		return $this->selectBox;
253	}
254
255	protected function getDimensions($width, $height, $maxWidth, $maxHeight) {
256		if ($width > $maxWidth) {
257			$factor  = (float) $maxWidth / $width;
258			$width   = $maxWidth;
259			$height *= $factor;
260		}
261
262		if ($height > $maxHeight) {
263			$factor  = (float) $maxHeight / $height;
264			$height  = $maxHeight;
265			$width  *= $factor;
266		}
267
268		return array(ceil($width), ceil($height));
269	}
270
271	protected function isDocType(sly_Model_Medium $medium) {
272		static $docTypes = array(
273			'bmp', 'css', 'doc', 'docx', 'eps', 'gif', 'gz', 'jpg', 'mov', 'mp3',
274			'ogg', 'pdf', 'png', 'ppt', 'pptx','pps', 'ppsx', 'rar', 'rtf', 'swf',
275			'tar', 'tif', 'txt', 'wma', 'xls', 'xlsx', 'zip'
276		);
277
278		return in_array($medium->getExtension(), $docTypes);
279	}
280
281	protected function isImage(sly_Model_Medium $medium) {
282		static $exts = array('gif', 'jpeg', 'jpg', 'png', 'bmp', 'tif', 'tiff', 'webp');
283		return in_array($medium->getExtension(), $exts);
284	}
285
286	protected function isInUse(sly_Model_Medium $medium) {
287		$sql      = sly_DB_Persistence::getInstance();
288		$filename = addslashes($medium->getFilename());
289		$prefix   = sly_Core::getTablePrefix();
290		$query    =
291			'SELECT s.article_id, s.clang FROM '.$prefix.'slice sv, '.$prefix.'article_slice s, '.$prefix.'article a '.
292			'WHERE sv.id = s.slice_id AND a.id = s.article_id AND a.clang = s.clang '.
293			'AND serialized_values LIKE "%'.$filename.'%" GROUP BY s.article_id, s.clang';
294
295		$res    = array();
296		$usages = array();
297		$router = $this->getContainer()->getApplication()->getRouter();
298
299		$sql->query($query);
300		foreach ($sql as $row) $res[] = $row;
301
302		foreach ($res as $row) {
303			$article = sly_Util_Article::findById($row['article_id'], $row['clang']);
304
305			$usages[] = array(
306				'title' => $article->getName(),
307				'type'  => 'sly-article',
308				'link'  => $router->getPlainUrl('content', null, array('article_id' => $row['article_id'], 'clang' => $row['clang']))
309			);
310		}
311
312		$usages = sly_Core::dispatcher()->filter('SLY_MEDIA_USAGES', $usages, array(
313			'filename' => $medium->getFilename(),
314			'media'    => $medium
315		));
316
317		return empty($usages) ? false : $usages;
318	}
319
320	protected function revalidate() {
321		// re-validate asset cache
322		sly_Service_Factory::getAssetService()->validateCache();
323	}
324}