admincontroller.php 74 KB

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