admincontroller.php 74 KB

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