admincontroller.php 76 KB

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