admincontroller.php 75 KB

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