controller.php 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  1. <?php
  2. namespace Grav\Plugin;
  3. use Grav\Common\Cache;
  4. use Grav\Common\Config\Config;
  5. use Grav\Common\Filesystem\Folder;
  6. use Grav\Common\GPM\Installer;
  7. use Grav\Common\Grav;
  8. use Grav\Common\Themes;
  9. use Grav\Common\Uri;
  10. use Grav\Common\Data;
  11. use Grav\Common\Page;
  12. use Grav\Common\Page\Collection;
  13. use Grav\Common\User\User;
  14. use Grav\Common\Utils;
  15. use Grav\Common\Backup\ZipBackup;
  16. use Grav\Common\Markdown\Parsedown;
  17. use Grav\Common\Markdown\ParsedownExtra;
  18. use RocketTheme\Toolbox\File\File;
  19. use RocketTheme\Toolbox\File\JsonFile;
  20. use Symfony\Component\Yaml\Yaml;
  21. class AdminController
  22. {
  23. /**
  24. * @var Grav
  25. */
  26. public $grav;
  27. /**
  28. * @var string
  29. */
  30. public $view;
  31. /**
  32. * @var string
  33. */
  34. public $task;
  35. /**
  36. * @var string
  37. */
  38. public $route;
  39. /**
  40. * @var array
  41. */
  42. public $post;
  43. /**
  44. * @var Admin
  45. */
  46. protected $admin;
  47. /**
  48. * @var string
  49. */
  50. protected $redirect;
  51. /**
  52. * @var int
  53. */
  54. protected $redirectCode;
  55. /**
  56. * @param Grav $grav
  57. * @param string $view
  58. * @param string $task
  59. * @param string $route
  60. * @param array $post
  61. */
  62. public function __construct(Grav $grav, $view, $task, $route, $post)
  63. {
  64. $this->grav = $grav;
  65. $this->view = $view;
  66. $this->task = $task ? $task : 'display';
  67. $this->post = $this->getPost($post);
  68. $this->route = $route;
  69. $this->admin = $this->grav['admin'];
  70. }
  71. /**
  72. * Performs a task.
  73. *
  74. * @return bool True if the action was performed successfully.
  75. */
  76. public function execute()
  77. {
  78. $success = false;
  79. $method = 'task' . ucfirst($this->task);
  80. if (method_exists($this, $method)) {
  81. try {
  82. $success = call_user_func(array($this, $method));
  83. } catch (\RuntimeException $e) {
  84. $success = true;
  85. $this->admin->setMessage($e->getMessage(), 'error');
  86. }
  87. // Grab redirect parameter.
  88. $redirect = isset($this->post['_redirect']) ? $this->post['_redirect'] : null;
  89. unset($this->post['_redirect']);
  90. // Redirect if requested.
  91. if ($redirect) {
  92. $this->setRedirect($redirect);
  93. }
  94. }
  95. return $success;
  96. }
  97. /**
  98. * Redirect to the route stored in $this->redirect
  99. */
  100. public function redirect()
  101. {
  102. if (!$this->redirect) {
  103. return;
  104. }
  105. $base = $this->admin->base;
  106. $this->redirect = '/' . ltrim($this->redirect, '/');
  107. $multilang = $this->isMultilang();
  108. $redirect = '';
  109. if ($multilang) {
  110. // if base path does not already contain the lang code, add it
  111. $langPrefix = '/' . $this->grav['session']->admin_lang;
  112. if (!Utils::startsWith($base, $langPrefix . '/')) {
  113. $base = $langPrefix . $base;
  114. }
  115. // now the first 4 chars of base contain the lang code.
  116. // if redirect path already contains the lang code, and is != than the base lang code, then use redirect path as-is
  117. if (Utils::pathPrefixedByLangCode($base) &&
  118. Utils::pathPrefixedByLangCode($this->redirect) &&
  119. substr($base, 0, 4) != substr($this->redirect, 0, 4)) {
  120. $redirect = $this->redirect;
  121. } else {
  122. if (!Utils::startsWith($this->redirect, $base)) {
  123. $this->redirect = $base . $this->redirect;
  124. }
  125. }
  126. } else {
  127. if (!Utils::startsWith($this->redirect, $base)) {
  128. $this->redirect = $base . $this->redirect;
  129. }
  130. }
  131. if (!$redirect) {
  132. $redirect = $this->redirect;
  133. }
  134. $this->grav->redirect($redirect, $this->redirectCode);
  135. }
  136. /**
  137. * Return true if multilang is active
  138. *
  139. * @return bool True if multilang is active
  140. */
  141. protected function isMultilang() {
  142. return count($this->grav['config']->get('system.languages.supported', [])) > 1;
  143. }
  144. /**
  145. * Handle login.
  146. *
  147. * @return bool True if the action was performed.
  148. */
  149. protected function taskLogin()
  150. {
  151. if ($this->admin->authenticate($this->post)) {
  152. // should never reach here, redirects first
  153. } else {
  154. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.LOGIN_FAILED'), 'error');
  155. }
  156. return true;
  157. }
  158. /**
  159. * Handle logout.
  160. *
  161. * @return bool True if the action was performed.
  162. */
  163. protected function taskLogout()
  164. {
  165. $this->admin->session()->invalidate()->start();
  166. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.LOGGED_OUT'), 'info');
  167. $this->setRedirect('/logout');
  168. return true;
  169. }
  170. /**
  171. * Handle logout.
  172. *
  173. * @return bool True if the action was performed.
  174. */
  175. protected function taskKeepAlive()
  176. {
  177. exit();
  178. }
  179. /**
  180. * Handle the email password recovery procedure.
  181. *
  182. * @return bool True if the action was performed.
  183. */
  184. protected function taskForgot()
  185. {
  186. $param_sep = $this->grav['config']->get('system.param_sep', ':');
  187. $data = $this->post;
  188. $username = isset($data['username']) ? $data['username'] : '';
  189. $user = !empty($username) ? User::load($username) : null;
  190. if (!isset($this->grav['Email'])) {
  191. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_EMAIL_NOT_CONFIGURED'), 'error');
  192. $this->setRedirect('/');
  193. return true;
  194. }
  195. if (!$user || !$user->exists()) {
  196. $this->admin->setMessage($this->admin->translate(['PLUGIN_ADMIN.FORGOT_USERNAME_DOES_NOT_EXIST', $username]), 'error');
  197. $this->setRedirect('/forgot');
  198. return true;
  199. }
  200. if (empty($user->email)) {
  201. $this->admin->setMessage($this->admin->translate(['PLUGIN_ADMIN.FORGOT_CANNOT_RESET_EMAIL_NO_EMAIL', $username]), 'error');
  202. $this->setRedirect('/forgot');
  203. return true;
  204. }
  205. $token = md5(uniqid(mt_rand(), true));
  206. $expire = time() + 604800; // next week
  207. $user->reset = $token . '::' . $expire;
  208. $user->save();
  209. $author = $this->grav['config']->get('site.author.name', '');
  210. $fullname = $user->fullname ?: $username;
  211. $reset_link = rtrim($this->grav['uri']->rootUrl(true), '/') . '/' . trim($this->admin->base, '/') . '/reset/task' . $param_sep . 'reset/user'. $param_sep . $username . '/token' . $param_sep . $token;
  212. $sitename = $this->grav['config']->get('site.title', 'Website');
  213. $from = $this->grav['config']->get('plugins.email.from', 'noreply@getgrav.org');
  214. $to = $user->email;
  215. $subject = $this->admin->translate(['PLUGIN_ADMIN.FORGOT_EMAIL_SUBJECT', $sitename]);
  216. $content = $this->admin->translate(['PLUGIN_ADMIN.FORGOT_EMAIL_BODY', $fullname, $reset_link, $author, $sitename]);
  217. $body = $this->grav['twig']->processTemplate('email/base.html.twig', ['content' => $content]);
  218. $message = $this->grav['Email']->message($subject, $body, 'text/html')
  219. ->setFrom($from)
  220. ->setTo($to);
  221. $sent = $this->grav['Email']->send($message);
  222. if ($sent < 1) {
  223. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.FORGOT_FAILED_TO_EMAIL'), 'error');
  224. } else {
  225. $this->admin->setMessage($this->admin->translate(['PLUGIN_ADMIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL', $to]), 'info');
  226. }
  227. $this->setRedirect('/');
  228. return true;
  229. }
  230. /**
  231. * Handle the reset password action.
  232. *
  233. * @return bool True if the action was performed.
  234. */
  235. public function taskReset()
  236. {
  237. $data = $this->post;
  238. if (isset($data['password'])) {
  239. $username = isset($data['username']) ? $data['username'] : null;
  240. $user = !empty($username) ? User::load($username) : null;
  241. $password = isset($data['password']) ? $data['password'] : null;
  242. $token = isset($data['token']) ? $data['token'] : null;
  243. if (!empty($user) && $user->exists() && !empty($user->reset)) {
  244. list($good_token, $expire) = explode('::', $user->reset);
  245. if ($good_token === $token) {
  246. if (time() > $expire) {
  247. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_LINK_EXPIRED'), 'error');
  248. $this->setRedirect('/forgot');
  249. return true;
  250. }
  251. unset($user->hashed_password);
  252. unset($user->reset);
  253. $user->password = $password;
  254. $user->validate();
  255. $user->filter();
  256. $user->save();
  257. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_PASSWORD_RESET'), 'info');
  258. $this->setRedirect('/');
  259. return true;
  260. }
  261. }
  262. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_INVALID_LINK'), 'error');
  263. $this->setRedirect('/forgot');
  264. return true;
  265. } else {
  266. $user = $this->grav['uri']->param('user');
  267. $token = $this->grav['uri']->param('token');
  268. if (empty($user) || empty($token)) {
  269. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.RESET_INVALID_LINK'), 'error');
  270. $this->setRedirect('/forgot');
  271. return true;
  272. }
  273. $this->admin->forgot = [ 'username' => $user, 'token' => $token ];
  274. }
  275. return true;
  276. }
  277. /**
  278. * Clear the cache.
  279. *
  280. * @return bool True if the action was performed.
  281. */
  282. protected function taskClearCache()
  283. {
  284. if (!$this->authorizeTask('clear cache', ['admin.cache', 'admin.super'])) {
  285. return;
  286. }
  287. // get optional cleartype param
  288. $clear_type = $this->grav['uri']->param('cleartype');
  289. if ($clear_type) {
  290. $clear = $clear_type;
  291. } else {
  292. $clear = 'standard';
  293. }
  294. $results = Cache::clearCache($clear);
  295. if (count($results) > 0) {
  296. $this->admin->json_response = ['status' => 'success', 'message' => $this->admin->translate('PLUGIN_ADMIN.CACHE_CLEARED') . ' <br />' . $this->admin->translate('PLUGIN_ADMIN.METHOD') . ': ' . $clear . ''];
  297. } else {
  298. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.ERROR_CLEARING_CACHE')];
  299. }
  300. return true;
  301. }
  302. /**
  303. * Handle the backup action
  304. *
  305. * @return bool True if the action was performed.
  306. */
  307. protected function taskBackup()
  308. {
  309. $param_sep = $this->grav['config']->get('system.param_sep', ':');
  310. if (!$this->authorizeTask('backup', ['admin.maintenance', 'admin.super'])) {
  311. return;
  312. }
  313. $download = $this->grav['uri']->param('download');
  314. if ($download) {
  315. Utils::download(base64_decode(urldecode($download)), true);
  316. }
  317. $log = JsonFile::instance($this->grav['locator']->findResource("log://backup.log", true, true));
  318. try {
  319. $backup = ZipBackup::backup();
  320. } catch (\Exception $e) {
  321. $this->admin->json_response = [
  322. 'status' => 'error',
  323. 'message' => $this->admin->translate('PLUGIN_ADMIN.AN_ERROR_OCCURRED') . '. '. $e->getMessage()
  324. ];
  325. return true;
  326. }
  327. $download = urlencode(base64_encode($backup));
  328. $url = rtrim($this->grav['uri']->rootUrl(true), '/') . '/' . trim($this->admin->base, '/') . '/task' . $param_sep . 'backup/download' . $param_sep . $download;
  329. $log->content([
  330. 'time' => time(),
  331. 'location' => $backup
  332. ]);
  333. $log->save();
  334. $this->admin->json_response = [
  335. 'status' => 'success',
  336. 'message' => $this->admin->translate('PLUGIN_ADMIN.YOUR_BACKUP_IS_READY_FOR_DOWNLOAD') . '. <a href="'.$url.'" class="button">' . $this->admin->translate('PLUGIN_ADMIN.DOWNLOAD_BACKUP') .'</a>',
  337. 'toastr' => [
  338. 'timeOut' => 0,
  339. 'closeButton' => true
  340. ]
  341. ];
  342. return true;
  343. }
  344. /**
  345. * Handles filtering the page by modular/visible/routable in the pages list.
  346. */
  347. protected function taskFilterPages()
  348. {
  349. if (!$this->authorizeTask('filter pages', ['admin.pages', 'admin.super'])) {
  350. return;
  351. }
  352. $data = $this->post;
  353. $flags = !empty($data['flags']) ? array_map('strtolower', explode(',', $data['flags'])) : [];
  354. $queries = !empty($data['query']) ? explode(',', $data['query']) : [];
  355. /** @var Collection $collection */
  356. $collection = $this->grav['pages']->all();
  357. if (count($flags)) {
  358. // Filter by state
  359. $pageStates = array('modular', 'nonmodular', 'visible', 'nonvisible', 'routable', 'nonroutable', 'published', 'nonpublished');
  360. if (count(array_intersect($pageStates, $flags)) > 0) {
  361. if (in_array('modular', $flags))
  362. $collection = $collection->modular();
  363. if (in_array('nonmodular', $flags))
  364. $collection = $collection->nonModular();
  365. if (in_array('visible', $flags))
  366. $collection = $collection->visible();
  367. if (in_array('nonvisible', $flags))
  368. $collection = $collection->nonVisible();
  369. if (in_array('routable', $flags))
  370. $collection = $collection->routable();
  371. if (in_array('nonroutable', $flags))
  372. $collection = $collection->nonRoutable();
  373. if (in_array('published', $flags))
  374. $collection = $collection->published();
  375. if (in_array('nonpublished', $flags))
  376. $collection = $collection->nonPublished();
  377. }
  378. foreach ($pageStates as $pageState) {
  379. if (($pageState = array_search($pageState, $flags)) !== false) {
  380. unset($flags[$pageState]);
  381. }
  382. }
  383. // Filter by page type
  384. if (count($flags)) {
  385. $types = $flags;
  386. $collection = $collection->ofOneOfTheseTypes($types);
  387. }
  388. }
  389. if (!empty($queries)) {
  390. foreach ($collection as $page) {
  391. foreach ($queries as $query) {
  392. $query = trim($query);
  393. // $page->content();
  394. if (stripos($page->getRawContent(), $query) === false && stripos($page->title(), $query) === false) {
  395. $collection->remove($page);
  396. }
  397. }
  398. }
  399. }
  400. $results = [];
  401. foreach ($collection as $path => $page) {
  402. $results[] = $page->route();
  403. }
  404. $this->admin->json_response = [
  405. 'status' => 'success',
  406. 'message' => $this->admin->translate('PLUGIN_ADMIN.PAGES_FILTERED'),
  407. 'results' => $results
  408. ];
  409. $this->admin->collection = $collection;
  410. }
  411. /**
  412. * Determines the file types allowed to be uploaded
  413. *
  414. * @return bool True if the action was performed.
  415. */
  416. protected function taskListmedia()
  417. {
  418. if (!$this->authorizeTask('list media', ['admin.pages', 'admin.super'])) {
  419. return;
  420. }
  421. $page = $this->admin->page(true);
  422. if (!$page) {
  423. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_PAGE_FOUND')];
  424. return false;
  425. }
  426. $media_list = array();
  427. foreach ($page->media()->all() as $name => $media) {
  428. $media_list[$name] = ['url' => $media->cropZoom(150, 100)->url(), 'size' => $media->get('size')];
  429. }
  430. $this->admin->json_response = ['status' => 'ok', 'results' => $media_list];
  431. return true;
  432. }
  433. /**
  434. * Handles adding a media file to a page
  435. */
  436. protected function taskAddmedia()
  437. {
  438. if (!$this->authorizeTask('add media', ['admin.pages', 'admin.super'])) {
  439. return;
  440. }
  441. $page = $this->admin->page(true);
  442. /** @var Config $config */
  443. $config = $this->grav['config'];
  444. if (!isset($_FILES['file']['error']) || is_array($_FILES['file']['error'])) {
  445. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.INVALID_PARAMETERS')];
  446. return;
  447. }
  448. // Check $_FILES['file']['error'] value.
  449. switch ($_FILES['file']['error']) {
  450. case UPLOAD_ERR_OK:
  451. break;
  452. case UPLOAD_ERR_NO_FILE:
  453. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_FILES_SENT')];
  454. return;
  455. case UPLOAD_ERR_INI_SIZE:
  456. case UPLOAD_ERR_FORM_SIZE:
  457. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.EXCEEDED_FILESIZE_LIMIT')];
  458. return;
  459. default:
  460. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.UNKNOWN_ERRORS')];
  461. return;
  462. }
  463. $grav_limit = $config->get('system.media.upload_limit', 0);
  464. // You should also check filesize here.
  465. if ($grav_limit > 0 && $_FILES['file']['size'] > $grav_limit) {
  466. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.EXCEEDED_GRAV_FILESIZE_LIMIT')];
  467. return;
  468. }
  469. // Check extension
  470. $fileParts = pathinfo($_FILES['file']['name']);
  471. $fileExt = strtolower($fileParts['extension']);
  472. // If not a supported type, return
  473. if (!$config->get("media.{$fileExt}")) {
  474. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.UNSUPPORTED_FILE_TYPE') . ': '.$fileExt];
  475. return;
  476. }
  477. // Upload it
  478. if (!move_uploaded_file($_FILES['file']['tmp_name'], sprintf('%s/%s', $page->path(), $_FILES['file']['name']))) {
  479. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.FAILED_TO_MOVE_UPLOADED_FILE')];
  480. return;
  481. }
  482. $this->admin->json_response = ['status' => 'success', 'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_UPLOADED_SUCCESSFULLY')];
  483. return;
  484. }
  485. /**
  486. * Handles deleting a media file from a page
  487. *
  488. * @return bool True if the action was performed.
  489. */
  490. protected function taskDelmedia()
  491. {
  492. if (!$this->authorizeTask('delete media', ['admin.pages', 'admin.super'])) {
  493. return;
  494. }
  495. $page = $this->admin->page(true);
  496. if (!$page) {
  497. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_PAGE_FOUND')];
  498. return false;
  499. }
  500. $filename = !empty($this->post['filename']) ? $this->post['filename'] : null;
  501. if ($filename) {
  502. $targetPath = $page->path().'/'.$filename;
  503. if (file_exists($targetPath)) {
  504. if (unlink($targetPath)) {
  505. $this->admin->json_response = ['status' => 'success', 'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_DELETED') . ': '.$filename];
  506. } else {
  507. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_COULD_NOT_BE_DELETED') . ': '.$filename];
  508. }
  509. } else {
  510. //Try with responsive images @1x, @2x, @3x
  511. $ext = pathinfo($targetPath, PATHINFO_EXTENSION);
  512. $filename = $page->path() . '/'. basename($targetPath, ".$ext");
  513. $responsiveTargetPath = $filename . '@1x.' . $ext;
  514. $deletedResponsiveImage = false;
  515. if (file_exists($responsiveTargetPath) && unlink($responsiveTargetPath)) {
  516. $deletedResponsiveImage = true;
  517. }
  518. $responsiveTargetPath = $filename . '@2x.' . $ext;
  519. if (file_exists($responsiveTargetPath) && unlink($responsiveTargetPath)) {
  520. $deletedResponsiveImage = true;
  521. }
  522. $responsiveTargetPath = $filename . '@3x.' . $ext;
  523. if (file_exists($responsiveTargetPath) && unlink($responsiveTargetPath)) {
  524. $deletedResponsiveImage = true;
  525. }
  526. if ($deletedResponsiveImage) {
  527. $this->admin->json_response = ['status' => 'success', 'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_DELETED') . ': '.$filename];
  528. } else {
  529. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.FILE_NOT_FOUND') . ': '.$filename];
  530. }
  531. }
  532. } else {
  533. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_FILE_FOUND')];
  534. }
  535. return true;
  536. }
  537. /**
  538. * Process the page Markdown
  539. */
  540. protected function taskProcessMarkdown()
  541. {
  542. // if (!$this->authorizeTask('process markdown', ['admin.pages', 'admin.super'])) {
  543. // return;
  544. // }
  545. try {
  546. $page = $this->admin->page(true);
  547. if (!$page) {
  548. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.NO_PAGE_FOUND')];
  549. return false;
  550. }
  551. $this->preparePage($page, true);
  552. $page->header();
  553. // Add theme template paths to Twig loader
  554. $template_paths = $this->grav['locator']->findResources('theme://templates');
  555. $loader_chain = $this->grav['twig']->twig->getLoader()->addLoader(new \Twig_Loader_Filesystem($template_paths));
  556. $html = $page->content();
  557. $this->admin->json_response = ['status' => 'success', 'message' => $html];
  558. return true;
  559. } catch (\Exception $e) {
  560. $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()];
  561. return false;
  562. }
  563. }
  564. /**
  565. * Enable a plugin.
  566. *
  567. * @return bool True if the action was performed.
  568. */
  569. public function taskEnable()
  570. {
  571. if (!$this->authorizeTask('enable plugin', ['admin.plugins', 'admin.super'])) {
  572. return;
  573. }
  574. if ($this->view != 'plugins') {
  575. return false;
  576. }
  577. // Filter value and save it.
  578. $this->post = array('enabled' => 1, '_redirect' => 'plugins');
  579. $obj = $this->prepareData();
  580. $obj->save();
  581. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_ENABLED_PLUGIN'), 'info');
  582. return true;
  583. }
  584. /**
  585. * Disable a plugin.
  586. *
  587. * @return bool True if the action was performed.
  588. */
  589. public function taskDisable()
  590. {
  591. if (!$this->authorizeTask('disable plugin', ['admin.plugins', 'admin.super'])) {
  592. return;
  593. }
  594. if ($this->view != 'plugins') {
  595. return false;
  596. }
  597. // Filter value and save it.
  598. $this->post = array('enabled' => 0, '_redirect' => 'plugins');
  599. $obj = $this->prepareData();
  600. $obj->save();
  601. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_DISABLED_PLUGIN'), 'info');
  602. return true;
  603. }
  604. /**
  605. * Set the default theme.
  606. *
  607. * @return bool True if the action was performed.
  608. */
  609. public function taskActivate()
  610. {
  611. if (!$this->authorizeTask('activate theme', ['admin.themes', 'admin.super'])) {
  612. return;
  613. }
  614. if ($this->view != 'themes') {
  615. return false;
  616. }
  617. $this->post = array('_redirect' => 'themes');
  618. // Make sure theme exists (throws exception)
  619. $name = $this->route;
  620. $this->grav['themes']->get($name);
  621. // Store system configuration.
  622. $system = $this->admin->data('system');
  623. $system->set('pages.theme', $name);
  624. $system->save();
  625. // Force configuration reload and save.
  626. /** @var Config $config */
  627. $config = $this->grav['config'];
  628. $config->reload()->save();
  629. $config->set('system.pages.theme', $name);
  630. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_CHANGED_THEME'), 'info');
  631. return true;
  632. }
  633. /**
  634. * Handles installing plugins and themes
  635. *
  636. * @return bool True is the action was performed
  637. */
  638. public function taskInstall()
  639. {
  640. $type = $this->view === 'plugins' ? 'plugins' : 'themes';
  641. if (!$this->authorizeTask('install ' . $type, ['admin.' . $type, 'admin.super'])) {
  642. return;
  643. }
  644. require_once __DIR__ . '/gpm.php';
  645. $package = $this->route;
  646. $result = \Grav\Plugin\Admin\Gpm::install($package, ['theme' => ($type == 'themes')]);
  647. if ($result) {
  648. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSTALLATION_SUCCESSFUL'), 'info');
  649. } else {
  650. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSTALLATION_FAILED'), 'error');
  651. }
  652. $this->post = array('_redirect' => $this->view . '/' . $this->route);
  653. return true;
  654. }
  655. /**
  656. * Handles updating Grav
  657. *
  658. * @return bool True is the action was performed
  659. */
  660. public function taskUpdategrav()
  661. {
  662. require_once __DIR__ . '/gpm.php';
  663. if (!$this->authorizeTask('install grav', ['admin.super'])) {
  664. return;
  665. }
  666. $result = \Grav\Plugin\Admin\Gpm::selfupgrade();
  667. if ($result) {
  668. $this->admin->json_response = ['status' => 'success', 'message' => $this->admin->translate('PLUGIN_ADMIN.GRAV_WAS_SUCCESSFULLY_UPDATED_TO') . ' '];
  669. } else {
  670. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.GRAV_UPDATE_FAILED') . ' <br>' . Installer::lastErrorMsg()];
  671. }
  672. return true;
  673. }
  674. /**
  675. * Handles updating plugins and themes
  676. *
  677. * @return bool True is the action was performed
  678. */
  679. public function taskUpdate()
  680. {
  681. require_once __DIR__ . '/gpm.php';
  682. $package = $this->route;
  683. $permissions = [];
  684. $type = $this->view === 'plugins' ? 'plugins' : 'themes';
  685. // Update multi mode
  686. if (!$package) {
  687. $package = [];
  688. if ($this->view === 'plugins' || $this->view === 'update') {
  689. $package = $this->admin->gpm()->getUpdatablePlugins();
  690. $permissions['plugins'] = ['admin.super', 'admin.plugins'];
  691. }
  692. if ($this->view === 'themes' || $this->view === 'update') {
  693. $package = array_merge($package, $this->admin->gpm()->getUpdatableThemes());
  694. $permissions['themes'] = ['admin.super', 'admin.themes'];
  695. }
  696. }
  697. foreach ($permissions as $type => $p) {
  698. if (!$this->authorizeTask('update ' . $type , $p)) {
  699. return;
  700. }
  701. }
  702. $result = \Grav\Plugin\Admin\Gpm::update($package, ['theme' => ($type == 'themes')]);
  703. if ($this->view === 'update') {
  704. if ($result) {
  705. $this->admin->json_response = ['status' => 'success', 'message' => $this->admin->translate('PLUGIN_ADMIN.EVERYTHING_UPDATED')];
  706. } else {
  707. $this->admin->json_response = ['status' => 'error', 'message' => $this->admin->translate('PLUGIN_ADMIN.UPDATES_FAILED')];
  708. }
  709. } else {
  710. if ($result) {
  711. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSTALLATION_SUCCESSFUL'), 'info');
  712. } else {
  713. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSTALLATION_FAILED'), 'error');
  714. }
  715. $this->post = array('_redirect' => $this->view . '/' . $this->route);
  716. }
  717. return true;
  718. }
  719. /**
  720. * Handles uninstalling plugins and themes
  721. *
  722. * @return bool True is the action was performed
  723. */
  724. public function taskUninstall()
  725. {
  726. $type = $this->view === 'plugins' ? 'plugins' : 'themes';
  727. if (!$this->authorizeTask('uninstall ' . $type, ['admin.' . $type, 'admin.super'])) {
  728. return;
  729. }
  730. require_once __DIR__ . '/gpm.php';
  731. $package = $this->route;
  732. $result = \Grav\Plugin\Admin\Gpm::uninstall($package, []);
  733. if ($result) {
  734. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.UNINSTALL_SUCCESSFUL'), 'info');
  735. } else {
  736. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.UNINSTALL_FAILED'), 'error');
  737. }
  738. $this->post = array('_redirect' => $this->view);
  739. return true;
  740. }
  741. /**
  742. * Handles form and saves the input data if its valid.
  743. *
  744. * @return bool True if the action was performed.
  745. */
  746. public function taskSave()
  747. {
  748. if (!$this->authorizeTask('save', $this->dataPermissions())) {
  749. return;
  750. }
  751. $reorder = false;
  752. $data = $this->post;
  753. // Special handler for pages data.
  754. if ($this->view == 'pages') {
  755. /** @var Page\Pages $pages */
  756. $pages = $this->grav['pages'];
  757. // Find new parent page in order to build the path.
  758. $route = !isset($data['route']) ? dirname($this->admin->route) : $data['route'];
  759. $parent = $route && $route != '/' ? $pages->dispatch($route, true) : $pages->root();
  760. $obj = $this->admin->page(true);
  761. $original_slug = $obj->slug();
  762. $original_order = intval(trim($obj->order(), '.'));
  763. // Change parent if needed and initialize move (might be needed also on ordering/folder change).
  764. $obj = $obj->move($parent);
  765. $this->preparePage($obj, false, $obj->language());
  766. // Reset slug and route. For now we do not support slug twig variable on save.
  767. $obj->slug($original_slug);
  768. $obj->validate();
  769. $obj->filter();
  770. // rename folder based on visible
  771. if ($original_order == 1000) {
  772. // increment order to force reshuffle
  773. $obj->order($original_order + 1);
  774. }
  775. // add or remove numeric prefix based on ordering value
  776. if (isset($data['ordering'])) {
  777. if ($data['ordering'] && !$obj->order()) {
  778. $obj->order(1001);
  779. } elseif (!$data['ordering'] && $obj->order()) {
  780. $obj->folder($obj->slug());
  781. }
  782. }
  783. } else {
  784. // Handle standard data types.
  785. $obj = $this->prepareData();
  786. $obj->validate();
  787. $obj->filter();
  788. }
  789. if ($obj) {
  790. $obj->save(true);
  791. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SAVED'), 'info');
  792. }
  793. if ($this->view != 'pages') {
  794. // Force configuration reload.
  795. /** @var Config $config */
  796. $config = $this->grav['config'];
  797. $config->reload();
  798. if ($this->view === 'users') {
  799. $this->grav['user']->merge(User::load($this->admin->route)->toArray());
  800. }
  801. }
  802. // Always redirect if a page route was changed, to refresh it
  803. if ($obj instanceof Page\Page) {
  804. if (method_exists($obj, 'unsetRouteSlug')) {
  805. $obj->unsetRouteSlug();
  806. }
  807. $multilang = $this->isMultilang();
  808. if ($multilang) {
  809. if (!$obj->language()) {
  810. $obj->language($this->grav['session']->admin_lang);
  811. }
  812. }
  813. $admin_route = $this->grav['config']->get('plugins.admin.route');
  814. $redirect_url = '/' . ($multilang ? ($obj->language()) : '') . $admin_route . '/' . $this->view . $obj->route();
  815. $this->setRedirect($redirect_url);
  816. }
  817. return true;
  818. }
  819. /**
  820. * Continue to the new page.
  821. *
  822. * @return bool True if the action was performed.
  823. */
  824. public function taskContinue()
  825. {
  826. if ($this->view == 'users') {
  827. $this->setRedirect("{$this->view}/{$this->post['username']}");
  828. return true;
  829. }
  830. if ($this->view != 'pages') {
  831. return false;
  832. }
  833. $data = $this->post;
  834. $route = $data['route'] != '/' ? $data['route'] : '';
  835. $folder = ltrim($data['folder'], '_');
  836. if (!empty($data['modular'])) {
  837. $folder = '_' . $folder;
  838. }
  839. $path = $route . '/' . $folder;
  840. $this->admin->session()->{$path} = $data;
  841. // Store the name and route of a page, to be used prefilled defaults of the form in the future
  842. $this->admin->session()->lastPageName = $data['name'];
  843. $this->admin->session()->lastPageRoute = $data['route'];
  844. $this->setRedirect("{$this->view}/". ltrim($path, '/'));
  845. return true;
  846. }
  847. /**
  848. * Save page as a new copy.
  849. *
  850. * @return bool True if the action was performed.
  851. * @throws \RuntimeException
  852. */
  853. protected function taskCopy()
  854. {
  855. if (!$this->authorizeTask('copy page', ['admin.pages', 'admin.super'])) {
  856. return;
  857. }
  858. // Only applies to pages.
  859. if ($this->view != 'pages') {
  860. return false;
  861. }
  862. try {
  863. /** @var Page\Pages $pages */
  864. $pages = $this->grav['pages'];
  865. $data = $this->post;
  866. // And then get the current page.
  867. $page = $this->admin->page(true);
  868. // Find new parent page in order to build the path.
  869. $parent = $page->parent() ?: $pages->root();
  870. // Make a copy of the current page and fill the updated information into it.
  871. $page = $page->copy($parent);
  872. $this->preparePage($page);
  873. // Make sure the header is loaded in case content was set through raw() (expert mode)
  874. $page->header();
  875. // Deal with folder naming conflicts, but limit number of searches to 99.
  876. $break = 99;
  877. while ($break > 0 && file_exists($page->filePath())) {
  878. $break--;
  879. $match = preg_split('/-(\d+)$/', $page->path(), 2, PREG_SPLIT_DELIM_CAPTURE);
  880. $page->path($match[0] . '-' . (isset($match[1]) ? (int) $match[1] + 1 : 2));
  881. // Reset slug and route. For now we do not support slug twig variable on save.
  882. $page->slug('');
  883. }
  884. $page->save();
  885. // Enqueue message and redirect to new location.
  886. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_COPIED'), 'info');
  887. $parent_route = $parent->route() ? '/' . ltrim($parent->route(), '/') : '';
  888. $this->setRedirect($this->view . $parent_route . '/'. $page->slug());
  889. } catch (\Exception $e) {
  890. throw new \RuntimeException('Copying page failed on error: ' . $e->getMessage());
  891. }
  892. return true;
  893. }
  894. /**
  895. * Reorder pages.
  896. *
  897. * @return bool True if the action was performed.
  898. */
  899. protected function taskReorder()
  900. {
  901. if (!$this->authorizeTask('reorder pages', ['admin.pages', 'admin.super'])) {
  902. return;
  903. }
  904. // Only applies to pages.
  905. if ($this->view != 'pages') {
  906. return false;
  907. }
  908. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.REORDERING_WAS_SUCCESSFUL'), 'info');
  909. return true;
  910. }
  911. /**
  912. * Delete page.
  913. *
  914. * @return bool True if the action was performed.
  915. * @throws \RuntimeException
  916. */
  917. protected function taskDelete()
  918. {
  919. if (!$this->authorizeTask('delete page', ['admin.pages', 'admin.super'])) {
  920. return;
  921. }
  922. // Only applies to pages.
  923. if ($this->view != 'pages') {
  924. return false;
  925. }
  926. /** @var Uri $uri */
  927. $uri = $this->grav['uri'];
  928. try {
  929. $page = $this->admin->page();
  930. if (count($page->translatedLanguages()) > 1) {
  931. $page->file()->delete();
  932. } else {
  933. Folder::delete($page->path());
  934. }
  935. $results = Cache::clearCache('standard');
  936. // Set redirect to either referrer or pages list.
  937. $redirect = 'pages';
  938. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_DELETED'), 'info');
  939. $this->setRedirect($redirect);
  940. } catch (\Exception $e) {
  941. throw new \RuntimeException('Deleting page failed on error: ' . $e->getMessage());
  942. }
  943. return true;
  944. }
  945. /**
  946. * Switch the content language. Optionally redirect to a different page.
  947. *
  948. * @return bool True if the action was performed.
  949. */
  950. protected function taskSwitchlanguage() {
  951. $data = $this->post;
  952. if (isset($data['lang'])) {
  953. $language = $data['lang'];
  954. } else {
  955. $language = $this->grav['uri']->param('lang');
  956. }
  957. if (isset($data['redirect'])) {
  958. $redirect = 'pages/' . $data['redirect'];
  959. } else {
  960. $redirect = 'pages';
  961. }
  962. if ($language) {
  963. $this->grav['session']->admin_lang = $language ?: 'en';
  964. }
  965. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SWITCHED_LANGUAGE'), 'info');
  966. $admin_route = $this->grav['config']->get('plugins.admin.route');
  967. $this->setRedirect('/' . $language . $admin_route . '/' . $redirect);
  968. }
  969. /**
  970. * Save the current page in a different language. Automatically switches to that language.
  971. *
  972. * @return bool True if the action was performed.
  973. */
  974. protected function taskSaveas() {
  975. if (!$this->authorizeTask('save', $this->dataPermissions())) {
  976. return;
  977. }
  978. // $reorder = false;
  979. $data = $this->post;
  980. $language = $data['lang'];
  981. if ($language) {
  982. $this->grav['session']->admin_lang = $language ?: 'en';
  983. }
  984. // /** @var Page\Pages $pages */
  985. $pages = $this->grav['pages'];
  986. $uri = $this->grav['uri'];
  987. $obj = $this->admin->page($uri->route());
  988. $this->preparePage($obj, false, $language);
  989. $file = $obj->file();
  990. if ($file) {
  991. $filename = substr($obj->name(), 0, -(strlen('.' . $language . '.md')));
  992. if (substr($filename, -3, 1) == '.') {
  993. if (substr($filename, -2) == substr($language, 0, 2)) {
  994. $filename = str_replace(substr($filename, -2), $language, $filename);
  995. }
  996. } elseif (substr($filename, -6, 1) == '.') {
  997. if (substr($filename, -5) == substr($language, 0, 5)) {
  998. $filename = str_replace(substr($filename, -5), $language, $filename);
  999. }
  1000. } else {
  1001. $filename .= '.' . $language;
  1002. }
  1003. $path = $obj->path() . DS . $filename . '.md';
  1004. $aFile = File::instance($path);
  1005. $aFile->save();
  1006. $aPage = new Page\Page();
  1007. $aPage->init(new \SplFileInfo($path), $language .'.md');
  1008. $aPage->header($obj->header());
  1009. $aPage->rawMarkdown($obj->rawMarkdown());
  1010. $aPage->validate();
  1011. $aPage->filter();
  1012. $aPage->save();
  1013. }
  1014. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SWITCHED_LANGUAGE'), 'info');
  1015. $this->setRedirect('/' . $language . $uri->route());
  1016. return true;
  1017. }
  1018. /**
  1019. * Prepare and return POST data.
  1020. *
  1021. * @param array $post
  1022. * @return array
  1023. */
  1024. protected function &getPost($post)
  1025. {
  1026. unset($post['task']);
  1027. // Decode JSON encoded fields and merge them to data.
  1028. if (isset($post['_json'])) {
  1029. $post = array_merge_recursive($post, $this->jsonDecode($post['_json']));
  1030. unset($post['_json']);
  1031. }
  1032. return $post;
  1033. }
  1034. /**
  1035. * Recursively JSON decode data.
  1036. *
  1037. * @param array $data
  1038. * @return array
  1039. */
  1040. protected function jsonDecode(array $data)
  1041. {
  1042. foreach ($data as &$value) {
  1043. if (is_array($value)) {
  1044. $value = $this->jsonDecode($value);
  1045. } else {
  1046. $value = json_decode($value, true);
  1047. }
  1048. }
  1049. return $data;
  1050. }
  1051. /**
  1052. * Sets the page redirect.
  1053. *
  1054. * @param string $path The path to redirect to
  1055. * @param int $code The HTTP redirect code
  1056. */
  1057. protected function setRedirect($path, $code = 303)
  1058. {
  1059. $this->redirect = $path;
  1060. $this->code = $code;
  1061. }
  1062. /**
  1063. * Gets the configuration data for a given view & post
  1064. *
  1065. * @return object
  1066. */
  1067. protected function prepareData()
  1068. {
  1069. $type = trim("{$this->view}/{$this->admin->route}", '/');
  1070. $data = $this->admin->data($type, $this->post);
  1071. return $data;
  1072. }
  1073. /**
  1074. * Gets the permissions needed to access a given view
  1075. *
  1076. * @return array An array of permissions
  1077. */
  1078. protected function dataPermissions()
  1079. {
  1080. $type = $this->view;
  1081. $permissions = ['admin.super'];
  1082. switch ($type) {
  1083. case 'configuration':
  1084. case 'system':
  1085. $permissions[] = 'admin.configuration';
  1086. break;
  1087. case 'settings':
  1088. case 'site':
  1089. $permissions[] = 'admin.settings';
  1090. break;
  1091. case 'plugins':
  1092. $permissions[] = 'admin.plugins';
  1093. break;
  1094. case 'themes':
  1095. $permissions[] = 'admin.themes';
  1096. break;
  1097. case 'users':
  1098. $permissions[] = 'admin.users';
  1099. break;
  1100. case 'pages':
  1101. $permissions[] = 'admin.pages';
  1102. break;
  1103. }
  1104. return $permissions;
  1105. }
  1106. /**
  1107. * Prepare a page to be stored: update its folder, name, template, header and content
  1108. *
  1109. * @param \Grav\Common\Page\Page $page
  1110. * @param bool $clean_header
  1111. */
  1112. protected function preparePage(\Grav\Common\Page\Page $page, $clean_header = false, $language = null)
  1113. {
  1114. $input = $this->post;
  1115. if (isset($input['order'])) {
  1116. $order = max(0, (int) isset($input['order']) ? $input['order'] : $page->value('order'));
  1117. $ordering = $order ? sprintf('%02d.', $order) : '';
  1118. $slug = empty($input['folder']) ? $page->value('folder') : (string) $input['folder'];
  1119. $page->folder($ordering . $slug);
  1120. }
  1121. if (isset($input['name']) && !empty($input['name'])) {
  1122. $type = (string) strtolower($input['name']);
  1123. $name = preg_replace('|.*/|', '', $type);
  1124. if ($language) {
  1125. $name .= '.' . $language;
  1126. } else {
  1127. $language = $this->grav['language'];
  1128. if ($language->enabled()) {
  1129. $name .= '.' . $language->getLanguage();
  1130. }
  1131. }
  1132. $name .= '.md';
  1133. $page->name($name);
  1134. $page->template($type);
  1135. }
  1136. // Special case for Expert mode: build the raw, unset content
  1137. if (isset($input['frontmatter']) && isset($input['content'])) {
  1138. $page->raw("---\n" . (string) $input['frontmatter'] . "\n---\n" . (string) $input['content']);
  1139. unset($input['content']);
  1140. }
  1141. if (isset($input['header'])) {
  1142. $header = $input['header'];
  1143. foreach($header as $key => $value) {
  1144. if ($key == 'metadata') {
  1145. foreach ($header['metadata'] as $key2 => $value2) {
  1146. if (isset($input['toggleable_header']['metadata'][$key2]) && !$input['toggleable_header']['metadata'][$key2]) {
  1147. $header['metadata'][$key2] = '';
  1148. }
  1149. }
  1150. } elseif ($key == 'taxonomy') {
  1151. foreach ($header[$key] as $taxkey => $taxonomy) {
  1152. if (is_array($taxonomy) && count($taxonomy) == 1 && trim($taxonomy[0]) == '') {
  1153. unset($header[$key][$taxkey]);
  1154. }
  1155. }
  1156. } else {
  1157. if (isset($input['toggleable_header'][$key]) && !$input['toggleable_header'][$key]) {
  1158. $header[$key] = null;
  1159. }
  1160. }
  1161. }
  1162. if ($clean_header) {
  1163. $header = Utils::arrayFilterRecursive($header, function($k, $v) {
  1164. return !(is_null($v) || $v === '');
  1165. });
  1166. }
  1167. $page->header((object) $header);
  1168. $page->frontmatter(Yaml::dump((array) $page->header()));
  1169. }
  1170. // Fill content last because it also renders the output.
  1171. if (isset($input['content'])) {
  1172. $page->rawMarkdown((string) $input['content']);
  1173. }
  1174. }
  1175. /**
  1176. * Checks if the user is allowed to perform the given task with its associated permissions
  1177. *
  1178. * @param string $task The task to execute
  1179. * @param array $permissions The permissions given
  1180. * @return bool True if authorized. False if not.
  1181. */
  1182. protected function authorizeTask($task = '', $permissions = [])
  1183. {
  1184. if (!$this->admin->authorize($permissions)) {
  1185. if ($this->grav['uri']->extension() === 'json')
  1186. $this->admin->json_response = ['status' => 'unauthorized', 'message' => $this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' ' . $task . '.'];
  1187. else
  1188. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' ' . $task . '.', 'error');
  1189. return false;
  1190. }
  1191. return true;
  1192. }
  1193. }