adminbasecontroller.php 34 KB

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