Open Journal Systems  3.3.0
CategoryForm.inc.php
1 <?php
2 
16 import('lib.pkp.classes.form.Form');
17 
18 class CategoryForm extends Form {
20  var $_categoryId;
21 
24 
26  var $_userId;
27 
30 
32  var $_sizeArray;
33 
34 
40  function __construct($contextId, $categoryId = null) {
41  parent::__construct('controllers/grid/settings/category/form/categoryForm.tpl');
42  $this->_contextId = $contextId;
43  $this->_categoryId = $categoryId;
44 
45  $request = Application::get()->getRequest();
46  $user = $request->getUser();
47  $this->_userId = $user->getId();
48 
49  // Validation checks for this form
50  $form = $this;
51  $this->addCheck(new FormValidatorLocale($this, 'name', 'required', 'grid.category.nameRequired'));
52  $this->addCheck(new FormValidatorRegExp($this, 'path', 'required', 'grid.category.pathAlphaNumeric', '/^[a-zA-Z0-9\/._-]+$/'));
53  $this->addCheck(new FormValidatorCustom(
54  $this, 'path', 'required', 'grid.category.pathExists',
55  function($path) use ($form, $contextId) {
56  $categoryDao = DAORegistry::getDAO('CategoryDAO'); /* @var $categoryDao CategoryDAO */
57  return !$categoryDao->categoryExistsByPath($path,$contextId) || ($form->getData('oldPath') != null && $form->getData('oldPath') == $path);
58  }
59  ));
60  $this->addCheck(new FormValidatorPost($this));
61  $this->addCheck(new FormValidatorCSRF($this));
62  }
63 
64  //
65  // Getters and Setters
66  //
71  function getCategoryId() {
72  return $this->_categoryId;
73  }
74 
79  function setCategoryId($categoryId) {
80  $this->_categoryId = $categoryId;
81  }
82 
87  function getContextId() {
88  return $this->_contextId;
89  }
90 
91  //
92  // Implement template methods from Form.
93  //
97  function getLocaleFieldNames() {
98  $categoryDao = DAORegistry::getDAO('CategoryDAO'); /* @var $categoryDao CategoryDAO */
99  return $categoryDao->getLocaleFieldNames();
100  }
101 
105  function initData() {
106  $categoryDao = DAORegistry::getDAO('CategoryDAO'); /* @var $categoryDao CategoryDAO */
107  $category = $categoryDao->getById($this->getCategoryId(), $this->getContextId());
108 
109  if ($category) {
110  $this->setData('name', $category->getTitle(null)); // Localized
111  $this->setData('description', $category->getDescription(null)); // Localized
112  $this->setData('parentId', $category->getParentId());
113  $this->setData('path', $category->getPath());
114  $this->setData('image', $category->getImage());
115 
116  $submissionDao = DAORegistry::getDAO('SubmissionDAO'); /* @var $submissionDao SubmissionDAO */
117  $sortOption = $category->getSortOption() ? $category->getSortOption() : $submissionDao->getDefaultSortOption();
118  $this->setData('sortOption', $sortOption);
119  }
120  }
121 
125  function validate($callHooks = true) {
126  if ($temporaryFileId = $this->getData('temporaryFileId')) {
127  import('lib.pkp.classes.file.TemporaryFileManager');
128  $temporaryFileManager = new TemporaryFileManager();
129  $temporaryFileDao = DAORegistry::getDAO('TemporaryFileDAO'); /* @var $temporaryFileDao TemporaryFileDAO */
130  $temporaryFile = $temporaryFileDao->getTemporaryFile($temporaryFileId, $this->_userId);
131  if ( !$temporaryFile ||
132  !($this->_imageExtension = $temporaryFileManager->getImageExtension($temporaryFile->getFileType())) ||
133  !($this->_sizeArray = getimagesize($temporaryFile->getFilePath())) ||
134  $this->_sizeArray[0] <= 0 || $this->_sizeArray[1] <= 0
135  ) {
136  $this->addError('temporaryFileId', __('form.invalidImage'));
137  return false;
138  }
139  }
140  return parent::validate($callHooks);
141  }
142 
146  function readInputData() {
147  $this->readUserVars(array('name', 'parentId', 'path', 'description', 'temporaryFileId', 'sortOption', 'subEditors'));
148 
149  // For path duplicate checking; excuse the current path.
150  if ($categoryId = $this->getCategoryId()) {
151  $categoryDao = DAORegistry::getDAO('CategoryDAO'); /* @var $categoryDao CategoryDAO */
152  $category = $categoryDao->getById($categoryId, $this->getContextId());
153  $this->setData('oldPath', $category->getPath());
154  }
155  }
156 
160  function fetch($request, $template = null, $display = false) {
161  $categoryDao = DAORegistry::getDAO('CategoryDAO'); /* @var $categoryDao CategoryDAO */
162  $context = $request->getContext();
163  $templateMgr = TemplateManager::getManager($request);
164  $templateMgr->assign('categoryId', $this->getCategoryId());
165 
166  // Provide a list of root categories to the template
167  $rootCategoriesIterator = $categoryDao->getByParentId(0, $context->getId());
168  $rootCategories = array(0 => __('common.none'));
169  while ($category = $rootCategoriesIterator->next()) {
170  $categoryId = $category->getId();
171  if ($categoryId != $this->getCategoryId()) {
172  // Don't permit time travel paradox
173  $rootCategories[$categoryId] = $category->getLocalizedTitle();
174  }
175  }
176  $templateMgr->assign('rootCategories', $rootCategories);
177 
178  // Determine if this category has children of its own;
179  // if so, prevent the user from giving it a parent.
180  // (Forced two-level maximum tree depth.)
181  if ($this->getCategoryId()) {
182  $children = $categoryDao->getByParentId($this->getCategoryId(), $context->getId());
183  if ($children->next()) {
184  $templateMgr->assign('cannotSelectChild', true);
185  }
186  }
187  // Sort options.
188  $submissionDao = DAORegistry::getDAO('SubmissionDAO'); /* @var $submissionDao SubmissionDAO */
189  $templateMgr->assign('sortOptions', $submissionDao->getSortSelectOptions());
190 
191  // Sub Editors
192  $usersIterator = Services::get('user')->getMany([
193  'contextId' => $context->getId(),
194  'roleIds' => ROLE_ID_SUB_EDITOR,
195  ]);
196  $availableSubeditors = [];
197  foreach ($usersIterator as $user) {
198  $availableSubeditors[(int) $user->getId()] = $user->getFullName();
199  }
200  $assignedToCategory = [];
201  if ($this->getCategoryId()) {
202  $assignedToCategory = Services::get('user')->getIds([
203  'contextId' => $context->getId(),
204  'roleIds' => ROLE_ID_SUB_EDITOR,
205  'assignedToCategory' => (int) $this->getCategoryId(),
206  ]);
207  }
208  $templateMgr->assign([
209  'availableSubeditors' => $availableSubeditors,
210  'assignedToCategory' => $assignedToCategory,
211  ]);
212 
213  return parent::fetch($request, $template, $display);
214  }
215 
219  function execute(...$functionArgs) {
220  $categoryId = $this->getCategoryId();
221  $categoryDao = DAORegistry::getDAO('CategoryDAO'); /* @var $categoryDao CategoryDAO */
222 
223  // Get a category object to edit or create
224  if ($categoryId == null) {
225  $category = $categoryDao->newDataObject();
226  $category->setContextId($this->getContextId());
227  } else {
228  $category = $categoryDao->getById($categoryId, $this->getContextId());
229  }
230 
231  // Set the editable properties of the category object
232  $category->setTitle($this->getData('name'), null); // Localized
233  $category->setDescription($this->getData('description'), null); // Localized
234  $category->setParentId($this->getData('parentId'));
235  $category->setPath($this->getData('path'));
236  $category->setSortOption($this->getData('sortOption'));
237 
238  // Update or insert the category object
239  if ($categoryId == null) {
240  $this->setCategoryId($categoryDao->insertObject($category));
241  } else {
242  $category->setSequence(REALLY_BIG_NUMBER);
243  $categoryDao->updateObject($category);
244  $categoryDao->resequenceCategories($this->getContextId());
245  }
246 
247  // Update category editors
248  $subEditorsDao = DAORegistry::getDAO('SubEditorsDAO'); /* @var $subEditorsDao SubEditorsDAO */
249  $subEditorsDao->deleteBySubmissionGroupId($category->getId(), ASSOC_TYPE_CATEGORY, $category->getContextId());
250  $subEditors = $this->getData('subEditors');
251  if (!empty($subEditors)) {
252  $roleDao = DAORegistry::getDAO('RoleDAO'); /* @var $roleDao RoleDAO */
253  foreach ($subEditors as $subEditor) {
254  if ($roleDao->userHasRole($category->getContextId(), $subEditor, ROLE_ID_SUB_EDITOR)) {
255  $subEditorsDao->insertEditor($category->getContextId(), $category->getId(), $subEditor, ASSOC_TYPE_CATEGORY);
256  }
257  }
258  }
259 
260  // Handle the image upload if there was one.
261  if ($temporaryFileId = $this->getData('temporaryFileId')) {
262  // Fetch the temporary file storing the uploaded library file
263  $temporaryFileDao = DAORegistry::getDAO('TemporaryFileDAO'); /* @var $temporaryFileDao TemporaryFileDAO */
264 
265  $temporaryFile = $temporaryFileDao->getTemporaryFile($temporaryFileId, $this->_userId);
266  $temporaryFilePath = $temporaryFile->getFilePath();
267  import('lib.pkp.classes.file.ContextFileManager');
268  $contextFileManager = new ContextFileManager($this->getContextId());
269  $basePath = $contextFileManager->getBasePath() . '/categories/';
270 
271  // Delete the old file if it exists
272  $oldSetting = $category->getImage();
273  if ($oldSetting) {
274  $contextFileManager->deleteByPath($basePath . $oldSetting['thumbnailName']);
275  $contextFileManager->deleteByPath($basePath . $oldSetting['name']);
276  }
277 
278  // The following variables were fetched in validation
279  assert($this->_sizeArray && $this->_imageExtension);
280 
281  // Generate the surrogate images.
282  switch ($this->_imageExtension) {
283  case '.jpg': $image = imagecreatefromjpeg($temporaryFilePath); break;
284  case '.png': $image = imagecreatefrompng($temporaryFilePath); break;
285  case '.gif': $image = imagecreatefromgif($temporaryFilePath); break;
286  default: $image = null; // Suppress warning
287  }
288  assert($image);
289 
290  $context = Application::get()->getRequest()->getContext();
291  $coverThumbnailsMaxWidth = $context->getSetting('coverThumbnailsMaxWidth');
292  $coverThumbnailsMaxHeight = $context->getSetting('coverThumbnailsMaxHeight');
293  $thumbnailFilename = $category->getId() . '-category-thumbnail' . $this->_imageExtension;
294  $xRatio = min(1, ($coverThumbnailsMaxWidth?$coverThumbnailsMaxWidth:100) / $this->_sizeArray[0]);
295  $yRatio = min(1, ($coverThumbnailsMaxHeight?$coverThumbnailsMaxHeight:100) / $this->_sizeArray[1]);
296 
297  $ratio = min($xRatio, $yRatio);
298 
299  $thumbnailWidth = round($ratio * $this->_sizeArray[0]);
300  $thumbnailHeight = round($ratio * $this->_sizeArray[1]);
301  $thumbnail = imagecreatetruecolor($thumbnailWidth, $thumbnailHeight);
302  imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $thumbnailWidth, $thumbnailHeight, $this->_sizeArray[0], $this->_sizeArray[1]);
303 
304  // Copy the new file over
305  $filename = $category->getId() . '-category' . $this->_imageExtension;
306  $contextFileManager->copyFile($temporaryFile->getFilePath(), $basePath . $filename);
307 
308  switch ($this->_imageExtension) {
309  case '.jpg': imagejpeg($thumbnail, $basePath . $thumbnailFilename); break;
310  case '.png': imagepng($thumbnail, $basePath . $thumbnailFilename); break;
311  case '.gif': imagegif($thumbnail, $basePath . $thumbnailFilename); break;
312  }
313  imagedestroy($thumbnail);
314  imagedestroy($image);
315 
316  $category->setImage(array(
317  'name' => $filename,
318  'width' => $this->_sizeArray[0],
319  'height' => $this->_sizeArray[1],
320  'thumbnailName' => $thumbnailFilename,
321  'thumbnailWidth' => $thumbnailWidth,
322  'thumbnailHeight' => $thumbnailHeight,
323  'uploadName' => $temporaryFile->getOriginalFileName(),
324  'dateUploaded' => Core::getCurrentDate(),
325  ));
326 
327  // Clean up the temporary file
328  import('lib.pkp.classes.file.TemporaryFileManager');
329  $temporaryFileManager = new TemporaryFileManager();
330  $temporaryFileManager->deleteById($temporaryFileId, $this->_userId);
331  }
332 
333  // Update category object to store image information.
334  $categoryDao->updateObject($category);
335  parent::execute(...$functionArgs);
336  return $category;
337  }
338 }
339 
CategoryForm\execute
execute(... $functionArgs)
Definition: CategoryForm.inc.php:234
TemporaryFileManager
Definition: TemporaryFileManager.inc.php:19
CategoryForm\readInputData
readInputData()
Definition: CategoryForm.inc.php:161
CategoryForm\getCategoryId
getCategoryId()
Definition: CategoryForm.inc.php:86
CategoryForm\setCategoryId
setCategoryId($categoryId)
Definition: CategoryForm.inc.php:94
DAORegistry\getDAO
static & getDAO($name, $dbconn=null)
Definition: DAORegistry.inc.php:57
FormValidatorLocale
Class to represent a form validation check for localized fields.
Definition: FormValidatorLocale.inc.php:16
CategoryForm\getLocaleFieldNames
getLocaleFieldNames()
Definition: CategoryForm.inc.php:112
Form\setData
setData($key, $value=null)
Definition: Form.inc.php:229
Form\readUserVars
readUserVars($vars)
Definition: Form.inc.php:378
Form\getData
getData($key)
Definition: Form.inc.php:220
FormValidatorPost
Form validation check to make sure the form is POSTed.
Definition: FormValidatorPost.inc.php:18
Form\addError
addError($field, $message)
Definition: Form.inc.php:404
ContextFileManager
Class defining operations for private context file management.
Definition: ContextFileManager.inc.php:19
CategoryForm\fetch
fetch($request, $template=null, $display=false)
Definition: CategoryForm.inc.php:175
PKPTemplateManager\getManager
static & getManager($request=null)
Definition: PKPTemplateManager.inc.php:1239
FormValidatorRegExp
Form validation check using a regular expression.
Definition: FormValidatorRegExp.inc.php:18
CategoryForm\$_userId
$_userId
Definition: CategoryForm.inc.php:35
Core\getCurrentDate
static getCurrentDate($ts=null)
Definition: Core.inc.php:63
Form\addCheck
addCheck($formValidator)
Definition: Form.inc.php:395
CategoryForm
Form to add/edit category.
Definition: CategoryForm.inc.php:18
FormValidatorCSRF
Form validation check to make sure the CSRF token is correct.
Definition: FormValidatorCSRF.inc.php:18
Form
Class defining basic operations for handling HTML forms.
Definition: Form.inc.php:47
CategoryForm\initData
initData()
Definition: CategoryForm.inc.php:120
PKPApplication\get
static get()
Definition: PKPApplication.inc.php:235
CategoryForm\validate
validate($callHooks=true)
Definition: CategoryForm.inc.php:140
FormValidatorCustom
Form validation check with a custom user function performing the validation check.
Definition: FormValidatorCustom.inc.php:18
CategoryForm\$_imageExtension
$_imageExtension
Definition: CategoryForm.inc.php:41
CategoryForm\$_contextId
$_contextId
Definition: CategoryForm.inc.php:29
CategoryForm\$_categoryId
$_categoryId
Definition: CategoryForm.inc.php:23
CategoryForm\__construct
__construct($contextId, $categoryId=null)
Definition: CategoryForm.inc.php:55
PKPServices\get
static get($service)
Definition: PKPServices.inc.php:49
CategoryForm\getContextId
getContextId()
Definition: CategoryForm.inc.php:102
CategoryForm\$_sizeArray
$_sizeArray
Definition: CategoryForm.inc.php:47