adminbasecontroller.php 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. <?php
  2. namespace Grav\Plugin\Admin;
  3. use Grav\Common\Config\Config;
  4. use Grav\Common\Filesystem\Folder;
  5. use Grav\Common\Grav;
  6. use Grav\Common\Page\Media;
  7. use Grav\Common\Utils;
  8. use Grav\Common\Plugin;
  9. use Grav\Common\Theme;
  10. use RocketTheme\Toolbox\Event\Event;
  11. use RocketTheme\Toolbox\File\File;
  12. /**
  13. * Class AdminController
  14. *
  15. * @package Grav\Plugin
  16. */
  17. class AdminBaseController
  18. {
  19. /**
  20. * @var Grav
  21. */
  22. public $grav;
  23. /**
  24. * @var string
  25. */
  26. public $view;
  27. /**
  28. * @var string
  29. */
  30. public $task;
  31. /**
  32. * @var string
  33. */
  34. public $route;
  35. /**
  36. * @var array
  37. */
  38. public $post;
  39. /**
  40. * @var array|null
  41. */
  42. public $data;
  43. /**
  44. * @var \Grav\Common\Uri
  45. */
  46. protected $uri;
  47. /**
  48. * @var Admin
  49. */
  50. protected $admin;
  51. /**
  52. * @var string
  53. */
  54. protected $redirect;
  55. /**
  56. * @var int
  57. */
  58. protected $redirectCode;
  59. protected $upload_errors = [
  60. 0 => 'There is no error, the file uploaded with success',
  61. 1 => 'The uploaded file exceeds the max upload size',
  62. 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML',
  63. 3 => 'The uploaded file was only partially uploaded',
  64. 4 => 'No file was uploaded',
  65. 6 => 'Missing a temporary folder',
  66. 7 => 'Failed to write file to disk',
  67. 8 => 'A PHP extension stopped the file upload'
  68. ];
  69. /** @var array */
  70. public $blacklist_views = [];
  71. /**
  72. * Performs a task.
  73. *
  74. * @return bool True if the action was performed successfully.
  75. */
  76. public function execute()
  77. {
  78. if (in_array($this->view, $this->blacklist_views, true)) {
  79. return false;
  80. }
  81. if (!$this->validateNonce()) {
  82. return false;
  83. }
  84. $method = 'task' . ucfirst($this->task);
  85. if (method_exists($this, $method)) {
  86. try {
  87. $success = $this->{$method}();
  88. } catch (\RuntimeException $e) {
  89. $success = true;
  90. $this->admin->setMessage($e->getMessage(), 'error');
  91. }
  92. } else {
  93. $success = $this->grav->fireEvent('onAdminTaskExecute',
  94. new Event(['controller' => $this, 'method' => $method]));
  95. }
  96. // Grab redirect parameter.
  97. $redirect = isset($this->post['_redirect']) ? $this->post['_redirect'] : null;
  98. unset($this->post['_redirect']);
  99. // Redirect if requested.
  100. if ($redirect) {
  101. $this->setRedirect($redirect);
  102. }
  103. return $success;
  104. }
  105. protected function validateNonce()
  106. {
  107. if (strtolower($_SERVER['REQUEST_METHOD']) === 'post') {
  108. if (isset($this->post['admin-nonce'])) {
  109. $nonce = $this->post['admin-nonce'];
  110. } else {
  111. $nonce = $this->grav['uri']->param('admin-nonce');
  112. }
  113. if (!$nonce || !Utils::verifyNonce($nonce, 'admin-form')) {
  114. if ($this->task === 'addmedia') {
  115. $message = sprintf($this->admin->translate('PLUGIN_ADMIN.FILE_TOO_LARGE', null),
  116. ini_get('post_max_size'));
  117. //In this case it's more likely that the image is too big than POST can handle. Show message
  118. $this->admin->json_response = [
  119. 'status' => 'error',
  120. 'message' => $message
  121. ];
  122. return false;
  123. }
  124. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN'), 'error');
  125. $this->admin->json_response = [
  126. 'status' => 'error',
  127. 'message' => $this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN')
  128. ];
  129. return false;
  130. }
  131. unset($this->post['admin-nonce']);
  132. } else {
  133. if ($this->task === 'logout') {
  134. $nonce = $this->grav['uri']->param('logout-nonce');
  135. if (null === $nonce || !Utils::verifyNonce($nonce, 'logout-form')) {
  136. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN'),
  137. 'error');
  138. $this->admin->json_response = [
  139. 'status' => 'error',
  140. 'message' => $this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN')
  141. ];
  142. return false;
  143. }
  144. } else {
  145. $nonce = $this->grav['uri']->param('admin-nonce');
  146. if (null === $nonce || !Utils::verifyNonce($nonce, 'admin-form')) {
  147. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN'),
  148. 'error');
  149. $this->admin->json_response = [
  150. 'status' => 'error',
  151. 'message' => $this->admin->translate('PLUGIN_ADMIN.INVALID_SECURITY_TOKEN')
  152. ];
  153. return false;
  154. }
  155. }
  156. }
  157. return true;
  158. }
  159. /**
  160. * Sets the page redirect.
  161. *
  162. * @param string $path The path to redirect to
  163. * @param int $code The HTTP redirect code
  164. */
  165. public function setRedirect($path, $code = 303)
  166. {
  167. $this->redirect = $path;
  168. $this->redirectCode = $code;
  169. }
  170. /**
  171. * Handles ajax upload for files.
  172. * Stores in a flash object the temporary file and deals with potential file errors.
  173. *
  174. * @return bool True if the action was performed.
  175. */
  176. public function taskFilesUpload()
  177. {
  178. if (null === $_FILES || !$this->authorizeTask('save', $this->dataPermissions())) {
  179. return false;
  180. }
  181. /** @var Config $config */
  182. $config = $this->grav['config'];
  183. $data = $this->view === 'pages' ? $this->admin->page(true) : $this->prepareData([]);
  184. $settings = $data->blueprints()->schema()->getProperty($this->post['name']);
  185. $settings = (object)array_merge([
  186. 'avoid_overwriting' => false,
  187. 'random_name' => false,
  188. 'accept' => ['image/*'],
  189. 'limit' => 10,
  190. 'filesize' => $config->get('system.media.upload_limit', 5242880) // 5MB
  191. ], (array)$settings, ['name' => $this->post['name']]);
  192. $upload = $this->normalizeFiles($_FILES['data'], $settings->name);
  193. $filename = trim($upload->file->name);
  194. // Handle bad filenames.
  195. if (strtr($filename, "\t\n\r\0\x0b", '_____') !== $filename || rtrim($filename, '. ') !== $filename || preg_match('|\.php|', $filename)) {
  196. $this->admin->json_response = [
  197. 'status' => 'error',
  198. 'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_UPLOAD', null),
  199. $filename, 'Bad filename')
  200. ];
  201. return false;
  202. }
  203. if (!isset($settings->destination)) {
  204. $this->admin->json_response = [
  205. 'status' => 'error',
  206. 'message' => $this->admin->translate('PLUGIN_ADMIN.DESTINATION_NOT_SPECIFIED', null)
  207. ];
  208. return false;
  209. }
  210. // Do not use self@ outside of pages
  211. if ($this->view !== 'pages' && in_array($settings->destination, ['@self', 'self@'])) {
  212. $this->admin->json_response = [
  213. 'status' => 'error',
  214. 'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_PREVENT_SELF', null),
  215. $settings->destination)
  216. ];
  217. return false;
  218. }
  219. // Handle errors and breaks without proceeding further
  220. if ($upload->file->error != UPLOAD_ERR_OK) {
  221. $this->admin->json_response = [
  222. 'status' => 'error',
  223. 'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_UPLOAD', null),
  224. $upload->file->name, $this->upload_errors[$upload->file->error])
  225. ];
  226. return false;
  227. }
  228. // Handle file size limits
  229. $settings->filesize *= 1048576; // 2^20 [MB in Bytes]
  230. if ($settings->filesize > 0 && $upload->file->size > $settings->filesize) {
  231. $this->admin->json_response = [
  232. 'status' => 'error',
  233. 'message' => $this->admin->translate('PLUGIN_ADMIN.EXCEEDED_GRAV_FILESIZE_LIMIT')
  234. ];
  235. return false;
  236. }
  237. // Handle Accepted file types
  238. // Accept can only be mime types (image/png | image/*) or file extensions (.pdf|.jpg)
  239. $accepted = false;
  240. $errors = [];
  241. foreach ((array)$settings->accept as $type) {
  242. // Force acceptance of any file when star notation
  243. if ($type === '*') {
  244. $accepted = true;
  245. break;
  246. }
  247. $isMime = strstr($type, '/');
  248. $find = str_replace('*', '.*', $type);
  249. $match = preg_match('#' . $find . '$#', $isMime ? $upload->file->type : $upload->file->name);
  250. if (!$match) {
  251. $message = $isMime ? 'The MIME type "' . $upload->file->type . '"' : 'The File Extension';
  252. $errors[] = $message . ' for the file "' . $upload->file->name . '" is not an accepted.';
  253. $accepted |= false;
  254. } else {
  255. $accepted |= true;
  256. }
  257. }
  258. if (!$accepted) {
  259. $this->admin->json_response = [
  260. 'status' => 'error',
  261. 'message' => implode('<br />', $errors)
  262. ];
  263. return false;
  264. }
  265. // Remove the error object to avoid storing it
  266. unset($upload->file->error);
  267. // we need to move the file at this stage or else
  268. // it won't be available upon save later on
  269. // since php removes it from the upload location
  270. $tmp_dir = Admin::getTempDir();
  271. $tmp_file = $upload->file->tmp_name;
  272. $tmp = $tmp_dir . '/uploaded-files/' . basename($tmp_file);
  273. Folder::create(dirname($tmp));
  274. if (!move_uploaded_file($tmp_file, $tmp)) {
  275. $this->admin->json_response = [
  276. 'status' => 'error',
  277. 'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_MOVE', null), '',
  278. $tmp)
  279. ];
  280. return false;
  281. }
  282. $upload->file->tmp_name = $tmp;
  283. // Retrieve the current session of the uploaded files for the field
  284. // and initialize it if it doesn't exist
  285. $sessionField = base64_encode($this->grav['uri']->url());
  286. $flash = $this->admin->session()->getFlashObject('files-upload');
  287. if (!$flash) {
  288. $flash = [];
  289. }
  290. if (!isset($flash[$sessionField])) {
  291. $flash[$sessionField] = [];
  292. }
  293. if (!isset($flash[$sessionField][$upload->field])) {
  294. $flash[$sessionField][$upload->field] = [];
  295. }
  296. // Set destination
  297. if ($this->grav['locator']->isStream($settings->destination)) {
  298. $destination = $this->grav['locator']->findResource($settings->destination, false, true);
  299. } else {
  300. $destination = Folder::getRelativePath(rtrim($settings->destination, '/'));
  301. $destination = $this->admin->getPagePathFromToken($destination);
  302. }
  303. // Create destination if needed
  304. if (!is_dir($destination)) {
  305. Folder::mkdir($destination);
  306. }
  307. // Generate random name if required
  308. if ($settings->random_name) { // TODO: document
  309. $extension = pathinfo($upload->file->name)['extension'];
  310. $upload->file->name = Utils::generateRandomString(15) . '.' . $extension;
  311. }
  312. // Handle conflicting name if needed
  313. if ($settings->avoid_overwriting) { // TODO: document
  314. if (file_exists($destination . '/' . $upload->file->name)) {
  315. $upload->file->name = date('YmdHis') . '-' . $upload->file->name;
  316. }
  317. }
  318. // Prepare object for later save
  319. $path = $destination . '/' . $upload->file->name;
  320. $upload->file->path = $path;
  321. // $upload->file->route = $page ? $path : null;
  322. // Prepare data to be saved later
  323. $flash[$sessionField][$upload->field][$path] = (array)$upload->file;
  324. // Finally store the new uploaded file in the field session
  325. $this->admin->session()->setFlashObject('files-upload', $flash);
  326. $this->admin->json_response = [
  327. 'status' => 'success',
  328. 'session' => \json_encode([
  329. 'sessionField' => base64_encode($this->grav['uri']->url()),
  330. 'path' => $upload->file->path,
  331. 'field' => $settings->name
  332. ])
  333. ];
  334. return true;
  335. }
  336. /**
  337. * Checks if the user is allowed to perform the given task with its associated permissions
  338. *
  339. * @param string $task The task to execute
  340. * @param array $permissions The permissions given
  341. *
  342. * @return bool True if authorized. False if not.
  343. */
  344. public function authorizeTask($task = '', $permissions = [])
  345. {
  346. if (!$this->admin->authorize($permissions)) {
  347. if ($this->grav['uri']->extension() === 'json') {
  348. $this->admin->json_response = [
  349. 'status' => 'unauthorized',
  350. 'message' => $this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' ' . $task . '.'
  351. ];
  352. } else {
  353. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' ' . $task . '.',
  354. 'error');
  355. }
  356. return false;
  357. }
  358. return true;
  359. }
  360. /**
  361. * Gets the permissions needed to access a given view
  362. *
  363. * @return array An array of permissions
  364. */
  365. protected function dataPermissions()
  366. {
  367. $type = $this->view;
  368. $permissions = ['admin.super'];
  369. switch ($type) {
  370. case 'configuration':
  371. case 'config':
  372. case 'system':
  373. $permissions[] = 'admin.configuration';
  374. break;
  375. case 'settings':
  376. case 'site':
  377. $permissions[] = 'admin.settings';
  378. break;
  379. case 'plugins':
  380. $permissions[] = 'admin.plugins';
  381. break;
  382. case 'themes':
  383. $permissions[] = 'admin.themes';
  384. break;
  385. case 'users':
  386. $permissions[] = 'admin.users';
  387. break;
  388. case 'user':
  389. $permissions[] = 'admin.login';
  390. $permissions[] = 'admin.users';
  391. break;
  392. case 'pages':
  393. $permissions[] = 'admin.pages';
  394. break;
  395. }
  396. return $permissions;
  397. }
  398. /**
  399. * Gets the configuration data for a given view & post
  400. *
  401. * @param array $data
  402. *
  403. * @return array
  404. */
  405. protected function prepareData(array $data)
  406. {
  407. return $data;
  408. }
  409. /**
  410. * Internal method to normalize the $_FILES array
  411. *
  412. * @param array $data $_FILES starting point data
  413. * @param string $key
  414. *
  415. * @return object a new Object with a normalized list of files
  416. */
  417. protected function normalizeFiles($data, $key = '')
  418. {
  419. $files = new \stdClass();
  420. $files->field = $key;
  421. $files->file = new \stdClass();
  422. foreach ($data as $fieldName => $fieldValue) {
  423. // Since Files Upload are always happening via Ajax
  424. // we are not interested in handling `multiple="true"`
  425. // because they are always handled one at a time.
  426. // For this reason we normalize the value to string,
  427. // in case it is arriving as an array.
  428. $value = (array)Utils::getDotNotation($fieldValue, $key);
  429. $files->file->{$fieldName} = array_shift($value);
  430. }
  431. return $files;
  432. }
  433. /**
  434. * Removes a file from the flash object session, before it gets saved
  435. *
  436. * @return bool True if the action was performed.
  437. */
  438. public function taskFilesSessionRemove()
  439. {
  440. if (!$this->authorizeTask('save', $this->dataPermissions()) || !isset($_FILES)) {
  441. return false;
  442. }
  443. // Retrieve the current session of the uploaded files for the field
  444. // and initialize it if it doesn't exist
  445. $sessionField = base64_encode($this->grav['uri']->url());
  446. $request = \json_decode($this->post['session']);
  447. // Ensure the URI requested matches the current one, otherwise fail
  448. if ($request->sessionField !== $sessionField) {
  449. return false;
  450. }
  451. // Retrieve the flash object and remove the requested file from it
  452. $flash = $this->admin->session()->getFlashObject('files-upload');
  453. $endpoint = $flash[$request->sessionField][$request->field][$request->path];
  454. if (isset($endpoint)) {
  455. if (file_exists($endpoint['tmp_name'])) {
  456. unlink($endpoint['tmp_name']);
  457. }
  458. unset($endpoint);
  459. }
  460. // Walk backward to cleanup any empty field that's left
  461. // Field
  462. if (isset($flash[$request->sessionField][$request->field][$request->path])) {
  463. unset($flash[$request->sessionField][$request->field][$request->path]);
  464. }
  465. // Field
  466. if (isset($flash[$request->sessionField][$request->field]) && empty($flash[$request->sessionField][$request->field])) {
  467. unset($flash[$request->sessionField][$request->field]);
  468. }
  469. // Session Field
  470. if (isset($flash[$request->sessionField]) && empty($flash[$request->sessionField])) {
  471. unset($flash[$request->sessionField]);
  472. }
  473. // If there's anything left to restore in the flash object, do so
  474. if (count($flash)) {
  475. $this->admin->session()->setFlashObject('files-upload', $flash);
  476. }
  477. $this->admin->json_response = ['status' => 'success'];
  478. return true;
  479. }
  480. /**
  481. * Redirect to the route stored in $this->redirect
  482. */
  483. public function redirect()
  484. {
  485. if (!$this->redirect) {
  486. return;
  487. }
  488. $base = $this->admin->base;
  489. $this->redirect = '/' . ltrim($this->redirect, '/');
  490. $multilang = $this->isMultilang();
  491. $redirect = '';
  492. if ($multilang) {
  493. // if base path does not already contain the lang code, add it
  494. $langPrefix = '/' . $this->grav['session']->admin_lang;
  495. if (!Utils::startsWith($base, $langPrefix . '/')) {
  496. $base = $langPrefix . $base;
  497. }
  498. // now the first 4 chars of base contain the lang code.
  499. // if redirect path already contains the lang code, and is != than the base lang code, then use redirect path as-is
  500. if (Utils::pathPrefixedByLangCode($base) && Utils::pathPrefixedByLangCode($this->redirect)
  501. && 0 !== strpos($this->redirect, substr($base, 0, 4))
  502. ) {
  503. $redirect = $this->redirect;
  504. } else {
  505. if (!Utils::startsWith($this->redirect, $base)) {
  506. $this->redirect = $base . $this->redirect;
  507. }
  508. }
  509. } else {
  510. if (!Utils::startsWith($this->redirect, $base)) {
  511. $this->redirect = $base . $this->redirect;
  512. }
  513. }
  514. if (!$redirect) {
  515. $redirect = $this->redirect;
  516. }
  517. $this->grav->redirect($redirect, $this->redirectCode);
  518. }
  519. /**
  520. * Prepare and return POST data.
  521. *
  522. * @param array $post
  523. *
  524. * @return array
  525. */
  526. protected function getPost($post)
  527. {
  528. if (!is_array($post)) {
  529. return [];
  530. }
  531. unset($post['task']);
  532. // Decode JSON encoded fields and merge them to data.
  533. if (isset($post['_json'])) {
  534. $post = array_replace_recursive($post, $this->jsonDecode($post['_json']));
  535. unset($post['_json']);
  536. }
  537. $post = $this->cleanDataKeys($post);
  538. return $post;
  539. }
  540. /**
  541. * Recursively JSON decode data.
  542. *
  543. * @param array $data
  544. *
  545. * @return array
  546. */
  547. protected function jsonDecode(array $data)
  548. {
  549. foreach ($data as &$value) {
  550. if (is_array($value)) {
  551. $value = $this->jsonDecode($value);
  552. } else {
  553. $value = json_decode($value, true);
  554. }
  555. }
  556. return $data;
  557. }
  558. protected function cleanDataKeys($source = [])
  559. {
  560. $out = [];
  561. if (is_array($source)) {
  562. foreach ($source as $key => $value) {
  563. $key = str_replace(['%5B', '%5D'], ['[', ']'], $key);
  564. if (is_array($value)) {
  565. $out[$key] = $this->cleanDataKeys($value);
  566. } else {
  567. $out[$key] = $value;
  568. }
  569. }
  570. }
  571. return $out;
  572. }
  573. /**
  574. * Return true if multilang is active
  575. *
  576. * @return bool True if multilang is active
  577. */
  578. protected function isMultilang()
  579. {
  580. return count($this->grav['config']->get('system.languages.supported', [])) > 1;
  581. }
  582. /**
  583. * @param \Grav\Common\Page\Page|\Grav\Common\Data\Data $obj
  584. *
  585. * @return \Grav\Common\Page\Page|\Grav\Common\Data\Data
  586. */
  587. protected function storeFiles($obj)
  588. {
  589. // Process previously uploaded files for the current URI
  590. // and finally store them. Everything else will get discarded
  591. $queue = $this->admin->session()->getFlashObject('files-upload');
  592. $queue = $queue[base64_encode($this->grav['uri']->url())];
  593. if (is_array($queue)) {
  594. foreach ($queue as $key => $files) {
  595. foreach ($files as $destination => $file) {
  596. if (!rename($file['tmp_name'], $destination)) {
  597. throw new \RuntimeException(sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_MOVE',
  598. null), '"' . $file['tmp_name'] . '"', $destination));
  599. }
  600. unset($files[$destination]['tmp_name']);
  601. }
  602. if ($this->view === 'pages') {
  603. $keys = explode('.', preg_replace('/^header./', '', $key));
  604. $init_key = array_shift($keys);
  605. if (count($keys) > 0) {
  606. $new_data = isset($obj->header()->{$init_key}) ? $obj->header()->{$init_key} : [];
  607. Utils::setDotNotation($new_data, implode('.', $keys), $files, true);
  608. } else {
  609. $new_data = $files;
  610. }
  611. if (isset($data['header'][$init_key])) {
  612. $obj->modifyHeader($init_key,
  613. array_replace_recursive([], $data['header'][$init_key], $new_data));
  614. } else {
  615. $obj->modifyHeader($init_key, $new_data);
  616. }
  617. } else {
  618. // TODO: [this is JS handled] if it's single file, remove existing and use set, if it's multiple, use join
  619. $obj->join($key, $files); // stores
  620. }
  621. }
  622. }
  623. return $obj;
  624. }
  625. /**
  626. * Used by the filepicker field to get a list of files in a folder.
  627. */
  628. protected function taskGetFilesInFolder()
  629. {
  630. if (!$this->authorizeTask('save', $this->dataPermissions())) {
  631. return false;
  632. }
  633. $data = $this->view === 'pages' ? $this->admin->page(true) : $this->prepareData([]);
  634. $settings = $data->blueprints()->schema()->getProperty($this->post['name']);
  635. if (isset($settings['folder'])) {
  636. $folder = $settings['folder'];
  637. } else {
  638. $folder = '@self';
  639. }
  640. // Do not use self@ outside of pages
  641. if ($this->view !== 'pages' && in_array($folder, ['@self', 'self@', '@self@'])) {
  642. $this->admin->json_response = [
  643. 'status' => 'error',
  644. 'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_PREVENT_SELF', null), $folder)
  645. ];
  646. return false;
  647. }
  648. // Set destination
  649. $folder = Folder::getRelativePath(rtrim($folder, '/'));
  650. $folder = $this->admin->getPagePathFromToken($folder);
  651. $media = new Media($folder);
  652. $available_files = [];
  653. $metadata = [];
  654. $thumbs = [];
  655. foreach ($media->all() as $name => $medium) {
  656. $available_files[] = $name;
  657. if (isset($settings['include_metadata'])) {
  658. $img_metadata = $medium->metadata();
  659. if ($img_metadata) {
  660. $metadata[$name] = $img_metadata;
  661. }
  662. }
  663. }
  664. // Peak in the flashObject for optimistic filepicker updates
  665. $pending_files = [];
  666. $sessionField = base64_encode($this->grav['uri']->url());
  667. $flash = $this->admin->session()->getFlashObject('files-upload');
  668. if ($flash && isset($flash[$sessionField])) {
  669. foreach ($flash[$sessionField] as $field => $data) {
  670. foreach ($data as $file) {
  671. if (dirname($file['path']) === $folder) {
  672. $pending_files[] = $file['name'];
  673. }
  674. }
  675. }
  676. }
  677. $this->admin->session()->setFlashObject('files-upload', $flash);
  678. // Handle Accepted file types
  679. // Accept can only be file extensions (.pdf|.jpg)
  680. if (isset($settings['accept'])) {
  681. $available_files = array_filter($available_files, function ($file) use ($settings) {
  682. return $this->filterAcceptedFiles($file, $settings);
  683. });
  684. $pending_files = array_filter($pending_files, function ($file) use ($settings) {
  685. return $this->filterAcceptedFiles($file, $settings);
  686. });
  687. }
  688. // Generate thumbs if needed
  689. if (isset($settings['preview_images']) && $settings['preview_images'] === true) {
  690. foreach ($available_files as $filename) {
  691. $thumbs[$filename] = $media[$filename]->zoomCrop(100,100)->url();
  692. }
  693. }
  694. $this->admin->json_response = [
  695. 'status' => 'success',
  696. 'files' => array_values($available_files),
  697. 'pending' => array_values($pending_files),
  698. 'folder' => $folder,
  699. 'metadata' => $metadata,
  700. 'thumbs' => $thumbs
  701. ];
  702. return true;
  703. }
  704. protected function filterAcceptedFiles($file, $settings)
  705. {
  706. $valid = false;
  707. foreach ((array)$settings['accept'] as $type) {
  708. $find = str_replace('*', '.*', $type);
  709. $valid |= preg_match('#' . $find . '$#', $file);
  710. }
  711. return $valid;
  712. }
  713. /**
  714. * Handle deleting a file from a blueprint
  715. *
  716. * @return bool True if the action was performed.
  717. */
  718. protected function taskRemoveFileFromBlueprint()
  719. {
  720. $uri = $this->grav['uri'];
  721. $blueprint = base64_decode($uri->param('blueprint'));
  722. $path = base64_decode($uri->param('path'));
  723. $proute = base64_decode($uri->param('proute'));
  724. $type = $uri->param('type');
  725. $field = $uri->param('field');
  726. $this->taskRemoveMedia();
  727. if ($type === 'pages') {
  728. $page = $this->admin->page(true, $proute);
  729. $keys = explode('.', preg_replace('/^header./', '', $field));
  730. $header = (array)$page->header();
  731. $data_path = implode('.', $keys);
  732. $data = Utils::getDotNotation($header, $data_path);
  733. if (isset($data[$path])) {
  734. unset($data[$path]);
  735. Utils::setDotNotation($header, $data_path, $data);
  736. $page->header($header);
  737. }
  738. $page->save();
  739. } else {
  740. $blueprint_prefix = $type === 'config' ? '' : $type . '.';
  741. $blueprint_name = str_replace(['config/', '/blueprints'], '', $blueprint);
  742. $blueprint_field = $blueprint_prefix . $blueprint_name . '.' . $field;
  743. $files = $this->grav['config']->get($blueprint_field);
  744. if ($files) {
  745. foreach ($files as $key => $value) {
  746. if ($key == $path) {
  747. unset($files[$key]);
  748. }
  749. }
  750. }
  751. $this->grav['config']->set($blueprint_field, $files);
  752. switch ($type) {
  753. case 'config':
  754. $data = $this->grav['config']->get($blueprint_name);
  755. $config = $this->admin->data($blueprint, $data);
  756. $config->save();
  757. break;
  758. case 'themes':
  759. Theme::saveConfig($blueprint_name);
  760. break;
  761. case 'plugins':
  762. Plugin::saveConfig($blueprint_name);
  763. break;
  764. }
  765. }
  766. $this->admin->json_response = [
  767. 'status' => 'success',
  768. 'message' => $this->admin->translate('PLUGIN_ADMIN.REMOVE_SUCCESSFUL')
  769. ];
  770. return true;
  771. }
  772. /**
  773. * Handles removing a media file
  774. *
  775. * @return bool True if the action was performed
  776. */
  777. public function taskRemoveMedia()
  778. {
  779. if (!$this->canEditMedia()) {
  780. return false;
  781. }
  782. $filename = base64_decode($this->grav['uri']->param('route'));
  783. if (!$filename) {
  784. $filename = base64_decode($this->route);
  785. }
  786. $file = File::instance($filename);
  787. $resultRemoveMedia = false;
  788. if ($file->exists()) {
  789. $resultRemoveMedia = $file->delete();
  790. $fileParts = pathinfo($filename);
  791. foreach (scandir($fileParts['dirname']) as $file) {
  792. $regex_pattern = '/' . preg_quote($fileParts['filename'], '/') . "@\d+x\." . $fileParts['extension'] . "(?:\.meta\.yaml)?$|" . preg_quote($fileParts['basename'], '/') . "\.meta\.yaml$/";
  793. if (preg_match($regex_pattern, $file)) {
  794. $path = $fileParts['dirname'] . '/' . $file;
  795. @unlink($path);
  796. }
  797. }
  798. }
  799. if ($resultRemoveMedia) {
  800. if ($this->grav['uri']->extension() === 'json') {
  801. $this->admin->json_response = [
  802. 'status' => 'success',
  803. 'message' => $this->admin->translate('PLUGIN_ADMIN.REMOVE_SUCCESSFUL')
  804. ];
  805. } else {
  806. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.REMOVE_SUCCESSFUL'), 'info');
  807. $this->clearMediaCache();
  808. $this->setRedirect('/media-manager');
  809. }
  810. return true;
  811. }
  812. if ($this->grav['uri']->extension() === 'json') {
  813. $this->admin->json_response = [
  814. 'status' => 'success',
  815. 'message' => $this->admin->translate('PLUGIN_ADMIN.REMOVE_FAILED')
  816. ];
  817. } else {
  818. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.REMOVE_FAILED'), 'error');
  819. }
  820. return false;
  821. }
  822. /**
  823. * Handles clearing the media cache
  824. *
  825. * @return bool True if the action was performed
  826. */
  827. protected function clearMediaCache()
  828. {
  829. $key = 'media-manager-files';
  830. $cache = $this->grav['cache'];
  831. $cache->delete(md5($key));
  832. return true;
  833. }
  834. /**
  835. * Determine if the user can edit media
  836. *
  837. * @param string $type
  838. *
  839. * @return bool True if the media action is allowed
  840. */
  841. protected function canEditMedia($type = 'media')
  842. {
  843. if (!$this->authorizeTask('edit media', ['admin.' . $type, 'admin.super'])) {
  844. return false;
  845. }
  846. return true;
  847. }
  848. }