AdminController.php 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044
  1. <?php
  2. namespace Grav\Plugin\Admin;
  3. use Grav\Common\Backup\Backups;
  4. use Grav\Common\Cache;
  5. use Grav\Common\Config\Config;
  6. use Grav\Common\Debugger;
  7. use Grav\Common\File\CompiledYamlFile;
  8. use Grav\Common\Filesystem\Folder;
  9. use Grav\Common\Flex\Types\Pages\PageIndex;
  10. use Grav\Common\GPM\GPM as GravGPM;
  11. use Grav\Common\GPM\Installer;
  12. use Grav\Common\Grav;
  13. use Grav\Common\Data;
  14. use Grav\Common\Helpers\Excerpts;
  15. use Grav\Common\Language\Language;
  16. use Grav\Common\Page\Interfaces\PageInterface;
  17. use Grav\Common\Page\Media;
  18. use Grav\Common\Page\Medium\ImageMedium;
  19. use Grav\Common\Page\Medium\Medium;
  20. use Grav\Common\Page\Page;
  21. use Grav\Common\Page\Pages;
  22. use Grav\Common\Page\Collection;
  23. use Grav\Common\Security;
  24. use Grav\Common\User\Interfaces\UserCollectionInterface;
  25. use Grav\Common\User\Interfaces\UserInterface;
  26. use Grav\Common\Utils;
  27. use Grav\Framework\Flex\Flex;
  28. use Grav\Framework\Psr7\Response;
  29. use Grav\Framework\RequestHandler\Exception\RequestException;
  30. use Grav\Plugin\Login\TwoFactorAuth\TwoFactorAuth;
  31. use Grav\Common\Yaml;
  32. use PicoFeed\Parser\MalformedXmlException;
  33. use Psr\Http\Message\ResponseInterface;
  34. use RocketTheme\Toolbox\Event\Event;
  35. use RocketTheme\Toolbox\File\File;
  36. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  37. use Twig\Loader\FilesystemLoader;
  38. /**
  39. * Class AdminController
  40. *
  41. * @package Grav\Plugin
  42. */
  43. class AdminController extends AdminBaseController
  44. {
  45. /**
  46. * @param Grav|null $grav
  47. * @param string|null $view
  48. * @param string|null $task
  49. * @param string|null $route
  50. * @param array|null $post
  51. * @return void
  52. */
  53. public function initialize(Grav $grav = null, $view = null, $task = null, $route = null, $post = null)
  54. {
  55. $this->grav = $grav;
  56. $this->admin = $this->grav['admin'];
  57. $this->view = $view;
  58. $this->task = $task ?: 'display';
  59. if (isset($post['data'])) {
  60. $this->data = $this->getPost($post['data']);
  61. unset($post['data']);
  62. } else {
  63. // Backwards compatibility for Form plugin <= 1.2
  64. $this->data = $this->getPost($post);
  65. }
  66. $this->post = $this->getPost($post);
  67. $this->route = $route;
  68. $this->grav->fireEvent('onAdminControllerInit', new Event(['controller' => &$this]));
  69. }
  70. // GENERAL TASKS
  71. /**
  72. * Keep alive
  73. *
  74. * Route: POST /task:keepAlive (AJAX call)
  75. *
  76. * @return void
  77. */
  78. protected function taskKeepAlive(): void
  79. {
  80. // This task is available for all admin users.
  81. $response = new Response(200);
  82. $this->close($response);
  83. }
  84. /**
  85. * Clear the cache.
  86. *
  87. * Route: GET /cache.json/task:clearCache (AJAX call)
  88. *
  89. * @return bool True if the action was performed.
  90. */
  91. protected function taskClearCache()
  92. {
  93. if (!$this->authorizeTask('clear cache', ['admin.cache', 'admin.maintenance', 'admin.super'])) {
  94. $this->admin->json_response = [
  95. 'status' => 'error',
  96. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  97. ];
  98. return false;
  99. }
  100. // get optional cleartype param
  101. $clear_type = $this->grav['uri']->param('cleartype');
  102. if ($clear_type) {
  103. $clear = $clear_type;
  104. } else {
  105. $clear = 'standard';
  106. }
  107. if ($clear === 'purge') {
  108. $msg = Cache::purgeJob();
  109. $this->admin->json_response = [
  110. 'status' => 'success',
  111. 'message' => $msg,
  112. ];
  113. } else {
  114. $results = Cache::clearCache($clear);
  115. if (count($results) > 0) {
  116. $this->admin->json_response = [
  117. 'status' => 'success',
  118. 'message' => $this->admin::translate('PLUGIN_ADMIN.CACHE_CLEARED') . ' <br />' . $this->admin::translate('PLUGIN_ADMIN.METHOD') . ': ' . $clear . ''
  119. ];
  120. } else {
  121. $this->admin->json_response = [
  122. 'status' => 'error',
  123. 'message' => $this->admin::translate('PLUGIN_ADMIN.ERROR_CLEARING_CACHE')
  124. ];
  125. }
  126. }
  127. return true;
  128. }
  129. /**
  130. * Handles form and saves the input data if its valid.
  131. *
  132. * Route: POST /pages?task:save
  133. * Route: POST /user?task:save
  134. * Route: POST /*?task:save
  135. *
  136. * @return bool True if the action was performed.
  137. */
  138. public function taskSave()
  139. {
  140. if (!$this->authorizeTask('save', $this->dataPermissions())) {
  141. return false;
  142. }
  143. $this->grav['twig']->twig_vars['current_form_data'] = (array)$this->data;
  144. switch ($this->view) {
  145. case 'pages':
  146. // Not used if Flex-Objects plugin handles pages.
  147. return $this->savePage();
  148. case 'user':
  149. // Not used if Flex-Objects plugin handles users.
  150. return $this->saveUser();
  151. default:
  152. if ($this->saveDefault()) {
  153. $route = $this->grav['uri']::getCurrentRoute();
  154. $this->setRedirect($route->withGravParam('task', null)->toString(), 302);
  155. $this->redirect();
  156. }
  157. return false;
  158. }
  159. }
  160. /**
  161. * @return bool
  162. */
  163. protected function saveDefault()
  164. {
  165. try {
  166. // Handle standard data types.
  167. $type = $this->getDataType();
  168. $obj = $this->admin->getConfigurationData($type, $this->data);
  169. $obj->validate();
  170. } catch (\Exception $e) {
  171. /** @var Debugger $debugger */
  172. $debugger = $this->grav['debugger'];
  173. $debugger->addException($e);
  174. $this->admin->setMessage($e->getMessage(), 'error');
  175. return false;
  176. }
  177. $obj->filter(false, true);
  178. $obj = $this->storeFiles($obj);
  179. if ($obj) {
  180. // Event to manipulate data before saving the object
  181. $this->grav->fireEvent('onAdminSave', new Event(['object' => &$obj]));
  182. $obj->save();
  183. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_SAVED'), 'info');
  184. $this->grav->fireEvent('onAdminAfterSave', new Event(['object' => $obj]));
  185. }
  186. Cache::clearCache('invalidate');
  187. // Force configuration reload.
  188. /** @var Config $config */
  189. $config = $this->grav['config'];
  190. $config->reload();
  191. if ($this->view === 'config') {
  192. $this->setRedirect($this->admin->getAdminRoute("/{$this->view}/{$this->route}")->toString());
  193. }
  194. return true;
  195. }
  196. // USER TASKS
  197. /**
  198. * Handle logout.
  199. *
  200. * Route: GET /task:logout
  201. * Route: POST ?task=logout
  202. *
  203. * @return bool True if the action was performed.
  204. */
  205. protected function taskLogout()
  206. {
  207. if (!$this->authorizeTask('logout', ['admin.login', 'admin.super'])) {
  208. return false;
  209. }
  210. $this->admin->logout($this->data, $this->post);
  211. }
  212. /**
  213. * Route: POST /ajax.json/task:regenerate2FASecret (AJAX call)
  214. *
  215. * @return bool
  216. */
  217. public function taskRegenerate2FASecret()
  218. {
  219. if (!$this->authorizeTask('regenerate 2FA Secret', ['admin.login', 'admin.super'])) {
  220. $this->admin->json_response = [
  221. 'status' => 'error',
  222. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  223. ];
  224. return false;
  225. }
  226. try {
  227. /** @var UserInterface $user */
  228. $user = $this->grav['user'];
  229. /** @var TwoFactorAuth $twoFa */
  230. $twoFa = $this->grav['login']->twoFactorAuth();
  231. $secret = $twoFa->createSecret();
  232. $image = $twoFa->getQrImageData($user->username, $secret);
  233. $user->set('twofa_secret', $secret);
  234. // TODO: data user can also use save, but please test it before removing this code.
  235. if ($user instanceof \Grav\Common\User\DataUser\User) {
  236. // Save secret into the user file.
  237. $file = $user->file();
  238. if ($file->exists()) {
  239. $content = (array)$file->content();
  240. $content['twofa_secret'] = $secret;
  241. $file->save($content);
  242. $file->free();
  243. }
  244. } else {
  245. $user->save();
  246. }
  247. $this->admin->json_response = ['status' => 'success', 'image' => $image, 'secret' => preg_replace('|(\w{4})|', '\\1 ', $secret)];
  248. } catch (\Exception $e) {
  249. /** @var Debugger $debugger */
  250. $debugger = $this->grav['debugger'];
  251. $debugger->addException($e);
  252. $this->admin->json_response = ['status' => 'error', 'message' => htmlspecialchars($e->getMessage(), ENT_QUOTES | ENT_HTML5, 'UTF-8')];
  253. return false;
  254. }
  255. return true;
  256. }
  257. /**
  258. * Save user account.
  259. *
  260. * Called by more general save task.
  261. *
  262. * @note Not used if Flex-Objects plugin handles users.
  263. *
  264. * @return bool
  265. */
  266. protected function saveUser()
  267. {
  268. /** @var UserCollectionInterface $users */
  269. $users = $this->grav['accounts'];
  270. $user = $users->load($this->admin->route);
  271. if (!$this->admin->authorize(['admin.super', 'admin.users'])) {
  272. // no user file or not admin.super or admin.users
  273. if ($user->username !== $this->grav['user']->username) {
  274. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' save.','error');
  275. return false;
  276. }
  277. }
  278. /** @var Data\Blueprint $blueprint */
  279. $blueprint = $user->blueprints();
  280. $data = $blueprint->processForm($this->admin->cleanUserPost((array)$this->data));
  281. $data = new Data\Data($data, $blueprint);
  282. try {
  283. $data->validate();
  284. $data->filter();
  285. } catch (\Exception $e) {
  286. /** @var Debugger $debugger */
  287. $debugger = $this->grav['debugger'];
  288. $debugger->addException($e);
  289. $this->admin->setMessage($e->getMessage(), 'error');
  290. return false;
  291. }
  292. $user->update($data->toArray());
  293. $user = $this->storeFiles($user);
  294. if ($user) {
  295. // Event to manipulate data before saving the object
  296. $this->grav->fireEvent('onAdminSave', new Event(['object' => &$user]));
  297. $user->save();
  298. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_SAVED'), 'info');
  299. $this->grav->fireEvent('onAdminAfterSave', new Event(['object' => $user]));
  300. }
  301. if ($user->username === $this->grav['user']->username) {
  302. /** @var UserCollectionInterface $users */
  303. $users = $this->grav['accounts'];
  304. //Editing current user. Reload user object
  305. $this->grav['user']->undef('avatar');
  306. $this->grav['user']->merge($users->load($this->admin->route)->toArray());
  307. }
  308. return true;
  309. }
  310. // DASHBOARD TASKS
  311. /**
  312. * Get Notifications
  313. *
  314. * Route: POST /task:getNotifications (AJAX call)
  315. *
  316. * @return bool
  317. */
  318. protected function taskGetNotifications()
  319. {
  320. if (!$this->authorizeTask('dashboard', ['admin.login', 'admin.super'])) {
  321. $this->admin->json_response = [
  322. 'status' => 'error',
  323. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  324. ];
  325. return false;
  326. }
  327. // do we need to force a reload
  328. $refresh = $this->data['refresh'] === 'true';
  329. $filter = $this->data['filter'] ?? '';
  330. $filter_types = !empty($filter) ? array_map('trim', explode(',', $filter)) : [];
  331. try {
  332. $notifications = $this->admin->getNotifications($refresh);
  333. $notification_data = [];
  334. foreach ($notifications as $type => $type_notifications) {
  335. if ($filter_types && in_array($type, $filter_types, true)) {
  336. $twig_template = 'partials/notification-' . $type . '-block.html.twig';
  337. $notification_data[$type] = $this->grav['twig']->processTemplate($twig_template, ['notifications' => $type_notifications]);
  338. }
  339. }
  340. $json_response = [
  341. 'status' => 'success',
  342. 'notifications' => $notification_data
  343. ];
  344. } catch (\Exception $e) {
  345. /** @var Debugger $debugger */
  346. $debugger = $this->grav['debugger'];
  347. $debugger->addException($e);
  348. $json_response = ['status' => 'error', 'message' => htmlspecialchars($e->getMessage(), ENT_QUOTES | ENT_HTML5, 'UTF-8')];
  349. }
  350. $this->sendJsonResponse($json_response);
  351. }
  352. /**
  353. * Hide notifications.
  354. *
  355. * Route: POST /notifications.json/task:hideNotification/notification_id:ID (AJAX call)
  356. *
  357. * @return bool True if the action was performed.
  358. */
  359. protected function taskHideNotification()
  360. {
  361. if (!$this->authorizeTask('hide notification', ['admin.login', 'admin.super'])) {
  362. $this->admin->json_response = [
  363. 'status' => 'error',
  364. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  365. ];
  366. return false;
  367. }
  368. $notification_id = $this->grav['uri']->param('notification_id');
  369. if (!$notification_id) {
  370. $this->admin->json_response = [
  371. 'status' => 'error'
  372. ];
  373. return false;
  374. }
  375. $filename = $this->grav['locator']->findResource('user://data/notifications/' . $this->grav['user']->username . YAML_EXT, true, true);
  376. $file = CompiledYamlFile::instance($filename);
  377. $data = (array)$file->content();
  378. $date = new \DateTime();
  379. $data[$notification_id] = $date->format('r');
  380. $file->save($data);
  381. $this->admin->json_response = [
  382. 'status' => 'success'
  383. ];
  384. return true;
  385. }
  386. /**
  387. * Get Newsfeeds
  388. *
  389. * Route: POST /ajax.json/task:getNewsFeed (AJAX call)
  390. *
  391. * @return bool
  392. */
  393. protected function taskGetNewsFeed()
  394. {
  395. if (!$this->authorizeTask('dashboard', ['admin.login', 'admin.super'])) {
  396. $this->admin->json_response = [
  397. 'status' => 'error',
  398. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  399. ];
  400. return false;
  401. }
  402. $refresh = $this->data['refresh'] === 'true' ? true : false;
  403. try {
  404. $feed = $this->admin->getFeed($refresh);
  405. $feed_data = $this->grav['twig']->processTemplate('partials/feed-block.html.twig', ['feed' => $feed]);
  406. $json_response = [
  407. 'status' => 'success',
  408. 'feed_data' => $feed_data
  409. ];
  410. } catch (MalformedXmlException $e) {
  411. /** @var Debugger $debugger */
  412. $debugger = $this->grav['debugger'];
  413. $debugger->addException($e);
  414. $json_response = ['status' => 'error', 'message' => htmlspecialchars($e->getMessage(), ENT_QUOTES | ENT_HTML5, 'UTF-8')];
  415. }
  416. $this->sendJsonResponse($json_response);
  417. }
  418. // BACKUP TASKS
  419. /**
  420. * Handle the backup action
  421. *
  422. * Route: GET /backup.json/id:BACKUP_ID/task:backup (AJAX call)
  423. *
  424. * @return bool True if the action was performed.
  425. */
  426. protected function taskBackup()
  427. {
  428. if (!$this->authorizeTask('backup', ['admin.maintenance', 'admin.super'])) {
  429. $this->admin->json_response = [
  430. 'status' => 'error',
  431. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  432. ];
  433. return false;
  434. }
  435. $param_sep = $this->grav['config']->get('system.param_sep', ':');
  436. $download = $this->grav['uri']->param('download');
  437. try {
  438. if ($download) {
  439. $filename = basename(base64_decode(urldecode($download)));
  440. $file = $this->grav['locator']->findResource("backup://{$filename}", true);
  441. if (!$file || !Utils::endsWith($filename, '.zip', false)) {
  442. header('HTTP/1.1 401 Unauthorized');
  443. exit();
  444. }
  445. Utils::download($file, true);
  446. }
  447. $id = $this->grav['uri']->param('id', 0);
  448. $backup = Backups::backup($id);
  449. } catch (\Exception $e) {
  450. /** @var Debugger $debugger */
  451. $debugger = $this->grav['debugger'];
  452. $debugger->addException($e);
  453. $this->admin->json_response = [
  454. 'status' => 'error',
  455. 'message' => $this->admin::translate('PLUGIN_ADMIN.AN_ERROR_OCCURRED') . '. ' . htmlspecialchars($e->getMessage(), ENT_QUOTES | ENT_HTML5, 'UTF-8')
  456. ];
  457. return true;
  458. }
  459. $download = urlencode(base64_encode($backup));
  460. $url = rtrim($this->grav['uri']->rootUrl(false), '/') . '/' . trim($this->admin->base,
  461. '/') . '/task' . $param_sep . 'backup/download' . $param_sep . $download . '/admin-nonce' . $param_sep . Utils::getNonce('admin-form');
  462. $this->admin->json_response = [
  463. 'status' => 'success',
  464. '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>',
  465. 'toastr' => [
  466. 'timeOut' => 0,
  467. 'extendedTimeOut' => 0,
  468. 'closeButton' => true
  469. ]
  470. ];
  471. return true;
  472. }
  473. /**
  474. * Handle delete backup action
  475. *
  476. * Route: GET /backup.json/backup:BACKUP_FILE/task:backupDelete (AJAX call)
  477. *
  478. * @return bool
  479. */
  480. protected function taskBackupDelete()
  481. {
  482. if (!$this->authorizeTask('backup', ['admin.maintenance', 'admin.super'])) {
  483. $this->admin->json_response = [
  484. 'status' => 'error',
  485. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  486. ];
  487. return false;
  488. }
  489. $backup = $this->grav['uri']->param('backup', null);
  490. if (null !== $backup) {
  491. $filename = basename(base64_decode(urldecode($backup)));
  492. $file = $this->grav['locator']->findResource("backup://{$filename}", true);
  493. if ($file && Utils::endsWith($filename, '.zip', false)) {
  494. unlink($file);
  495. $this->admin->json_response = [
  496. 'status' => 'success',
  497. 'message' => $this->admin::translate('PLUGIN_ADMIN.BACKUP_DELETED'),
  498. 'toastr' => [
  499. 'closeButton' => true
  500. ]
  501. ];
  502. return true;
  503. }
  504. }
  505. $this->admin->json_response = [
  506. 'status' => 'error',
  507. 'message' => $this->admin::translate('PLUGIN_ADMIN.BACKUP_NOT_FOUND'),
  508. ];
  509. return true;
  510. }
  511. // PLUGIN / THEME TASKS
  512. /**
  513. * Enable a plugin.
  514. *
  515. * Route: GET /plugins/SLUG/task:enable
  516. *
  517. * @return bool True if the action was performed.
  518. */
  519. public function taskEnable()
  520. {
  521. if ($this->view !== 'plugins') {
  522. return false;
  523. }
  524. if (!$this->authorizeTask('enable plugin', ['admin.plugins', 'admin.super'])) {
  525. return false;
  526. }
  527. // Filter value and save it.
  528. $this->post = ['enabled' => true];
  529. $obj = $this->prepareData($this->post);
  530. $obj->save();
  531. $this->post = ['_redirect' => 'plugins'];
  532. if ($this->grav['uri']->param('redirect')) {
  533. $this->post = ['_redirect' => 'plugins/' . $this->route];
  534. }
  535. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_ENABLED_PLUGIN'), 'info');
  536. Cache::clearCache('invalidate');
  537. return true;
  538. }
  539. /**
  540. * Disable a plugin.
  541. *
  542. * Route: GET /plugins/SLUG/task:disable
  543. *
  544. * @return bool True if the action was performed.
  545. */
  546. public function taskDisable()
  547. {
  548. if ($this->view !== 'plugins') {
  549. return false;
  550. }
  551. if (!$this->authorizeTask('disable plugin', ['admin.plugins', 'admin.super'])) {
  552. return false;
  553. }
  554. // Filter value and save it.
  555. $this->post = ['enabled' => false];
  556. $obj = $this->prepareData($this->post);
  557. $obj->save();
  558. $this->post = ['_redirect' => 'plugins'];
  559. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_DISABLED_PLUGIN'), 'info');
  560. Cache::clearCache('invalidate');
  561. return true;
  562. }
  563. /**
  564. * Set the default theme.
  565. *
  566. * Route: GET /themes/SLUG/task:activate
  567. *
  568. * @return bool True if the action was performed.
  569. */
  570. public function taskActivate()
  571. {
  572. if ($this->view !== 'themes') {
  573. return false;
  574. }
  575. if (!$this->authorizeTask('activate theme', ['admin.themes', 'admin.super'])) {
  576. return false;
  577. }
  578. $this->post = ['_redirect' => 'themes' ];
  579. // Make sure theme exists (throws exception)
  580. $name = $this->route;
  581. $this->grav['themes']->get($name);
  582. // Store system configuration.
  583. $system = $this->admin->getConfigurationData('config/system');
  584. $system->set('pages.theme', $name);
  585. $system->save();
  586. // Force configuration reload and save.
  587. /** @var Config $config */
  588. $config = $this->grav['config'];
  589. $config->reload()->save();
  590. $config->set('system.pages.theme', $name);
  591. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_CHANGED_THEME'), 'info');
  592. Cache::clearCache('invalidate');
  593. $this->post = ['_redirect' => 'themes/' . $name ];
  594. return true;
  595. }
  596. // INSTALL & UPGRADE
  597. /**
  598. * Handles updating Grav
  599. *
  600. * Route: GET /update.json/task:updategrav (AJAX call)
  601. *
  602. * @return bool False if user has no permissions.
  603. */
  604. public function taskUpdategrav()
  605. {
  606. if (!$this->authorizeTask('install grav', ['admin.super'])) {
  607. $this->admin->json_response = [
  608. 'status' => 'error',
  609. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  610. ];
  611. return false;
  612. }
  613. $gpm = Gpm::GPM();
  614. $version = $gpm->grav->getVersion();
  615. $result = Gpm::selfupgrade();
  616. if ($result) {
  617. $json_response = [
  618. 'status' => 'success',
  619. 'type' => 'updategrav',
  620. 'version' => $version,
  621. 'message' => $this->admin::translate('PLUGIN_ADMIN.GRAV_WAS_SUCCESSFULLY_UPDATED_TO') . ' ' . $version
  622. ];
  623. } else {
  624. $json_response = [
  625. 'status' => 'error',
  626. 'type' => 'updategrav',
  627. 'version' => GRAV_VERSION,
  628. 'message' => $this->admin::translate('PLUGIN_ADMIN.GRAV_UPDATE_FAILED') . ' <br>' . Installer::lastErrorMsg()
  629. ];
  630. }
  631. $this->sendJsonResponse($json_response);
  632. }
  633. /**
  634. * Handles uninstalling plugins and themes
  635. *
  636. * @return bool True if the action was performed
  637. * @deprecated Not being used anymore
  638. */
  639. public function taskUninstall()
  640. {
  641. $type = $this->view;
  642. if ($type !== 'plugins' && $type !== 'themes') {
  643. return false;
  644. }
  645. if (!$this->authorizeTask('uninstall ' . $type, ['admin.' . $type, 'admin.super'])) {
  646. return false;
  647. }
  648. $package = $this->route;
  649. $result = Gpm::uninstall($package, []);
  650. if ($result) {
  651. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.UNINSTALL_SUCCESSFUL'), 'info');
  652. } else {
  653. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.UNINSTALL_FAILED'), 'error');
  654. }
  655. $this->post = ['_redirect' => $this->view];
  656. return true;
  657. }
  658. /**
  659. * Toggle the gpm.releases setting
  660. *
  661. * Route: POST /ajax.json/task:gpmRelease (AJAX call)
  662. *
  663. * @return bool
  664. */
  665. protected function taskGpmRelease()
  666. {
  667. if (!$this->authorizeTask('configuration', ['admin.super'])) {
  668. $this->admin->json_response = [
  669. 'status' => 'error',
  670. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  671. ];
  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. * Get update status from GPM
  700. *
  701. * Request: POST /update.json/task:getUpdates (AJAX call)
  702. *
  703. * @return bool
  704. */
  705. protected function taskGetUpdates()
  706. {
  707. if ($this->view !== 'update') {
  708. return false;
  709. }
  710. if (!$this->authorizeTask('dashboard', ['admin.plugins', 'admin.themes', 'admin.super'])) {
  711. $this->admin->json_response = [
  712. 'status' => 'error',
  713. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  714. ];
  715. return false;
  716. }
  717. $data = $this->post;
  718. $flush = !empty($data['flush']);
  719. if (isset($this->grav['session'])) {
  720. $this->grav['session']->close();
  721. }
  722. try {
  723. $gpm = new GravGPM($flush);
  724. $resources_updates = $gpm->getUpdatable();
  725. foreach ($resources_updates as $key => $update) {
  726. if (!is_iterable($update)) {
  727. continue;
  728. }
  729. foreach ($update as $slug => $item) {
  730. $resources_updates[$key][$slug] = $item;
  731. }
  732. }
  733. if ($gpm->grav !== null) {
  734. $grav_updates = [
  735. 'isUpdatable' => $gpm->grav->isUpdatable(),
  736. 'assets' => $gpm->grav->getAssets(),
  737. 'version' => GRAV_VERSION,
  738. 'available' => $gpm->grav->getVersion(),
  739. 'date' => $gpm->grav->getDate(),
  740. 'isSymlink' => $gpm->grav->isSymlink()
  741. ];
  742. $this->admin->json_response = [
  743. 'status' => 'success',
  744. 'payload' => [
  745. 'resources' => $resources_updates,
  746. 'grav' => $grav_updates,
  747. 'installed' => $gpm->countInstalled(),
  748. 'flushed' => $flush
  749. ]
  750. ];
  751. } else {
  752. $this->admin->json_response = ['status' => 'error', 'message' => 'Cannot connect to the GPM'];
  753. return false;
  754. }
  755. } catch (\Exception $e) {
  756. /** @var Debugger $debugger */
  757. $debugger = $this->grav['debugger'];
  758. $debugger->addException($e);
  759. $this->admin->json_response = ['status' => 'error', 'message' => htmlspecialchars($e->getMessage(), ENT_QUOTES | ENT_HTML5, 'UTF-8')];
  760. return false;
  761. }
  762. return true;
  763. }
  764. /**
  765. * Handle getting a new package dependencies needed to be installed.
  766. *
  767. * Route: /plugins.json/task:getPackagesDependencies (AJAX call)
  768. * Route: /themes.json/task:getPackagesDependencies (AJAX call)
  769. *
  770. * @return bool
  771. */
  772. protected function taskGetPackagesDependencies()
  773. {
  774. $type = $this->view;
  775. if ($type !== 'plugins' && $type !== 'themes') {
  776. return false;
  777. }
  778. if (!$this->authorizeTask('get package dependencies', ['admin.' . $type, 'admin.super'])) {
  779. $this->admin->json_response = [
  780. 'status' => 'error',
  781. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  782. ];
  783. return false;
  784. }
  785. $data = $this->post;
  786. $packages = isset($data['packages']) ? explode(',', $data['packages']) : '';
  787. $packages = (array)$packages;
  788. try {
  789. $this->admin->checkPackagesCanBeInstalled($packages);
  790. $dependencies = $this->admin->getDependenciesNeededToInstall($packages);
  791. } catch (\Exception $e) {
  792. /** @var Debugger $debugger */
  793. $debugger = $this->grav['debugger'];
  794. $debugger->addException($e);
  795. $this->admin->json_response = ['status' => 'error', 'message' => htmlspecialchars($e->getMessage(), ENT_QUOTES | ENT_HTML5, 'UTF-8')];
  796. return false;
  797. }
  798. $this->admin->json_response = ['status' => 'success', 'dependencies' => $dependencies];
  799. return true;
  800. }
  801. /**
  802. * Route: /plugins.json/task:installDependenciesOfPackages (AJAX call)
  803. * Route: /themes.json/task:installDependenciesOfPackages (AJAX call)
  804. *
  805. * @return bool
  806. */
  807. protected function taskInstallDependenciesOfPackages()
  808. {
  809. $type = $this->view;
  810. if ($type !== 'plugins' && $type !== 'themes') {
  811. return false;
  812. }
  813. if (!$this->authorizeTask('install dependencies', ['admin.' . $type, 'admin.super'])) {
  814. $this->admin->json_response = [
  815. 'status' => 'error',
  816. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  817. ];
  818. return false;
  819. }
  820. $data = $this->post;
  821. $packages = isset($data['packages']) ? explode(',', $data['packages']) : '';
  822. $packages = (array)$packages;
  823. try {
  824. $dependencies = $this->admin->getDependenciesNeededToInstall($packages);
  825. } catch (\Exception $e) {
  826. /** @var Debugger $debugger */
  827. $debugger = $this->grav['debugger'];
  828. $debugger->addException($e);
  829. $this->admin->json_response = ['status' => 'error', 'message' => htmlspecialchars($e->getMessage(), ENT_QUOTES | ENT_HTML5, 'UTF-8')];
  830. return false;
  831. }
  832. $result = Gpm::install(array_keys($dependencies), ['theme' => $type === 'themes']);
  833. if ($result) {
  834. $this->admin->json_response = ['status' => 'success', 'message' => 'Dependencies installed successfully'];
  835. } else {
  836. $this->admin->json_response = [
  837. 'status' => 'error',
  838. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSTALLATION_FAILED')
  839. ];
  840. }
  841. return true;
  842. }
  843. /**
  844. * Route: /plugins.json/task:installPackage (AJAX call)
  845. * Route: /themes.json/task:installPackage (AJAX call)
  846. *
  847. * @param bool $reinstall
  848. * @return bool
  849. */
  850. protected function taskInstallPackage($reinstall = false)
  851. {
  852. $type = $this->view;
  853. if ($type !== 'plugins' && $type !== 'themes') {
  854. return false;
  855. }
  856. if (!$this->authorizeTask('install ' . $type, ['admin.' . $type, 'admin.super'])) {
  857. $this->admin->json_response = [
  858. 'status' => 'error',
  859. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  860. ];
  861. return false;
  862. }
  863. $data = $this->post;
  864. $package = $data['package'] ?? '';
  865. try {
  866. $result = Gpm::install($package, ['theme' => $type === 'themes']);
  867. } catch (\Exception $e) {
  868. /** @var Debugger $debugger */
  869. $debugger = $this->grav['debugger'];
  870. $debugger->addException($e);
  871. $msg = $e->getMessage();
  872. $msg = Utils::contains($msg, '401 Unauthorized') ? "ERROR: License key for this resource is invalid." : $msg;
  873. $msg = Utils::contains($msg, '404 Not Found') ? "ERROR: Resource not found" : $msg;
  874. $this->admin->json_response = ['status' => 'error', 'message' => htmlspecialchars($msg, ENT_QUOTES | ENT_HTML5, 'UTF-8')];
  875. return false;
  876. }
  877. if ($result) {
  878. $this->admin->json_response = [
  879. 'status' => 'success',
  880. 'message' => $this->admin::translate(is_string($result) ? $result : sprintf($this->admin::translate($reinstall ?: 'PLUGIN_ADMIN.PACKAGE_X_REINSTALLED_SUCCESSFULLY',
  881. null), $package))
  882. ];
  883. } else {
  884. $this->admin->json_response = [
  885. 'status' => 'error',
  886. 'message' => $this->admin::translate($reinstall ?: 'PLUGIN_ADMIN.INSTALLATION_FAILED')
  887. ];
  888. }
  889. return true;
  890. }
  891. /**
  892. * Handle removing a package
  893. *
  894. * Route: /plugins.json/task:removePackage (AJAX call)
  895. * Route: /themes.json/task:removePackage (AJAX call)
  896. *
  897. * @return bool
  898. */
  899. protected function taskRemovePackage(): bool
  900. {
  901. $type = $this->view;
  902. if ($type !== 'plugins' && $type !== 'themes') {
  903. return false;
  904. }
  905. if (!$this->authorizeTask('uninstall ' . $type, ['admin.' . $type, 'admin.super'])) {
  906. $json_response = [
  907. 'status' => 'error',
  908. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  909. ];
  910. $this->sendJsonResponse($json_response, 403);
  911. }
  912. $data = $this->post;
  913. $package = $data['package'] ?? '';
  914. $result = false;
  915. //check if there are packages that have this as a dependency. Abort and show which ones
  916. $dependent_packages = $this->admin->getPackagesThatDependOnPackage($package);
  917. if (count($dependent_packages) > 0) {
  918. if (count($dependent_packages) > 1) {
  919. $message = 'The installed packages <cyan>' . implode('</cyan>, <cyan>',
  920. $dependent_packages) . '</cyan> depends on this package. Please remove those first.';
  921. } else {
  922. $message = 'The installed package <cyan>' . implode('</cyan>, <cyan>',
  923. $dependent_packages) . '</cyan> depends on this package. Please remove it first.';
  924. }
  925. $json_response = ['status' => 'error', 'message' => $message];
  926. $this->sendJsonResponse($json_response, 200);
  927. }
  928. $dependencies = false;
  929. try {
  930. $dependencies = $this->admin->dependenciesThatCanBeRemovedWhenRemoving($package);
  931. $result = Gpm::uninstall($package, []);
  932. } catch (\Exception $e) {
  933. /** @var Debugger $debugger */
  934. $debugger = $this->grav['debugger'];
  935. $debugger->addException($e);
  936. $json_response = ['status' => 'error', 'message' => htmlspecialchars($e->getMessage(), ENT_QUOTES | ENT_HTML5, 'UTF-8')];
  937. $this->sendJsonResponse($json_response, 200);
  938. }
  939. if ($result) {
  940. $json_response = [
  941. 'status' => 'success',
  942. 'dependencies' => $dependencies,
  943. 'message' => $this->admin::translate(is_string($result) ? $result : 'PLUGIN_ADMIN.UNINSTALL_SUCCESSFUL')
  944. ];
  945. $this->sendJsonResponse($json_response, 200);
  946. }
  947. $json_response = [
  948. 'status' => 'error',
  949. 'message' => $this->admin::translate('PLUGIN_ADMIN.UNINSTALL_FAILED')
  950. ];
  951. $this->sendJsonResponse($json_response, 200);
  952. }
  953. /**
  954. * Handle reinstalling a package
  955. *
  956. * Route: /plugins.json/task:reinstallPackage (AJAX call)
  957. * Route: /themes.json/task:reinstallPackage (AJAX call)
  958. *
  959. * @return bool
  960. */
  961. protected function taskReinstallPackage()
  962. {
  963. $type = $this->view;
  964. if ($type !== 'plugins' && $type !== 'themes') {
  965. return false;
  966. }
  967. if (!$this->authorizeTask('install ' . $type, ['admin.' . $type, 'admin.super'])) {
  968. $json_response = [
  969. 'status' => 'error',
  970. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  971. ];
  972. $this->sendJsonResponse($json_response, 403);
  973. }
  974. $data = $this->post;
  975. $slug = $data['slug'] ?? '';
  976. $package_name = $data['package_name'] ?? '';
  977. $current_version = $data['current_version'] ?? '';
  978. $url = "https://getgrav.org/download/{$type}s/$slug/$current_version";
  979. $result = Gpm::directInstall($url);
  980. if ($result === true) {
  981. $this->admin->json_response = [
  982. 'status' => 'success',
  983. 'message' => $this->admin::translate(sprintf($this->admin::translate('PLUGIN_ADMIN.PACKAGE_X_REINSTALLED_SUCCESSFULLY',
  984. null), $package_name))
  985. ];
  986. } else {
  987. $this->admin->json_response = [
  988. 'status' => 'error',
  989. 'message' => $this->admin::translate('PLUGIN_ADMIN.REINSTALLATION_FAILED')
  990. ];
  991. }
  992. return true;
  993. }
  994. /**
  995. * Handle direct install.
  996. *
  997. * Request: POST /tools/direct-install?task=directInstall
  998. *
  999. * @return bool
  1000. */
  1001. protected function taskDirectInstall()
  1002. {
  1003. if (!$this->authorizeTask('install', ['admin.super'])) {
  1004. return false;
  1005. }
  1006. $file_path = $this->data['file_path'] ?? null;
  1007. if (isset($_FILES['uploaded_file'])) {
  1008. // Check $_FILES['file']['error'] value.
  1009. switch ($_FILES['uploaded_file']['error']) {
  1010. case UPLOAD_ERR_OK:
  1011. break;
  1012. case UPLOAD_ERR_NO_FILE:
  1013. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.NO_FILES_SENT'), 'error');
  1014. return false;
  1015. case UPLOAD_ERR_INI_SIZE:
  1016. case UPLOAD_ERR_FORM_SIZE:
  1017. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.EXCEEDED_FILESIZE_LIMIT'), 'error');
  1018. return false;
  1019. case UPLOAD_ERR_NO_TMP_DIR:
  1020. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.UPLOAD_ERR_NO_TMP_DIR'), 'error');
  1021. return false;
  1022. default:
  1023. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.UNKNOWN_ERRORS'), 'error');
  1024. return false;
  1025. }
  1026. $file_name = $_FILES['uploaded_file']['name'];
  1027. $file_path = $_FILES['uploaded_file']['tmp_name'];
  1028. // Handle bad filenames.
  1029. if (!Utils::checkFilename($file_name)) {
  1030. $this->admin->json_response = [
  1031. 'status' => 'error',
  1032. 'message' => $this->admin::translate('PLUGIN_ADMIN.UNKNOWN_ERRORS')
  1033. ];
  1034. return false;
  1035. }
  1036. }
  1037. $result = Gpm::directInstall($file_path);
  1038. if ($result === true) {
  1039. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.INSTALLATION_SUCCESSFUL'), 'info');
  1040. } else {
  1041. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.INSTALLATION_FAILED') . ': ' . $result,
  1042. 'error');
  1043. }
  1044. $this->setRedirect('/tools');
  1045. return true;
  1046. }
  1047. // PAGE TASKS
  1048. /**
  1049. * Handles creating an empty page folder (without markdown file)
  1050. *
  1051. * Route: /pages
  1052. *
  1053. * @note Not used if Flex-Objects plugin handles pages.
  1054. *
  1055. * @return bool True if the action was performed.
  1056. */
  1057. public function taskSaveNewFolder()
  1058. {
  1059. if ($this->view !== 'pages') {
  1060. return false;
  1061. }
  1062. if (!$this->authorizeTask('new folder', ['admin.pages', 'admin.pages.create', 'admin.super'])) {
  1063. return false;
  1064. }
  1065. $data = (array)$this->data;
  1066. $folder = $data['folder'] ?? '';
  1067. if ($folder === '' || mb_strpos($folder, '/') !== false) {
  1068. throw new \RuntimeException('Creating folder failed: bad folder name', 400);
  1069. }
  1070. if ($data['route'] === '' || $data['route'] === '/') {
  1071. $path = $this->grav['locator']->findResource('page://');
  1072. } else {
  1073. $pages = $this->admin::enablePages();
  1074. $page = $pages->find($data['route']);
  1075. if (!$page) {
  1076. return false;
  1077. }
  1078. $path = $page->path();
  1079. }
  1080. $orderOfNewFolder = static::getNextOrderInFolder($path);
  1081. $new_path = $path . '/' . $orderOfNewFolder . '.' . $folder;
  1082. Folder::create($new_path);
  1083. Cache::clearCache('invalidate');
  1084. $this->grav->fireEvent('onAdminAfterSaveAs', new Event(['path' => $new_path]));
  1085. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_SAVED'), 'info');
  1086. $this->setRedirect($this->admin->getAdminRoute("/{$this->view}")->toString());
  1087. return true;
  1088. }
  1089. /**
  1090. * @note Not used if Flex-Objects plugin handles pages.
  1091. *
  1092. * @return bool
  1093. */
  1094. protected function savePage()
  1095. {
  1096. $reorder = true;
  1097. $data = (array)$this->data;
  1098. $this->grav['twig']->twig_vars['current_form_data'] = $data;
  1099. $pages = $this->admin::enablePages();
  1100. // Find new parent page in order to build the path.
  1101. $path = trim($data['route'] ?? dirname($this->admin->route), '/');
  1102. if ($path === '.') {
  1103. $path = '';
  1104. }
  1105. /** @var PageInterface $obj */
  1106. $obj = $this->admin->page(true);
  1107. $folder = $data['folder'] ?? null;
  1108. if ($folder === '' || mb_strpos($folder, '/') !== false) {
  1109. throw new \RuntimeException('Saving page failed: bad folder name', 400);
  1110. }
  1111. if (!isset($data['folder']) || !$data['folder']) {
  1112. $data['folder'] = $obj->slug();
  1113. $this->data['folder'] = $obj->slug();
  1114. }
  1115. // Check for valid frontmatter
  1116. if (isset($data['frontmatter']) && !$this->checkValidFrontmatter($data['frontmatter'])) {
  1117. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.INVALID_FRONTMATTER_COULD_NOT_SAVE'),
  1118. 'error');
  1119. return false;
  1120. }
  1121. // XSS Checks for page content
  1122. $xss_whitelist = $this->grav['config']->get('security.xss_whitelist', 'admin.super');
  1123. if (!$this->admin->authorize($xss_whitelist)) {
  1124. $check_what = ['header' => $data['header'] ?? '', 'frontmatter' => $data['frontmatter'] ?? '', 'content' => $data['content'] ?? ''];
  1125. $results = Security::detectXssFromArray($check_what);
  1126. if (!empty($results)) {
  1127. $this->admin->setMessage('<i class="fa fa-ban"></i> ' . $this->admin::translate('PLUGIN_ADMIN.XSS_ONSAVE_ISSUE'),
  1128. 'error');
  1129. return false;
  1130. }
  1131. }
  1132. if ($path !== '') {
  1133. // First try to get page by its path.
  1134. $parent = $pages->get(GRAV_ROOT . '/' . $path);
  1135. if (!$parent) {
  1136. // Fall back using the route.
  1137. $route = '/' . preg_replace(PageIndex::PAGE_ROUTE_REGEX, '/', $path);
  1138. $parent = $pages->find($route, true);
  1139. if (!$parent) {
  1140. throw new \RuntimeException('New parent page cannot be resolved!');
  1141. }
  1142. }
  1143. } else {
  1144. $parent = $pages->root();
  1145. }
  1146. $original_order = (int)trim($obj->order(), '.');
  1147. try {
  1148. // Change parent if needed and initialize move (might be needed also on ordering/folder change).
  1149. $obj = $obj->move($parent);
  1150. $this->preparePage($obj, false, $obj->language());
  1151. $obj->validate();
  1152. } catch (\Exception $e) {
  1153. /** @var Debugger $debugger */
  1154. $debugger = $this->grav['debugger'];
  1155. $debugger->addException($e);
  1156. $this->admin->setMessage($e->getMessage(), 'error');
  1157. return false;
  1158. }
  1159. $obj->filter();
  1160. // rename folder based on visible
  1161. if ($original_order === 1000) {
  1162. // increment order to force reshuffle
  1163. $obj->order($original_order + 1);
  1164. }
  1165. if (isset($data['order']) && !empty($data['order'])) {
  1166. $reorder = explode(',', $data['order']);
  1167. }
  1168. // add or remove numeric prefix based on ordering value
  1169. if (isset($data['ordering'])) {
  1170. if ($data['ordering'] && !$obj->order()) {
  1171. $obj->order(static::getNextOrderInFolder($obj->parent()->path()));
  1172. $reorder = false;
  1173. } elseif (!$data['ordering'] && $obj->order()) {
  1174. $obj->folder($obj->slug());
  1175. }
  1176. }
  1177. $obj = $this->storeFiles($obj);
  1178. if ($obj) {
  1179. // Event to manipulate data before saving the object
  1180. // DEPRECATED: page
  1181. $this->grav->fireEvent('onAdminSave', new Event(['object' => &$obj, 'page' => &$obj]));
  1182. $obj->save($reorder);
  1183. Cache::clearCache('invalidate');
  1184. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_SAVED'), 'info');
  1185. // DEPRECATED: page
  1186. $this->grav->fireEvent('onAdminAfterSave', new Event(['object' => $obj, 'page' => $obj]));
  1187. }
  1188. if (method_exists($obj, 'unsetRouteSlug')) {
  1189. $obj->unsetRouteSlug();
  1190. }
  1191. $multilang = $this->isMultilang();
  1192. if ($multilang && !$obj->language()) {
  1193. $obj->language($this->admin->getLanguage());
  1194. }
  1195. $admin_route = $this->admin->base;
  1196. $route = $obj->rawRoute();
  1197. $redirect_url = ($multilang ? '/' . $obj->language() : '') . $admin_route . '/' . $this->view . $route;
  1198. $this->setRedirect($redirect_url);
  1199. return true;
  1200. }
  1201. /**
  1202. * Save page as a new copy.
  1203. *
  1204. * Route: /pages
  1205. *
  1206. * @note Not used if Flex-Objects plugin handles pages.
  1207. *
  1208. * @return bool True if the action was performed.
  1209. * @throws \RuntimeException
  1210. */
  1211. protected function taskCopy()
  1212. {
  1213. if ($this->view !== 'pages') {
  1214. return false;
  1215. }
  1216. if (!$this->authorizeTask('copy page', ['admin.pages', 'admin.pages.create', 'admin.super'])) {
  1217. return false;
  1218. }
  1219. try {
  1220. $pages = $this->admin::enablePages();
  1221. // Get the current page.
  1222. $original_page = $this->admin->page(true);
  1223. // Find new parent page in order to build the path.
  1224. $parent = $original_page->parent() ?: $pages->root();
  1225. // Make a copy of the current page and fill the updated information into it.
  1226. $page = $original_page->copy($parent);
  1227. $order = 0;
  1228. if ($page->order()) {
  1229. $order = $this->getNextOrderInFolder($page->parent()->path());
  1230. }
  1231. // Make sure the header is loaded in case content was set through raw() (expert mode)
  1232. $page->header();
  1233. if ($page->order()) {
  1234. $page->order($order);
  1235. }
  1236. $folder = $this->findFirstAvailable('folder', $page);
  1237. $slug = $this->findFirstAvailable('slug', $page);
  1238. $page->path($page->parent()->path() . DS . $page->order() . $folder);
  1239. $page->route($page->parent()->route() . '/' . $slug);
  1240. $page->rawRoute($page->parent()->rawRoute() . '/' . $slug);
  1241. // Append progressive number to the copied page title
  1242. $match = preg_split('/(\d+)(?!.*\d)/', $original_page->title(), 2, PREG_SPLIT_DELIM_CAPTURE);
  1243. $header = $page->header();
  1244. if (!isset($match[1])) {
  1245. $header->title = $match[0] . ' 2';
  1246. } else {
  1247. $header->title = $match[0] . ((int)$match[1] + 1);
  1248. }
  1249. $page->header($header);
  1250. $page->save(false);
  1251. $redirect = $this->view . $page->rawRoute();
  1252. $header = $page->header();
  1253. if (isset($header->slug)) {
  1254. $match = preg_split('/-(\d+)$/', $header->slug, 2, PREG_SPLIT_DELIM_CAPTURE);
  1255. $header->slug = $match[0] . '-' . (isset($match[1]) ? (int)$match[1] + 1 : 2);
  1256. }
  1257. $page->header($header);
  1258. $page->save();
  1259. Cache::clearCache('invalidate');
  1260. // DEPRECATED: page
  1261. $this->grav->fireEvent('onAdminAfterSave', new Event(['object' => $page, 'page' => $page]));
  1262. // Enqueue message and redirect to new location.
  1263. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_COPIED'), 'info');
  1264. $this->setRedirect($redirect);
  1265. } catch (\Exception $e) {
  1266. throw new \RuntimeException('Copying page failed on error: ' . $e->getMessage());
  1267. }
  1268. return true;
  1269. }
  1270. /**
  1271. * Reorder pages.
  1272. *
  1273. * Route: /pages
  1274. *
  1275. * @note Not used if Flex-Objects plugin handles pages.
  1276. *
  1277. * @return bool True if the action was performed.
  1278. */
  1279. protected function taskReorder()
  1280. {
  1281. if ($this->view !== 'pages') {
  1282. return false;
  1283. }
  1284. if (!$this->authorizeTask('reorder pages', ['admin.pages', 'admin.pages.update', 'admin.super'])) {
  1285. return false;
  1286. }
  1287. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.REORDERING_WAS_SUCCESSFUL'), 'info');
  1288. return true;
  1289. }
  1290. /**
  1291. * Delete page.
  1292. *
  1293. * Route: /pages
  1294. *
  1295. * @note Not used if Flex-Objects plugin handles pages.
  1296. *
  1297. * @return bool True if the action was performed.
  1298. * @throws \RuntimeException
  1299. */
  1300. protected function taskDelete()
  1301. {
  1302. if ($this->view !== 'pages') {
  1303. return false;
  1304. }
  1305. if (!$this->authorizeTask('delete page', ['admin.pages', 'admin.pages.delete', 'admin.super'])) {
  1306. return false;
  1307. }
  1308. try {
  1309. $page = $this->admin->page();
  1310. if (count($page->translatedLanguages()) > 1) {
  1311. $page->file()->delete();
  1312. } else {
  1313. Folder::delete($page->path());
  1314. }
  1315. // DEPRECATED: page
  1316. $this->grav->fireEvent('onAdminAfterDelete', new Event(['object' => $page, 'page' => $page]));
  1317. Cache::clearCache('invalidate');
  1318. // Set redirect to pages list.
  1319. $redirect = 'pages';
  1320. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_DELETED'), 'info');
  1321. $this->setRedirect($redirect);
  1322. } catch (\Exception $e) {
  1323. throw new \RuntimeException('Deleting page failed on error: ' . $e->getMessage());
  1324. }
  1325. return true;
  1326. }
  1327. /**
  1328. * Switch the content language. Optionally redirect to a different page.
  1329. *
  1330. * Route: /pages
  1331. *
  1332. * @note Not used if Flex-Objects plugin handles pages.
  1333. *
  1334. * @return bool
  1335. */
  1336. protected function taskSwitchlanguage()
  1337. {
  1338. if ($this->view !== 'pages') {
  1339. return false;
  1340. }
  1341. if (!$this->authorizeTask('switch language', ['admin.pages', 'admin.pages.list', 'admin.super'])) {
  1342. return false;
  1343. }
  1344. $data = (array)$this->data;
  1345. $language = $data['lang'] ?? $this->grav['uri']->param('lang');
  1346. if (isset($data['redirect'])) {
  1347. $redirect = '/pages/' . $data['redirect'];
  1348. } else {
  1349. $redirect = '/pages';
  1350. }
  1351. if ($language) {
  1352. $this->grav['session']->admin_lang = $language ?: 'en';
  1353. }
  1354. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_SWITCHED_LANGUAGE'), 'info');
  1355. $this->setRedirect($this->admin->getAdminRoute($redirect)->toString());
  1356. return true;
  1357. }
  1358. /**
  1359. * Save the current page in a different language. Automatically switches to that language.
  1360. *
  1361. * Route: /pages
  1362. *
  1363. * @note Not used if Flex-Objects plugin handles pages.
  1364. *
  1365. * @return bool True if the action was performed.
  1366. */
  1367. protected function taskSaveas()
  1368. {
  1369. if ($this->view !== 'pages') {
  1370. return false;
  1371. }
  1372. if (!$this->authorizeTask('save as', ['admin.pages', 'admin.pages.create', 'admin.super'])) {
  1373. return false;
  1374. }
  1375. /** @var Language $language */
  1376. $language = $this->grav['language'];
  1377. $data = (array)$this->data;
  1378. $lang = $data['lang'] ?? null;
  1379. if ($lang) {
  1380. $this->grav['session']->admin_lang = $lang ?: 'en';
  1381. }
  1382. $uri = $this->grav['uri'];
  1383. $obj = $this->admin->page($uri->route());
  1384. $this->preparePage($obj, false, $lang);
  1385. $file = $obj->file();
  1386. if ($file) {
  1387. $filename = $this->determineFilenameIncludingLanguage($obj->name(), $lang);
  1388. $path = $obj->path() . DS . $filename;
  1389. $aFile = File::instance($path);
  1390. $aFile->save();
  1391. $aPage = new Page();
  1392. $aPage->init(new \SplFileInfo($path), $lang . '.md');
  1393. $aPage->header($obj->header());
  1394. $aPage->rawMarkdown($obj->rawMarkdown());
  1395. $aPage->template($obj->template());
  1396. $aPage->validate();
  1397. $aPage->filter();
  1398. // DEPRECATED: page
  1399. $this->grav->fireEvent('onAdminSave', new Event(['object' => $aPage, 'page' => &$aPage]));
  1400. $aPage->save();
  1401. Cache::clearCache('invalidate');
  1402. // DEPRECATED: page
  1403. $this->grav->fireEvent('onAdminAfterSave', new Event(['object' => $aPage, 'page' => $aPage]));
  1404. }
  1405. $this->admin->setMessage($this->admin::translate('PLUGIN_ADMIN.SUCCESSFULLY_SWITCHED_LANGUAGE'), 'info');
  1406. // TODO: better multilanguage support needed.
  1407. $this->setRedirect($language->getLanguageURLPrefix($lang) . $uri->route());
  1408. return true;
  1409. }
  1410. /**
  1411. * Continue to the new page.
  1412. *
  1413. * @note Not used if Flex-Objects plugin handles pages, users and user groups.
  1414. *
  1415. * @return bool True if the action was performed.
  1416. */
  1417. public function taskContinue()
  1418. {
  1419. $data = (array)$this->data;
  1420. if ($this->view === 'users') {
  1421. $username = strip_tags(strtolower($data['username']));
  1422. $this->setRedirect("{$this->view}/{$username}");
  1423. return true;
  1424. }
  1425. if ($this->view !== 'pages') {
  1426. return false;
  1427. }
  1428. $route = $data['route'] !== '/' ? $data['route'] : '';
  1429. $folder = $data['folder'] ?? null;
  1430. $title = $data['title'] ?? null;
  1431. // Handle @slugify-{field} value, automatically slugifies the specified field
  1432. if (null !== $folder && 0 === strpos($folder, '@slugify-')) {
  1433. $folder = \Grav\Plugin\Admin\Utils::slug($data[substr($folder, 9)] ?? '');
  1434. }
  1435. if (!$folder) {
  1436. $folder = \Grav\Plugin\Admin\Utils::slug($title) ?: '';
  1437. }
  1438. $folder = ltrim($folder, '_');
  1439. if ($folder === '' || mb_strpos($folder, '/') !== false) {
  1440. throw new \RuntimeException('Creating page failed: bad folder name', 400);
  1441. }
  1442. if (!empty($data['modular'])) {
  1443. $folder = '_' . $folder;
  1444. }
  1445. $data['folder'] = $folder;
  1446. $path = $route . '/' . $folder;
  1447. $this->admin->session()->{$path} = $data;
  1448. // Store the name and route of a page, to be used pre-filled defaults of the form in the future
  1449. $this->admin->session()->lastPageName = $data['name'];
  1450. $this->admin->session()->lastPageRoute = $data['route'];
  1451. $this->setRedirect("{$this->view}/" . ltrim($path, '/'));
  1452. return true;
  1453. }
  1454. /**
  1455. * $data['route'] = $this->grav['uri']->param('route');
  1456. * $data['sortby'] = $this->grav['uri']->param('sortby', null);
  1457. * $data['filters'] = $this->grav['uri']->param('filters', null);
  1458. * $data['page'] $this->grav['uri']->param('page', true);
  1459. * $data['base'] = $this->grav['uri']->param('base');
  1460. * $initial = (bool) $this->grav['uri']->param('initial');
  1461. *
  1462. * @return ResponseInterface
  1463. * @throws RequestException
  1464. */
  1465. protected function taskGetLevelListing(): ResponseInterface
  1466. {
  1467. $this->checkTaskAuthorization('save', $this->dataPermissions());
  1468. $request = $this->getRequest();
  1469. $data = $request->getParsedBody();
  1470. if (!isset($data['field'])) {
  1471. throw new RequestException($request, 'Bad Request', 400);
  1472. }
  1473. // Base64 decode the route
  1474. $data['route'] = isset($data['route']) ? base64_decode($data['route']) : null;
  1475. $initial = $data['initial'] ?? null;
  1476. if ($initial) {
  1477. $data['leaf_route'] = $data['route'];
  1478. $data['route'] = null;
  1479. $data['level'] = 1;
  1480. }
  1481. [$status, $message, $response,] = $this->getLevelListing($data);
  1482. $json = [
  1483. 'status' => $status,
  1484. 'message' => $this->admin::translate($message ?? 'PLUGIN_ADMIN.NO_ROUTE_PROVIDED'),
  1485. 'data' => array_values($response)
  1486. ];
  1487. return $this->createJsonResponse($json, 200);
  1488. }
  1489. /**
  1490. * Route: /ajax.json
  1491. *
  1492. * @note Not used if Flex-Objects plugin handles pages.
  1493. *
  1494. * @return bool
  1495. */
  1496. protected function taskGetChildTypes()
  1497. {
  1498. if ($this->view !== 'ajax') {
  1499. return false;
  1500. }
  1501. if (!$this->authorizeTask('get childtypes', ['admin.pages', 'admin.pages.list', 'admin.super'])) {
  1502. $this->admin->json_response = [
  1503. 'status' => 'error',
  1504. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  1505. ];
  1506. return false;
  1507. }
  1508. $data = $this->post;
  1509. $route = $data['rawroute'] ?? null;
  1510. if ($route) {
  1511. /** @var Flex $flex */
  1512. $flex = $this->grav['flex'];
  1513. $page = $flex->getObject(trim($route, '/'), 'pages');
  1514. if ($page instanceof PageInterface) {
  1515. $child_type = $page->childType();
  1516. if ($child_type !== '') {
  1517. $this->admin->json_response = [
  1518. 'status' => 'success',
  1519. 'child_type' => $child_type
  1520. ];
  1521. return true;
  1522. }
  1523. }
  1524. }
  1525. $this->admin->json_response = [
  1526. 'status' => 'success',
  1527. 'child_type' => '',
  1528. ];
  1529. return true;
  1530. }
  1531. /**
  1532. * Handles filtering the page by modular/visible/routable in the pages list.
  1533. *
  1534. * @note Used only in legacy pages.
  1535. *
  1536. * @return bool
  1537. */
  1538. protected function taskFilterPages()
  1539. {
  1540. if ($this->view !== 'pages-filter') {
  1541. return false;
  1542. }
  1543. if (!$this->authorizeTask('filter pages', ['admin.pages', 'admin.pages.list', 'admin.super'])) {
  1544. $this->admin->json_response = [
  1545. 'status' => 'error',
  1546. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  1547. ];
  1548. return false;
  1549. }
  1550. $data = $this->post;
  1551. $flags = !empty($data['flags']) ? array_map('strtolower', explode(',', $data['flags'])) : [];
  1552. $queries = !empty($data['query']) ? explode(',', $data['query']) : [];
  1553. $pages = $this->admin::enablePages();
  1554. /** @var Collection $collection */
  1555. $collection = $pages->all();
  1556. if (count($flags)) {
  1557. // Filter by state
  1558. $pageStates = [
  1559. 'modular',
  1560. 'nonmodular',
  1561. 'visible',
  1562. 'nonvisible',
  1563. 'routable',
  1564. 'nonroutable',
  1565. 'published',
  1566. 'nonpublished'
  1567. ];
  1568. if (count(array_intersect($pageStates, $flags)) > 0) {
  1569. if (in_array('modular', $flags, true)) {
  1570. $collection = $collection->modular();
  1571. }
  1572. if (in_array('nonmodular', $flags, true)) {
  1573. $collection = $collection->nonModular();
  1574. }
  1575. if (in_array('visible', $flags, true)) {
  1576. $collection = $collection->visible();
  1577. }
  1578. if (in_array('nonvisible', $flags, true)) {
  1579. $collection = $collection->nonVisible();
  1580. }
  1581. if (in_array('routable', $flags, true)) {
  1582. $collection = $collection->routable();
  1583. }
  1584. if (in_array('nonroutable', $flags, true)) {
  1585. $collection = $collection->nonRoutable();
  1586. }
  1587. if (in_array('published', $flags, true)) {
  1588. $collection = $collection->published();
  1589. }
  1590. if (in_array('nonpublished', $flags, true)) {
  1591. $collection = $collection->nonPublished();
  1592. }
  1593. }
  1594. foreach ($pageStates as $pageState) {
  1595. if (($pageState = array_search($pageState, $flags, true)) !== false) {
  1596. unset($flags[$pageState]);
  1597. }
  1598. }
  1599. // Filter by page type
  1600. if ($flags) {
  1601. $types = [];
  1602. $pageTypes = array_keys(Pages::pageTypes());
  1603. foreach ($pageTypes as $pageType) {
  1604. if (($pageKey = array_search($pageType, $flags, true)) !== false) {
  1605. $types[] = $pageType;
  1606. unset($flags[$pageKey]);
  1607. }
  1608. }
  1609. if (count($types)) {
  1610. $collection = $collection->ofOneOfTheseTypes($types);
  1611. }
  1612. }
  1613. // Filter by page type
  1614. if ($flags) {
  1615. $accessLevels = $flags;
  1616. $collection = $collection->ofOneOfTheseAccessLevels($accessLevels);
  1617. }
  1618. }
  1619. if (!empty($queries)) {
  1620. foreach ($collection as $page) {
  1621. foreach ($queries as $query) {
  1622. $query = trim($query);
  1623. if (stripos($page->getRawContent(), $query) === false
  1624. && stripos($page->title(), $query) === false
  1625. && stripos($page->folder(), $query) === false
  1626. && stripos($page->slug(), \Grav\Plugin\Admin\Utils::slug($query)) === false
  1627. ) {
  1628. $collection->remove($page);
  1629. }
  1630. }
  1631. }
  1632. }
  1633. $results = [];
  1634. foreach ($collection as $path => $page) {
  1635. $results[] = $page->route();
  1636. }
  1637. $this->admin->json_response = [
  1638. 'status' => 'success',
  1639. 'message' => $this->admin::translate('PLUGIN_ADMIN.PAGES_FILTERED'),
  1640. 'results' => $results
  1641. ];
  1642. $this->admin->collection = $collection;
  1643. return true;
  1644. }
  1645. /**
  1646. * Process the page Markdown
  1647. *
  1648. * Preview task in the builtin editor.
  1649. *
  1650. * @return bool True if the action was performed.
  1651. */
  1652. protected function taskProcessMarkdown()
  1653. {
  1654. if (!$this->authorizeTask('process markdown', ['admin.pages', 'admin.pages.read', 'admin.super'])) {
  1655. $this->admin->json_response = [
  1656. 'status' => 'error',
  1657. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  1658. ];
  1659. return false;
  1660. }
  1661. try {
  1662. $page = $this->admin->page(true);
  1663. if (!$page) {
  1664. $this->admin->json_response = [
  1665. 'status' => 'error',
  1666. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_PAGE_FOUND')
  1667. ];
  1668. return false;
  1669. }
  1670. $this->preparePage($page, true);
  1671. $page->header();
  1672. $page->templateFormat('html');
  1673. // Add theme template paths to Twig loader
  1674. $template_paths = $this->grav['locator']->findResources('theme://templates');
  1675. $this->grav['twig']->twig->getLoader()->addLoader(new FilesystemLoader($template_paths));
  1676. $html = $page->content();
  1677. $this->admin->json_response = ['status' => 'success', 'preview' => $html];
  1678. } catch (\Exception $e) {
  1679. /** @var Debugger $debugger */
  1680. $debugger = $this->grav['debugger'];
  1681. $debugger->addException($e);
  1682. $this->admin->json_response = ['status' => 'error', 'message' => htmlspecialchars($e->getMessage(), ENT_QUOTES | ENT_HTML5, 'UTF-8')];
  1683. return false;
  1684. }
  1685. return true;
  1686. }
  1687. // MEDIA TASKS
  1688. /**
  1689. * Determines the file types allowed to be uploaded
  1690. *
  1691. * Used by pagemedia field. Works only within legacy pages.
  1692. *
  1693. * @return bool True if the action was performed.
  1694. */
  1695. protected function taskListmedia()
  1696. {
  1697. if ($this->view !== 'media') {
  1698. return false;
  1699. }
  1700. if (!$this->authorizeTask('list media', ['admin.pages', 'admin.pages.read', 'admin.super'])) {
  1701. $this->admin->json_response = [
  1702. 'status' => 'error',
  1703. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  1704. ];
  1705. return false;
  1706. }
  1707. $media = $this->getMedia();
  1708. if (!$media) {
  1709. $this->admin->json_response = [
  1710. 'status' => 'error',
  1711. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_PAGE_FOUND')
  1712. ];
  1713. return false;
  1714. }
  1715. $media_list = [];
  1716. /**
  1717. * @var string $name
  1718. * @var Medium|ImageMedium $medium
  1719. */
  1720. foreach ($media->all() as $name => $medium) {
  1721. $metadata = [];
  1722. $img_metadata = $medium->metadata();
  1723. if ($img_metadata) {
  1724. $metadata = $img_metadata;
  1725. }
  1726. // Get original name
  1727. /** @var ImageMedium $source */
  1728. $source = method_exists($medium, 'higherQualityAlternative') ? $medium->higherQualityAlternative() : null;
  1729. $media_list[$name] = [
  1730. 'url' => $medium->display($medium->get('extension') === 'svg' ? 'source' : 'thumbnail')->cropZoom(400, 300)->url(),
  1731. 'size' => $medium->get('size'),
  1732. 'metadata' => $metadata,
  1733. 'original' => $source ? $source->get('filename') : null
  1734. ];
  1735. }
  1736. $this->admin->json_response = ['status' => 'success', 'results' => $media_list];
  1737. return true;
  1738. }
  1739. /**
  1740. * Handles adding a media file to a page.
  1741. *
  1742. * Used by pagemedia field. Works only within legacy pages.
  1743. *
  1744. * @return bool True if the action was performed.
  1745. */
  1746. protected function taskAddmedia()
  1747. {
  1748. if ($this->view !== 'media') {
  1749. return false;
  1750. }
  1751. if (!$this->authorizeTask('add media', ['admin.pages', 'admin.pages.update', 'admin.super'])) {
  1752. $this->admin->json_response = [
  1753. 'status' => 'error',
  1754. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  1755. ];
  1756. return false;
  1757. }
  1758. /** @var Config $config */
  1759. $config = $this->grav['config'];
  1760. if (empty($_FILES)) {
  1761. $this->admin->json_response = [
  1762. 'status' => 'error',
  1763. 'message' => $this->admin::translate('PLUGIN_ADMIN.EXCEEDED_POSTMAX_LIMIT')
  1764. ];
  1765. return false;
  1766. }
  1767. if (!isset($_FILES['file']['error']) || is_array($_FILES['file']['error'])) {
  1768. $this->admin->json_response = [
  1769. 'status' => 'error',
  1770. 'message' => $this->admin::translate('PLUGIN_ADMIN.INVALID_PARAMETERS')
  1771. ];
  1772. return false;
  1773. }
  1774. // Check $_FILES['file']['error'] value.
  1775. switch ($_FILES['file']['error']) {
  1776. case UPLOAD_ERR_OK:
  1777. break;
  1778. case UPLOAD_ERR_NO_FILE:
  1779. $this->admin->json_response = [
  1780. 'status' => 'error',
  1781. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_FILES_SENT')
  1782. ];
  1783. return false;
  1784. case UPLOAD_ERR_INI_SIZE:
  1785. case UPLOAD_ERR_FORM_SIZE:
  1786. $this->admin->json_response = [
  1787. 'status' => 'error',
  1788. 'message' => $this->admin::translate('PLUGIN_ADMIN.EXCEEDED_FILESIZE_LIMIT')
  1789. ];
  1790. return false;
  1791. case UPLOAD_ERR_NO_TMP_DIR:
  1792. $this->admin->json_response = [
  1793. 'status' => 'error',
  1794. 'message' => $this->admin::translate('PLUGIN_ADMIN.UPLOAD_ERR_NO_TMP_DIR')
  1795. ];
  1796. return false;
  1797. default:
  1798. $this->admin->json_response = [
  1799. 'status' => 'error',
  1800. 'message' => $this->admin::translate('PLUGIN_ADMIN.UNKNOWN_ERRORS')
  1801. ];
  1802. return false;
  1803. }
  1804. $filename = $_FILES['file']['name'];
  1805. // Handle bad filenames.
  1806. if (!Utils::checkFilename($filename)) {
  1807. $this->admin->json_response = [
  1808. 'status' => 'error',
  1809. 'message' => sprintf($this->admin::translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_UPLOAD'),
  1810. htmlspecialchars($filename, ENT_QUOTES | ENT_HTML5, 'UTF-8'), 'Bad filename')
  1811. ];
  1812. return false;
  1813. }
  1814. // You should also check filesize here.
  1815. $grav_limit = Utils::getUploadLimit();
  1816. if ($grav_limit > 0 && $_FILES['file']['size'] > $grav_limit) {
  1817. $this->admin->json_response = [
  1818. 'status' => 'error',
  1819. 'message' => $this->admin::translate('PLUGIN_ADMIN.EXCEEDED_GRAV_FILESIZE_LIMIT')
  1820. ];
  1821. return false;
  1822. }
  1823. // Check extension
  1824. $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  1825. // If not a supported type, return
  1826. if (!$extension || !$config->get("media.types.{$extension}")) {
  1827. $this->admin->json_response = [
  1828. 'status' => 'error',
  1829. 'message' => $this->admin::translate('PLUGIN_ADMIN.UNSUPPORTED_FILE_TYPE') . ': ' . $extension
  1830. ];
  1831. return false;
  1832. }
  1833. $page = $this->admin->page($this->route);
  1834. $media = $page ? $this->getMedia($page) : null;
  1835. if (!$media) {
  1836. $this->admin->json_response = [
  1837. 'status' => 'error',
  1838. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_PAGE_FOUND')
  1839. ];
  1840. return false;
  1841. }
  1842. /** @var UniformResourceLocator $locator */
  1843. $locator = $this->grav['locator'];
  1844. $path = $media->getPath();
  1845. if ($locator->isStream($path)) {
  1846. $path = $locator->findResource($path, true, true);
  1847. }
  1848. // Special Sanitization for SVG
  1849. if (Utils::contains($extension, 'svg', false)) {
  1850. Security::sanitizeSVG($_FILES['file']['tmp_name']);
  1851. }
  1852. // Upload it
  1853. if (!move_uploaded_file($_FILES['file']['tmp_name'], sprintf('%s/%s', $path, $filename))) {
  1854. $this->admin->json_response = [
  1855. 'status' => 'error',
  1856. 'message' => $this->admin::translate('PLUGIN_ADMIN.FAILED_TO_MOVE_UPLOADED_FILE')
  1857. ];
  1858. return false;
  1859. }
  1860. Cache::clearCache('invalidate');
  1861. // Add metadata if needed
  1862. $include_metadata = Grav::instance()['config']->get('system.media.auto_metadata_exif', false);
  1863. $basename = str_replace(['@3x', '@2x'], '', pathinfo($filename, PATHINFO_BASENAME));
  1864. $metadata = [];
  1865. if ($include_metadata && isset($media[$basename])) {
  1866. $img_metadata = $media[$basename]->metadata();
  1867. if ($img_metadata) {
  1868. $metadata = $img_metadata;
  1869. }
  1870. }
  1871. // DEPRECATED: page
  1872. $this->grav->fireEvent('onAdminAfterAddMedia', new Event(['object' => $page, 'page' => $page]));
  1873. $this->admin->json_response = [
  1874. 'status' => 'success',
  1875. 'message' => $this->admin::translate('PLUGIN_ADMIN.FILE_UPLOADED_SUCCESSFULLY'),
  1876. 'metadata' => $metadata,
  1877. ];
  1878. return true;
  1879. }
  1880. /**
  1881. * Request: POST .json/task:compileScss (AJAX call)
  1882. *
  1883. * @return bool
  1884. */
  1885. protected function taskCompileScss()
  1886. {
  1887. if (!$this->authorizeTask('compile scss', ['admin.plugins', 'admin.super'])) {
  1888. $this->admin->json_response = [
  1889. 'status' => 'error',
  1890. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  1891. ];
  1892. return false;
  1893. }
  1894. $default_scheme = $this->grav['config']->get('plugins.admin.whitelabel.color_scheme');
  1895. $preview = $this->post['preview'] ?? false;
  1896. $data = ['color_scheme' => $this->data['whitelabel']['color_scheme'] ?? $default_scheme];
  1897. $output_file = $preview ? 'admin-preset.css' : 'admin-preset__tmp.css';
  1898. $options = [
  1899. 'input' => 'plugin://admin/themes/grav/scss/preset.scss',
  1900. 'output' => 'asset://' .$output_file
  1901. ];
  1902. [$compile_status, $msg] = $this->grav['admin-whitelabel']->compilePresetScss($data, $options);
  1903. $json_response = [
  1904. 'status' => $compile_status ? 'success' : 'error',
  1905. 'message' => ($preview ? 'Preview ' : 'SCSS ') . $msg,
  1906. 'files' => [
  1907. 'color_scheme' => Utils::url($options['output'])
  1908. ]
  1909. ];
  1910. $this->sendJsonResponse($json_response);
  1911. }
  1912. /**
  1913. * Request: POST .json/task:exportScss (AJAX call)
  1914. *
  1915. * @return bool
  1916. */
  1917. protected function taskExportScss()
  1918. {
  1919. if (!$this->authorizeTask('export scss', ['admin.plugins', 'admin.super'])) {
  1920. $this->admin->json_response = [
  1921. 'status' => 'error',
  1922. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  1923. ];
  1924. return false;
  1925. }
  1926. $data = ['color_scheme' => $this->data['whitelabel']['color_scheme'] ?? null];
  1927. $name = empty($this->data['whitelabel']['color_scheme']['name']) ? 'admin-theme-export' : \Grav\Plugin\Admin\Utils::slug($this->data['whitelabel']['color_scheme']['name']);
  1928. $location = 'asset://' . $name . '.yaml';
  1929. [$status, $msg] = $this->grav['admin-whitelabel']->exportPresetScsss($data, $location);
  1930. $json_response = [
  1931. 'status' => $status ? 'success' : 'error',
  1932. 'message' => $msg,
  1933. 'files' => [
  1934. 'download' => Utils::url($location)
  1935. ]
  1936. ];
  1937. $this->sendJsonResponse($json_response);
  1938. }
  1939. /**
  1940. * Handles deleting a media file from a page.
  1941. *
  1942. * Used by pagemedia field.
  1943. *
  1944. * @return bool True if the action was performed.
  1945. */
  1946. protected function taskDelmedia()
  1947. {
  1948. if ($this->view !== 'media') {
  1949. return false;
  1950. }
  1951. if (!$this->authorizeTask('delete media', ['admin.pages', 'admin.pages.update', 'admin.super'])) {
  1952. $this->admin->json_response = [
  1953. 'status' => 'error',
  1954. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  1955. ];
  1956. return false;
  1957. }
  1958. $page = $this->admin->page($this->route);
  1959. $media = $page ? $this->getMedia($page) : null;
  1960. if (null === $media) {
  1961. $this->admin->json_response = [
  1962. 'status' => 'error',
  1963. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_PAGE_FOUND')
  1964. ];
  1965. return false;
  1966. }
  1967. $filename = !empty($this->post['filename']) ? basename($this->post['filename']) : null;
  1968. // Handle bad filenames.
  1969. if (!$filename || !Utils::checkFilename($filename)) {
  1970. $this->admin->json_response = [
  1971. 'status' => 'error',
  1972. 'message' => $this->admin::translate('PLUGIN_ADMIN.NO_FILE_FOUND')
  1973. ];
  1974. return false;
  1975. }
  1976. /** @var UniformResourceLocator $locator */
  1977. $locator = $this->grav['locator'];
  1978. $targetPath = $media->getPath() . '/' . $filename;
  1979. if ($locator->isStream($targetPath)) {
  1980. $targetPath = $locator->findResource($targetPath, true, true);
  1981. }
  1982. $fileParts = pathinfo($filename);
  1983. $found = false;
  1984. if (file_exists($targetPath)) {
  1985. $found = true;
  1986. $result = unlink($targetPath);
  1987. if (!$result) {
  1988. $this->admin->json_response = [
  1989. 'status' => 'error',
  1990. 'message' => $this->admin::translate('PLUGIN_ADMIN.FILE_COULD_NOT_BE_DELETED') . ': ' . htmlspecialchars($filename, ENT_QUOTES | ENT_HTML5, 'UTF-8')
  1991. ];
  1992. return false;
  1993. }
  1994. }
  1995. // Remove Extra Files
  1996. foreach (scandir($media->getPath(), SCANDIR_SORT_NONE) as $file) {
  1997. if (preg_match("/{$fileParts['filename']}@\d+x\.{$fileParts['extension']}(?:\.meta\.yaml)?$|{$filename}\.meta\.yaml$/", $file)) {
  1998. $targetPath = $media->getPath() . '/' . $file;
  1999. if ($locator->isStream($targetPath)) {
  2000. $targetPath = $locator->findResource($targetPath, true, true);
  2001. }
  2002. $result = unlink($targetPath);
  2003. if (!$result) {
  2004. $this->admin->json_response = [
  2005. 'status' => 'error',
  2006. 'message' => $this->admin::translate('PLUGIN_ADMIN.FILE_COULD_NOT_BE_DELETED') . ': ' . htmlspecialchars($filename, ENT_QUOTES | ENT_HTML5, 'UTF-8')
  2007. ];
  2008. return false;
  2009. }
  2010. $found = true;
  2011. }
  2012. }
  2013. Cache::clearCache('invalidate');
  2014. if (!$found) {
  2015. $this->admin->json_response = [
  2016. 'status' => 'error',
  2017. 'message' => $this->admin::translate('PLUGIN_ADMIN.FILE_NOT_FOUND') . ': ' . htmlspecialchars($filename, ENT_QUOTES | ENT_HTML5, 'UTF-8')
  2018. ];
  2019. return false;
  2020. }
  2021. // DEPRECATED: page
  2022. $this->grav->fireEvent('onAdminAfterDelMedia', new Event(['object' => $page, 'page' => $page, 'media' => $media, 'filename' => $filename]));
  2023. $this->admin->json_response = [
  2024. 'status' => 'success',
  2025. 'message' => $this->admin::translate('PLUGIN_ADMIN.FILE_DELETED') . ': ' . htmlspecialchars($filename, ENT_QUOTES | ENT_HTML5, 'UTF-8')
  2026. ];
  2027. return true;
  2028. }
  2029. /**
  2030. * @param array $data
  2031. * @return array
  2032. */
  2033. protected function getLevelListing($data)
  2034. {
  2035. // Valid types are dir|file|link
  2036. $default_filters = ['type'=> ['root', 'dir'], 'name' => null, 'extension' => null];
  2037. $pages = $this->admin::enablePages();
  2038. $page_instances = $pages->instances();
  2039. $is_page = $data['page'] ?? true;
  2040. $route = $data['route'] ?? null;
  2041. $leaf_route = $data['leaf_route'] ?? null;
  2042. $sortby = $data['sortby'] ?? 'filename';
  2043. $order = $data['order'] ?? SORT_ASC;
  2044. $initial = $data['initial'] ?? null;
  2045. $filters = isset($data['filters']) ? $default_filters + json_decode($data['filters']) : $default_filters;
  2046. $filter_type = (array) $filters['type'];
  2047. $status = 'error';
  2048. $msg = null;
  2049. $response = [];
  2050. $children = null;
  2051. $sub_route = null;
  2052. $extra = null;
  2053. $root = false;
  2054. // Handle leaf_route
  2055. if ($leaf_route && $route !== $leaf_route) {
  2056. $nodes = explode('/', $leaf_route);
  2057. $sub_route = '/' . implode('/', array_slice($nodes, 1, $data['level']++));
  2058. $data['route'] = $sub_route;
  2059. [$status, $msg, $children, $extra] = $this->getLevelListing($data);
  2060. }
  2061. // Handle no route, assume page tree root
  2062. if (!$route) {
  2063. $is_page = false;
  2064. $route = $this->grav['locator']->findResource('page://', true);
  2065. $root = true;
  2066. }
  2067. if ($is_page) {
  2068. // Try the path
  2069. /** @var PageInterface $page */
  2070. $page = $pages->get(GRAV_ROOT . $route);
  2071. // Try a real route (like homepage)
  2072. if (is_null($page)) {
  2073. $page = $pages->find($route);
  2074. }
  2075. $path = $page ? $page->path() : null;
  2076. } else {
  2077. // Try a physical path
  2078. if (!Utils::startsWith($route, GRAV_ROOT)) {
  2079. $try_path = GRAV_ROOT . $route;
  2080. } else {
  2081. $try_path = $route;
  2082. }
  2083. $path = file_exists($try_path) ? $try_path : null;
  2084. }
  2085. $blueprintsData = $this->admin->page(true);
  2086. if (null !== $blueprintsData) {
  2087. if (method_exists($blueprintsData, 'blueprints')) {
  2088. $settings = $blueprintsData->blueprints()->schema()->getProperty($data['field']);
  2089. } elseif (method_exists($blueprintsData, 'getBlueprint')) {
  2090. $settings = $blueprintsData->getBlueprint()->schema()->getProperty($data['field']);
  2091. }
  2092. $filters = array_merge([], $filters, ($settings['filters'] ?? []));
  2093. $filter_type = $filters['type'] ?? $filter_type;
  2094. }
  2095. if ($path) {
  2096. $status = 'success';
  2097. $msg = 'PLUGIN_ADMIN.PAGE_ROUTE_FOUND';
  2098. foreach (new \DirectoryIterator($path) as $fileInfo) {
  2099. $fileName = $fileInfo->getFilename();
  2100. $filePath = str_replace('\\', '/', $fileInfo->getPathname());
  2101. if (($fileInfo->isDot() && $fileName !== '.' && $initial) || (Utils::startsWith($fileName, '.') && strlen($fileName) > 1)) {
  2102. continue;
  2103. }
  2104. if ($fileInfo->isDot()) {
  2105. if ($root) {
  2106. $payload = [
  2107. 'name' => '<root>',
  2108. 'value' => '',
  2109. 'item-key' => '',
  2110. 'filename' => '.',
  2111. 'extension' => '',
  2112. 'type' => 'root',
  2113. 'modified' => $fileInfo->getMTime(),
  2114. 'size' => 0,
  2115. 'has-children' => false
  2116. ];
  2117. } else {
  2118. continue;
  2119. }
  2120. } else {
  2121. $file_page = $page_instances[$filePath] ?? null;
  2122. $file_path = Utils::replaceFirstOccurrence(GRAV_ROOT, '', $filePath);
  2123. $type = $fileInfo->getType();
  2124. $child_path = $file_page ? $file_page->path() : $filePath;
  2125. $count_children = Folder::countChildren($child_path);
  2126. $payload = [
  2127. 'name' => $file_page ? $file_page->title() : $fileName,
  2128. 'value' => $file_page ? $file_page->rawRoute() : $file_path,
  2129. 'item-key' => basename($file_page ? $file_page->route() : $file_path),
  2130. 'filename' => $fileName,
  2131. 'extension' => $type === 'dir' ? '' : $fileInfo->getExtension(),
  2132. 'type' => $type,
  2133. 'modified' => $fileInfo->getMTime(),
  2134. 'size' => $count_children,
  2135. 'symlink' => false,
  2136. 'has-children' => $count_children > 0
  2137. ];
  2138. }
  2139. // Fix for symlink
  2140. if ($payload['type'] === 'link') {
  2141. $payload['symlink'] = true;
  2142. $physical_path = $fileInfo->getRealPath();
  2143. $payload['type'] = is_dir($physical_path) ? 'dir' : 'file';
  2144. }
  2145. // filter types
  2146. if ($filters['type']) {
  2147. if (!in_array($payload['type'], $filter_type)) {
  2148. continue;
  2149. }
  2150. }
  2151. // Simple filter for name or extension
  2152. if (($filters['name'] && Utils::contains($payload['basename'], $filters['name'])) ||
  2153. ($filters['extension'] && Utils::contains($payload['extension'], $filters['extension']))) {
  2154. continue;
  2155. }
  2156. // Add children if any
  2157. if ($filePath === $extra && is_array($children)) {
  2158. $payload['children'] = array_values($children);
  2159. }
  2160. $response[] = $payload;
  2161. }
  2162. } else {
  2163. $msg = 'PLUGIN_ADMIN.PAGE_ROUTE_NOT_FOUND';
  2164. }
  2165. // Sorting
  2166. $response = Utils::sortArrayByKey($response, $sortby, $order);
  2167. $temp_array = [];
  2168. foreach ($response as $index => $item) {
  2169. $temp_array[$item['type']][$index] = $item;
  2170. }
  2171. $sorted = Utils::sortArrayByArray($temp_array, $filter_type);
  2172. $response = Utils::arrayFlatten($sorted);
  2173. return [$status, $this->admin::translate($msg ?? 'PLUGIN_ADMIN.NO_ROUTE_PROVIDED'), $response, $path];
  2174. }
  2175. /**
  2176. * Get page media.
  2177. *
  2178. * @param PageInterface|null $page
  2179. * @return Media|null
  2180. */
  2181. public function getMedia(PageInterface $page = null)
  2182. {
  2183. $page = $page ?? $this->admin->page($this->route);
  2184. if (!$page) {
  2185. return null;
  2186. }
  2187. $this->uri = $this->uri ?? $this->grav['uri'];
  2188. $field = (string)$this->uri->post('field', '');
  2189. $order = $this->uri->post('order') ?: null;
  2190. if ($order && is_string($order)) {
  2191. $order = array_map('trim', explode(',', $order));
  2192. }
  2193. $blueprints = $page->blueprints();
  2194. $settings = $this->getMediaFieldSettings($blueprints, $field);
  2195. $path = $settings['destination'] ?? $page->path();
  2196. return $path ? new Media($path, $order) : null;
  2197. }
  2198. /**
  2199. * @param Data\Blueprint|null $blueprint
  2200. * @param string $field
  2201. * @return array|null
  2202. */
  2203. protected function getMediaFieldSettings(?Data\Blueprint $blueprint, string $field): ?array
  2204. {
  2205. $schema = $blueprint ? $blueprint->schema() : null;
  2206. if (!$schema || $field === '') {
  2207. return null;
  2208. }
  2209. $settings = is_object($schema) ? (array)$schema->getProperty($field) : null;
  2210. if (null === $settings) {
  2211. return null;
  2212. }
  2213. if (empty($settings['destination']) || \in_array($settings['destination'], ['@self', 'self@', '@self@'], true)) {
  2214. unset($settings['destination']);
  2215. }
  2216. return $settings + ['accept' => '*', 'limit' => 1000];
  2217. }
  2218. /**
  2219. * @return string
  2220. */
  2221. protected function getDataType()
  2222. {
  2223. return trim("{$this->view}/{$this->admin->route}", '/');
  2224. }
  2225. /**
  2226. * Gets the configuration data for a given view & post
  2227. *
  2228. * @param array $data
  2229. * @return object
  2230. */
  2231. protected function prepareData(array $data)
  2232. {
  2233. $type = $this->getDataType();
  2234. return $this->admin->data($type, $data);
  2235. }
  2236. /**
  2237. * Prepare a page to be stored: update its folder, name, template, header and content
  2238. *
  2239. * @param PageInterface $page
  2240. * @param bool $clean_header
  2241. * @param string $languageCode
  2242. * @return void
  2243. */
  2244. protected function preparePage(PageInterface $page, $clean_header = false, $languageCode = ''): void
  2245. {
  2246. $input = (array)$this->data;
  2247. $this->admin::enablePages();
  2248. if (isset($input['folder']) && $input['folder'] !== $page->value('folder')) {
  2249. $order = $page->value('order');
  2250. $ordering = $order ? sprintf('%02d.', $order) : '';
  2251. $page->folder($ordering . $input['folder']);
  2252. }
  2253. if (isset($input['name']) && !empty($input['name'])) {
  2254. $type = strtolower($input['name']);
  2255. $page->template($type);
  2256. $name = preg_replace('|.*/|', '', $type);
  2257. /** @var Language $language */
  2258. $language = $this->grav['language'];
  2259. if ($language->enabled()) {
  2260. $languageCode = $languageCode ?: $language->getLanguage();
  2261. if ($languageCode) {
  2262. $isDefault = $languageCode === $language->getDefault();
  2263. $includeLang = !$isDefault || (bool)$this->grav['config']->get('system.languages.include_default_lang_file_extension', true);
  2264. if (!$includeLang) {
  2265. // Check if the language specific file exists; use it if it does.
  2266. $includeLang = file_exists("{$page->path()}/{$name}.{$languageCode}.md");
  2267. }
  2268. // Keep existing .md file if we're updating default language, otherwise always append the language.
  2269. if ($includeLang) {
  2270. $name .= '.' . $languageCode;
  2271. }
  2272. }
  2273. }
  2274. $name .= '.md';
  2275. $page->name($name);
  2276. }
  2277. // Special case for Expert mode: build the raw, unset content
  2278. if (isset($input['frontmatter'], $input['content'])) {
  2279. $page->raw("---\n" . (string)$input['frontmatter'] . "\n---\n" . (string)$input['content']);
  2280. unset($input['content']);
  2281. // Handle header normally
  2282. } elseif (isset($input['header'])) {
  2283. $header = $input['header'];
  2284. foreach ($header as $key => $value) {
  2285. if ($key === 'metadata' && is_array($header[$key])) {
  2286. foreach ($header['metadata'] as $key2 => $value2) {
  2287. if (isset($input['toggleable_header']['metadata'][$key2]) && !$input['toggleable_header']['metadata'][$key2]) {
  2288. $header['metadata'][$key2] = '';
  2289. }
  2290. }
  2291. } elseif ($key === 'taxonomy' && is_array($header[$key])) {
  2292. foreach ($header[$key] as $taxkey => $taxonomy) {
  2293. if (is_array($taxonomy) && \count($taxonomy) === 1 && trim($taxonomy[0]) === '') {
  2294. unset($header[$key][$taxkey]);
  2295. }
  2296. }
  2297. } else {
  2298. if (isset($input['toggleable_header'][$key]) && !$input['toggleable_header'][$key]) {
  2299. $header[$key] = null;
  2300. }
  2301. }
  2302. }
  2303. if ($clean_header) {
  2304. $header = Utils::arrayFilterRecursive($header, function ($k, $v) {
  2305. return !(null === $v || $v === '');
  2306. });
  2307. }
  2308. $page->header((object)$header);
  2309. $page->frontmatter(Yaml::dump((array)$page->header(), 20));
  2310. }
  2311. // Fill content last because it also renders the output.
  2312. if (isset($input['content'])) {
  2313. $page->rawMarkdown((string)$input['content']);
  2314. }
  2315. }
  2316. /**
  2317. * Find the first available $item ('slug' | 'folder') for a page
  2318. * Used when copying a page, to determine the first available slot
  2319. *
  2320. * @param string $item
  2321. * @param PageInterface $page
  2322. * @return string The first available slot
  2323. */
  2324. protected function findFirstAvailable($item, PageInterface $page)
  2325. {
  2326. $parent = $page->parent();
  2327. if (!$parent || !$parent->children()) {
  2328. return $page->{$item}();
  2329. }
  2330. $withoutPrefix = function ($string) {
  2331. $match = preg_split('/^[0-9]+\./u', $string, 2, PREG_SPLIT_DELIM_CAPTURE);
  2332. return $match[1] ?? $match[0];
  2333. };
  2334. $withoutPostfix = function ($string) {
  2335. $match = preg_split('/-(\d+)$/', $string, 2, PREG_SPLIT_DELIM_CAPTURE);
  2336. return $match[0];
  2337. };
  2338. /* $appendedNumber = function ($string) {
  2339. $match = preg_split('/-(\d+)$/', $string, 2, PREG_SPLIT_DELIM_CAPTURE);
  2340. $append = (isset($match[1]) ? (int)$match[1] + 1 : 2);
  2341. return $append;
  2342. };*/
  2343. $highest = 1;
  2344. $siblings = $parent->children();
  2345. $findCorrectAppendedNumber = function ($item, $page_item, $highest) use (
  2346. $siblings,
  2347. &$findCorrectAppendedNumber,
  2348. &$withoutPrefix
  2349. ) {
  2350. foreach ($siblings as $sibling) {
  2351. if ($withoutPrefix($sibling->{$item}()) == ($highest === 1 ? $page_item : $page_item . '-' . $highest)) {
  2352. $highest = $findCorrectAppendedNumber($item, $page_item, $highest + 1);
  2353. return $highest;
  2354. }
  2355. }
  2356. return $highest;
  2357. };
  2358. $base = $withoutPrefix($withoutPostfix($page->$item()));
  2359. $return = $base;
  2360. $highest = $findCorrectAppendedNumber($item, $base, $highest);
  2361. if ($highest > 1) {
  2362. $return .= '-' . $highest;
  2363. }
  2364. return $return;
  2365. }
  2366. /**
  2367. * @param string $frontmatter
  2368. * @return bool
  2369. */
  2370. public function checkValidFrontmatter($frontmatter)
  2371. {
  2372. try {
  2373. Yaml::parse($frontmatter);
  2374. } catch (\RuntimeException $e) {
  2375. return false;
  2376. }
  2377. return true;
  2378. }
  2379. /**
  2380. * The what should be the new filename when saving as a new language
  2381. *
  2382. * @param string $current_filename the current file name, including .md. Example: default.en.md
  2383. * @param string $language The new language it will be saved as. Example: 'it' or 'en-GB'.
  2384. * @return string The new filename. Example: 'default.it'
  2385. */
  2386. public function determineFilenameIncludingLanguage($current_filename, $language)
  2387. {
  2388. $ext = '.md';
  2389. $filename = substr($current_filename, 0, -strlen($ext));
  2390. $languages_enabled = $this->grav['config']->get('system.languages.supported', []);
  2391. $parts = explode('.', trim($filename, '.'));
  2392. $lang = array_pop($parts);
  2393. if ($lang === $language) {
  2394. return $filename . $ext;
  2395. }
  2396. if (in_array($lang, $languages_enabled, true)) {
  2397. $filename = implode('.', $parts);
  2398. }
  2399. return $filename . '.' . $language . $ext;
  2400. }
  2401. /**
  2402. * Get the next available ordering number in a folder
  2403. *
  2404. * @param string $path
  2405. * @return string the correct order string to prepend
  2406. */
  2407. public static function getNextOrderInFolder($path)
  2408. {
  2409. $files = Folder::all($path, ['recursive' => false]);
  2410. $highestOrder = 0;
  2411. foreach ($files as $file) {
  2412. preg_match(PAGE_ORDER_PREFIX_REGEX, $file, $order);
  2413. if (isset($order[0])) {
  2414. $theOrder = (int)trim($order[0], '.');
  2415. } else {
  2416. $theOrder = 0;
  2417. }
  2418. if ($theOrder >= $highestOrder) {
  2419. $highestOrder = $theOrder;
  2420. }
  2421. }
  2422. $orderOfNewFolder = $highestOrder + 1;
  2423. if ($orderOfNewFolder < 10) {
  2424. $orderOfNewFolder = '0' . $orderOfNewFolder;
  2425. }
  2426. return $orderOfNewFolder;
  2427. }
  2428. /**
  2429. * Used in 3rd party editors (e.g. next-gen).
  2430. *
  2431. * @return ResponseInterface|false
  2432. */
  2433. protected function taskConvertUrls()
  2434. {
  2435. if (!$this->authorizeTask('access page', ['admin.pages', 'admin.pages.list', 'admin.super'])) {
  2436. $this->admin->json_response = [
  2437. 'status' => 'error',
  2438. 'message' => $this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK')
  2439. ];
  2440. return false;
  2441. }
  2442. $request = $this->getRequest();
  2443. $data = $request->getParsedBody();
  2444. $converted_links = [];
  2445. $converted_images = [];
  2446. $status = 'success';
  2447. $message = 'All links converted';
  2448. $data['route'] = isset($data['route']) ? base64_decode($data['route']) : null;
  2449. $data['data'] = json_decode($data['data'] ?? '{}', true);
  2450. // use the route if passed, else use current page in admin as reference
  2451. $page_route = $data['route'] ?? $this->admin->page(true);
  2452. /** @var PageInterface */
  2453. $pages = $this->admin::enablePages();
  2454. $page = $pages->find($page_route);
  2455. if (!$page) {
  2456. throw new RequestException($request,'Page Not Found', 404);
  2457. }
  2458. if (!isset($data['data'])) {
  2459. throw new RequestException($request, 'Bad Request', 400);
  2460. }
  2461. foreach ($data['data']['a'] ?? [] as $link) {
  2462. $converted_links[$link] = Excerpts::processLinkHtml($link, $page);
  2463. }
  2464. foreach ($data['data']['img'] ?? [] as $image) {
  2465. $converted_images[$image] = Excerpts::processImageHtml($image, $page);
  2466. }
  2467. $json = [
  2468. 'status' => $status,
  2469. 'message' => $message,
  2470. 'data' => ['links' => $converted_links, 'images' => $converted_images]
  2471. ];
  2472. return $this->createJsonResponse($json, 200);
  2473. }
  2474. }