Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like AssetAdmin often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use AssetAdmin, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
49 | class AssetAdmin extends LeftAndMain implements PermissionProvider |
||
50 | { |
||
51 | private static $url_segment = 'assets'; |
||
52 | |||
53 | private static $url_rule = '/$Action/$ID'; |
||
54 | |||
55 | private static $menu_title = 'Files'; |
||
56 | |||
57 | private static $tree_class = 'SilverStripe\\Assets\\Folder'; |
||
58 | |||
59 | private static $url_handlers = [ |
||
60 | // Legacy redirect for SS3-style detail view |
||
61 | 'EditForm/field/File/item/$FileID/$Action' => 'legacyRedirectForEditView', |
||
62 | // Pass all URLs to the index, for React to unpack |
||
63 | 'show/$FolderID/edit/$FileID' => 'index', |
||
64 | // API access points with structured data |
||
65 | 'POST api/createFolder' => 'apiCreateFolder', |
||
66 | 'POST api/createFile' => 'apiCreateFile', |
||
67 | 'GET api/readFolder' => 'apiReadFolder', |
||
68 | 'PUT api/updateFolder' => 'apiUpdateFolder', |
||
69 | 'DELETE api/delete' => 'apiDelete', |
||
70 | 'GET api/search' => 'apiSearch', |
||
71 | 'GET api/history' => 'apiHistory' |
||
72 | ]; |
||
73 | |||
74 | /** |
||
75 | * Amount of results showing on a single page. |
||
76 | * |
||
77 | * @config |
||
78 | * @var int |
||
79 | */ |
||
80 | private static $page_length = 15; |
||
81 | |||
82 | /** |
||
83 | * @config |
||
84 | * @see Upload->allowedMaxFileSize |
||
85 | * @var int |
||
86 | */ |
||
87 | private static $allowed_max_file_size; |
||
88 | |||
89 | /** |
||
90 | * @config |
||
91 | * |
||
92 | * @var int |
||
93 | */ |
||
94 | private static $max_history_entries = 100; |
||
95 | |||
96 | /** |
||
97 | * @var array |
||
98 | */ |
||
99 | private static $allowed_actions = array( |
||
100 | 'legacyRedirectForEditView', |
||
101 | 'apiCreateFolder', |
||
102 | 'apiCreateFile', |
||
103 | 'apiReadFolder', |
||
104 | 'apiUpdateFolder', |
||
105 | 'apiHistory', |
||
106 | 'apiDelete', |
||
107 | 'apiSearch', |
||
108 | 'fileEditForm', |
||
109 | 'fileHistoryForm', |
||
110 | 'addToCampaignForm', |
||
111 | 'fileInsertForm', |
||
112 | 'schema', |
||
113 | 'fileSelectForm', |
||
114 | 'fileSearchForm', |
||
115 | ); |
||
116 | |||
117 | private static $required_permission_codes = 'CMS_ACCESS_AssetAdmin'; |
||
118 | |||
119 | private static $thumbnail_width = 400; |
||
120 | |||
121 | private static $thumbnail_height = 300; |
||
122 | |||
123 | /** |
||
124 | * Set up the controller |
||
125 | */ |
||
126 | public function init() |
||
127 | { |
||
128 | parent::init(); |
||
129 | |||
130 | Requirements::add_i18n_javascript(ASSET_ADMIN_DIR . '/client/lang', false, true); |
||
131 | Requirements::javascript(ASSET_ADMIN_DIR . "/client/dist/js/bundle.js"); |
||
132 | Requirements::css(ASSET_ADMIN_DIR . "/client/dist/styles/bundle.css"); |
||
133 | |||
134 | CMSBatchActionHandler::register('delete', DeleteAssets::class, Folder::class); |
||
135 | } |
||
136 | |||
137 | public function getClientConfig() |
||
138 | { |
||
139 | $baseLink = $this->Link(); |
||
140 | return array_merge(parent::getClientConfig(), [ |
||
141 | 'reactRouter' => true, |
||
142 | 'createFileEndpoint' => [ |
||
143 | 'url' => Controller::join_links($baseLink, 'api/createFile'), |
||
144 | 'method' => 'post', |
||
145 | 'payloadFormat' => 'urlencoded', |
||
146 | ], |
||
147 | 'createFolderEndpoint' => [ |
||
148 | 'url' => Controller::join_links($baseLink, 'api/createFolder'), |
||
149 | 'method' => 'post', |
||
150 | 'payloadFormat' => 'urlencoded', |
||
151 | ], |
||
152 | 'readFolderEndpoint' => [ |
||
153 | 'url' => Controller::join_links($baseLink, 'api/readFolder'), |
||
154 | 'method' => 'get', |
||
155 | 'responseFormat' => 'json', |
||
156 | ], |
||
157 | 'searchEndpoint' => [ |
||
158 | 'url' => Controller::join_links($baseLink, 'api/search'), |
||
159 | 'method' => 'get', |
||
160 | 'responseFormat' => 'json', |
||
161 | ], |
||
162 | 'updateFolderEndpoint' => [ |
||
163 | 'url' => Controller::join_links($baseLink, 'api/updateFolder'), |
||
164 | 'method' => 'put', |
||
165 | 'payloadFormat' => 'urlencoded', |
||
166 | ], |
||
167 | 'deleteEndpoint' => [ |
||
168 | 'url' => Controller::join_links($baseLink, 'api/delete'), |
||
169 | 'method' => 'delete', |
||
170 | 'payloadFormat' => 'urlencoded', |
||
171 | ], |
||
172 | 'historyEndpoint' => [ |
||
173 | 'url' => Controller::join_links($baseLink, 'api/history'), |
||
174 | 'method' => 'get', |
||
175 | 'responseFormat' => 'json' |
||
176 | ], |
||
177 | 'limit' => $this->config()->page_length, |
||
178 | 'form' => [ |
||
179 | 'fileEditForm' => [ |
||
180 | 'schemaUrl' => $this->Link('schema/fileEditForm') |
||
181 | ], |
||
182 | 'fileInsertForm' => [ |
||
183 | 'schemaUrl' => $this->Link('schema/fileInsertForm') |
||
184 | ], |
||
185 | 'fileSelectForm' => [ |
||
186 | 'schemaUrl' => $this->Link('schema/fileSelectForm') |
||
187 | ], |
||
188 | 'addToCampaignForm' => [ |
||
189 | 'schemaUrl' => $this->Link('schema/addToCampaignForm') |
||
190 | ], |
||
191 | 'fileHistoryForm' => [ |
||
192 | 'schemaUrl' => $this->Link('schema/fileHistoryForm') |
||
193 | ], |
||
194 | 'fileSearchForm' => [ |
||
195 | 'schemaUrl' => $this->Link('schema/fileSearchForm') |
||
196 | ], |
||
197 | ], |
||
198 | ]); |
||
199 | } |
||
200 | |||
201 | /** |
||
202 | * Fetches a collection of files by ParentID. |
||
203 | * |
||
204 | * @param HTTPRequest $request |
||
205 | * @return HTTPResponse |
||
206 | */ |
||
207 | public function apiReadFolder(HTTPRequest $request) |
||
208 | { |
||
209 | $params = $request->requestVars(); |
||
210 | $items = array(); |
||
211 | $parentId = null; |
||
212 | $folderID = null; |
||
213 | |||
214 | if (!isset($params['id']) && !strlen($params['id'])) { |
||
215 | $this->httpError(400); |
||
216 | } |
||
217 | |||
218 | $folderID = (int)$params['id']; |
||
219 | /** @var Folder $folder */ |
||
220 | $folder = $folderID ? Folder::get()->byID($folderID) : Folder::singleton(); |
||
221 | |||
222 | if (!$folder) { |
||
223 | $this->httpError(400); |
||
224 | } |
||
225 | |||
226 | // TODO Limit results to avoid running out of memory (implement client-side pagination) |
||
227 | $files = $this->getList()->filter('ParentID', $folderID); |
||
228 | |||
229 | if ($files) { |
||
230 | /** @var File $file */ |
||
231 | foreach ($files as $file) { |
||
232 | if (!$file->canView()) { |
||
233 | continue; |
||
234 | } |
||
235 | |||
236 | $items[] = $this->getObjectFromData($file); |
||
237 | } |
||
238 | } |
||
239 | |||
240 | // Build parents (for breadcrumbs) |
||
241 | $parents = []; |
||
242 | $next = $folder->Parent(); |
||
243 | while ($next && $next->exists()) { |
||
244 | array_unshift($parents, [ |
||
245 | 'id' => $next->ID, |
||
246 | 'title' => $next->getTitle(), |
||
247 | 'filename' => $next->getFilename(), |
||
248 | ]); |
||
249 | if ($next->ParentID) { |
||
250 | $next = $next->Parent(); |
||
251 | } else { |
||
252 | break; |
||
253 | } |
||
254 | } |
||
255 | |||
256 | $column = 'title'; |
||
257 | $direction = 'asc'; |
||
258 | if (isset($params['sort'])) { |
||
259 | list($column, $direction) = explode(',', $params['sort']); |
||
260 | } |
||
261 | $multiplier = ($direction === 'asc') ? 1 : -1; |
||
262 | |||
263 | usort($items, function ($a, $b) use ($column, $multiplier) { |
||
264 | if (!isset($a[$column]) || !isset($b[$column])) { |
||
265 | return 0; |
||
266 | } |
||
267 | if ($a['type'] === 'folder' && $b['type'] !== 'folder') { |
||
268 | return -1; |
||
269 | } |
||
270 | if ($b['type'] === 'folder' && $a['type'] !== 'folder') { |
||
271 | return 1; |
||
272 | } |
||
273 | $numeric = (is_numeric($a[$column]) && is_numeric($b[$column])); |
||
274 | $fieldA = ($numeric) ? floatval($a[$column]) : strtolower($a[$column]); |
||
275 | $fieldB = ($numeric) ? floatval($b[$column]) : strtolower($b[$column]); |
||
276 | |||
277 | if ($fieldA < $fieldB) { |
||
278 | return $multiplier * -1; |
||
279 | } |
||
280 | |||
281 | if ($fieldA > $fieldB) { |
||
282 | return $multiplier; |
||
283 | } |
||
284 | |||
285 | return 0; |
||
286 | }); |
||
287 | |||
288 | $page = (isset($params['page'])) ? $params['page'] : 0; |
||
289 | $limit = (isset($params['limit'])) ? $params['limit'] : $this->config()->page_length; |
||
290 | $filteredItems = array_slice($items, $page * $limit, $limit); |
||
291 | |||
292 | // Build response |
||
293 | $response = new HTTPResponse(); |
||
294 | $response->addHeader('Content-Type', 'application/json'); |
||
295 | $response->setBody(json_encode([ |
||
296 | 'files' => $filteredItems, |
||
297 | 'title' => $folder->getTitle(), |
||
298 | 'count' => count($items), |
||
299 | 'parents' => $parents, |
||
300 | 'parent' => $parents ? $parents[count($parents) - 1] : null, |
||
301 | 'parentID' => $folder->exists() ? $folder->ParentID : null, // grandparent |
||
302 | 'folderID' => $folderID, |
||
303 | 'canEdit' => $folder->canEdit(), |
||
304 | 'canDelete' => $folder->canArchive(), |
||
305 | ])); |
||
306 | |||
307 | return $response; |
||
308 | } |
||
309 | |||
310 | /** |
||
311 | * @param HTTPRequest $request |
||
312 | * |
||
313 | * @return HTTPResponse |
||
314 | */ |
||
315 | public function apiSearch(HTTPRequest $request) |
||
316 | { |
||
317 | $params = $request->getVars(); |
||
318 | $list = $this->getList($params); |
||
319 | |||
320 | $response = new HTTPResponse(); |
||
321 | $response->addHeader('Content-Type', 'application/json'); |
||
322 | $response->setBody(json_encode([ |
||
323 | // Serialisation |
||
324 | "files" => array_map(function ($file) { |
||
325 | return $this->getObjectFromData($file); |
||
326 | }, $list->toArray()), |
||
327 | "count" => $list->count(), |
||
328 | ])); |
||
329 | |||
330 | return $response; |
||
331 | } |
||
332 | |||
333 | /** |
||
334 | * @param HTTPRequest $request |
||
335 | * |
||
336 | * @return HTTPResponse |
||
337 | */ |
||
338 | public function apiDelete(HTTPRequest $request) |
||
339 | { |
||
340 | parse_str($request->getBody(), $vars); |
||
341 | |||
342 | // CSRF check |
||
343 | $token = SecurityToken::inst(); |
||
344 | View Code Duplication | if (empty($vars[$token->getName()]) || !$token->check($vars[$token->getName()])) { |
|
345 | return new HTTPResponse(null, 400); |
||
346 | } |
||
347 | |||
348 | View Code Duplication | if (!isset($vars['ids']) || !$vars['ids']) { |
|
349 | return (new HTTPResponse(json_encode(['status' => 'error']), 400)) |
||
350 | ->addHeader('Content-Type', 'application/json'); |
||
351 | } |
||
352 | |||
353 | $fileIds = $vars['ids']; |
||
354 | $files = $this->getList()->filter("ID", $fileIds)->toArray(); |
||
355 | |||
356 | View Code Duplication | if (!count($files)) { |
|
357 | return (new HTTPResponse(json_encode(['status' => 'error']), 404)) |
||
358 | ->addHeader('Content-Type', 'application/json'); |
||
359 | } |
||
360 | |||
361 | if (!min(array_map(function (File $file) { |
||
362 | return $file->canArchive(); |
||
363 | }, $files))) { |
||
364 | return (new HTTPResponse(json_encode(['status' => 'error']), 401)) |
||
365 | ->addHeader('Content-Type', 'application/json'); |
||
366 | } |
||
367 | |||
368 | /** @var File $file */ |
||
369 | foreach ($files as $file) { |
||
370 | $file->doArchive(); |
||
371 | } |
||
372 | |||
373 | return (new HTTPResponse(json_encode(['status' => 'file was deleted']))) |
||
374 | ->addHeader('Content-Type', 'application/json'); |
||
375 | } |
||
376 | |||
377 | /** |
||
378 | * Creates a single file based on a form-urlencoded upload. |
||
379 | * |
||
380 | * @param HTTPRequest $request |
||
381 | * @return HTTPRequest|HTTPResponse |
||
382 | */ |
||
383 | public function apiCreateFile(HTTPRequest $request) |
||
384 | { |
||
385 | $data = $request->postVars(); |
||
386 | $upload = $this->getUpload(); |
||
387 | |||
388 | // CSRF check |
||
389 | $token = SecurityToken::inst(); |
||
390 | View Code Duplication | if (empty($data[$token->getName()]) || !$token->check($data[$token->getName()])) { |
|
391 | return new HTTPResponse(null, 400); |
||
392 | } |
||
393 | |||
394 | // Check parent record |
||
395 | /** @var Folder $parentRecord */ |
||
396 | $parentRecord = null; |
||
397 | if (!empty($data['ParentID']) && is_numeric($data['ParentID'])) { |
||
398 | $parentRecord = Folder::get()->byID($data['ParentID']); |
||
399 | } |
||
400 | $data['Parent'] = $parentRecord; |
||
401 | |||
402 | $tmpFile = $request->postVar('Upload'); |
||
403 | if (!$upload->validate($tmpFile)) { |
||
404 | $result = ['message' => null]; |
||
405 | $errors = $upload->getErrors(); |
||
406 | if ($message = array_shift($errors)) { |
||
407 | $result['message'] = [ |
||
408 | 'type' => 'error', |
||
409 | 'value' => $message, |
||
410 | ]; |
||
411 | } |
||
412 | return (new HTTPResponse(json_encode($result), 400)) |
||
413 | ->addHeader('Content-Type', 'application/json'); |
||
414 | } |
||
415 | |||
416 | // TODO Allow batch uploads |
||
417 | $fileClass = File::get_class_for_file_extension(File::get_file_extension($tmpFile['name'])); |
||
418 | /** @var File $file */ |
||
419 | $file = Injector::inst()->create($fileClass); |
||
420 | |||
421 | // check canCreate permissions |
||
422 | View Code Duplication | if (!$file->canCreate(null, $data)) { |
|
423 | $result = ['message' => [ |
||
424 | 'type' => 'error', |
||
425 | 'value' => _t( |
||
426 | 'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.CreatePermissionDenied', |
||
427 | 'You do not have permission to add files' |
||
428 | ) |
||
429 | ]]; |
||
430 | return (new HTTPResponse(json_encode($result), 403)) |
||
431 | ->addHeader('Content-Type', 'application/json'); |
||
432 | } |
||
433 | |||
434 | $uploadResult = $upload->loadIntoFile($tmpFile, $file, $parentRecord ? $parentRecord->getFilename() : '/'); |
||
435 | View Code Duplication | if (!$uploadResult) { |
|
436 | $result = ['message' => [ |
||
437 | 'type' => 'error', |
||
438 | 'value' => _t( |
||
439 | 'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.LoadIntoFileFailed', |
||
440 | 'Failed to load file' |
||
441 | ) |
||
442 | ]]; |
||
443 | return (new HTTPResponse(json_encode($result), 400)) |
||
444 | ->addHeader('Content-Type', 'application/json'); |
||
445 | } |
||
446 | |||
447 | $file->ParentID = $parentRecord ? $parentRecord->ID : 0; |
||
448 | $file->write(); |
||
449 | |||
450 | $result = [$this->getObjectFromData($file)]; |
||
451 | |||
452 | return (new HTTPResponse(json_encode($result))) |
||
453 | ->addHeader('Content-Type', 'application/json'); |
||
454 | } |
||
455 | |||
456 | /** |
||
457 | * Returns a JSON array for history of a given file ID. Returns a list of all the history. |
||
458 | * |
||
459 | * @param HTTPRequest $request |
||
460 | * @return HTTPResponse |
||
461 | */ |
||
462 | public function apiHistory(HTTPRequest $request) |
||
463 | { |
||
464 | // CSRF check not required as the GET request has no side effects. |
||
465 | $fileId = $request->getVar('fileId'); |
||
466 | |||
467 | if (!$fileId || !is_numeric($fileId)) { |
||
468 | return new HTTPResponse(null, 400); |
||
469 | } |
||
470 | |||
471 | $class = File::class; |
||
472 | $file = DataObject::get($class)->byID($fileId); |
||
473 | |||
474 | if (!$file) { |
||
475 | return new HTTPResponse(null, 404); |
||
476 | } |
||
477 | |||
478 | if (!$file->canView()) { |
||
479 | return new HTTPResponse(null, 403); |
||
480 | } |
||
481 | |||
482 | $versions = Versioned::get_all_versions($class, $fileId) |
||
483 | ->limit($this->config()->max_history_entries) |
||
484 | ->sort('Version', 'DESC'); |
||
485 | |||
486 | $output = array(); |
||
487 | $next = array(); |
||
488 | $prev = null; |
||
489 | |||
490 | // swap the order so we can get the version number to compare against. |
||
491 | // i.e version 3 needs to know version 2 is the previous version |
||
492 | $copy = $versions->map('Version', 'Version')->toArray(); |
||
493 | foreach (array_reverse($copy) as $k => $v) { |
||
494 | if ($prev) { |
||
495 | $next[$v] = $prev; |
||
496 | } |
||
497 | |||
498 | $prev = $v; |
||
499 | } |
||
500 | |||
501 | $_cachedMembers = array(); |
||
502 | |||
503 | /** @var File $version */ |
||
504 | foreach ($versions as $version) { |
||
505 | $author = null; |
||
506 | |||
507 | if ($version->AuthorID) { |
||
508 | if (!isset($_cachedMembers[$version->AuthorID])) { |
||
509 | $_cachedMembers[$version->AuthorID] = DataObject::get(Member::class) |
||
510 | ->byID($version->AuthorID); |
||
511 | } |
||
512 | |||
513 | $author = $_cachedMembers[$version->AuthorID]; |
||
514 | } |
||
515 | |||
516 | if ($version->canView()) { |
||
517 | if (isset($next[$version->Version])) { |
||
518 | $summary = $version->humanizedChanges( |
||
519 | $version->Version, |
||
520 | $next[$version->Version] |
||
521 | ); |
||
522 | |||
523 | // if no summary returned by humanizedChanges, i.e we cannot work out what changed, just show a |
||
524 | // generic message |
||
525 | if (!$summary) { |
||
526 | $summary = _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.SAVEDFILE', "Saved file"); |
||
527 | } |
||
528 | } else { |
||
529 | $summary = _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.UPLOADEDFILE', "Uploaded file"); |
||
530 | } |
||
531 | |||
532 | $output[] = array( |
||
533 | 'versionid' => $version->Version, |
||
534 | 'date_ago' => $version->dbObject('LastEdited')->Ago(), |
||
535 | 'date_formatted' => $version->dbObject('LastEdited')->Nice(), |
||
536 | 'status' => ($version->WasPublished) ? _t('File.PUBLISHED', 'Published') : '', |
||
537 | 'author' => ($author) |
||
538 | ? $author->Name |
||
539 | : _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.UNKNOWN', "Unknown"), |
||
540 | 'summary' => ($summary) |
||
541 | ? $summary |
||
542 | : _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.NOSUMMARY', "No summary available") |
||
543 | ); |
||
544 | } |
||
545 | } |
||
546 | |||
547 | return |
||
548 | (new HTTPResponse(json_encode($output)))->addHeader('Content-Type', 'application/json'); |
||
549 | } |
||
550 | |||
551 | |||
552 | /** |
||
553 | * Creates a single folder, within an optional parent folder. |
||
554 | * |
||
555 | * @param HTTPRequest $request |
||
556 | * @return HTTPRequest|HTTPResponse |
||
557 | */ |
||
558 | public function apiCreateFolder(HTTPRequest $request) |
||
559 | { |
||
560 | $data = $request->postVars(); |
||
561 | |||
562 | $class = 'SilverStripe\\Assets\\Folder'; |
||
563 | |||
564 | // CSRF check |
||
565 | $token = SecurityToken::inst(); |
||
566 | View Code Duplication | if (empty($data[$token->getName()]) || !$token->check($data[$token->getName()])) { |
|
567 | return new HTTPResponse(null, 400); |
||
568 | } |
||
569 | |||
570 | // check addchildren permissions |
||
571 | /** @var Folder $parentRecord */ |
||
572 | $parentRecord = null; |
||
573 | if (!empty($data['ParentID']) && is_numeric($data['ParentID'])) { |
||
574 | $parentRecord = DataObject::get_by_id($class, $data['ParentID']); |
||
575 | } |
||
576 | $data['Parent'] = $parentRecord; |
||
577 | $data['ParentID'] = $parentRecord ? (int)$parentRecord->ID : 0; |
||
578 | |||
579 | // Build filename |
||
580 | $baseFilename = isset($data['Name']) |
||
581 | ? basename($data['Name']) |
||
582 | : _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.NEWFOLDER', "NewFolder"); |
||
583 | |||
584 | if ($parentRecord && $parentRecord->ID) { |
||
585 | $baseFilename = $parentRecord->getFilename() . '/' . $baseFilename; |
||
586 | } |
||
587 | |||
588 | // Ensure name is unique |
||
589 | $nameGenerator = $this->getNameGenerator($baseFilename); |
||
590 | $filename = null; |
||
591 | foreach ($nameGenerator as $filename) { |
||
592 | if (! File::find($filename)) { |
||
593 | break; |
||
594 | } |
||
595 | } |
||
596 | $data['Name'] = basename($filename); |
||
597 | |||
598 | // Create record |
||
599 | /** @var Folder $record */ |
||
600 | $record = Injector::inst()->create($class); |
||
601 | |||
602 | // check create permissions |
||
603 | if (!$record->canCreate(null, $data)) { |
||
604 | return (new HTTPResponse(null, 403)) |
||
605 | ->addHeader('Content-Type', 'application/json'); |
||
606 | } |
||
607 | |||
608 | $record->ParentID = $data['ParentID']; |
||
609 | $record->Name = $record->Title = basename($data['Name']); |
||
610 | $record->write(); |
||
611 | |||
612 | $result = $this->getObjectFromData($record); |
||
613 | |||
614 | return (new HTTPResponse(json_encode($result)))->addHeader('Content-Type', 'application/json'); |
||
615 | } |
||
616 | |||
617 | /** |
||
618 | * Redirects 3.x style detail links to new 4.x style routing. |
||
619 | * |
||
620 | * @param HTTPRequest $request |
||
621 | */ |
||
622 | public function legacyRedirectForEditView($request) |
||
623 | { |
||
624 | $fileID = $request->param('FileID'); |
||
625 | /** @var File $file */ |
||
626 | $file = File::get()->byID($fileID); |
||
627 | $link = $this->getFileEditLink($file) ?: $this->Link(); |
||
628 | $this->redirect($link); |
||
629 | } |
||
630 | |||
631 | /** |
||
632 | * Given a file return the CMS link to edit it |
||
633 | * |
||
634 | * @param File $file |
||
635 | * @return string |
||
636 | */ |
||
637 | public function getFileEditLink($file) |
||
638 | { |
||
639 | if (!$file || !$file->isInDB()) { |
||
640 | return null; |
||
641 | } |
||
642 | |||
643 | return Controller::join_links( |
||
644 | $this->Link('show'), |
||
645 | $file->ParentID, |
||
646 | 'edit', |
||
647 | $file->ID |
||
648 | ); |
||
649 | } |
||
650 | |||
651 | /** |
||
652 | * Get the search context from {@link File}, used to create the search form |
||
653 | * as well as power the /search API endpoint. |
||
654 | * |
||
655 | * @return SearchContext |
||
656 | */ |
||
657 | public function getSearchContext() |
||
658 | { |
||
659 | $context = File::singleton()->getDefaultSearchContext(); |
||
660 | |||
661 | // Customize fields |
||
662 | $dateHeader = HeaderField::create('Date', _t('CMSSearch.FILTERDATEHEADING', 'Date'), 4); |
||
663 | $dateFrom = DateField::create('CreatedFrom', _t('CMSSearch.FILTERDATEFROM', 'From')) |
||
664 | ->setConfig('showcalendar', true); |
||
665 | $dateTo = DateField::create('CreatedTo', _t('CMSSearch.FILTERDATETO', 'To')) |
||
666 | ->setConfig('showcalendar', true); |
||
667 | $dateGroup = FieldGroup::create( |
||
668 | $dateHeader, |
||
669 | $dateFrom, |
||
670 | $dateTo |
||
671 | ); |
||
672 | $context->addField($dateGroup); |
||
673 | /** @skipUpgrade */ |
||
674 | $appCategories = array( |
||
675 | 'archive' => _t( |
||
676 | 'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryArchive', |
||
677 | 'Archive' |
||
678 | ), |
||
679 | 'audio' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryAudio', 'Audio'), |
||
680 | 'document' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryDocument', 'Document'), |
||
681 | 'flash' => _t( |
||
682 | 'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryFlash', |
||
683 | 'Flash', |
||
684 | 'The fileformat' |
||
685 | ), |
||
686 | 'image' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryImage', 'Image'), |
||
687 | 'video' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryVideo', 'Video'), |
||
688 | ); |
||
689 | $context->addField( |
||
690 | $typeDropdown = new DropdownField( |
||
691 | 'AppCategory', |
||
692 | _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.Filetype', 'File type'), |
||
693 | $appCategories |
||
694 | ) |
||
695 | ); |
||
696 | |||
697 | $typeDropdown->setEmptyString(' '); |
||
698 | |||
699 | $currentfolderLabel = _t( |
||
700 | 'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.CurrentFolderOnly', |
||
701 | 'Limit to current folder?' |
||
702 | ); |
||
703 | $context->addField( |
||
704 | new CheckboxField('CurrentFolderOnly', $currentfolderLabel) |
||
705 | ); |
||
706 | $context->getFields()->removeByName('Title'); |
||
707 | |||
708 | return $context; |
||
709 | } |
||
710 | |||
711 | /** |
||
712 | * Get an asset renamer for the given filename. |
||
713 | * |
||
714 | * @param string $filename Path name |
||
715 | * @return AssetNameGenerator |
||
716 | */ |
||
717 | protected function getNameGenerator($filename) |
||
718 | { |
||
719 | return Injector::inst() |
||
720 | ->createWithArgs('AssetNameGenerator', array($filename)); |
||
721 | } |
||
722 | |||
723 | /** |
||
724 | * @todo Implement on client |
||
725 | * |
||
726 | * @param bool $unlinked |
||
727 | * @return ArrayList |
||
728 | */ |
||
729 | public function breadcrumbs($unlinked = false) |
||
730 | { |
||
731 | return null; |
||
732 | } |
||
733 | |||
734 | |||
735 | /** |
||
736 | * Don't include class namespace in auto-generated CSS class |
||
737 | */ |
||
738 | public function baseCSSClasses() |
||
739 | { |
||
740 | return 'AssetAdmin LeftAndMain'; |
||
741 | } |
||
742 | |||
743 | public function providePermissions() |
||
744 | { |
||
745 | return array( |
||
746 | "CMS_ACCESS_AssetAdmin" => array( |
||
747 | 'name' => _t('CMSMain.ACCESS', "Access to '{title}' section", array( |
||
748 | 'title' => static::menu_title() |
||
749 | )), |
||
750 | 'category' => _t('Permission.CMS_ACCESS_CATEGORY', 'CMS Access') |
||
751 | ) |
||
752 | ); |
||
753 | } |
||
754 | |||
755 | /** |
||
756 | * Build a form scaffolder for this model |
||
757 | * |
||
758 | * NOTE: Volatile api. May be moved to {@see LeftAndMain} |
||
759 | * |
||
760 | * @param File $file |
||
761 | * @return FormFactory |
||
762 | */ |
||
763 | public function getFormFactory(File $file) |
||
764 | { |
||
765 | // Get service name based on file class |
||
766 | $name = null; |
||
767 | if ($file instanceof Folder) { |
||
768 | $name = FolderFormFactory::class; |
||
769 | } elseif ($file instanceof Image) { |
||
770 | $name = ImageFormFactory::class; |
||
771 | } else { |
||
772 | $name = FileFormFactory::class; |
||
773 | } |
||
774 | return Injector::inst()->get($name); |
||
775 | } |
||
776 | |||
777 | /** |
||
778 | * The form is used to generate a form schema, |
||
779 | * as well as an intermediary object to process data through API endpoints. |
||
780 | * Since it's used directly on API endpoints, it does not have any form actions. |
||
781 | * It handles both {@link File} and {@link Folder} records. |
||
782 | * |
||
783 | * @param int $id |
||
784 | * @return Form |
||
785 | */ |
||
786 | public function getFileEditForm($id) |
||
787 | { |
||
788 | return $this->getAbstractFileForm($id, 'fileEditForm'); |
||
789 | } |
||
790 | |||
791 | /** |
||
792 | * Get file edit form |
||
793 | * |
||
794 | * @return Form |
||
795 | */ |
||
796 | View Code Duplication | public function fileEditForm() |
|
797 | { |
||
798 | // Get ID either from posted back value, or url parameter |
||
799 | $request = $this->getRequest(); |
||
800 | $id = $request->param('ID') ?: $request->postVar('ID'); |
||
801 | return $this->getFileEditForm($id); |
||
802 | } |
||
803 | |||
804 | /** |
||
805 | * The form is used to generate a form schema, |
||
806 | * as well as an intermediary object to process data through API endpoints. |
||
807 | * Since it's used directly on API endpoints, it does not have any form actions. |
||
808 | * It handles both {@link File} and {@link Folder} records. |
||
809 | * |
||
810 | * @param int $id |
||
811 | * @return Form |
||
812 | */ |
||
813 | public function getFileInsertForm($id) |
||
814 | { |
||
815 | return $this->getAbstractFileForm($id, 'fileInsertForm', [ 'Type' => AssetFormFactory::TYPE_INSERT ]); |
||
816 | } |
||
817 | |||
818 | /** |
||
819 | * Get file insert form |
||
820 | * |
||
821 | * @return Form |
||
822 | */ |
||
823 | View Code Duplication | public function fileInsertForm() |
|
830 | |||
831 | /** |
||
832 | * Abstract method for generating a form for a file |
||
833 | * |
||
834 | * @param int $id Record ID |
||
835 | * @param string $name Form name |
||
836 | * @param array $context Form context |
||
837 | * @return Form |
||
838 | */ |
||
839 | protected function getAbstractFileForm($id, $name, $context = []) |
||
840 | { |
||
841 | /** @var File $file */ |
||
842 | $file = $this->getList()->byID($id); |
||
843 | |||
844 | View Code Duplication | if (!$file->canView()) { |
|
845 | $this->httpError(403, _t( |
||
846 | 'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.ErrorItemPermissionDenied', |
||
847 | 'You don\'t have the necessary permissions to modify {ObjectTitle}', |
||
848 | '', |
||
868 | |||
869 | /** |
||
870 | * Get form for selecting a file |
||
871 | * |
||
872 | * @return Form |
||
873 | */ |
||
874 | public function fileSelectForm() |
||
881 | |||
882 | /** |
||
883 | * Get form for selecting a file |
||
884 | * |
||
885 | * @param int $id ID of the record being selected |
||
886 | * @return Form |
||
887 | */ |
||
888 | public function getFileSelectForm($id) |
||
892 | |||
893 | /** |
||
894 | * @param array $context |
||
895 | * @return Form |
||
896 | * @throws InvalidArgumentException |
||
897 | */ |
||
898 | public function getFileHistoryForm($context) |
||
940 | |||
941 | /** |
||
942 | * Gets a JSON schema representing the current edit form. |
||
943 | * |
||
944 | * WARNING: Experimental API. |
||
945 | * |
||
946 | * @param HTTPRequest $request |
||
947 | * @return HTTPResponse |
||
948 | */ |
||
949 | public function schema($request) |
||
972 | |||
973 | /** |
||
974 | * Get file history form |
||
975 | * |
||
976 | * @return Form |
||
977 | */ |
||
978 | public function fileHistoryForm() |
||
989 | |||
990 | /** |
||
991 | * @param array $data |
||
992 | * @param Form $form |
||
993 | * @return HTTPResponse |
||
994 | */ |
||
995 | public function save($data, $form) |
||
999 | |||
1000 | /** |
||
1001 | * @param array $data |
||
1002 | * @param Form $form |
||
1003 | * @return HTTPResponse |
||
1004 | */ |
||
1005 | public function publish($data, $form) |
||
1009 | |||
1010 | /** |
||
1011 | * Update thisrecord |
||
1012 | * |
||
1013 | * @param array $data |
||
1014 | * @param Form $form |
||
1015 | * @param bool $doPublish |
||
1016 | * @return HTTPResponse |
||
1017 | */ |
||
1018 | protected function saveOrPublish($data, $form, $doPublish = false) |
||
1050 | |||
1051 | public function unpublish($data, $form) |
||
1075 | |||
1076 | /** |
||
1077 | * @param File $file |
||
1078 | * |
||
1079 | * @return array |
||
1080 | */ |
||
1081 | public function getObjectFromData(File $file) |
||
1151 | |||
1152 | /** |
||
1153 | * Returns the files and subfolders contained in the currently selected folder, |
||
1154 | * defaulting to the root node. Doubles as search results, if any search parameters |
||
1155 | * are set through {@link SearchForm()}. |
||
1156 | * |
||
1157 | * @param array $params Unsanitised request parameters |
||
1158 | * @return DataList |
||
1159 | */ |
||
1160 | protected function getList($params = array()) |
||
1215 | |||
1216 | /** |
||
1217 | * Action handler for adding pages to a campaign |
||
1218 | * |
||
1219 | * @param array $data |
||
1220 | * @param Form $form |
||
1221 | * @return DBHTMLText|HTTPResponse |
||
1222 | */ |
||
1223 | public function addtocampaign($data, $form) |
||
1239 | |||
1240 | /** |
||
1241 | * Url handler for add to campaign form |
||
1242 | * |
||
1243 | * @param HTTPRequest $request |
||
1244 | * @return Form |
||
1245 | */ |
||
1246 | public function addToCampaignForm($request) |
||
1252 | |||
1253 | /** |
||
1254 | * @param int $id |
||
1255 | * @return Form |
||
1256 | */ |
||
1257 | public function getAddToCampaignForm($id) |
||
1291 | |||
1292 | /** |
||
1293 | * @return Upload |
||
1294 | */ |
||
1295 | protected function getUpload() |
||
1305 | |||
1306 | /** |
||
1307 | * Get response for successfully updated record |
||
1308 | * |
||
1309 | * @param File $record |
||
1310 | * @param Form $form |
||
1311 | * @return HTTPResponse |
||
1312 | */ |
||
1313 | protected function getRecordUpdatedResponse($record, $form) |
||
1320 | |||
1321 | /** |
||
1322 | * Scaffold a search form. |
||
1323 | * Note: This form does not submit to itself, but rather uses the apiSearch endpoint |
||
1324 | * (to be replaced with graphql) |
||
1325 | * |
||
1326 | * @return Form |
||
1327 | */ |
||
1328 | public function fileSearchForm() |
||
1333 | |||
1334 | /** |
||
1335 | * Allow search form to be accessible to schema |
||
1336 | * |
||
1337 | * @return Form |
||
1338 | */ |
||
1339 | public function getFileSearchform() { |
||
1342 | } |
||
1343 |