admincontroller.php 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697
  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: License key for this resource is invalid." : $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. $filename = basename(base64_decode(urldecode($download)));
  1066. $file = $this->grav['locator']->findResource("backup://{$filename}", true);
  1067. if (!$file || !Utils::endsWith($filename, '.zip', false)) {
  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. if (!$this->authorizeTask('backup', ['admin.maintenance', 'admin.super'])) {
  1104. return false;
  1105. }
  1106. $backup = $this->grav['uri']->param('backup', null);
  1107. if (null !== $backup) {
  1108. $filename = basename(base64_decode(urldecode($backup)));
  1109. $file = $this->grav['locator']->findResource("backup://{$filename}", true);
  1110. if ($file && Utils::endsWith($filename, '.zip', false)) {
  1111. unlink($file);
  1112. $this->admin->json_response = [
  1113. 'status' => 'success',
  1114. 'message' => $this->admin::translate('PLUGIN_ADMIN.BACKUP_DELETED'),
  1115. 'toastr' => [
  1116. 'closeButton' => true
  1117. ]
  1118. ];
  1119. return true;
  1120. }
  1121. }
  1122. $this->admin->json_response = [
  1123. 'status' => 'error',
  1124. 'message' => $this->admin::translate('PLUGIN_ADMIN.BACKUP_NOT_FOUND'),
  1125. ];
  1126. return true;
  1127. }
  1128. protected function taskGetChildTypes()
  1129. {
  1130. if (!$this->authorizeTask('get childtypes', ['admin.pages', 'admin.super'])) {
  1131. return false;
  1132. }
  1133. $data = $this->post;
  1134. $rawroute = $data['rawroute'] ?? null;
  1135. if ($rawroute) {
  1136. /** @var PageInterface $page */
  1137. $page = $this->grav['pages']->dispatch($rawroute);
  1138. if ($page) {
  1139. $child_type = $page->childType();
  1140. if ($child_type !== '') {
  1141. $this->admin->json_response = [
  1142. 'status' => 'success',
  1143. 'child_type' => $child_type
  1144. ];
  1145. return true;
  1146. }
  1147. }
  1148. }
  1149. $this->admin->json_response = [
  1150. 'status' => 'success',
  1151. 'child_type' => '',
  1152. // 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_CHILD_TYPE')
  1153. ];
  1154. return true;
  1155. }
  1156. /**
  1157. * Handles filtering the page by modular/visible/routable in the pages list.
  1158. */
  1159. protected function taskFilterPages()
  1160. {
  1161. if (!$this->authorizeTask('filter pages', ['admin.pages', 'admin.super'])) {
  1162. return;
  1163. }
  1164. $data = $this->post;
  1165. $flags = !empty($data['flags']) ? array_map('strtolower', explode(',', $data['flags'])) : [];
  1166. $queries = !empty($data['query']) ? explode(',', $data['query']) : [];
  1167. /** @var Collection $collection */
  1168. $collection = $this->grav['pages']->all();
  1169. if (count($flags)) {
  1170. // Filter by state
  1171. $pageStates = [
  1172. 'modular',
  1173. 'nonmodular',
  1174. 'visible',
  1175. 'nonvisible',
  1176. 'routable',
  1177. 'nonroutable',
  1178. 'published',
  1179. 'nonpublished'
  1180. ];
  1181. if (count(array_intersect($pageStates, $flags)) > 0) {
  1182. if (in_array('modular', $flags, true)) {
  1183. $collection = $collection->modular();
  1184. }
  1185. if (in_array('nonmodular', $flags, true)) {
  1186. $collection = $collection->nonModular();
  1187. }
  1188. if (in_array('visible', $flags, true)) {
  1189. $collection = $collection->visible();
  1190. }
  1191. if (in_array('nonvisible', $flags, true)) {
  1192. $collection = $collection->nonVisible();
  1193. }
  1194. if (in_array('routable', $flags, true)) {
  1195. $collection = $collection->routable();
  1196. }
  1197. if (in_array('nonroutable', $flags, true)) {
  1198. $collection = $collection->nonRoutable();
  1199. }
  1200. if (in_array('published', $flags, true)) {
  1201. $collection = $collection->published();
  1202. }
  1203. if (in_array('nonpublished', $flags, true)) {
  1204. $collection = $collection->nonPublished();
  1205. }
  1206. }
  1207. foreach ($pageStates as $pageState) {
  1208. if (($pageState = array_search($pageState, $flags, true)) !== false) {
  1209. unset($flags[$pageState]);
  1210. }
  1211. }
  1212. // Filter by page type
  1213. if ($flags) {
  1214. $types = [];
  1215. $pageTypes = array_keys(Pages::pageTypes());
  1216. foreach ($pageTypes as $pageType) {
  1217. if (($pageKey = array_search($pageType, $flags, true)) !== false) {
  1218. $types[] = $pageType;
  1219. unset($flags[$pageKey]);
  1220. }
  1221. }
  1222. if (count($types)) {
  1223. $collection = $collection->ofOneOfTheseTypes($types);
  1224. }
  1225. }
  1226. // Filter by page type
  1227. if ($flags) {
  1228. $accessLevels = $flags;
  1229. $collection = $collection->ofOneOfTheseAccessLevels($accessLevels);
  1230. }
  1231. }
  1232. if (!empty($queries)) {
  1233. foreach ($collection as $page) {
  1234. foreach ($queries as $query) {
  1235. $query = trim($query);
  1236. if (stripos($page->getRawContent(), $query) === false
  1237. && stripos($page->title(), $query) === false
  1238. && stripos($page->folder(), $query) === false
  1239. && stripos($page->slug(), \Grav\Plugin\Admin\Utils::slug($query)) === false
  1240. ) {
  1241. $collection->remove($page);
  1242. }
  1243. }
  1244. }
  1245. }
  1246. $results = [];
  1247. foreach ($collection as $path => $page) {
  1248. $results[] = $page->route();
  1249. }
  1250. $this->admin->json_response = [
  1251. 'status' => 'success',
  1252. 'message' => $this->admin::translate('PLUGIN_ADMIN.PAGES_FILTERED'),
  1253. 'results' => $results
  1254. ];
  1255. $this->admin->collection = $collection;
  1256. }
  1257. /**
  1258. * Determines the file types allowed to be uploaded
  1259. *
  1260. * Used by pagemedia field.
  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. * Get page media.
  1303. *
  1304. * @return Media|null
  1305. */
  1306. public function getMedia()
  1307. {
  1308. if ($this->view !== 'media') {
  1309. return null;
  1310. }
  1311. $this->uri = $this->uri ?? $this->grav['uri'];
  1312. $this->grav['twig']->twig_vars['current_form_data'] = (array)$this->data;
  1313. $field = (string)$this->uri->post('field', '');
  1314. $order = $this->uri->post('order') ?: null;
  1315. if (!is_array($order)) {
  1316. $order = array_map('trim', explode(',', $order));
  1317. }
  1318. $page = $this->admin->page($this->route);
  1319. if (!$page) {
  1320. return null;
  1321. }
  1322. $blueprints = $page->blueprints();
  1323. $settings = $this->getMediaFieldSettings($blueprints, $field);
  1324. $path = $settings['destination'] ?? $page->path();
  1325. return $path ? new Media($path, $order) : null;
  1326. }
  1327. /**
  1328. * @param Data\Blueprint|null $blueprint
  1329. * @param string $field
  1330. * @return array|null
  1331. */
  1332. protected function getMediaFieldSettings(?Data\Blueprint $blueprint, string $field): ?array
  1333. {
  1334. $schema = $blueprint ? $blueprint->schema() : null;
  1335. if (!$schema || $field === '') {
  1336. return null;
  1337. }
  1338. $settings = is_object($schema) ? (array)$schema->getProperty($field) : null;
  1339. if (null === $settings) {
  1340. return null;
  1341. }
  1342. if (empty($settings['destination']) || \in_array($settings['destination'], ['@self', 'self@', '@self@'], true)) {
  1343. unset($settings['destination']);
  1344. }
  1345. return $settings + ['accept' => '*', 'limit' => 1000];
  1346. }
  1347. /**
  1348. * Handles adding a media file to a page.
  1349. *
  1350. * Used by pagemedia field.
  1351. *
  1352. * @return bool True if the action was performed.
  1353. */
  1354. protected function taskAddmedia()
  1355. {
  1356. if (!$this->authorizeTask('add media', ['admin.pages', 'admin.super'])) {
  1357. return false;
  1358. }
  1359. /** @var Config $config */
  1360. $config = $this->grav['config'];
  1361. if (empty($_FILES)) {
  1362. $this->admin->json_response = [
  1363. 'status' => 'error',
  1364. 'message' => $this->admin::translate('PLUGIN_ADMIN.EXCEEDED_POSTMAX_LIMIT')
  1365. ];
  1366. return false;
  1367. }
  1368. if (!isset($_FILES['file']['error']) || is_array($_FILES['file']['error'])) {
  1369. $this->admin->json_response = [
  1370. 'status' => 'error',
  1371. 'message' => $this->admin::translate('PLUGIN_ADMIN.INVALID_PARAMETERS')
  1372. ];
  1373. return false;
  1374. }
  1375. // Check $_FILES['file']['error'] value.
  1376. switch ($_FILES['file']['error']) {
  1377. case UPLOAD_ERR_OK:
  1378. break;
  1379. case UPLOAD_ERR_NO_FILE:
  1380. $this->admin->json_response = [
  1381. 'status' => 'error',
  1382. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_FILES_SENT')
  1383. ];
  1384. return false;
  1385. case UPLOAD_ERR_INI_SIZE:
  1386. case UPLOAD_ERR_FORM_SIZE:
  1387. $this->admin->json_response = [
  1388. 'status' => 'error',
  1389. 'message' => $this->admin::translate('PLUGIN_ADMIN.EXCEEDED_FILESIZE_LIMIT')
  1390. ];
  1391. return false;
  1392. case UPLOAD_ERR_NO_TMP_DIR:
  1393. $this->admin->json_response = [
  1394. 'status' => 'error',
  1395. 'message' => $this->admin::translate('PLUGIN_ADMIN.UPLOAD_ERR_NO_TMP_DIR')
  1396. ];
  1397. return false;
  1398. default:
  1399. $this->admin->json_response = [
  1400. 'status' => 'error',
  1401. 'message' => $this->admin::translate('PLUGIN_ADMIN.UNKNOWN_ERRORS')
  1402. ];
  1403. return false;
  1404. }
  1405. $filename = $_FILES['file']['name'];
  1406. // Handle bad filenames.
  1407. if (!Utils::checkFilename($filename)) {
  1408. $this->admin->json_response = [
  1409. 'status' => 'error',
  1410. 'message' => sprintf($this->admin::translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_UPLOAD'),
  1411. $filename, 'Bad filename')
  1412. ];
  1413. return false;
  1414. }
  1415. // You should also check filesize here.
  1416. $grav_limit = Utils::getUploadLimit();
  1417. if ($grav_limit > 0 && $_FILES['file']['size'] > $grav_limit) {
  1418. $this->admin->json_response = [
  1419. 'status' => 'error',
  1420. 'message' => $this->admin::translate('PLUGIN_ADMIN.EXCEEDED_GRAV_FILESIZE_LIMIT')
  1421. ];
  1422. return false;
  1423. }
  1424. // Check extension
  1425. $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  1426. // If not a supported type, return
  1427. if (!$extension || !$config->get("media.types.{$extension}")) {
  1428. $this->admin->json_response = [
  1429. 'status' => 'error',
  1430. 'message' => $this->admin::translate('PLUGIN_ADMIN.UNSUPPORTED_FILE_TYPE') . ': ' . $extension
  1431. ];
  1432. return false;
  1433. }
  1434. $media = $this->getMedia();
  1435. if (!$media) {
  1436. $this->admin->json_response = [
  1437. 'status' => 'error',
  1438. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_PAGE_FOUND')
  1439. ];
  1440. return false;
  1441. }
  1442. /** @var UniformResourceLocator $locator */
  1443. $locator = $this->grav['locator'];
  1444. $path = $media->getPath();
  1445. if ($locator->isStream($path)) {
  1446. $path = $locator->findResource($path, true, true);
  1447. }
  1448. // Upload it
  1449. if (!move_uploaded_file($_FILES['file']['tmp_name'], sprintf('%s/%s', $path, $filename))) {
  1450. $this->admin->json_response = [
  1451. 'status' => 'error',
  1452. 'message' => $this->admin::translate('PLUGIN_ADMIN.FAILED_TO_MOVE_UPLOADED_FILE')
  1453. ];
  1454. return false;
  1455. }
  1456. // Add metadata if needed
  1457. $include_metadata = Grav::instance()['config']->get('system.media.auto_metadata_exif', false);
  1458. $basename = str_replace(['@3x', '@2x'], '', pathinfo($filename, PATHINFO_BASENAME));
  1459. $metadata = [];
  1460. if ($include_metadata && isset($media[$basename])) {
  1461. $img_metadata = $media[$basename]->metadata();
  1462. if ($img_metadata) {
  1463. $metadata = $img_metadata;
  1464. }
  1465. }
  1466. $page = $this->admin->page(true);
  1467. if ($page) {
  1468. $this->grav->fireEvent('onAdminAfterAddMedia', new Event(['page' => $page]));
  1469. }
  1470. $this->admin->json_response = [
  1471. 'status' => 'success',
  1472. 'message' => $this->admin::translate('PLUGIN_ADMIN.FILE_UPLOADED_SUCCESSFULLY'),
  1473. 'metadata' => $metadata,
  1474. ];
  1475. return true;
  1476. }
  1477. /**
  1478. * Handles deleting a media file from a page.
  1479. *
  1480. * Used by pagemedia field.
  1481. *
  1482. * @return bool True if the action was performed.
  1483. */
  1484. protected function taskDelmedia()
  1485. {
  1486. if (!$this->authorizeTask('delete media', ['admin.pages', 'admin.super'])) {
  1487. return false;
  1488. }
  1489. $media = $this->getMedia();
  1490. if (!$media) {
  1491. $this->admin->json_response = [
  1492. 'status' => 'error',
  1493. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_PAGE_FOUND')
  1494. ];
  1495. return false;
  1496. }
  1497. $filename = !empty($this->post['filename']) ? basename($this->post['filename']) : null;
  1498. // Handle bad filenames.
  1499. if (!$filename || !Utils::checkFilename($filename)) {
  1500. $this->admin->json_response = [
  1501. 'status' => 'error',
  1502. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_FILE_FOUND')
  1503. ];
  1504. return false;
  1505. }
  1506. /** @var UniformResourceLocator $locator */
  1507. $locator = $this->grav['locator'];
  1508. $targetPath = $media->getPath() . '/' . $filename;
  1509. if ($locator->isStream($targetPath)) {
  1510. $targetPath = $locator->findResource($targetPath, true, true);
  1511. }
  1512. $fileParts = pathinfo($filename);
  1513. $found = false;
  1514. if (file_exists($targetPath)) {
  1515. $found = true;
  1516. $result = unlink($targetPath);
  1517. if (!$result) {
  1518. $this->admin->json_response = [
  1519. 'status' => 'error',
  1520. 'message' => $this->admin::translate('PLUGIN_ADMIN.FILE_COULD_NOT_BE_DELETED') . ': ' . $filename
  1521. ];
  1522. return false;
  1523. }
  1524. }
  1525. // Remove Extra Files
  1526. foreach (scandir($media->getPath(), SCANDIR_SORT_NONE) as $file) {
  1527. if (preg_match("/{$fileParts['filename']}@\d+x\.{$fileParts['extension']}(?:\.meta\.yaml)?$|{$filename}\.meta\.yaml$/", $file)) {
  1528. $targetPath = $media->getPath() . '/' . $file;
  1529. if ($locator->isStream($targetPath)) {
  1530. $targetPath = $locator->findResource($targetPath, true, true);
  1531. }
  1532. $result = unlink($targetPath);
  1533. if (!$result) {
  1534. $this->admin->json_response = [
  1535. 'status' => 'error',
  1536. 'message' => $this->admin::translate('PLUGIN_ADMIN.FILE_COULD_NOT_BE_DELETED') . ': ' . $filename
  1537. ];
  1538. return false;
  1539. }
  1540. $found = true;
  1541. }
  1542. }
  1543. if (!$found) {
  1544. $this->admin->json_response = [
  1545. 'status' => 'error',
  1546. 'message' => $this->admin::translate('PLUGIN_ADMIN.FILE_NOT_FOUND') . ': ' . $filename
  1547. ];
  1548. return false;
  1549. }
  1550. $page = $this->admin->page(true);
  1551. if ($page) {
  1552. $this->grav->fireEvent('onAdminAfterDelMedia', new Event(['page' => $page]));
  1553. }
  1554. $this->admin->json_response = [
  1555. 'status' => 'success',
  1556. 'message' => $this->admin::translate('PLUGIN_ADMIN.FILE_DELETED') . ': ' . $filename
  1557. ];
  1558. return true;
  1559. }
  1560. /**
  1561. * Process the page Markdown
  1562. *
  1563. * @return bool True if the action was performed.
  1564. */
  1565. protected function taskProcessMarkdown()
  1566. {
  1567. if (!$this->authorizeTask('process markdown', ['admin.pages', 'admin.super'])) {
  1568. return false;
  1569. }
  1570. try {
  1571. $page = $this->admin->page(true);
  1572. if (!$page) {
  1573. $this->admin->json_response = [
  1574. 'status' => 'error',
  1575. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_PAGE_FOUND')
  1576. ];
  1577. return false;
  1578. }
  1579. $this->preparePage($page, true);
  1580. $page->header();
  1581. $page->templateFormat('html');
  1582. // Add theme template paths to Twig loader
  1583. $template_paths = $this->grav['locator']->findResources('theme://templates');
  1584. $this->grav['twig']->twig->getLoader()->addLoader(new \Twig_Loader_Filesystem($template_paths));
  1585. $html = $page->content();
  1586. $this->admin->json_response = ['status' => 'success', 'preview' => $html];
  1587. } catch (\Exception $e) {
  1588. $this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()];
  1589. return false;
  1590. }
  1591. return true;
  1592. }
  1593. /**
  1594. * Prepare a page to be stored: update its folder, name, template, header and content
  1595. *
  1596. * @param PageInterface $page
  1597. * @param bool $clean_header
  1598. * @param string $language
  1599. */
  1600. protected function preparePage(PageInterface $page, $clean_header = false, $language = '')
  1601. {
  1602. $input = (array)$this->data;
  1603. if (isset($input['folder']) && $input['folder'] !== $page->value('folder')) {
  1604. $order = $page->value('order');
  1605. $ordering = $order ? sprintf('%02d.', $order) : '';
  1606. $page->folder($ordering . $input['folder']);
  1607. }
  1608. if (isset($input['name']) && !empty($input['name'])) {
  1609. $type = strtolower($input['name']);
  1610. $name = preg_replace('|.*/|', '', $type);
  1611. if ($language) {
  1612. $name .= '.' . $language;
  1613. } else {
  1614. $language = $this->grav['language'];
  1615. if ($language->enabled()) {
  1616. $name .= '.' . $language->getLanguage();
  1617. }
  1618. }
  1619. $name .= '.md';
  1620. $page->name($name);
  1621. $page->template($type);
  1622. }
  1623. // Special case for Expert mode: build the raw, unset content
  1624. if (isset($input['frontmatter'], $input['content'])) {
  1625. $page->raw("---\n" . (string)$input['frontmatter'] . "\n---\n" . (string)$input['content']);
  1626. unset($input['content']);
  1627. // Handle header normally
  1628. } elseif (isset($input['header'])) {
  1629. $header = $input['header'];
  1630. foreach ($header as $key => $value) {
  1631. if ($key === 'metadata' && is_array($header[$key])) {
  1632. foreach ($header['metadata'] as $key2 => $value2) {
  1633. if (isset($input['toggleable_header']['metadata'][$key2]) && !$input['toggleable_header']['metadata'][$key2]) {
  1634. $header['metadata'][$key2] = '';
  1635. }
  1636. }
  1637. } elseif ($key === 'taxonomy' && is_array($header[$key])) {
  1638. foreach ($header[$key] as $taxkey => $taxonomy) {
  1639. if (is_array($taxonomy) && \count($taxonomy) === 1 && trim($taxonomy[0]) === '') {
  1640. unset($header[$key][$taxkey]);
  1641. }
  1642. }
  1643. } else {
  1644. if (isset($input['toggleable_header'][$key]) && !$input['toggleable_header'][$key]) {
  1645. $header[$key] = null;
  1646. }
  1647. }
  1648. }
  1649. if ($clean_header) {
  1650. $header = Utils::arrayFilterRecursive($header, function ($k, $v) {
  1651. return !(null === $v || $v === '');
  1652. });
  1653. }
  1654. $page->header((object)$header);
  1655. $page->frontmatter(Yaml::dump((array)$page->header(), 20));
  1656. }
  1657. // Fill content last because it also renders the output.
  1658. if (isset($input['content'])) {
  1659. $page->rawMarkdown((string)$input['content']);
  1660. }
  1661. }
  1662. /**
  1663. * Save page as a new copy.
  1664. *
  1665. * @return bool True if the action was performed.
  1666. * @throws \RuntimeException
  1667. */
  1668. protected function taskCopy()
  1669. {
  1670. if (!$this->authorizeTask('copy page', ['admin.pages', 'admin.super'])) {
  1671. return false;
  1672. }
  1673. // Only applies to pages.
  1674. if ($this->view !== 'pages') {
  1675. return false;
  1676. }
  1677. try {
  1678. /** @var Pages $pages */
  1679. $pages = $this->grav['pages'];
  1680. // Get the current page.
  1681. $original_page = $this->admin->page(true);
  1682. // Find new parent page in order to build the path.
  1683. $parent = $original_page->parent() ?: $pages->root();
  1684. // Make a copy of the current page and fill the updated information into it.
  1685. $page = $original_page->copy($parent);
  1686. $order = 0;
  1687. if ($page->order()) {
  1688. $order = $this->getNextOrderInFolder($page->parent()->path());
  1689. }
  1690. // Make sure the header is loaded in case content was set through raw() (expert mode)
  1691. $page->header();
  1692. if ($page->order()) {
  1693. $page->order($order);
  1694. }
  1695. $folder = $this->findFirstAvailable('folder', $page);
  1696. $slug = $this->findFirstAvailable('slug', $page);
  1697. $page->path($page->parent()->path() . DS . $page->order() . $folder);
  1698. $page->route($page->parent()->route() . '/' . $slug);
  1699. $page->rawRoute($page->parent()->rawRoute() . '/' . $slug);
  1700. // Append progressive number to the copied page title
  1701. $match = preg_split('/(\d+)(?!.*\d)/', $original_page->title(), 2, PREG_SPLIT_DELIM_CAPTURE);
  1702. $header = $page->header();
  1703. if (!isset($match[1])) {
  1704. $header->title = $match[0] . ' 2';
  1705. } else {
  1706. $header->title = $match[0] . ((int)$match[1] + 1);
  1707. }
  1708. $page->header($header);
  1709. $page->save(false);
  1710. $redirect = $this->view . $page->rawRoute();
  1711. $header = $page->header();
  1712. if (isset($header->slug)) {
  1713. $match = preg_split('/-(\d+)$/', $header->slug, 2, PREG_SPLIT_DELIM_CAPTURE);
  1714. $header->slug = $match[0] . '-' . (isset($match[1]) ? (int)$match[1] + 1 : 2);
  1715. }
  1716. $page->header($header);
  1717. $page->save();
  1718. $this->grav->fireEvent('onAdminAfterSave', new Event(['page' => $page]));
  1719. // Enqueue message and redirect to new location.
  1720. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_COPIED'), 'info');
  1721. $this->setRedirect($redirect);
  1722. } catch (\Exception $e) {
  1723. throw new \RuntimeException('Copying page failed on error: ' . $e->getMessage());
  1724. }
  1725. return true;
  1726. }
  1727. /**
  1728. * Find the first available $item ('slug' | 'folder') for a page
  1729. * Used when copying a page, to determine the first available slot
  1730. *
  1731. * @param string $item
  1732. * @param PageInterface $page
  1733. *
  1734. * @return string The first available slot
  1735. */
  1736. protected function findFirstAvailable($item, PageInterface $page)
  1737. {
  1738. if (!$page->parent()->children()) {
  1739. return $page->{$item}();
  1740. }
  1741. $withoutPrefix = function ($string) {
  1742. $match = preg_split('/^[0-9]+\./u', $string, 2, PREG_SPLIT_DELIM_CAPTURE);
  1743. return $match[1] ?? $match[0];
  1744. };
  1745. $withoutPostfix = function ($string) {
  1746. $match = preg_split('/-(\d+)$/', $string, 2, PREG_SPLIT_DELIM_CAPTURE);
  1747. return $match[0];
  1748. };
  1749. /* $appendedNumber = function ($string) {
  1750. $match = preg_split('/-(\d+)$/', $string, 2, PREG_SPLIT_DELIM_CAPTURE);
  1751. $append = (isset($match[1]) ? (int)$match[1] + 1 : 2);
  1752. return $append;
  1753. };*/
  1754. $highest = 1;
  1755. $siblings = $page->parent()->children();
  1756. $findCorrectAppendedNumber = function ($item, $page_item, $highest) use (
  1757. $siblings,
  1758. &$findCorrectAppendedNumber,
  1759. &$withoutPrefix
  1760. ) {
  1761. foreach ($siblings as $sibling) {
  1762. if ($withoutPrefix($sibling->{$item}()) == ($highest === 1 ? $page_item : $page_item . '-' . $highest)) {
  1763. $highest = $findCorrectAppendedNumber($item, $page_item, $highest + 1);
  1764. return $highest;
  1765. }
  1766. }
  1767. return $highest;
  1768. };
  1769. $base = $withoutPrefix($withoutPostfix($page->$item()));
  1770. $return = $base;
  1771. $highest = $findCorrectAppendedNumber($item, $base, $highest);
  1772. if ($highest > 1) {
  1773. $return .= '-' . $highest;
  1774. }
  1775. return $return;
  1776. }
  1777. /**
  1778. * Reorder pages.
  1779. *
  1780. * @return bool True if the action was performed.
  1781. */
  1782. protected function taskReorder()
  1783. {
  1784. if (!$this->authorizeTask('reorder pages', ['admin.pages', 'admin.super'])) {
  1785. return false;
  1786. }
  1787. // Only applies to pages.
  1788. if ($this->view !== 'pages') {
  1789. return false;
  1790. }
  1791. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.REORDERING_WAS_SUCCESSFUL'), 'info');
  1792. return true;
  1793. }
  1794. /**
  1795. * Delete page.
  1796. *
  1797. * @return bool True if the action was performed.
  1798. * @throws \RuntimeException
  1799. */
  1800. protected function taskDelete()
  1801. {
  1802. if (!$this->authorizeTask('delete page', ['admin.pages', 'admin.super'])) {
  1803. return false;
  1804. }
  1805. // Only applies to pages.
  1806. if ($this->view !== 'pages') {
  1807. return false;
  1808. }
  1809. try {
  1810. $page = $this->admin->page();
  1811. if (count($page->translatedLanguages()) > 1) {
  1812. $page->file()->delete();
  1813. } else {
  1814. Folder::delete($page->path());
  1815. }
  1816. $this->grav->fireEvent('onAdminAfterDelete', new Event(['page' => $page]));
  1817. Cache::clearCache('invalidate');
  1818. // Set redirect to pages list.
  1819. $redirect = 'pages';
  1820. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_DELETED'), 'info');
  1821. $this->setRedirect($redirect);
  1822. } catch (\Exception $e) {
  1823. throw new \RuntimeException('Deleting page failed on error: ' . $e->getMessage());
  1824. }
  1825. return true;
  1826. }
  1827. /**
  1828. * Switch the content language. Optionally redirect to a different page.
  1829. *
  1830. */
  1831. protected function taskSwitchlanguage()
  1832. {
  1833. if (!$this->authorizeTask('switch language', ['admin.pages', 'admin.super'])) {
  1834. return false;
  1835. }
  1836. $data = (array)$this->data;
  1837. if (isset($data['lang'])) {
  1838. $language = $data['lang'];
  1839. } else {
  1840. $language = $this->grav['uri']->param('lang');
  1841. }
  1842. if (isset($data['redirect'])) {
  1843. $redirect = 'pages/' . $data['redirect'];
  1844. } else {
  1845. $redirect = 'pages';
  1846. }
  1847. if ($language) {
  1848. $this->grav['session']->admin_lang = $language ?: 'en';
  1849. }
  1850. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_SWITCHED_LANGUAGE'), 'info');
  1851. $admin_route = $this->admin->base;
  1852. $this->setRedirect('/' . $language . $admin_route . '/' . $redirect);
  1853. return true;
  1854. }
  1855. /**
  1856. * Handle direct install.
  1857. */
  1858. protected function taskDirectInstall()
  1859. {
  1860. if (!$this->authorizeTask('install', ['admin.super'])) {
  1861. return false;
  1862. }
  1863. $file_path = $this->data['file_path'] ?? null;
  1864. if (isset($_FILES['uploaded_file'])) {
  1865. // Check $_FILES['file']['error'] value.
  1866. switch ($_FILES['uploaded_file']['error']) {
  1867. case UPLOAD_ERR_OK:
  1868. break;
  1869. case UPLOAD_ERR_NO_FILE:
  1870. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.NO_FILES_SENT'), 'error');
  1871. return false;
  1872. case UPLOAD_ERR_INI_SIZE:
  1873. case UPLOAD_ERR_FORM_SIZE:
  1874. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.EXCEEDED_FILESIZE_LIMIT'), 'error');
  1875. return false;
  1876. case UPLOAD_ERR_NO_TMP_DIR:
  1877. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.UPLOAD_ERR_NO_TMP_DIR'), 'error');
  1878. return false;
  1879. default:
  1880. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.UNKNOWN_ERRORS'), 'error');
  1881. return false;
  1882. }
  1883. $file_name = $_FILES['uploaded_file']['name'];
  1884. $file_path = $_FILES['uploaded_file']['tmp_name'];
  1885. // Handle bad filenames.
  1886. if (!Utils::checkFilename($file_name)) {
  1887. $this->admin->json_response = [
  1888. 'status' => 'error',
  1889. 'message' => $this->admin::translate('PLUGIN_ADMIN.UNKNOWN_ERRORS')
  1890. ];
  1891. return false;
  1892. }
  1893. }
  1894. $result = Gpm::directInstall($file_path);
  1895. if ($result === true) {
  1896. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.INSTALLATION_SUCCESSFUL'), 'info');
  1897. } else {
  1898. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.INSTALLATION_FAILED') . ': ' . $result,
  1899. 'error');
  1900. }
  1901. $this->setRedirect('/tools');
  1902. return true;
  1903. }
  1904. /**
  1905. * Save the current page in a different language. Automatically switches to that language.
  1906. *
  1907. * @return bool True if the action was performed.
  1908. */
  1909. protected function taskSaveas()
  1910. {
  1911. if (!$this->authorizeTask('save', $this->dataPermissions())) {
  1912. return false;
  1913. }
  1914. $data = (array)$this->data;
  1915. $language = $data['lang'];
  1916. if ($language) {
  1917. $this->grav['session']->admin_lang = $language ?: 'en';
  1918. }
  1919. $uri = $this->grav['uri'];
  1920. $obj = $this->admin->page($uri->route());
  1921. $this->preparePage($obj, false, $language);
  1922. $file = $obj->file();
  1923. if ($file) {
  1924. $filename = $this->determineFilenameIncludingLanguage($obj->name(), $language);
  1925. $path = $obj->path() . DS . $filename;
  1926. $aFile = File::instance($path);
  1927. $aFile->save();
  1928. $aPage = new Page();
  1929. $aPage->init(new \SplFileInfo($path), $language . '.md');
  1930. $aPage->header($obj->header());
  1931. $aPage->rawMarkdown($obj->rawMarkdown());
  1932. $aPage->template($obj->template());
  1933. $aPage->validate();
  1934. $aPage->filter();
  1935. $this->grav->fireEvent('onAdminSave', new Event(['page' => &$aPage]));
  1936. $aPage->save();
  1937. $this->grav->fireEvent('onAdminAfterSave', new Event(['page' => $aPage]));
  1938. }
  1939. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_SWITCHED_LANGUAGE'), 'info');
  1940. $this->setRedirect('/' . $language . $uri->route());
  1941. return true;
  1942. }
  1943. /**
  1944. * The what should be the new filename when saving as a new language
  1945. *
  1946. * @param string $current_filename the current file name, including .md. Example: default.en.md
  1947. * @param string $language The new language it will be saved as. Example: 'it' or 'en-GB'.
  1948. *
  1949. * @return string The new filename. Example: 'default.it'
  1950. */
  1951. public function determineFilenameIncludingLanguage($current_filename, $language)
  1952. {
  1953. $ext = '.md';
  1954. $filename = substr($current_filename, 0, -strlen($ext));
  1955. $languages_enabled = $this->grav['config']->get('system.languages.supported', []);
  1956. $parts = explode('.', trim($filename, '.'));
  1957. $lang = array_pop($parts);
  1958. if ($lang === $language) {
  1959. return $filename . $ext;
  1960. } elseif (in_array($lang, $languages_enabled)) {
  1961. $filename = implode('.', $parts);
  1962. }
  1963. return $filename . '.' . $language . $ext;
  1964. }
  1965. protected function taskGetLevelListing()
  1966. {
  1967. $data = $this->getPost($_POST);
  1968. if (!isset($data['field'])) {
  1969. $json = [
  1970. 'status' => 'error',
  1971. 'message' => 'Bad Request'
  1972. ];
  1973. return $this->sendJsonResponse($json, 400);
  1974. }
  1975. // Base64 decode the route
  1976. $data['route'] = isset($data['route']) ? base64_decode($data['route']) : null;
  1977. $initial = $data['initial'] ?? null;
  1978. if ($initial) {
  1979. $data['leaf_route'] = $data['route'];
  1980. $data['route'] = null;
  1981. $data['level'] = 1;
  1982. }
  1983. [$status, $message, $response,] = $this->getLevelListing($data);
  1984. $json = [
  1985. 'status' => $status,
  1986. 'message' => $this->admin::translate($message ?? 'PLUGIN_ADMIN.NO_ROUTE_PROVIDED'),
  1987. 'data' => array_values($response)
  1988. ];
  1989. return $this->sendJsonResponse($json, 200);
  1990. }
  1991. protected function getLevelListing($data)
  1992. {
  1993. // Valid types are dir|file|link
  1994. $default_filters = ['type'=> ['root', 'dir'], 'name' => null, 'extension' => null];
  1995. $pages = $this->grav['pages'];
  1996. $pages_instances = $pages->instances();
  1997. $is_page = $data['page'] ?? true;
  1998. $route = $data['route'] ?? null;
  1999. $leaf_route = $data['leaf_route'] ?? null;
  2000. $sortby = $data['sortby'] ?? 'filename';
  2001. $order = $data['order'] ?? SORT_ASC;
  2002. $initial = $data['initial'] ?? null;
  2003. $filters = isset($data['filters']) ? $default_filters + json_decode($data['filters']) : $default_filters;
  2004. $filter_type = (array) $filters['type'];
  2005. $status = 'error';
  2006. $msg = null;
  2007. $response = [];
  2008. $children = null;
  2009. $sub_route = null;
  2010. $extra = null;
  2011. $root = false;
  2012. // Handle leaf_route
  2013. if ($leaf_route && $route !== $leaf_route) {
  2014. $nodes = explode('/', $leaf_route);
  2015. $sub_route = '/' . implode('/', array_slice($nodes, 1, $data['level']++));
  2016. $data['route'] = $sub_route;
  2017. [$status, $msg, $children, $extra] = $this->getLevelListing($data);
  2018. }
  2019. // Handle no route, assume page tree root
  2020. if (!$route) {
  2021. $is_page = false;
  2022. $route = $this->grav['locator']->findResource('page://', true);
  2023. $root = true;
  2024. }
  2025. if ($is_page) {
  2026. // Try the path
  2027. /** @var PageInterface $page */
  2028. $page = $pages->get(GRAV_ROOT . $route);
  2029. // Try a real route (like homepage)
  2030. if (is_null($page)) {
  2031. $page = $pages->find($route);
  2032. }
  2033. $path = $page ? $page->path() : null;
  2034. } else {
  2035. // Try a physical path
  2036. if (!Utils::startsWith($route, GRAV_ROOT)) {
  2037. $try_path = GRAV_ROOT . $route;
  2038. } else {
  2039. $try_path = $route;
  2040. }
  2041. $path = file_exists($try_path) ? $try_path : null;
  2042. }
  2043. $blueprintsData = $this->admin->page(true);
  2044. if (null !== $blueprintsData) {
  2045. if (method_exists($blueprintsData, 'blueprints')) {
  2046. $settings = $blueprintsData->blueprints()->schema()->getProperty($data['field']);
  2047. } elseif (method_exists($blueprintsData, 'getBlueprint')) {
  2048. $settings = $blueprintsData->getBlueprint()->schema()->getProperty($data['field']);
  2049. }
  2050. $filters = array_merge([], $filters, ($settings['filters'] ?? []));
  2051. $filter_type = $filters['type'] ?? $filter_type;
  2052. }
  2053. if ($path) {
  2054. /** @var \SplFileInfo $fileInfo */
  2055. $status = 'success';
  2056. $msg = 'PLUGIN_ADMIN.PAGE_ROUTE_FOUND';
  2057. foreach (new \DirectoryIterator($path) as $fileInfo) {
  2058. $fileName = $fileInfo->getFilename();
  2059. $filePath = str_replace('\\', '/', $fileInfo->getPathname());
  2060. if (($fileInfo->isDot() && $fileName !== '.' && $initial) || (Utils::startsWith($fileName, '.') && strlen($fileName) > 1)) {
  2061. continue;
  2062. }
  2063. if ($fileInfo->isDot()) {
  2064. if ($root) {
  2065. $payload = [
  2066. 'name' => '<root>',
  2067. 'value' => '',
  2068. 'item-key' => '',
  2069. 'filename' => '.',
  2070. 'extension' => '',
  2071. 'type' => 'root',
  2072. 'modified' => $fileInfo->getMTime(),
  2073. 'size' => 0,
  2074. 'has-children' => false
  2075. ];
  2076. } else {
  2077. continue;
  2078. }
  2079. } else {
  2080. $file_page = $pages_instances[$filePath] ?? null;
  2081. $file_path = Utils::replaceFirstOccurrence(GRAV_ROOT, '', $filePath);
  2082. $type = $fileInfo->getType();
  2083. $child_path = $file_page ? $file_page->path() : $filePath;
  2084. $count_children = Folder::countChildren($child_path);
  2085. $payload = [
  2086. 'name' => $file_page ? $file_page->title() : $fileName,
  2087. 'value' => $file_page ? $file_page->rawRoute() : $file_path,
  2088. 'item-key' => basename($file_page ? $file_page->route() : $file_path),
  2089. 'filename' => $fileName,
  2090. 'extension' => $type === 'dir' ? '' : $fileInfo->getExtension(),
  2091. 'type' => $type,
  2092. 'modified' => $fileInfo->getMTime(),
  2093. 'size' => $count_children,
  2094. 'symlink' => false,
  2095. 'has-children' => $count_children > 0
  2096. ];
  2097. }
  2098. // Fix for symlink
  2099. if ($payload['type'] === 'link') {
  2100. $payload['symlink'] = true;
  2101. $physical_path = $fileInfo->getRealPath();
  2102. $payload['type'] = is_dir($physical_path) ? 'dir' : 'file';
  2103. }
  2104. // filter types
  2105. if ($filters['type']) {
  2106. if (!in_array($payload['type'], $filter_type)) {
  2107. continue;
  2108. }
  2109. }
  2110. // Simple filter for name or extension
  2111. if (($filters['name'] && Utils::contains($payload['basename'], $filters['name'])) ||
  2112. ($filters['extension'] && Utils::contains($payload['extension'], $filters['extension']))) {
  2113. continue;
  2114. }
  2115. // Add children if any
  2116. if ($filePath === $extra && is_array($children)) {
  2117. $payload['children'] = array_values($children);
  2118. }
  2119. $response[] = $payload;
  2120. }
  2121. } else {
  2122. $msg = 'PLUGIN_ADMIN.PAGE_ROUTE_NOT_FOUND';
  2123. }
  2124. // Sorting
  2125. $response = Utils::sortArrayByKey($response, $sortby, $order);
  2126. $temp_array = [];
  2127. foreach ($response as $index => $item) {
  2128. $temp_array[$item['type']][$index] = $item;
  2129. }
  2130. $sorted = Utils::sortArrayByArray($temp_array, $filter_type);
  2131. $response = Utils::arrayFlatten($sorted);
  2132. return [$status, $this->admin::translate($msg ?? 'PLUGIN_ADMIN.NO_ROUTE_PROVIDED'), $response, $path];
  2133. }
  2134. protected function taskConvertUrls()
  2135. {
  2136. $data = $this->getPost($_POST);
  2137. $converted_links = [];
  2138. $converted_images = [];
  2139. $status = 'success';
  2140. $message = 'All links converted';
  2141. $data['route'] = isset($data['route']) ? base64_decode($data['route']) : null;
  2142. $data['data'] = json_decode($data['data'] ?? '{}', true);
  2143. // use the route if passed, else use current page in admin as reference
  2144. $page_route = $data['route'] ?? $this->admin->page(true);
  2145. /** @var PageInterface */
  2146. $page = $this->grav['pages']->find($page_route);
  2147. if (!$page) {
  2148. $json = [
  2149. 'status' => 'error',
  2150. 'message' => 'Page Not Found'
  2151. ];
  2152. return $this->sendJsonResponse($json, 404);
  2153. }
  2154. if (!isset($data['data'])) {
  2155. $json = [
  2156. 'status' => 'error',
  2157. 'message' => 'Bad Request'
  2158. ];
  2159. return $this->sendJsonResponse($json, 400);
  2160. }
  2161. foreach ($data['data']['a'] ?? [] as $link) {
  2162. $converted_links[$link] = Excerpts::processLinkHtml($link, $page);
  2163. }
  2164. foreach ($data['data']['img'] ?? [] as $image) {
  2165. $converted_images[$image] = Excerpts::processImageHtml($image, $page);
  2166. }
  2167. $json = [
  2168. 'status' => $status,
  2169. 'message' => $message,
  2170. 'data' => ['links' => $converted_links, 'images' => $converted_images]
  2171. ];
  2172. return $this->sendJsonResponse($json, 200);
  2173. }
  2174. }