PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/plugins/Field/src/Field/ImageField.php

http://github.com/QuickAppsCMS/QuickApps-CMS
PHP | 298 lines | 214 code | 29 blank | 55 comment | 20 complexity | de9a7a02e4551fb20c041f73df481528 MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, GPL-3.0
  1. <?php
  2. /**
  3. * Licensed under The GPL-3.0 License
  4. * For full copyright and license information, please see the LICENSE.txt
  5. * Redistributions of files must retain the above copyright notice.
  6. *
  7. * @since 2.0.0
  8. * @author Christopher Castro <chris@quickapps.es>
  9. * @link http://www.quickappscms.org
  10. * @license http://opensource.org/licenses/gpl-3.0.html GPL-3.0 License
  11. */
  12. namespace Field\Field;
  13. use Cake\Filesystem\File;
  14. use Cake\ORM\TableRegistry;
  15. use Cake\Utility\Hash;
  16. use Cake\Validation\Validator;
  17. use CMS\View\View;
  18. use Field\Handler;
  19. use Field\Model\Entity\Field;
  20. use Field\Model\Entity\FieldInstance;
  21. use Field\Utility\ImageToolbox;
  22. /**
  23. * Image Field Handler.
  24. *
  25. * This field allows attach images to entities.
  26. */
  27. class ImageField extends Handler
  28. {
  29. /**
  30. * {@inheritDoc}
  31. */
  32. public function info()
  33. {
  34. return [
  35. 'type' => 'text',
  36. 'name' => __d('field', 'Image'),
  37. 'description' => __d('field', 'Allows to attach image files to contents.'),
  38. 'hidden' => false,
  39. 'maxInstances' => 0,
  40. 'searchable' => false,
  41. ];
  42. }
  43. /**
  44. * {@inheritDoc}
  45. */
  46. public function render(Field $field, View $view)
  47. {
  48. if ($field->metadata->settings['multi'] === 'custom') {
  49. $settings = $field->metadata->settings;
  50. $settings['multi'] = $field->metadata->settings['multi_custom'];
  51. $field->metadata->set('settings', $settings);
  52. }
  53. return $view->element('Field.ImageField/display', compact('field'));
  54. }
  55. /**
  56. * {@inheritDoc}
  57. */
  58. public function edit(Field $field, View $view)
  59. {
  60. return $view->element('Field.ImageField/edit', compact('field'));
  61. }
  62. /**
  63. * {@inheritDoc}
  64. */
  65. public function fieldAttached(Field $field)
  66. {
  67. $extra = (array)$field->extra;
  68. if (!empty($extra)) {
  69. $newExtra = [];
  70. foreach ($extra as $file) {
  71. $newExtra[] = array_merge([
  72. 'mime_icon' => '',
  73. 'file_name' => '',
  74. 'file_size' => '',
  75. 'title' => '',
  76. 'alt' => '',
  77. ], (array)$file);
  78. }
  79. $field->set('extra', $newExtra);
  80. }
  81. }
  82. /**
  83. * {@inheritDoc}
  84. */
  85. public function validate(Field $field, Validator $validator)
  86. {
  87. if ($field->metadata->required) {
  88. $validator
  89. ->add($field->name, 'isRequired', [
  90. 'rule' => function ($value, $context) use ($field) {
  91. if (isset($context['data'][$field->name])) {
  92. $count = 0;
  93. foreach ($context['data'][$field->name] as $k => $file) {
  94. if (is_integer($k)) {
  95. $count++;
  96. }
  97. }
  98. return $count > 0;
  99. }
  100. return false;
  101. },
  102. 'message' => __d('field', 'You must upload one image at least.')
  103. ]);
  104. }
  105. if ($field->metadata->settings['multi'] !== 'custom') {
  106. $maxFiles = intval($field->metadata->settings['multi']);
  107. } else {
  108. $maxFiles = intval($field->metadata->settings['multi_custom']);
  109. }
  110. $validator
  111. ->add($field->name, 'numberOfFiles', [
  112. 'rule' => function ($value, $context) use ($field, $maxFiles) {
  113. if (isset($context['data'][$field->name])) {
  114. $count = 0;
  115. foreach ($context['data'][$field->name] as $k => $file) {
  116. if (is_integer($k)) {
  117. $count++;
  118. }
  119. }
  120. return $count <= $maxFiles;
  121. }
  122. return false;
  123. },
  124. 'message' => __d('field', 'You can upload {0} images as maximum.', $maxFiles)
  125. ]);
  126. if (!empty($field->metadata->settings['extensions'])) {
  127. $extensions = $field->metadata->settings['extensions'];
  128. $extensions = array_map('strtolower', array_map('trim', explode(',', $extensions)));
  129. $validator
  130. ->add($field->name, 'extensions', [
  131. 'rule' => function ($value, $context) use ($field, $extensions) {
  132. if (isset($context['data'][$field->name])) {
  133. foreach ($context['data'][$field->name] as $k => $file) {
  134. if (is_integer($k)) {
  135. $ext = strtolower(str_replace('.', '', strrchr($file['file_name'], '.')));
  136. if (!in_array($ext, $extensions)) {
  137. return false;
  138. }
  139. }
  140. }
  141. return true;
  142. }
  143. return false;
  144. },
  145. 'message' => __d('field', 'Invalid image extension. Allowed extension are: {0}', $field->metadata->settings['extensions'])
  146. ]);
  147. }
  148. return true;
  149. }
  150. /**
  151. * {@inheritDoc}
  152. *
  153. * - extra: Holds a list (array) of files and their in formation (mime-icon,
  154. * file name, etc).
  155. *
  156. * - value: Holds a text containing all file names separated by space.
  157. */
  158. public function beforeSave(Field $field, $post)
  159. {
  160. // FIX Removes the "dummy" input from extra if exists, the "dummy" input is
  161. // used to force Field Handler to work when empty POST information is sent
  162. $extra = [];
  163. foreach ((array)$field->extra as $k => $v) {
  164. if (is_integer($k)) {
  165. $extra[] = $v;
  166. }
  167. }
  168. $field->set('extra', $extra);
  169. $files = (array)$post;
  170. if (!empty($files)) {
  171. $value = [];
  172. foreach ($files as $k => $file) {
  173. if (!is_integer($k)) {
  174. unset($files[$k]);
  175. continue;
  176. } else {
  177. $file = array_merge([
  178. 'mime_icon' => '',
  179. 'file_name' => '',
  180. 'file_size' => '',
  181. 'title' => '',
  182. 'alt' => '',
  183. ], (array)$file);
  184. }
  185. $value[] = trim("{$file['file_name']} {$file['title']} {$file['alt']}");
  186. }
  187. $field->set('value', implode(' ', $value));
  188. $field->set('extra', $files);
  189. }
  190. if ($field->metadata->value_id) {
  191. $newFileNames = Hash::extract($files, '{n}.file_name');
  192. try {
  193. $prevFiles = (array)TableRegistry::get('Eav.EavValues')
  194. ->get($field->metadata->value_id)
  195. ->extra;
  196. } catch (\Exception $ex) {
  197. $prevFiles = [];
  198. }
  199. foreach ($prevFiles as $f) {
  200. if (!in_array($f['file_name'], $newFileNames)) {
  201. $file = normalizePath(WWW_ROOT . "/files/{$field->settings['upload_folder']}/{$f['file_name']}", DS);
  202. $file = new File($file);
  203. $file->delete();
  204. }
  205. }
  206. }
  207. return true;
  208. }
  209. /**
  210. * {@inheritDoc}
  211. */
  212. public function beforeDelete(Field $field)
  213. {
  214. foreach ((array)$field->extra as $image) {
  215. if (!empty($image['file_name'])) {
  216. ImageToolbox::delete(WWW_ROOT . "/files/{$field->settings['upload_folder']}/{$image['file_name']}");
  217. }
  218. }
  219. }
  220. /**
  221. * {@inheritDoc}
  222. */
  223. public function settings(FieldInstance $instance, View $view)
  224. {
  225. return $view->element('Field.ImageField/settings_form', compact('instance'));
  226. }
  227. /**
  228. * {@inheritDoc}
  229. */
  230. public function defaultSettings(FieldInstance $instance)
  231. {
  232. return [
  233. 'extensions' => 'jpg,jpeg,png,bmp,gif,tif,tiff',
  234. 'multi' => 1,
  235. 'multi_custom' => 1,
  236. 'upload_folder' => '',
  237. 'description' => '',
  238. 'preview' => '',
  239. 'min_width' => '',
  240. 'min_height' => '',
  241. 'max_width' => '',
  242. 'max_height' => '',
  243. 'min_ratio' => '',
  244. 'max_ratio' => '',
  245. 'min_pixels' => '',
  246. 'max_pixels' => '',
  247. ];
  248. }
  249. /**
  250. * {@inheritDoc}
  251. */
  252. public function viewModeSettings(FieldInstance $instance, View $view, $viewMode)
  253. {
  254. return $view->element('Field.ImageField/view_mode_form', compact('instance', 'viewMode'));
  255. }
  256. /**
  257. * {@inheritDoc}
  258. */
  259. public function defaultViewModeSettings(FieldInstance $instance, $viewMode)
  260. {
  261. return [
  262. 'label_visibility' => 'above',
  263. 'shortcodes' => true,
  264. 'hidden' => false,
  265. 'size' => 'thumbnail',
  266. 'link_type' => '',
  267. ];
  268. }
  269. }