admincontroller.php 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668
  1. <?php
  2. namespace Grav\Plugin\Admin;
  3. use Grav\Common\Backup\Backups;
  4. use Grav\Common\Cache;
  5. use Grav\Common\Config\Config;
  6. use Grav\Common\File\CompiledYamlFile;
  7. use Grav\Common\Filesystem\Folder;
  8. use Grav\Common\GPM\GPM as GravGPM;
  9. use Grav\Common\GPM\Installer;
  10. use Grav\Common\Grav;
  11. use Grav\Common\Data;
  12. use Grav\Common\Helpers\Excerpts;
  13. use Grav\Common\Page\Interfaces\PageInterface;
  14. use Grav\Common\Page\Media;
  15. use Grav\Common\Page\Medium\ImageMedium;
  16. use Grav\Common\Page\Medium\Medium;
  17. use Grav\Common\Page\Page;
  18. use Grav\Common\Page\Pages;
  19. use Grav\Common\Page\Collection;
  20. use Grav\Common\Security;
  21. use Grav\Common\User\Interfaces\UserCollectionInterface;
  22. use Grav\Common\User\User;
  23. use Grav\Common\Utils;
  24. use Grav\Plugin\Login\TwoFactorAuth\TwoFactorAuth;
  25. use Grav\Common\Yaml;
  26. use PicoFeed\Parser\MalformedXmlException;
  27. use RocketTheme\Toolbox\Event\Event;
  28. use RocketTheme\Toolbox\File\File;
  29. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  30. /**
  31. * Class AdminController
  32. *
  33. * @package Grav\Plugin
  34. */
  35. class AdminController extends AdminBaseController
  36. {
  37. /**
  38. * @param Grav $grav
  39. * @param string $view
  40. * @param string $task
  41. * @param string $route
  42. * @param array $post
  43. */
  44. public function initialize(Grav $grav = null, $view = null, $task = null, $route = null, $post = null)
  45. {
  46. $this->grav = $grav;
  47. $this->view = $view;
  48. $this->task = $task ?: 'display';
  49. if (isset($post['data'])) {
  50. $this->data = $this->getPost($post['data']);
  51. unset($post['data']);
  52. } else {
  53. // Backwards compatibility for Form plugin <= 1.2
  54. $this->data = $this->getPost($post);
  55. }
  56. $this->post = $this->getPost($post);
  57. $this->route = $route;
  58. $this->admin = $this->grav['admin'];
  59. $this->grav->fireEvent('onAdminControllerInit', new Event(['controller' => &$this]));
  60. }
  61. /**
  62. * Handle login.
  63. *
  64. * @return bool True if the action was performed.
  65. */
  66. protected function taskLogin()
  67. {
  68. $this->admin->authenticate($this->data, $this->post);
  69. return true;
  70. }
  71. /**
  72. * @return bool True if the action was performed.
  73. */
  74. protected function taskTwofa()
  75. {
  76. $this->admin->twoFa($this->data, $this->post);
  77. return true;
  78. }
  79. /**
  80. * Handle logout.
  81. *
  82. * @return bool True if the action was performed.
  83. */
  84. protected function taskLogout()
  85. {
  86. $this->admin->logout($this->data, $this->post);
  87. return true;
  88. }
  89. /**
  90. * @return bool
  91. */
  92. public function taskRegenerate2FASecret()
  93. {
  94. if (!$this->authorizeTask('regenerate 2FA Secret', ['admin.login'])) {
  95. return false;
  96. }
  97. try {
  98. /** @var User $user */
  99. $user = $this->grav['user'];
  100. /** @var TwoFactorAuth $twoFa */
  101. $twoFa = $this->grav['login']->twoFactorAuth();
  102. $secret = $twoFa->createSecret();
  103. $image = $twoFa->getQrImageData($user->username, $secret);
  104. $user->set('twofa_secret', $secret);
  105. // TODO: data user can also use save, but please test it before removing this code.
  106. if ($user instanceof \Grav\Common\User\DataUser\User) {
  107. // Save secret into the user file.
  108. $file = $user->file();
  109. if ($file->exists()) {
  110. $content = (array)$file->content();
  111. $content['twofa_secret'] = $secret;
  112. $file->save($content);
  113. $file->free();
  114. }
  115. } else {
  116. $user->save();
  117. }
  118. $this->admin->json_response = ['status' => 'success', 'image' => $image, 'secret' => preg_replace('|(\w{4})|', '\\1 ', $secret)];
  119. } catch (\Exception $e) {
  120. $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()];
  121. return false;
  122. }
  123. return true;
  124. }
  125. /**
  126. * Handle the reset password action.
  127. *
  128. * @return bool True if the action was performed.
  129. */
  130. public function taskReset()
  131. {
  132. $data = $this->data;
  133. if (isset($data['password'])) {
  134. /** @var UserCollectionInterface $users */
  135. $users = $this->grav['accounts'];
  136. $username = isset($data['username']) ? strip_tags(strtolower($data['username'])) : null;
  137. $user = $username ? $users->load($username) : null;
  138. $password = $data['password'] ?? null;
  139. $token = $data['token'] ?? null;
  140. if ($user && $user->exists() && !empty($user->get('reset'))) {
  141. list($good_token, $expire) = explode('::', $user->get('reset'));
  142. if ($good_token === $token) {
  143. if (time() > $expire) {
  144. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.RESET_LINK_EXPIRED'), 'error');
  145. $this->setRedirect('/forgot');
  146. return true;
  147. }
  148. $user->undef('hashed_password');
  149. $user->undef('reset');
  150. $user->set('password', $password);
  151. $user->save();
  152. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.RESET_PASSWORD_RESET'), 'info');
  153. $this->setRedirect('/');
  154. return true;
  155. }
  156. }
  157. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.RESET_INVALID_LINK'), 'error');
  158. $this->setRedirect('/forgot');
  159. return true;
  160. }
  161. $user = $this->grav['uri']->param('user');
  162. $token = $this->grav['uri']->param('token');
  163. if (empty($user) || empty($token)) {
  164. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.RESET_INVALID_LINK'), 'error');
  165. $this->setRedirect('/forgot');
  166. return true;
  167. }
  168. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.RESET_NEW_PASSWORD'), 'info');
  169. $this->admin->forgot = ['username' => $user, 'token' => $token];
  170. return true;
  171. }
  172. /**
  173. * Handle the email password recovery procedure.
  174. *
  175. * @return bool True if the action was performed.
  176. */
  177. protected function taskForgot()
  178. {
  179. $param_sep = $this->grav['config']->get('system.param_sep', ':');
  180. $post = $this->post;
  181. $data = $this->data;
  182. $login = $this->grav['login'];
  183. /** @var UserCollectionInterface $users */
  184. $users = $this->grav['accounts'];
  185. $username = isset($data['username']) ? strip_tags(strtolower($data['username'])) : '';
  186. $user = !empty($username) ? $users->load($username) : null;
  187. if (!isset($this->grav['Email'])) {
  188. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.FORGOT_EMAIL_NOT_CONFIGURED'), 'error');
  189. $this->setRedirect($post['redirect']);
  190. return true;
  191. }
  192. if (!$user || !$user->exists()) {
  193. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL'),
  194. 'info');
  195. $this->setRedirect($post['redirect']);
  196. return true;
  197. }
  198. if (empty($user->email)) {
  199. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL'),
  200. 'info');
  201. $this->setRedirect($post['redirect']);
  202. return true;
  203. }
  204. $count = $this->grav['config']->get('plugins.login.max_pw_resets_count', 0);
  205. $interval =$this->grav['config']->get('plugins.login.max_pw_resets_interval', 2);
  206. if ($login->isUserRateLimited($user, 'pw_resets', $count, $interval)) {
  207. $this->admin->setMessage($this->admin::translate(['PLUGIN_LOGIN.FORGOT_CANNOT_RESET_IT_IS_BLOCKED', $user->email, $interval]), 'error');
  208. $this->setRedirect($post['redirect']);
  209. return true;
  210. }
  211. $token = md5(uniqid(mt_rand(), true));
  212. $expire = time() + 604800; // next week
  213. $user->set('reset', $token . '::' . $expire);
  214. $user->save();
  215. $author = $this->grav['config']->get('site.author.name', '');
  216. $fullname = $user->fullname ?: $username;
  217. $reset_link = rtrim($this->grav['uri']->rootUrl(true), '/') . '/' . trim($this->admin->base,
  218. '/') . '/reset/task' . $param_sep . 'reset/user' . $param_sep . $username . '/token' . $param_sep . $token . '/admin-nonce' . $param_sep . Utils::getNonce('admin-form');
  219. $sitename = $this->grav['config']->get('site.title', 'Website');
  220. $from = $this->grav['config']->get('plugins.email.from');
  221. if (empty($from)) {
  222. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.FORGOT_EMAIL_NOT_CONFIGURED'), 'error');
  223. $this->setRedirect($post['redirect']);
  224. return true;
  225. }
  226. $to = $user->email;
  227. $subject = $this->admin::translate(['PLUGIN_ADMIN.FORGOT_EMAIL_SUBJECT', $sitename]);
  228. $content = $this->admin::translate([
  229. 'PLUGIN_ADMIN.FORGOT_EMAIL_BODY',
  230. $fullname,
  231. $reset_link,
  232. $author,
  233. $sitename
  234. ]);
  235. $body = $this->grav['twig']->processTemplate('email/base.html.twig', ['content' => $content]);
  236. $message = $this->grav['Email']->message($subject, $body, 'text/html')->setFrom($from)->setTo($to);
  237. $sent = $this->grav['Email']->send($message);
  238. if ($sent < 1) {
  239. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.FORGOT_FAILED_TO_EMAIL'), 'error');
  240. } else {
  241. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL'),
  242. 'info');
  243. }
  244. $this->setRedirect('/');
  245. return true;
  246. }
  247. /**
  248. * Enable a plugin.
  249. *
  250. * @return bool True if the action was performed.
  251. */
  252. public function taskEnable()
  253. {
  254. if (!$this->authorizeTask('enable plugin', ['admin.plugins', 'admin.super'])) {
  255. return false;
  256. }
  257. if ($this->view !== 'plugins') {
  258. return false;
  259. }
  260. // Filter value and save it.
  261. $this->post = ['enabled' => true];
  262. $obj = $this->prepareData($this->post);
  263. $obj->save();
  264. $this->post = ['_redirect' => 'plugins'];
  265. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_ENABLED_PLUGIN'), 'info');
  266. return true;
  267. }
  268. /**
  269. * Gets the configuration data for a given view & post
  270. *
  271. * @param array $data
  272. *
  273. * @return object
  274. */
  275. protected function prepareData(array $data)
  276. {
  277. $type = trim("{$this->view}/{$this->admin->route}", '/');
  278. $data = $this->admin->data($type, $data);
  279. return $data;
  280. }
  281. /**
  282. * Disable a plugin.
  283. *
  284. * @return bool True if the action was performed.
  285. */
  286. public function taskDisable()
  287. {
  288. if (!$this->authorizeTask('disable plugin', ['admin.plugins', 'admin.super'])) {
  289. return false;
  290. }
  291. if ($this->view !== 'plugins') {
  292. return false;
  293. }
  294. // Filter value and save it.
  295. $this->post = ['enabled' => false];
  296. $obj = $this->prepareData($this->post);
  297. $obj->save();
  298. $this->post = ['_redirect' => 'plugins'];
  299. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_DISABLED_PLUGIN'), 'info');
  300. return true;
  301. }
  302. /**
  303. * Set the default theme.
  304. *
  305. * @return bool True if the action was performed.
  306. */
  307. public function taskActivate()
  308. {
  309. if (!$this->authorizeTask('activate theme', ['admin.themes', 'admin.super'])) {
  310. return false;
  311. }
  312. if ($this->view !== 'themes') {
  313. return false;
  314. }
  315. $this->post = ['_redirect' => 'themes'];
  316. // Make sure theme exists (throws exception)
  317. $name = $this->route;
  318. $this->grav['themes']->get($name);
  319. // Store system configuration.
  320. $system = $this->admin->data('config/system');
  321. $system->set('pages.theme', $name);
  322. $system->save();
  323. // Force configuration reload and save.
  324. /** @var Config $config */
  325. $config = $this->grav['config'];
  326. $config->reload()->save();
  327. $config->set('system.pages.theme', $name);
  328. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_CHANGED_THEME'), 'info');
  329. return true;
  330. }
  331. /**
  332. * Handles updating Grav
  333. *
  334. * @return bool False if user has no permissions.
  335. */
  336. public function taskUpdategrav()
  337. {
  338. if (!$this->authorizeTask('install grav', ['admin.super'])) {
  339. return false;
  340. }
  341. $gpm = Gpm::GPM();
  342. $version = $gpm->grav->getVersion();
  343. $result = Gpm::selfupgrade();
  344. if ($result) {
  345. $json_response = [
  346. 'status' => 'success',
  347. 'type' => 'updategrav',
  348. 'version' => $version,
  349. 'message' => $this->admin::translate('PLUGIN_ADMIN.GRAV_WAS_SUCCESSFULLY_UPDATED_TO') . ' ' . $version
  350. ];
  351. } else {
  352. $json_response = [
  353. 'status' => 'error',
  354. 'type' => 'updategrav',
  355. 'version' => GRAV_VERSION,
  356. 'message' => $this->admin::translate('PLUGIN_ADMIN.GRAV_UPDATE_FAILED') . ' <br>' . Installer::lastErrorMsg()
  357. ];
  358. }
  359. return $this->sendJsonResponse($json_response);
  360. }
  361. /**
  362. * Handles uninstalling plugins and themes
  363. *
  364. * @deprecated
  365. *
  366. * @return bool True if the action was performed
  367. */
  368. public function taskUninstall()
  369. {
  370. $type = $this->view === 'plugins' ? 'plugins' : 'themes';
  371. if (!$this->authorizeTask('uninstall ' . $type, ['admin.' . $type, 'admin.super'])) {
  372. return false;
  373. }
  374. $package = $this->route;
  375. $result = Gpm::uninstall($package, []);
  376. if ($result) {
  377. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.UNINSTALL_SUCCESSFUL'), 'info');
  378. } else {
  379. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.UNINSTALL_FAILED'), 'error');
  380. }
  381. $this->post = ['_redirect' => $this->view];
  382. return true;
  383. }
  384. /**
  385. * Handles creating an empty page folder (without markdown file)
  386. *
  387. * @return bool True if the action was performed.
  388. */
  389. public function taskSaveNewFolder()
  390. {
  391. if (!$this->authorizeTask('save', $this->dataPermissions())) {
  392. return false;
  393. }
  394. $data = (array)$this->data;
  395. $folder = $data['folder'] ?? '';
  396. if ($folder === '' || mb_strpos($folder, '/') !== false) {
  397. throw new \RuntimeException('Creating folder failed, bad folder name', 400);
  398. }
  399. if ($data['route'] === '/') {
  400. $path = $this->grav['locator']->findResource('page://');
  401. } else {
  402. $path = $this->grav['page']->find($data['route'])->path();
  403. }
  404. $orderOfNewFolder = static::getNextOrderInFolder($path);
  405. $new_path = $path . '/' . $orderOfNewFolder . '.' . $folder;
  406. Folder::create($new_path);
  407. Cache::clearCache('invalidate');
  408. $this->grav->fireEvent('onAdminAfterSaveAs', new Event(['path' => $new_path]));
  409. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_SAVED'), 'info');
  410. $multilang = $this->isMultilang();
  411. $admin_route = $this->admin->base;
  412. $redirect_url = '/' . ($multilang ? ($this->grav['session']->admin_lang) : '') . $admin_route . '/' . $this->view;
  413. $this->setRedirect($redirect_url);
  414. return true;
  415. }
  416. /**
  417. * Get the next available ordering number in a folder
  418. *
  419. * @param string $path
  420. *
  421. * @return string the correct order string to prepend
  422. */
  423. public static function getNextOrderInFolder($path)
  424. {
  425. $files = Folder::all($path, ['recursive' => false]);
  426. $highestOrder = 0;
  427. foreach ($files as $file) {
  428. preg_match(PAGE_ORDER_PREFIX_REGEX, $file, $order);
  429. if (isset($order[0])) {
  430. $theOrder = (int)trim($order[0], '.');
  431. } else {
  432. $theOrder = 0;
  433. }
  434. if ($theOrder >= $highestOrder) {
  435. $highestOrder = $theOrder;
  436. }
  437. }
  438. $orderOfNewFolder = $highestOrder + 1;
  439. if ($orderOfNewFolder < 10) {
  440. $orderOfNewFolder = '0' . $orderOfNewFolder;
  441. }
  442. return $orderOfNewFolder;
  443. }
  444. /**
  445. * Handles form and saves the input data if its valid.
  446. *
  447. * @return bool True if the action was performed.
  448. */
  449. public function taskSave()
  450. {
  451. if (!$this->authorizeTask('save', $this->dataPermissions())) {
  452. return false;
  453. }
  454. $this->grav['twig']->twig_vars['current_form_data'] = (array)$this->data;
  455. switch ($this->view) {
  456. case 'pages':
  457. return $this->taskSavePage();
  458. case 'user':
  459. return $this->taskSaveUser();
  460. default:
  461. return $this->taskSaveDefault();
  462. }
  463. }
  464. protected function taskSavePage()
  465. {
  466. $reorder = true;
  467. $data = (array)$this->data;
  468. $this->grav['twig']->twig_vars['current_form_data'] = $data;
  469. /** @var Pages $pages */
  470. $pages = $this->grav['pages'];
  471. // Find new parent page in order to build the path.
  472. $route = $data['route'] ?? dirname($this->admin->route);
  473. /** @var PageInterface $obj */
  474. $obj = $this->admin->page(true);
  475. $folder = $data['folder'] ?? null;
  476. if ($folder === '' || mb_strpos($folder, '/') !== false) {
  477. throw new \RuntimeException('Saving page failed: bad folder name', 400);
  478. }
  479. if (!isset($data['folder']) || !$data['folder']) {
  480. $data['folder'] = $obj->slug();
  481. $this->data['folder'] = $obj->slug();
  482. }
  483. // Ensure route is prefixed with a forward slash.
  484. $route = '/' . ltrim($route, '/');
  485. // Check for valid frontmatter
  486. if (isset($data['frontmatter']) && !$this->checkValidFrontmatter($data['frontmatter'])) {
  487. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.INVALID_FRONTMATTER_COULD_NOT_SAVE'),
  488. 'error');
  489. return false;
  490. }
  491. // XSS Checks for page content
  492. $xss_whitelist = $this->grav['config']->get('security.xss_whitelist', 'admin.super');
  493. if (!$this->admin->authorize($xss_whitelist)) {
  494. $check_what = ['header' => $data['header'] ?? '', 'frontmatter' => $data['frontmatter'] ?? '', 'content' => $data['content'] ?? ''];
  495. $results = Security::detectXssFromArray($check_what);
  496. if (!empty($results)) {
  497. $this->admin->setMessage('<i class="fa fa-ban"></i> ' . $this->admin::translate('PLUGIN_ADMIN.XSS_ONSAVE_ISSUE'),
  498. 'error');
  499. return false;
  500. }
  501. }
  502. $parent = $route && $route !== '/' && $route !== '.' && $route !== '/.' ? $pages->dispatch($route, true) : $pages->root();
  503. $original_order = (int)trim($obj->order(), '.');
  504. try {
  505. // Change parent if needed and initialize move (might be needed also on ordering/folder change).
  506. $obj = $obj->move($parent);
  507. $this->preparePage($obj, false, $obj->language());
  508. $obj->validate();
  509. } catch (\Exception $e) {
  510. $this->admin->setMessage($e->getMessage(), 'error');
  511. return false;
  512. }
  513. $obj->filter();
  514. // rename folder based on visible
  515. if ($original_order === 1000) {
  516. // increment order to force reshuffle
  517. $obj->order($original_order + 1);
  518. }
  519. if (isset($data['order']) && !empty($data['order'])) {
  520. $reorder = explode(',', $data['order']);
  521. }
  522. // add or remove numeric prefix based on ordering value
  523. if (isset($data['ordering'])) {
  524. if ($data['ordering'] && !$obj->order()) {
  525. $obj->order(static::getNextOrderInFolder($obj->parent()->path()));
  526. $reorder = false;
  527. } elseif (!$data['ordering'] && $obj->order()) {
  528. $obj->folder($obj->slug());
  529. }
  530. }
  531. $obj = $this->storeFiles($obj);
  532. if ($obj) {
  533. // Event to manipulate data before saving the object
  534. $this->grav->fireEvent('onAdminSave', new Event(['object' => &$obj]));
  535. $obj->save($reorder);
  536. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_SAVED'), 'info');
  537. $this->grav->fireEvent('onAdminAfterSave', new Event(['object' => $obj]));
  538. }
  539. if (method_exists($obj, 'unsetRouteSlug')) {
  540. $obj->unsetRouteSlug();
  541. }
  542. $multilang = $this->isMultilang();
  543. if ($multilang) {
  544. if (!$obj->language()) {
  545. $obj->language($this->grav['session']->admin_lang);
  546. }
  547. }
  548. $admin_route = $this->admin->base;
  549. $route = $obj->rawRoute();
  550. $redirect_url = ($multilang ? '/' . $obj->language() : '') . $admin_route . '/' . $this->view . $route;
  551. $this->setRedirect($redirect_url);
  552. return true;
  553. }
  554. protected function taskSaveUser()
  555. {
  556. /** @var UserCollectionInterface $users */
  557. $users = $this->grav['accounts'];
  558. $user = $users->load($this->admin->route);
  559. if (!$this->admin->authorize(['admin.super', 'admin.users'])) {
  560. // no user file or not admin.super or admin.users
  561. if ($user->username !== $this->grav['user']->username) {
  562. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' save.','error');
  563. return false;
  564. }
  565. }
  566. /** @var Data\Blueprint $blueprint */
  567. $blueprint = $user->blueprints();
  568. $data = $blueprint->processForm($this->admin->cleanUserPost((array)$this->data));
  569. $data = new Data\Data($data, $blueprint);
  570. try {
  571. $data->validate();
  572. $data->filter();
  573. } catch (\Exception $e) {
  574. $this->admin->setMessage($e->getMessage(), 'error');
  575. return false;
  576. }
  577. $user->update($data->toArray());
  578. $user = $this->storeFiles($user);
  579. if ($user) {
  580. // Event to manipulate data before saving the object
  581. $this->grav->fireEvent('onAdminSave', new Event(['object' => &$user]));
  582. $user->save();
  583. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_SAVED'), 'info');
  584. $this->grav->fireEvent('onAdminAfterSave', new Event(['object' => $user]));
  585. }
  586. if ($user->username === $this->grav['user']->username) {
  587. /** @var UserCollectionInterface $users */
  588. $users = $this->grav['accounts'];
  589. //Editing current user. Reload user object
  590. $this->grav['user']->undef('avatar');
  591. $this->grav['user']->merge($users->load($this->admin->route)->toArray());
  592. }
  593. return true;
  594. }
  595. protected function taskSaveDefault()
  596. {
  597. // Handle standard data types.
  598. $obj = $this->prepareData((array)$this->data);
  599. try {
  600. $obj->validate();
  601. } catch (\Exception $e) {
  602. $this->admin->setMessage($e->getMessage(), 'error');
  603. return false;
  604. }
  605. $obj->filter();
  606. $obj = $this->storeFiles($obj);
  607. if ($obj) {
  608. // Event to manipulate data before saving the object
  609. $this->grav->fireEvent('onAdminSave', new Event(['object' => &$obj]));
  610. $obj->save();
  611. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_SAVED'), 'info');
  612. $this->grav->fireEvent('onAdminAfterSave', new Event(['object' => $obj]));
  613. }
  614. // Force configuration reload.
  615. /** @var Config $config */
  616. $config = $this->grav['config'];
  617. $config->reload();
  618. return true;
  619. }
  620. /**
  621. * @param string $frontmatter
  622. *
  623. * @return bool
  624. */
  625. public function checkValidFrontmatter($frontmatter)
  626. {
  627. try {
  628. Yaml::parse($frontmatter);
  629. } catch (\RuntimeException $e) {
  630. return false;
  631. }
  632. return true;
  633. }
  634. /**
  635. * Continue to the new page.
  636. *
  637. * @return bool True if the action was performed.
  638. */
  639. public function taskContinue()
  640. {
  641. $data = (array)$this->data;
  642. if ($this->view === 'users') {
  643. $username = strip_tags(strtolower($data['username']));
  644. $this->setRedirect("{$this->view}/{$username}");
  645. return true;
  646. }
  647. if ($this->view === 'groups') {
  648. $this->setRedirect("{$this->view}/{$data['groupname']}");
  649. return true;
  650. }
  651. if ($this->view !== 'pages') {
  652. return false;
  653. }
  654. $route = $data['route'] !== '/' ? $data['route'] : '';
  655. $folder = $data['folder'];
  656. // Handle @slugify-{field} value, automatically slugifies the specified field
  657. if (0 === strpos($folder, '@slugify-')) {
  658. $folder = \Grav\Plugin\Admin\Utils::slug($data[substr($folder, 9)]);
  659. }
  660. $folder = ltrim($folder, '_');
  661. if ($folder === '' || mb_strpos($folder, '/') !== false) {
  662. throw new \RuntimeException('Creating page failed: bad folder name', 400);
  663. }
  664. if (!empty($data['modular'])) {
  665. $folder = '_' . $folder;
  666. }
  667. $path = $route . '/' . $folder;
  668. $this->admin->session()->{$path} = $data;
  669. // Store the name and route of a page, to be used pre-filled defaults of the form in the future
  670. $this->admin->session()->lastPageName = $data['name'];
  671. $this->admin->session()->lastPageRoute = $data['route'];
  672. $this->setRedirect("{$this->view}/" . ltrim($path, '/'));
  673. return true;
  674. }
  675. /**
  676. * Toggle the gpm.releases setting
  677. */
  678. protected function taskGpmRelease()
  679. {
  680. if (!$this->authorizeTask('configuration', ['admin.configuration', 'admin.super'])) {
  681. return false;
  682. }
  683. // Default release state
  684. $release = 'stable';
  685. $reload = false;
  686. // Get the testing release value if set
  687. if ($this->post['release'] === 'testing') {
  688. $release = 'testing';
  689. }
  690. $config = $this->grav['config'];
  691. $current_release = $config->get('system.gpm.releases');
  692. // If the releases setting is different, save it in the system config
  693. if ($current_release !== $release) {
  694. $data = new Data\Data($config->get('system'));
  695. $data->set('gpm.releases', $release);
  696. // Get the file location
  697. $file = CompiledYamlFile::instance($this->grav['locator']->findResource('config://system.yaml'));
  698. $data->file($file);
  699. // Save the configuration
  700. $data->save();
  701. $config->reload();
  702. $reload = true;
  703. }
  704. $this->admin->json_response = ['status' => 'success', 'reload' => $reload];
  705. return true;
  706. }
  707. /**
  708. * Keep alive
  709. */
  710. protected function taskKeepAlive()
  711. {
  712. exit();
  713. }
  714. /**
  715. * Get Notifications
  716. *
  717. */
  718. protected function taskGetNotifications()
  719. {
  720. if (!$this->authorizeTask('dashboard', ['admin.login', 'admin.super'])) {
  721. $this->sendJsonResponse(['status' => 'error', 'message' => 'unauthorized']);
  722. }
  723. // do we need to force a reload
  724. $refresh = $this->data['refresh'] === 'true';
  725. $filter = $this->data['filter'] ?? '';
  726. $filter_types = !empty($filter) ? array_map('trim', explode(',', $filter)) : [];
  727. try {
  728. $notifications = $this->admin->getNotifications($refresh);
  729. $notification_data = [];
  730. foreach ($notifications as $type => $type_notifications) {
  731. if ($filter_types && in_array($type, $filter_types, true)) {
  732. $twig_template = 'partials/notification-' . $type . '-block.html.twig';
  733. $notification_data[$type] = $this->grav['twig']->processTemplate($twig_template, ['notifications' => $type_notifications]);
  734. }
  735. }
  736. $json_response = [
  737. 'status' => 'success',
  738. 'notifications' => $notification_data
  739. ];
  740. } catch (\Exception $e) {
  741. $json_response = ['status' => 'error', 'message' => $e->getMessage()];
  742. }
  743. $this->sendJsonResponse($json_response);
  744. }
  745. /** Get Newsfeeds */
  746. protected function taskGetNewsFeed()
  747. {
  748. if (!$this->authorizeTask('dashboard', ['admin.login', 'admin.super'])) {
  749. $this->sendJsonResponse(['status' => 'error', 'message' => 'unauthorized']);
  750. }
  751. $refresh = $this->data['refresh'] === 'true' ? true : false;
  752. try {
  753. $feed = $this->admin->getFeed($refresh);
  754. $feed_data = $this->grav['twig']->processTemplate('partials/feed-block.html.twig', ['feed' => $feed]);
  755. $json_response = [
  756. 'status' => 'success',
  757. 'feed_data' => $feed_data
  758. ];
  759. } catch (MalformedXmlException $e) {
  760. $json_response = ['status' => 'error', 'message' => $e->getMessage()];
  761. }
  762. $this->sendJsonResponse($json_response);
  763. }
  764. /**
  765. * Get update status from GPM
  766. */
  767. protected function taskGetUpdates()
  768. {
  769. if (!$this->authorizeTask('dashboard', ['admin.login', 'admin.super'])) {
  770. return false;
  771. }
  772. $data = $this->post;
  773. $flush = !empty($data['flush']);
  774. if (isset($this->grav['session'])) {
  775. $this->grav['session']->close();
  776. }
  777. try {
  778. $gpm = new GravGPM($flush);
  779. $resources_updates = $gpm->getUpdatable();
  780. foreach ($resources_updates as $key => $update) {
  781. if (!is_iterable($update)) {
  782. continue;
  783. }
  784. foreach ($update as $slug => $item) {
  785. $resources_updates[$key][$slug] = $item;
  786. }
  787. }
  788. if ($gpm->grav !== null) {
  789. $grav_updates = [
  790. 'isUpdatable' => $gpm->grav->isUpdatable(),
  791. 'assets' => $gpm->grav->getAssets(),
  792. 'version' => GRAV_VERSION,
  793. 'available' => $gpm->grav->getVersion(),
  794. 'date' => $gpm->grav->getDate(),
  795. 'isSymlink' => $gpm->grav->isSymlink()
  796. ];
  797. $this->admin->json_response = [
  798. 'status' => 'success',
  799. 'payload' => [
  800. 'resources' => $resources_updates,
  801. 'grav' => $grav_updates,
  802. 'installed' => $gpm->countInstalled(),
  803. 'flushed' => $flush
  804. ]
  805. ];
  806. } else {
  807. $this->admin->json_response = ['status' => 'error', 'message' => 'Cannot connect to the GPM'];
  808. return false;
  809. }
  810. } catch (\Exception $e) {
  811. $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()];
  812. return false;
  813. }
  814. return true;
  815. }
  816. /**
  817. * Handle getting a new package dependencies needed to be installed
  818. *
  819. * @return bool
  820. */
  821. protected function taskGetPackagesDependencies()
  822. {
  823. $data = $this->post;
  824. $packages = isset($data['packages']) ? explode(',', $data['packages']) : '';
  825. $packages = (array)$packages;
  826. try {
  827. $this->admin->checkPackagesCanBeInstalled($packages);
  828. $dependencies = $this->admin->getDependenciesNeededToInstall($packages);
  829. } catch (\Exception $e) {
  830. $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()];
  831. return false;
  832. }
  833. $this->admin->json_response = ['status' => 'success', 'dependencies' => $dependencies];
  834. return true;
  835. }
  836. protected function taskInstallDependenciesOfPackages()
  837. {
  838. $data = $this->post;
  839. $packages = isset($data['packages']) ? explode(',', $data['packages']) : '';
  840. $packages = (array)$packages;
  841. $type = $data['type'] ?? '';
  842. if (!$this->authorizeTask('install ' . $type, ['admin.' . $type, 'admin.super'])) {
  843. $this->admin->json_response = [
  844. 'status' => 'error',
  845. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  846. ];
  847. return false;
  848. }
  849. try {
  850. $dependencies = $this->admin->getDependenciesNeededToInstall($packages);
  851. } catch (\Exception $e) {
  852. $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()];
  853. return false;
  854. }
  855. $result = Gpm::install(array_keys($dependencies), ['theme' => $type === 'theme']);
  856. if ($result) {
  857. $this->admin->json_response = ['status' => 'success', 'message' => 'Dependencies installed successfully'];
  858. } else {
  859. $this->admin->json_response = [
  860. 'status' => 'error',
  861. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSTALLATION_FAILED')
  862. ];
  863. }
  864. return true;
  865. }
  866. protected function taskInstallPackage($reinstall = false)
  867. {
  868. $data = $this->post;
  869. $package = $data['package'] ?? '';
  870. $type = $data['type'] ?? '';
  871. if (!$this->authorizeTask('install ' . $type, ['admin.' . $type, 'admin.super'])) {
  872. $this->admin->json_response = [
  873. 'status' => 'error',
  874. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  875. ];
  876. return false;
  877. }
  878. try {
  879. $result = Gpm::install($package, ['theme' => $type === 'theme']);
  880. } catch (\Exception $e) {
  881. $msg = $e->getMessage();
  882. $msg = Utils::contains($msg, '401 Unauthorized') ? "ERROR: Authorization failed for this resource" : $msg;
  883. $msg = Utils::contains($msg, '404 Not Found') ? "ERROR: Resource not found" : $msg;
  884. $this->admin->json_response = ['status' => 'error', 'message' => $msg];
  885. return false;
  886. }
  887. if ($result) {
  888. $this->admin->json_response = [
  889. 'status' => 'success',
  890. 'message' => $this->admin::translate(is_string($result) ? $result : sprintf($this->admin::translate($reinstall ?: 'PLUGIN_ADMIN.PACKAGE_X_REINSTALLED_SUCCESSFULLY',
  891. null), $package))
  892. ];
  893. } else {
  894. $this->admin->json_response = [
  895. 'status' => 'error',
  896. 'message' => $this->admin::translate($reinstall ?: 'PLUGIN_ADMIN.INSTALLATION_FAILED')
  897. ];
  898. }
  899. return true;
  900. }
  901. /**
  902. * Handle removing a package
  903. *
  904. * @return bool
  905. */
  906. protected function taskRemovePackage()
  907. {
  908. $data = $this->post;
  909. $package = $data['package'] ?? '';
  910. $type = $data['type'] ?? '';
  911. if (!$this->authorizeTask('uninstall ' . $type, ['admin.' . $type, 'admin.super'])) {
  912. $json_response = [
  913. 'status' => 'error',
  914. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  915. ];
  916. return $this->sendJsonResponse($json_response, 403);
  917. }
  918. //check if there are packages that have this as a dependency. Abort and show which ones
  919. $dependent_packages = $this->admin->getPackagesThatDependOnPackage($package);
  920. if (count($dependent_packages) > 0) {
  921. if (count($dependent_packages) > 1) {
  922. $message = 'The installed packages <cyan>' . implode('</cyan>, <cyan>',
  923. $dependent_packages) . '</cyan> depends on this package. Please remove those first.';
  924. } else {
  925. $message = 'The installed package <cyan>' . implode('</cyan>, <cyan>',
  926. $dependent_packages) . '</cyan> depends on this package. Please remove it first.';
  927. }
  928. $json_response = ['status' => 'error', 'message' => $message];
  929. return $this->sendJsonResponse($json_response, 200);
  930. }
  931. try {
  932. $dependencies = $this->admin->dependenciesThatCanBeRemovedWhenRemoving($package);
  933. $result = Gpm::uninstall($package, []);
  934. } catch (\Exception $e) {
  935. $json_response = ['status' => 'error', 'message' => $e->getMessage()];
  936. return $this->sendJsonResponse($json_response, 200);
  937. }
  938. if ($result) {
  939. $json_response = [
  940. 'status' => 'success',
  941. 'dependencies' => $dependencies,
  942. 'message' => $this->admin::translate(is_string($result) ? $result : 'PLUGIN_ADMIN.UNINSTALL_SUCCESSFUL')
  943. ];
  944. return $this->sendJsonResponse($json_response, 200);
  945. }
  946. $json_response = [
  947. 'status' => 'error',
  948. 'message' => $this->admin::translate('PLUGIN_ADMIN.UNINSTALL_FAILED')
  949. ];
  950. return $this->sendJsonResponse($json_response, 200);
  951. }
  952. /**
  953. * Handle reinstalling a package
  954. */
  955. protected function taskReinstallPackage()
  956. {
  957. $data = $this->post;
  958. $slug = $data['slug'] ?? '';
  959. $type = $data['type'] ?? '';
  960. $package_name = $data['package_name'] ?? '';
  961. $current_version = $data['current_version'] ?? '';
  962. if (!$this->authorizeTask('install ' . $type, ['admin.' . $type, 'admin.super'])) {
  963. $json_response = [
  964. 'status' => 'error',
  965. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  966. ];
  967. $this->sendJsonResponse($json_response, 403);
  968. }
  969. $url = "https://getgrav.org/download/{$type}s/$slug/$current_version";
  970. $result = Gpm::directInstall($url);
  971. if ($result === true) {
  972. $this->admin->json_response = [
  973. 'status' => 'success',
  974. 'message' => $this->admin::translate(sprintf($this->admin::translate('PLUGIN_ADMIN.PACKAGE_X_REINSTALLED_SUCCESSFULLY',
  975. null), $package_name))
  976. ];
  977. } else {
  978. $this->admin->json_response = [
  979. 'status' => 'error',
  980. 'message' => $this->admin::translate('PLUGIN_ADMIN.REINSTALLATION_FAILED')
  981. ];
  982. }
  983. }
  984. /**
  985. * Clear the cache.
  986. *
  987. * @return bool True if the action was performed.
  988. */
  989. protected function taskClearCache()
  990. {
  991. if (!$this->authorizeTask('clear cache', ['admin.cache', 'admin.super', 'admin.maintenance'])) {
  992. return false;
  993. }
  994. // get optional cleartype param
  995. $clear_type = $this->grav['uri']->param('cleartype');
  996. if ($clear_type) {
  997. $clear = $clear_type;
  998. } else {
  999. $clear = 'standard';
  1000. }
  1001. if ($clear === 'purge') {
  1002. $msg = Cache::purgeJob();
  1003. $this->admin->json_response = [
  1004. 'status' => 'success',
  1005. 'message' => $msg,
  1006. ];
  1007. } else {
  1008. $results = Cache::clearCache($clear);
  1009. if (count($results) > 0) {
  1010. $this->admin->json_response = [
  1011. 'status' => 'success',
  1012. 'message' => $this->admin::translate('PLUGIN_ADMIN.CACHE_CLEARED') . ' <br />' . $this->admin::translate('PLUGIN_ADMIN.METHOD') . ': ' . $clear . ''
  1013. ];
  1014. } else {
  1015. $this->admin->json_response = [
  1016. 'status' => 'error',
  1017. 'message' => $this->admin::translate('PLUGIN_ADMIN.ERROR_CLEARING_CACHE')
  1018. ];
  1019. }
  1020. }
  1021. return true;
  1022. }
  1023. /**
  1024. * Clear the cache.
  1025. *
  1026. * @return bool True if the action was performed.
  1027. */
  1028. protected function taskHideNotification()
  1029. {
  1030. if (!$this->authorizeTask('hide notification', ['admin.login'])) {
  1031. return false;
  1032. }
  1033. $notification_id = $this->grav['uri']->param('notification_id');
  1034. if (!$notification_id) {
  1035. $this->admin->json_response = [
  1036. 'status' => 'error'
  1037. ];
  1038. return false;
  1039. }
  1040. $filename = $this->grav['locator']->findResource('user://data/notifications/' . $this->grav['user']->username . YAML_EXT,
  1041. true, true);
  1042. $file = CompiledYamlFile::instance($filename);
  1043. $data = (array)$file->content();
  1044. $data[] = $notification_id;
  1045. $file->save($data);
  1046. $this->admin->json_response = [
  1047. 'status' => 'success'
  1048. ];
  1049. return true;
  1050. }
  1051. /**
  1052. * Handle the backup action
  1053. *
  1054. * @return bool True if the action was performed.
  1055. */
  1056. protected function taskBackup()
  1057. {
  1058. $param_sep = $this->grav['config']->get('system.param_sep', ':');
  1059. if (!$this->authorizeTask('backup', ['admin.maintenance', 'admin.super'])) {
  1060. return false;
  1061. }
  1062. $download = $this->grav['uri']->param('download');
  1063. try {
  1064. if ($download) {
  1065. $file = base64_decode(urldecode($download));
  1066. $backups_root_dir = $this->grav['locator']->findResource('backup://', true);
  1067. if (0 !== strpos($file, $backups_root_dir)) {
  1068. header('HTTP/1.1 401 Unauthorized');
  1069. exit();
  1070. }
  1071. Utils::download($file, true);
  1072. }
  1073. $id = $this->grav['uri']->param('id', 0);
  1074. $backup = Backups::backup($id);
  1075. } catch (\Exception $e) {
  1076. $this->admin->json_response = [
  1077. 'status' => 'error',
  1078. 'message' => $this->admin::translate('PLUGIN_ADMIN.AN_ERROR_OCCURRED') . '. ' . $e->getMessage()
  1079. ];
  1080. return true;
  1081. }
  1082. $download = urlencode(base64_encode($backup));
  1083. $url = rtrim($this->grav['uri']->rootUrl(false), '/') . '/' . trim($this->admin->base,
  1084. '/') . '/task' . $param_sep . 'backup/download' . $param_sep . $download . '/admin-nonce' . $param_sep . Utils::getNonce('admin-form');
  1085. $this->admin->json_response = [
  1086. 'status' => 'success',
  1087. '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>',
  1088. 'toastr' => [
  1089. 'timeOut' => 0,
  1090. 'extendedTimeOut' => 0,
  1091. 'closeButton' => true
  1092. ]
  1093. ];
  1094. return true;
  1095. }
  1096. /**
  1097. * Handle delete backup action
  1098. *
  1099. * @return bool
  1100. */
  1101. protected function taskBackupDelete()
  1102. {
  1103. $param_sep = $this->grav['config']->get('system.param_sep', ':');
  1104. if (!$this->authorizeTask('backup', ['admin.maintenance', 'admin.super'])) {
  1105. return false;
  1106. }
  1107. $backup = $this->grav['uri']->param('backup', null);
  1108. if (null !== $backup) {
  1109. $file = base64_decode(urldecode($backup));
  1110. $backups_root_dir = $this->grav['locator']->findResource('backup://', true);
  1111. $backup_path = $backups_root_dir . '/' . $file;
  1112. if (file_exists($backup_path)) {
  1113. unlink($backup_path);
  1114. $this->admin->json_response = [
  1115. 'status' => 'success',
  1116. 'message' => $this->admin::translate('PLUGIN_ADMIN.BACKUP_DELETED'),
  1117. 'toastr' => [
  1118. 'closeButton' => true
  1119. ]
  1120. ];
  1121. } else {
  1122. $this->admin->json_response = [
  1123. 'status' => 'error',
  1124. 'message' => $this->admin::translate('PLUGIN_ADMIN.BACKUP_NOT_FOUND'),
  1125. ];
  1126. }
  1127. }
  1128. return true;
  1129. }
  1130. protected function taskGetChildTypes()
  1131. {
  1132. if (!$this->authorizeTask('get childtypes', ['admin.pages', 'admin.super'])) {
  1133. return false;
  1134. }
  1135. $data = $this->post;
  1136. $rawroute = $data['rawroute'] ?? null;
  1137. if ($rawroute) {
  1138. /** @var PageInterface $page */
  1139. $page = $this->grav['pages']->dispatch($rawroute);
  1140. if ($page) {
  1141. $child_type = $page->childType();
  1142. if ($child_type !== '') {
  1143. $this->admin->json_response = [
  1144. 'status' => 'success',
  1145. 'child_type' => $child_type
  1146. ];
  1147. return true;
  1148. }
  1149. }
  1150. }
  1151. $this->admin->json_response = [
  1152. 'status' => 'success',
  1153. 'child_type' => '',
  1154. // 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_CHILD_TYPE')
  1155. ];
  1156. return true;
  1157. }
  1158. /**
  1159. * Handles filtering the page by modular/visible/routable in the pages list.
  1160. */
  1161. protected function taskFilterPages()
  1162. {
  1163. if (!$this->authorizeTask('filter pages', ['admin.pages', 'admin.super'])) {
  1164. return;
  1165. }
  1166. $data = $this->post;
  1167. $flags = !empty($data['flags']) ? array_map('strtolower', explode(',', $data['flags'])) : [];
  1168. $queries = !empty($data['query']) ? explode(',', $data['query']) : [];
  1169. /** @var Collection $collection */
  1170. $collection = $this->grav['pages']->all();
  1171. if (count($flags)) {
  1172. // Filter by state
  1173. $pageStates = [
  1174. 'modular',
  1175. 'nonmodular',
  1176. 'visible',
  1177. 'nonvisible',
  1178. 'routable',
  1179. 'nonroutable',
  1180. 'published',
  1181. 'nonpublished'
  1182. ];
  1183. if (count(array_intersect($pageStates, $flags)) > 0) {
  1184. if (in_array('modular', $flags, true)) {
  1185. $collection = $collection->modular();
  1186. }
  1187. if (in_array('nonmodular', $flags, true)) {
  1188. $collection = $collection->nonModular();
  1189. }
  1190. if (in_array('visible', $flags, true)) {
  1191. $collection = $collection->visible();
  1192. }
  1193. if (in_array('nonvisible', $flags, true)) {
  1194. $collection = $collection->nonVisible();
  1195. }
  1196. if (in_array('routable', $flags, true)) {
  1197. $collection = $collection->routable();
  1198. }
  1199. if (in_array('nonroutable', $flags, true)) {
  1200. $collection = $collection->nonRoutable();
  1201. }
  1202. if (in_array('published', $flags, true)) {
  1203. $collection = $collection->published();
  1204. }
  1205. if (in_array('nonpublished', $flags, true)) {
  1206. $collection = $collection->nonPublished();
  1207. }
  1208. }
  1209. foreach ($pageStates as $pageState) {
  1210. if (($pageState = array_search($pageState, $flags, true)) !== false) {
  1211. unset($flags[$pageState]);
  1212. }
  1213. }
  1214. // Filter by page type
  1215. if ($flags) {
  1216. $types = [];
  1217. $pageTypes = array_keys(Pages::pageTypes());
  1218. foreach ($pageTypes as $pageType) {
  1219. if (($pageKey = array_search($pageType, $flags, true)) !== false) {
  1220. $types[] = $pageType;
  1221. unset($flags[$pageKey]);
  1222. }
  1223. }
  1224. if (count($types)) {
  1225. $collection = $collection->ofOneOfTheseTypes($types);
  1226. }
  1227. }
  1228. // Filter by page type
  1229. if ($flags) {
  1230. $accessLevels = $flags;
  1231. $collection = $collection->ofOneOfTheseAccessLevels($accessLevels);
  1232. }
  1233. }
  1234. if (!empty($queries)) {
  1235. foreach ($collection as $page) {
  1236. foreach ($queries as $query) {
  1237. $query = trim($query);
  1238. if (stripos($page->getRawContent(), $query) === false
  1239. && stripos($page->title(), $query) === false
  1240. && stripos($page->folder(), $query) === false
  1241. && stripos($page->slug(), \Grav\Plugin\Admin\Utils::slug($query)) === false
  1242. ) {
  1243. $collection->remove($page);
  1244. }
  1245. }
  1246. }
  1247. }
  1248. $results = [];
  1249. foreach ($collection as $path => $page) {
  1250. $results[] = $page->route();
  1251. }
  1252. $this->admin->json_response = [
  1253. 'status' => 'success',
  1254. 'message' => $this->admin::translate('PLUGIN_ADMIN.PAGES_FILTERED'),
  1255. 'results' => $results
  1256. ];
  1257. $this->admin->collection = $collection;
  1258. }
  1259. /**
  1260. * Determines the file types allowed to be uploaded
  1261. *
  1262. * @return bool True if the action was performed.
  1263. */
  1264. protected function taskListmedia()
  1265. {
  1266. if (!$this->authorizeTask('list media', ['admin.pages', 'admin.super'])) {
  1267. return false;
  1268. }
  1269. $media = $this->getMedia();
  1270. if (!$media) {
  1271. $this->admin->json_response = [
  1272. 'status' => 'error',
  1273. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_PAGE_FOUND')
  1274. ];
  1275. return false;
  1276. }
  1277. $media_list = [];
  1278. /**
  1279. * @var string $name
  1280. * @var Medium|ImageMedium $medium
  1281. */
  1282. foreach ($media->all() as $name => $medium) {
  1283. $metadata = [];
  1284. $img_metadata = $medium->metadata();
  1285. if ($img_metadata) {
  1286. $metadata = $img_metadata;
  1287. }
  1288. // Get original name
  1289. /** @var ImageMedium $source */
  1290. $source = method_exists($medium, 'higherQualityAlternative') ? $medium->higherQualityAlternative() : null;
  1291. $media_list[$name] = [
  1292. 'url' => $medium->display($medium->get('extension') === 'svg' ? 'source' : 'thumbnail')->cropZoom(400, 300)->url(),
  1293. 'size' => $medium->get('size'),
  1294. 'metadata' => $metadata,
  1295. 'original' => $source ? $source->get('filename') : null
  1296. ];
  1297. }
  1298. $this->admin->json_response = ['status' => 'success', 'results' => $media_list];
  1299. return true;
  1300. }
  1301. /**
  1302. * @return Media
  1303. */
  1304. protected function getMedia()
  1305. {
  1306. $this->uri = $this->uri ?? $this->grav['uri'];
  1307. $uri = $this->uri->post('uri');
  1308. $order = $this->uri->post('order') ?: null;
  1309. if ($uri) {
  1310. /** @var UniformResourceLocator $locator */
  1311. $locator = $this->grav['locator'];
  1312. $media_path = $locator->isStream($uri) ? $uri : null;
  1313. } else {
  1314. $page = $this->admin->page(true);
  1315. $media_path = $page ? $page->path() : null;
  1316. }
  1317. if ($order) {
  1318. $order = array_map('trim', explode(',', $order));
  1319. }
  1320. return $media_path ? new Media($media_path, $order) : null;
  1321. }
  1322. /**
  1323. * Handles adding a media file to a page
  1324. *
  1325. * @return bool True if the action was performed.
  1326. */
  1327. protected function taskAddmedia()
  1328. {
  1329. if (!$this->authorizeTask('add media', ['admin.pages', 'admin.super'])) {
  1330. return false;
  1331. }
  1332. /** @var Config $config */
  1333. $config = $this->grav['config'];
  1334. if (empty($_FILES)) {
  1335. $this->admin->json_response = [
  1336. 'status' => 'error',
  1337. 'message' => $this->admin::translate('PLUGIN_ADMIN.EXCEEDED_POSTMAX_LIMIT')
  1338. ];
  1339. return false;
  1340. }
  1341. if (!isset($_FILES['file']['error']) || is_array($_FILES['file']['error'])) {
  1342. $this->admin->json_response = [
  1343. 'status' => 'error',
  1344. 'message' => $this->admin::translate('PLUGIN_ADMIN.INVALID_PARAMETERS')
  1345. ];
  1346. return false;
  1347. }
  1348. // Check $_FILES['file']['error'] value.
  1349. switch ($_FILES['file']['error']) {
  1350. case UPLOAD_ERR_OK:
  1351. break;
  1352. case UPLOAD_ERR_NO_FILE:
  1353. $this->admin->json_response = [
  1354. 'status' => 'error',
  1355. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_FILES_SENT')
  1356. ];
  1357. return false;
  1358. case UPLOAD_ERR_INI_SIZE:
  1359. case UPLOAD_ERR_FORM_SIZE:
  1360. $this->admin->json_response = [
  1361. 'status' => 'error',
  1362. 'message' => $this->admin::translate('PLUGIN_ADMIN.EXCEEDED_FILESIZE_LIMIT')
  1363. ];
  1364. return false;
  1365. case UPLOAD_ERR_NO_TMP_DIR:
  1366. $this->admin->json_response = [
  1367. 'status' => 'error',
  1368. 'message' => $this->admin::translate('PLUGIN_ADMIN.UPLOAD_ERR_NO_TMP_DIR')
  1369. ];
  1370. return false;
  1371. default:
  1372. $this->admin->json_response = [
  1373. 'status' => 'error',
  1374. 'message' => $this->admin::translate('PLUGIN_ADMIN.UNKNOWN_ERRORS')
  1375. ];
  1376. return false;
  1377. }
  1378. $filename = $_FILES['file']['name'];
  1379. // Handle bad filenames.
  1380. if (!Utils::checkFilename($filename)) {
  1381. $this->admin->json_response = [
  1382. 'status' => 'error',
  1383. 'message' => sprintf($this->admin::translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_UPLOAD'),
  1384. $filename, 'Bad filename')
  1385. ];
  1386. return false;
  1387. }
  1388. // You should also check filesize here.
  1389. $grav_limit = Utils::getUploadLimit();
  1390. if ($grav_limit > 0 && $_FILES['file']['size'] > $grav_limit) {
  1391. $this->admin->json_response = [
  1392. 'status' => 'error',
  1393. 'message' => $this->admin::translate('PLUGIN_ADMIN.EXCEEDED_GRAV_FILESIZE_LIMIT')
  1394. ];
  1395. return false;
  1396. }
  1397. // Check extension
  1398. $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  1399. // If not a supported type, return
  1400. if (!$extension || !$config->get("media.types.{$extension}")) {
  1401. $this->admin->json_response = [
  1402. 'status' => 'error',
  1403. 'message' => $this->admin::translate('PLUGIN_ADMIN.UNSUPPORTED_FILE_TYPE') . ': ' . $extension
  1404. ];
  1405. return false;
  1406. }
  1407. $media = $this->getMedia();
  1408. if (!$media) {
  1409. $this->admin->json_response = [
  1410. 'status' => 'error',
  1411. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_PAGE_FOUND')
  1412. ];
  1413. return false;
  1414. }
  1415. /** @var UniformResourceLocator $locator */
  1416. $locator = $this->grav['locator'];
  1417. $path = $media->getPath();
  1418. if ($locator->isStream($path)) {
  1419. $path = $locator->findResource($path, true, true);
  1420. }
  1421. // Upload it
  1422. if (!move_uploaded_file($_FILES['file']['tmp_name'], sprintf('%s/%s', $path, $filename))) {
  1423. $this->admin->json_response = [
  1424. 'status' => 'error',
  1425. 'message' => $this->admin::translate('PLUGIN_ADMIN.FAILED_TO_MOVE_UPLOADED_FILE')
  1426. ];
  1427. return false;
  1428. }
  1429. // Add metadata if needed
  1430. $include_metadata = Grav::instance()['config']->get('system.media.auto_metadata_exif', false);
  1431. $basename = str_replace(['@3x', '@2x'], '', pathinfo($filename, PATHINFO_BASENAME));
  1432. $metadata = [];
  1433. if ($include_metadata && isset($media[$basename])) {
  1434. $img_metadata = $media[$basename]->metadata();
  1435. if ($img_metadata) {
  1436. $metadata = $img_metadata;
  1437. }
  1438. }
  1439. $page = $this->admin->page(true);
  1440. if ($page) {
  1441. $this->grav->fireEvent('onAdminAfterAddMedia', new Event(['page' => $page]));
  1442. }
  1443. $this->admin->json_response = [
  1444. 'status' => 'success',
  1445. 'message' => $this->admin::translate('PLUGIN_ADMIN.FILE_UPLOADED_SUCCESSFULLY'),
  1446. 'metadata' => $metadata,
  1447. ];
  1448. return true;
  1449. }
  1450. /**
  1451. * Handles deleting a media file from a page
  1452. *
  1453. * @return bool True if the action was performed.
  1454. */
  1455. protected function taskDelmedia()
  1456. {
  1457. if (!$this->authorizeTask('delete media', ['admin.pages', 'admin.super'])) {
  1458. return false;
  1459. }
  1460. $media = $this->getMedia();
  1461. if (!$media) {
  1462. $this->admin->json_response = [
  1463. 'status' => 'error',
  1464. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_PAGE_FOUND')
  1465. ];
  1466. return false;
  1467. }
  1468. $filename = !empty($this->post['filename']) ? $this->post['filename'] : null;
  1469. // Handle bad filenames.
  1470. if (!Utils::checkFilename($filename)) {
  1471. $filename = null;
  1472. }
  1473. if (!$filename) {
  1474. $this->admin->json_response = [
  1475. 'status' => 'error',
  1476. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_FILE_FOUND')
  1477. ];
  1478. return false;
  1479. }
  1480. /** @var UniformResourceLocator $locator */
  1481. $locator = $this->grav['locator'];
  1482. $targetPath = $media->getPath() . '/' . $filename;
  1483. if ($locator->isStream($targetPath)) {
  1484. $targetPath = $locator->findResource($targetPath, true, true);
  1485. }
  1486. $fileParts = pathinfo($filename);
  1487. $found = false;
  1488. if (file_exists($targetPath)) {
  1489. $found = true;
  1490. $result = unlink($targetPath);
  1491. if (!$result) {
  1492. $this->admin->json_response = [
  1493. 'status' => 'error',
  1494. 'message' => $this->admin::translate('PLUGIN_ADMIN.FILE_COULD_NOT_BE_DELETED') . ': ' . $filename
  1495. ];
  1496. return false;
  1497. }
  1498. }
  1499. // Remove Extra Files
  1500. foreach (scandir($media->getPath(), SCANDIR_SORT_NONE) as $file) {
  1501. if (preg_match("/{$fileParts['filename']}@\d+x\.{$fileParts['extension']}(?:\.meta\.yaml)?$|{$filename}\.meta\.yaml$/", $file)) {
  1502. $targetPath = $media->getPath() . '/' . $file;
  1503. if ($locator->isStream($targetPath)) {
  1504. $targetPath = $locator->findResource($targetPath, true, true);
  1505. }
  1506. $result = unlink($targetPath);
  1507. if (!$result) {
  1508. $this->admin->json_response = [
  1509. 'status' => 'error',
  1510. 'message' => $this->admin::translate('PLUGIN_ADMIN.FILE_COULD_NOT_BE_DELETED') . ': ' . $filename
  1511. ];
  1512. return false;
  1513. }
  1514. $found = true;
  1515. }
  1516. }
  1517. if (!$found) {
  1518. $this->admin->json_response = [
  1519. 'status' => 'error',
  1520. 'message' => $this->admin::translate('PLUGIN_ADMIN.FILE_NOT_FOUND') . ': ' . $filename
  1521. ];
  1522. return false;
  1523. }
  1524. $page = $this->admin->page(true);
  1525. if ($page) {
  1526. $this->grav->fireEvent('onAdminAfterDelMedia', new Event(['page' => $page]));
  1527. }
  1528. $this->admin->json_response = [
  1529. 'status' => 'success',
  1530. 'message' => $this->admin::translate('PLUGIN_ADMIN.FILE_DELETED') . ': ' . $filename
  1531. ];
  1532. return true;
  1533. }
  1534. /**
  1535. * Process the page Markdown
  1536. *
  1537. * @return bool True if the action was performed.
  1538. */
  1539. protected function taskProcessMarkdown()
  1540. {
  1541. if (!$this->authorizeTask('process markdown', ['admin.pages', 'admin.super'])) {
  1542. return false;
  1543. }
  1544. try {
  1545. $page = $this->admin->page(true);
  1546. if (!$page) {
  1547. $this->admin->json_response = [
  1548. 'status' => 'error',
  1549. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_PAGE_FOUND')
  1550. ];
  1551. return false;
  1552. }
  1553. $this->preparePage($page, true);
  1554. $page->header();
  1555. $page->templateFormat('html');
  1556. // Add theme template paths to Twig loader
  1557. $template_paths = $this->grav['locator']->findResources('theme://templates');
  1558. $this->grav['twig']->twig->getLoader()->addLoader(new \Twig_Loader_Filesystem($template_paths));
  1559. $html = $page->content();
  1560. $this->admin->json_response = ['status' => 'success', 'preview' => $html];
  1561. } catch (\Exception $e) {
  1562. $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()];
  1563. return false;
  1564. }
  1565. return true;
  1566. }
  1567. /**
  1568. * Prepare a page to be stored: update its folder, name, template, header and content
  1569. *
  1570. * @param PageInterface $page
  1571. * @param bool $clean_header
  1572. * @param string $language
  1573. */
  1574. protected function preparePage(PageInterface $page, $clean_header = false, $language = '')
  1575. {
  1576. $input = (array)$this->data;
  1577. if (isset($input['folder']) && $input['folder'] !== $page->value('folder')) {
  1578. $order = $page->value('order');
  1579. $ordering = $order ? sprintf('%02d.', $order) : '';
  1580. $page->folder($ordering . $input['folder']);
  1581. }
  1582. if (isset($input['name']) && !empty($input['name'])) {
  1583. $type = strtolower($input['name']);
  1584. $name = preg_replace('|.*/|', '', $type);
  1585. if ($language) {
  1586. $name .= '.' . $language;
  1587. } else {
  1588. $language = $this->grav['language'];
  1589. if ($language->enabled()) {
  1590. $name .= '.' . $language->getLanguage();
  1591. }
  1592. }
  1593. $name .= '.md';
  1594. $page->name($name);
  1595. $page->template($type);
  1596. }
  1597. // Special case for Expert mode: build the raw, unset content
  1598. if (isset($input['frontmatter'], $input['content'])) {
  1599. $page->raw("---\n" . (string)$input['frontmatter'] . "\n---\n" . (string)$input['content']);
  1600. unset($input['content']);
  1601. // Handle header normally
  1602. } elseif (isset($input['header'])) {
  1603. $header = $input['header'];
  1604. foreach ($header as $key => $value) {
  1605. if ($key === 'metadata' && is_array($header[$key])) {
  1606. foreach ($header['metadata'] as $key2 => $value2) {
  1607. if (isset($input['toggleable_header']['metadata'][$key2]) && !$input['toggleable_header']['metadata'][$key2]) {
  1608. $header['metadata'][$key2] = '';
  1609. }
  1610. }
  1611. } elseif ($key === 'taxonomy' && is_array($header[$key])) {
  1612. foreach ($header[$key] as $taxkey => $taxonomy) {
  1613. if (is_array($taxonomy) && \count($taxonomy) === 1 && trim($taxonomy[0]) === '') {
  1614. unset($header[$key][$taxkey]);
  1615. }
  1616. }
  1617. } else {
  1618. if (isset($input['toggleable_header'][$key]) && !$input['toggleable_header'][$key]) {
  1619. $header[$key] = null;
  1620. }
  1621. }
  1622. }
  1623. if ($clean_header) {
  1624. $header = Utils::arrayFilterRecursive($header, function ($k, $v) {
  1625. return !(null === $v || $v === '');
  1626. });
  1627. }
  1628. $page->header((object)$header);
  1629. $page->frontmatter(Yaml::dump((array)$page->header(), 20));
  1630. }
  1631. // Fill content last because it also renders the output.
  1632. if (isset($input['content'])) {
  1633. $page->rawMarkdown((string)$input['content']);
  1634. }
  1635. }
  1636. /**
  1637. * Save page as a new copy.
  1638. *
  1639. * @return bool True if the action was performed.
  1640. * @throws \RuntimeException
  1641. */
  1642. protected function taskCopy()
  1643. {
  1644. if (!$this->authorizeTask('copy page', ['admin.pages', 'admin.super'])) {
  1645. return false;
  1646. }
  1647. // Only applies to pages.
  1648. if ($this->view !== 'pages') {
  1649. return false;
  1650. }
  1651. try {
  1652. /** @var Pages $pages */
  1653. $pages = $this->grav['pages'];
  1654. // Get the current page.
  1655. $original_page = $this->admin->page(true);
  1656. // Find new parent page in order to build the path.
  1657. $parent = $original_page->parent() ?: $pages->root();
  1658. // Make a copy of the current page and fill the updated information into it.
  1659. $page = $original_page->copy($parent);
  1660. $order = 0;
  1661. if ($page->order()) {
  1662. $order = $this->getNextOrderInFolder($page->parent()->path());
  1663. }
  1664. // Make sure the header is loaded in case content was set through raw() (expert mode)
  1665. $page->header();
  1666. if ($page->order()) {
  1667. $page->order($order);
  1668. }
  1669. $folder = $this->findFirstAvailable('folder', $page);
  1670. $slug = $this->findFirstAvailable('slug', $page);
  1671. $page->path($page->parent()->path() . DS . $page->order() . $folder);
  1672. $page->route($page->parent()->route() . '/' . $slug);
  1673. $page->rawRoute($page->parent()->rawRoute() . '/' . $slug);
  1674. // Append progressive number to the copied page title
  1675. $match = preg_split('/(\d+)(?!.*\d)/', $original_page->title(), 2, PREG_SPLIT_DELIM_CAPTURE);
  1676. $header = $page->header();
  1677. if (!isset($match[1])) {
  1678. $header->title = $match[0] . ' 2';
  1679. } else {
  1680. $header->title = $match[0] . ((int)$match[1] + 1);
  1681. }
  1682. $page->header($header);
  1683. $page->save(false);
  1684. $redirect = $this->view . $page->rawRoute();
  1685. $header = $page->header();
  1686. if (isset($header->slug)) {
  1687. $match = preg_split('/-(\d+)$/', $header->slug, 2, PREG_SPLIT_DELIM_CAPTURE);
  1688. $header->slug = $match[0] . '-' . (isset($match[1]) ? (int)$match[1] + 1 : 2);
  1689. }
  1690. $page->header($header);
  1691. $page->save();
  1692. $this->grav->fireEvent('onAdminAfterSave', new Event(['page' => $page]));
  1693. // Enqueue message and redirect to new location.
  1694. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_COPIED'), 'info');
  1695. $this->setRedirect($redirect);
  1696. } catch (\Exception $e) {
  1697. throw new \RuntimeException('Copying page failed on error: ' . $e->getMessage());
  1698. }
  1699. return true;
  1700. }
  1701. /**
  1702. * Find the first available $item ('slug' | 'folder') for a page
  1703. * Used when copying a page, to determine the first available slot
  1704. *
  1705. * @param string $item
  1706. * @param PageInterface $page
  1707. *
  1708. * @return string The first available slot
  1709. */
  1710. protected function findFirstAvailable($item, PageInterface $page)
  1711. {
  1712. if (!$page->parent()->children()) {
  1713. return $page->{$item}();
  1714. }
  1715. $withoutPrefix = function ($string) {
  1716. $match = preg_split('/^[0-9]+\./u', $string, 2, PREG_SPLIT_DELIM_CAPTURE);
  1717. return $match[1] ?? $match[0];
  1718. };
  1719. $withoutPostfix = function ($string) {
  1720. $match = preg_split('/-(\d+)$/', $string, 2, PREG_SPLIT_DELIM_CAPTURE);
  1721. return $match[0];
  1722. };
  1723. /* $appendedNumber = function ($string) {
  1724. $match = preg_split('/-(\d+)$/', $string, 2, PREG_SPLIT_DELIM_CAPTURE);
  1725. $append = (isset($match[1]) ? (int)$match[1] + 1 : 2);
  1726. return $append;
  1727. };*/
  1728. $highest = 1;
  1729. $siblings = $page->parent()->children();
  1730. $findCorrectAppendedNumber = function ($item, $page_item, $highest) use (
  1731. $siblings,
  1732. &$findCorrectAppendedNumber,
  1733. &$withoutPrefix
  1734. ) {
  1735. foreach ($siblings as $sibling) {
  1736. if ($withoutPrefix($sibling->{$item}()) == ($highest === 1 ? $page_item : $page_item . '-' . $highest)) {
  1737. $highest = $findCorrectAppendedNumber($item, $page_item, $highest + 1);
  1738. return $highest;
  1739. }
  1740. }
  1741. return $highest;
  1742. };
  1743. $base = $withoutPrefix($withoutPostfix($page->$item()));
  1744. $return = $base;
  1745. $highest = $findCorrectAppendedNumber($item, $base, $highest);
  1746. if ($highest > 1) {
  1747. $return .= '-' . $highest;
  1748. }
  1749. return $return;
  1750. }
  1751. /**
  1752. * Reorder pages.
  1753. *
  1754. * @return bool True if the action was performed.
  1755. */
  1756. protected function taskReorder()
  1757. {
  1758. if (!$this->authorizeTask('reorder pages', ['admin.pages', 'admin.super'])) {
  1759. return false;
  1760. }
  1761. // Only applies to pages.
  1762. if ($this->view !== 'pages') {
  1763. return false;
  1764. }
  1765. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.REORDERING_WAS_SUCCESSFUL'), 'info');
  1766. return true;
  1767. }
  1768. /**
  1769. * Delete page.
  1770. *
  1771. * @return bool True if the action was performed.
  1772. * @throws \RuntimeException
  1773. */
  1774. protected function taskDelete()
  1775. {
  1776. if (!$this->authorizeTask('delete page', ['admin.pages', 'admin.super'])) {
  1777. return false;
  1778. }
  1779. // Only applies to pages.
  1780. if ($this->view !== 'pages') {
  1781. return false;
  1782. }
  1783. try {
  1784. $page = $this->admin->page();
  1785. if (count($page->translatedLanguages()) > 1) {
  1786. $page->file()->delete();
  1787. } else {
  1788. Folder::delete($page->path());
  1789. }
  1790. $this->grav->fireEvent('onAdminAfterDelete', new Event(['page' => $page]));
  1791. Cache::clearCache('invalidate');
  1792. // Set redirect to pages list.
  1793. $redirect = 'pages';
  1794. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_DELETED'), 'info');
  1795. $this->setRedirect($redirect);
  1796. } catch (\Exception $e) {
  1797. throw new \RuntimeException('Deleting page failed on error: ' . $e->getMessage());
  1798. }
  1799. return true;
  1800. }
  1801. /**
  1802. * Switch the content language. Optionally redirect to a different page.
  1803. *
  1804. */
  1805. protected function taskSwitchlanguage()
  1806. {
  1807. if (!$this->authorizeTask('switch language', ['admin.pages', 'admin.super'])) {
  1808. return false;
  1809. }
  1810. $data = (array)$this->data;
  1811. if (isset($data['lang'])) {
  1812. $language = $data['lang'];
  1813. } else {
  1814. $language = $this->grav['uri']->param('lang');
  1815. }
  1816. if (isset($data['redirect'])) {
  1817. $redirect = 'pages/' . $data['redirect'];
  1818. } else {
  1819. $redirect = 'pages';
  1820. }
  1821. if ($language) {
  1822. $this->grav['session']->admin_lang = $language ?: 'en';
  1823. }
  1824. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_SWITCHED_LANGUAGE'), 'info');
  1825. $admin_route = $this->admin->base;
  1826. $this->setRedirect('/' . $language . $admin_route . '/' . $redirect);
  1827. return true;
  1828. }
  1829. /**
  1830. * Handle direct install.
  1831. */
  1832. protected function taskDirectInstall()
  1833. {
  1834. if (!$this->authorizeTask('install', ['admin.super'])) {
  1835. return false;
  1836. }
  1837. $file_path = $this->data['file_path'] ?? null;
  1838. if (isset($_FILES['uploaded_file'])) {
  1839. // Check $_FILES['file']['error'] value.
  1840. switch ($_FILES['uploaded_file']['error']) {
  1841. case UPLOAD_ERR_OK:
  1842. break;
  1843. case UPLOAD_ERR_NO_FILE:
  1844. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.NO_FILES_SENT'), 'error');
  1845. return false;
  1846. case UPLOAD_ERR_INI_SIZE:
  1847. case UPLOAD_ERR_FORM_SIZE:
  1848. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.EXCEEDED_FILESIZE_LIMIT'), 'error');
  1849. return false;
  1850. case UPLOAD_ERR_NO_TMP_DIR:
  1851. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.UPLOAD_ERR_NO_TMP_DIR'), 'error');
  1852. return false;
  1853. default:
  1854. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.UNKNOWN_ERRORS'), 'error');
  1855. return false;
  1856. }
  1857. $file_name = $_FILES['uploaded_file']['name'];
  1858. $file_path = $_FILES['uploaded_file']['tmp_name'];
  1859. // Handle bad filenames.
  1860. if (!Utils::checkFilename($file_name)) {
  1861. $this->admin->json_response = [
  1862. 'status' => 'error',
  1863. 'message' => $this->admin::translate('PLUGIN_ADMIN.UNKNOWN_ERRORS')
  1864. ];
  1865. return false;
  1866. }
  1867. }
  1868. $result = Gpm::directInstall($file_path);
  1869. if ($result === true) {
  1870. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.INSTALLATION_SUCCESSFUL'), 'info');
  1871. } else {
  1872. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.INSTALLATION_FAILED') . ': ' . $result,
  1873. 'error');
  1874. }
  1875. $this->setRedirect('/tools');
  1876. return true;
  1877. }
  1878. /**
  1879. * Save the current page in a different language. Automatically switches to that language.
  1880. *
  1881. * @return bool True if the action was performed.
  1882. */
  1883. protected function taskSaveas()
  1884. {
  1885. if (!$this->authorizeTask('save', $this->dataPermissions())) {
  1886. return false;
  1887. }
  1888. $data = (array)$this->data;
  1889. $language = $data['lang'];
  1890. if ($language) {
  1891. $this->grav['session']->admin_lang = $language ?: 'en';
  1892. }
  1893. $uri = $this->grav['uri'];
  1894. $obj = $this->admin->page($uri->route());
  1895. $this->preparePage($obj, false, $language);
  1896. $file = $obj->file();
  1897. if ($file) {
  1898. $filename = $this->determineFilenameIncludingLanguage($obj->name(), $language);
  1899. $path = $obj->path() . DS . $filename;
  1900. $aFile = File::instance($path);
  1901. $aFile->save();
  1902. $aPage = new Page();
  1903. $aPage->init(new \SplFileInfo($path), $language . '.md');
  1904. $aPage->header($obj->header());
  1905. $aPage->rawMarkdown($obj->rawMarkdown());
  1906. $aPage->template($obj->template());
  1907. $aPage->validate();
  1908. $aPage->filter();
  1909. $this->grav->fireEvent('onAdminSave', new Event(['page' => &$aPage]));
  1910. $aPage->save();
  1911. $this->grav->fireEvent('onAdminAfterSave', new Event(['page' => $aPage]));
  1912. }
  1913. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_SWITCHED_LANGUAGE'), 'info');
  1914. $this->setRedirect('/' . $language . $uri->route());
  1915. return true;
  1916. }
  1917. /**
  1918. * The what should be the new filename when saving as a new language
  1919. *
  1920. * @param string $current_filename the current file name, including .md. Example: default.en.md
  1921. * @param string $language The new language it will be saved as. Example: 'it' or 'en-GB'.
  1922. *
  1923. * @return string The new filename. Example: 'default.it'
  1924. */
  1925. public function determineFilenameIncludingLanguage($current_filename, $language)
  1926. {
  1927. $ext = '.md';
  1928. $filename = substr($current_filename, 0, -strlen($ext));
  1929. $languages_enabled = $this->grav['config']->get('system.languages.supported', []);
  1930. $parts = explode('.', trim($filename, '.'));
  1931. $lang = array_pop($parts);
  1932. if ($lang === $language) {
  1933. return $filename . $ext;
  1934. } elseif (in_array($lang, $languages_enabled)) {
  1935. $filename = implode('.', $parts);
  1936. }
  1937. return $filename . '.' . $language . $ext;
  1938. }
  1939. protected function taskGetLevelListing()
  1940. {
  1941. $data = $this->getPost($_POST);
  1942. if (!isset($data['field'])) {
  1943. $json = [
  1944. 'status' => 'error',
  1945. 'message' => 'Bad Request'
  1946. ];
  1947. return $this->sendJsonResponse($json, 400);
  1948. }
  1949. // Base64 decode the route
  1950. $data['route'] = isset($data['route']) ? base64_decode($data['route']) : null;
  1951. $initial = $data['initial'] ?? null;
  1952. if ($initial) {
  1953. $data['leaf_route'] = $data['route'];
  1954. $data['route'] = null;
  1955. $data['level'] = 1;
  1956. }
  1957. [$status, $message, $response,] = $this->getLevelListing($data);
  1958. $json = [
  1959. 'status' => $status,
  1960. 'message' => $this->admin::translate($message ?? 'PLUGIN_ADMIN.NO_ROUTE_PROVIDED'),
  1961. 'data' => array_values($response)
  1962. ];
  1963. return $this->sendJsonResponse($json, 200);
  1964. }
  1965. protected function getLevelListing($data)
  1966. {
  1967. // Valid types are dir|file|link
  1968. $default_filters = ['type'=> ['root', 'dir'], 'name' => null, 'extension' => null];
  1969. $pages = $this->grav['pages'];
  1970. $pages_instances = $pages->instances();
  1971. $is_page = $data['page'] ?? true;
  1972. $route = $data['route'] ?? null;
  1973. $leaf_route = $data['leaf_route'] ?? null;
  1974. $sortby = $data['sortby'] ?? 'filename';
  1975. $order = $data['order'] ?? SORT_ASC;
  1976. $initial = $data['initial'] ?? null;
  1977. $filters = isset($data['filters']) ? $default_filters + json_decode($data['filters']) : $default_filters;
  1978. $filter_type = (array) $filters['type'];
  1979. $status = 'error';
  1980. $msg = null;
  1981. $response = [];
  1982. $children = null;
  1983. $sub_route = null;
  1984. $extra = null;
  1985. $root = false;
  1986. // Handle leaf_route
  1987. if ($leaf_route && $route !== $leaf_route) {
  1988. $nodes = explode('/', $leaf_route);
  1989. $sub_route = '/' . implode('/', array_slice($nodes, 1, $data['level']++));
  1990. $data['route'] = $sub_route;
  1991. [$status, $msg, $children, $extra] = $this->getLevelListing($data);
  1992. }
  1993. // Handle no route, assume page tree root
  1994. if (!$route) {
  1995. $is_page = false;
  1996. $route = $this->grav['locator']->findResource('page://', true);
  1997. $root = true;
  1998. }
  1999. if ($is_page) {
  2000. // Try the path
  2001. /** @var PageInterface $page */
  2002. $page = $pages->get(GRAV_ROOT . $route);
  2003. // Try a real route (like homepage)
  2004. if (is_null($page)) {
  2005. $page = $pages->find($route);
  2006. }
  2007. $path = $page ? $page->path() : null;
  2008. } else {
  2009. // Try a physical path
  2010. if (!Utils::startsWith($route, GRAV_ROOT)) {
  2011. $try_path = GRAV_ROOT . $route;
  2012. } else {
  2013. $try_path = $route;
  2014. }
  2015. $path = file_exists($try_path) ? $try_path : null;
  2016. }
  2017. $blueprintsData = $this->admin->page(true);
  2018. if (null !== $blueprintsData) {
  2019. if (method_exists($blueprintsData, 'blueprints')) {
  2020. $settings = $blueprintsData->blueprints()->schema()->getProperty($data['field']);
  2021. } elseif (method_exists($blueprintsData, 'getBlueprint')) {
  2022. $settings = $blueprintsData->getBlueprint()->schema()->getProperty($data['field']);
  2023. }
  2024. $filters = array_merge([], $filters, ($settings['filters'] ?? []));
  2025. $filter_type = $filters['type'] ?? $filter_type;
  2026. }
  2027. if ($path) {
  2028. /** @var \SplFileInfo $fileInfo */
  2029. $status = 'success';
  2030. $msg = 'PLUGIN_ADMIN.PAGE_ROUTE_FOUND';
  2031. foreach (new \DirectoryIterator($path) as $fileInfo) {
  2032. $fileName = $fileInfo->getFilename();
  2033. $filePath = str_replace('\\', '/', $fileInfo->getPathname());
  2034. if (($fileInfo->isDot() && $fileName !== '.' && $initial) || (Utils::startsWith($fileName, '.') && strlen($fileName) > 1)) {
  2035. continue;
  2036. }
  2037. if ($fileInfo->isDot()) {
  2038. if ($root) {
  2039. $payload = [
  2040. 'name' => '<root>',
  2041. 'value' => '',
  2042. 'item-key' => '',
  2043. 'filename' => '.',
  2044. 'extension' => '',
  2045. 'type' => 'root',
  2046. 'modified' => $fileInfo->getMTime(),
  2047. 'size' => 0,
  2048. 'has-children' => false
  2049. ];
  2050. } else {
  2051. continue;
  2052. }
  2053. } else {
  2054. $file_page = $pages_instances[$filePath] ?? null;
  2055. $file_path = Utils::replaceFirstOccurrence(GRAV_ROOT, '', $filePath);
  2056. $type = $fileInfo->getType();
  2057. $child_path = $file_page ? $file_page->path() : $filePath;
  2058. $count_children = Folder::countChildren($child_path);
  2059. $payload = [
  2060. 'name' => $file_page ? $file_page->title() : $fileName,
  2061. 'value' => $file_page ? $file_page->rawRoute() : $file_path,
  2062. 'item-key' => basename($file_page ? $file_page->route() : $file_path),
  2063. 'filename' => $fileName,
  2064. 'extension' => $type === 'dir' ? '' : $fileInfo->getExtension(),
  2065. 'type' => $type,
  2066. 'modified' => $fileInfo->getMTime(),
  2067. 'size' => $count_children,
  2068. 'symlink' => false,
  2069. 'has-children' => $count_children > 0
  2070. ];
  2071. }
  2072. // Fix for symlink
  2073. if ($payload['type'] === 'link') {
  2074. $payload['symlink'] = true;
  2075. $physical_path = $fileInfo->getRealPath();
  2076. $payload['type'] = is_dir($physical_path) ? 'dir' : 'file';
  2077. }
  2078. // filter types
  2079. if ($filters['type']) {
  2080. if (!in_array($payload['type'], $filter_type)) {
  2081. continue;
  2082. }
  2083. }
  2084. // Simple filter for name or extension
  2085. if (($filters['name'] && Utils::contains($payload['basename'], $filters['name'])) ||
  2086. ($filters['extension'] && Utils::contains($payload['extension'], $filters['extension']))) {
  2087. continue;
  2088. }
  2089. // Add children if any
  2090. if ($filePath === $extra && is_array($children)) {
  2091. $payload['children'] = array_values($children);
  2092. }
  2093. $response[] = $payload;
  2094. }
  2095. } else {
  2096. $msg = 'PLUGIN_ADMIN.PAGE_ROUTE_NOT_FOUND';
  2097. }
  2098. // Sorting
  2099. $response = Utils::sortArrayByKey($response, $sortby, $order);
  2100. $temp_array = [];
  2101. foreach ($response as $index => $item) {
  2102. $temp_array[$item['type']][$index] = $item;
  2103. }
  2104. $sorted = Utils::sortArrayByArray($temp_array, $filter_type);
  2105. $response = Utils::arrayFlatten($sorted);
  2106. return [$status, $this->admin::translate($msg ?? 'PLUGIN_ADMIN.NO_ROUTE_PROVIDED'), $response, $path];
  2107. }
  2108. protected function taskConvertUrls()
  2109. {
  2110. $data = $this->getPost($_POST);
  2111. $converted_links = [];
  2112. $converted_images = [];
  2113. $status = 'success';
  2114. $message = 'All links converted';
  2115. $data['route'] = isset($data['route']) ? base64_decode($data['route']) : null;
  2116. $data['data'] = json_decode($data['data'] ?? '{}', true);
  2117. // use the route if passed, else use current page in admin as reference
  2118. $page_route = $data['route'] ?? $this->admin->page(true);
  2119. /** @var PageInterface */
  2120. $page = $this->grav['pages']->find($page_route);
  2121. if (!$page) {
  2122. $json = [
  2123. 'status' => 'error',
  2124. 'message' => 'Page Not Found'
  2125. ];
  2126. return $this->sendJsonResponse($json, 404);
  2127. }
  2128. if (!isset($data['data'])) {
  2129. $json = [
  2130. 'status' => 'error',
  2131. 'message' => 'Bad Request'
  2132. ];
  2133. return $this->sendJsonResponse($json, 400);
  2134. }
  2135. foreach ($data['data']['a'] ?? [] as $link) {
  2136. $converted_links[$link] = Excerpts::processLinkHtml($link, $page);
  2137. }
  2138. foreach ($data['data']['img'] ?? [] as $image) {
  2139. $converted_images[$image] = Excerpts::processImageHtml($image, $page);
  2140. }
  2141. $json = [
  2142. 'status' => $status,
  2143. 'message' => $message,
  2144. 'data' => ['links' => $converted_links, 'images' => $converted_images]
  2145. ];
  2146. return $this->sendJsonResponse($json, 200);
  2147. }
  2148. }