admincontroller.php 71 KB

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