admincontroller.php 72 KB

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