admincontroller.php 76 KB

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