admincontroller.php 73 KB

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