AdminController.php 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911
  1. <?php
  2. namespace Grav\Plugin\FlexObjects\Admin;
  3. use Exception;
  4. use Grav\Common\Cache;
  5. use Grav\Common\Config\Config;
  6. use Grav\Common\Data\Data;
  7. use Grav\Common\Debugger;
  8. use Grav\Common\Filesystem\Folder;
  9. use Grav\Common\Flex\Types\Pages\PageCollection;
  10. use Grav\Common\Flex\Types\Pages\PageIndex;
  11. use Grav\Common\Flex\Types\Pages\PageObject;
  12. use Grav\Common\Grav;
  13. use Grav\Common\Language\Language;
  14. use Grav\Common\Page\Interfaces\PageInterface;
  15. use Grav\Common\Uri;
  16. use Grav\Common\User\Interfaces\UserInterface;
  17. use Grav\Common\Utils;
  18. use Grav\Framework\Controller\Traits\ControllerResponseTrait;
  19. use Grav\Framework\File\Formatter\CsvFormatter;
  20. use Grav\Framework\File\Formatter\YamlFormatter;
  21. use Grav\Framework\File\Interfaces\FileFormatterInterface;
  22. use Grav\Framework\Flex\FlexForm;
  23. use Grav\Framework\Flex\FlexFormFlash;
  24. use Grav\Framework\Flex\FlexObject;
  25. use Grav\Framework\Flex\Interfaces\FlexAuthorizeInterface;
  26. use Grav\Framework\Flex\Interfaces\FlexCollectionInterface;
  27. use Grav\Framework\Flex\Interfaces\FlexDirectoryInterface;
  28. use Grav\Framework\Flex\Interfaces\FlexFormInterface;
  29. use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
  30. use Grav\Framework\Flex\Interfaces\FlexTranslateInterface;
  31. use Grav\Framework\Object\Interfaces\ObjectInterface;
  32. use Grav\Framework\Psr7\Response;
  33. use Grav\Framework\RequestHandler\Exception\RequestException;
  34. use Grav\Framework\Route\Route;
  35. use Grav\Framework\Route\RouteFactory;
  36. use Grav\Plugin\Admin\Admin;
  37. use Grav\Plugin\FlexObjects\Controllers\MediaController;
  38. use Grav\Plugin\FlexObjects\Flex;
  39. use Nyholm\Psr7\ServerRequest;
  40. use Psr\Http\Message\ResponseInterface;
  41. use Psr\Http\Message\ServerRequestInterface;
  42. use RocketTheme\Toolbox\Event\Event;
  43. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  44. use RocketTheme\Toolbox\Session\Message;
  45. use RuntimeException;
  46. use function dirname;
  47. use function in_array;
  48. use function is_array;
  49. use function is_callable;
  50. /**
  51. * Class AdminController
  52. * @package Grav\Plugin\FlexObjects
  53. */
  54. class AdminController
  55. {
  56. use ControllerResponseTrait;
  57. /** @var AdminController|null */
  58. private static $instance;
  59. /** @var Grav */
  60. public $grav;
  61. /** @var string */
  62. public $view;
  63. /** @var string */
  64. public $task;
  65. /** @var Route|null */
  66. public $route;
  67. /** @var array */
  68. public $post;
  69. /** @var array|null */
  70. public $data;
  71. /** @var array */
  72. protected $adminRoutes;
  73. /** @var Uri */
  74. protected $uri;
  75. /** @var Admin */
  76. protected $admin;
  77. /** @var UserInterface */
  78. protected $user;
  79. /** @var string */
  80. protected $redirect;
  81. /** @var int */
  82. protected $redirectCode;
  83. /** @var Route */
  84. protected $currentRoute;
  85. /** @var Route */
  86. protected $referrerRoute;
  87. /** @var string|null */
  88. protected $action;
  89. /** @var string|null */
  90. protected $location;
  91. /** @var string|null */
  92. protected $target;
  93. /** @var string|null */
  94. protected $id;
  95. /** @var bool */
  96. protected $active;
  97. /** @var FlexObjectInterface|false|null */
  98. protected $object;
  99. /** @var FlexCollectionInterface|null */
  100. protected $collection;
  101. /** @var FlexDirectoryInterface|null */
  102. protected $directory;
  103. /** @var string */
  104. protected $nonce_name = 'admin-nonce';
  105. /** @var string */
  106. protected $nonce_action = 'admin-form';
  107. /** @var string */
  108. protected $task_prefix = 'task';
  109. /** @var string */
  110. protected $action_prefix = 'action';
  111. /**
  112. * Unknown task, call onFlexTask[NAME] event.
  113. *
  114. * @return bool
  115. */
  116. public function taskDefault(): bool
  117. {
  118. $type = $this->target;
  119. $directory = $this->getDirectory($type);
  120. if (!$directory) {
  121. throw new RuntimeException('Not Found', 404);
  122. }
  123. $object = $this->getObject();
  124. $key = $this->id;
  125. if ($object && $object->exists()) {
  126. $event = new Event(
  127. [
  128. 'type' => $type,
  129. 'key' => $key,
  130. 'admin' => $this->admin,
  131. 'flex' => $this->getFlex(),
  132. 'directory' => $directory,
  133. 'object' => $object,
  134. 'data' => $this->data,
  135. 'redirect' => $this->redirect
  136. ]
  137. );
  138. try {
  139. $this->grav->fireEvent('onFlexTask' . ucfirst($this->task), $event);
  140. } catch (Exception $e) {
  141. /** @var Debugger $debugger */
  142. $debugger = $this->grav['debugger'];
  143. $debugger->addException($e);
  144. $this->admin->setMessage($e->getMessage(), 'error');
  145. }
  146. $redirect = $event['redirect'];
  147. if ($redirect) {
  148. $this->setRedirect($redirect);
  149. }
  150. return $event->isPropagationStopped();
  151. }
  152. return false;
  153. }
  154. /**
  155. * Default action, onFlexAction[NAME] event.
  156. *
  157. * @return bool
  158. */
  159. public function actionDefault(): bool
  160. {
  161. $type = $this->target;
  162. $directory = $this->getDirectory($type);
  163. if (!$directory) {
  164. throw new RuntimeException('Not Found', 404);
  165. }
  166. $object = $this->getObject();
  167. $key = $this->id;
  168. if ($object && $object->exists()) {
  169. $event = new Event(
  170. [
  171. 'type' => $type,
  172. 'key' => $key,
  173. 'admin' => $this->admin,
  174. 'flex' => $this->getFlex(),
  175. 'directory' => $directory,
  176. 'object' => $object,
  177. 'redirect' => $this->redirect
  178. ]
  179. );
  180. try {
  181. $this->grav->fireEvent('onFlexAction' . ucfirst($this->action), $event);
  182. } catch (Exception $e) {
  183. /** @var Debugger $debugger */
  184. $debugger = $this->grav['debugger'];
  185. $debugger->addException($e);
  186. $this->admin->setMessage($e->getMessage(), 'error');
  187. }
  188. $redirect = $event['redirect'];
  189. if ($redirect) {
  190. $this->setRedirect($redirect);
  191. }
  192. return $event->isPropagationStopped();
  193. }
  194. return false;
  195. }
  196. /**
  197. * Get datatable for list view.
  198. *
  199. * @return void
  200. */
  201. public function actionList(): void
  202. {
  203. $directory = $this->getDirectory();
  204. if (!$directory) {
  205. throw new RuntimeException('Not Found', 404);
  206. }
  207. // Check authorization.
  208. if (!$directory->isAuthorized('list', 'admin', $this->user)) {
  209. throw new RuntimeException($this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' list.', 403);
  210. }
  211. /** @var Uri $uri */
  212. $uri = $this->grav['uri'];
  213. if ($uri->extension() === 'json') {
  214. $options = [
  215. 'collection' => $this->getCollection(),
  216. 'url' => $uri->path(),
  217. 'page' => $uri->query('page'),
  218. 'limit' => $uri->query('per_page'),
  219. 'sort' => $uri->query('sort'),
  220. 'search' => $uri->query('filter'),
  221. 'filters' => $uri->query('filters'),
  222. ];
  223. $table = $this->getFlex()->getDataTable($directory, $options);
  224. $response = $this->createJsonResponse($table->jsonSerialize());
  225. $this->close($response);
  226. }
  227. }
  228. /**
  229. * Alias for Export action.
  230. *
  231. * @return void
  232. */
  233. public function actionCsv(): void
  234. {
  235. $this->actionExport();
  236. }
  237. /**
  238. * Export action. Defaults to CVS export.
  239. *
  240. * @return void
  241. */
  242. public function actionExport(): void
  243. {
  244. $collection = $this->getCollection();
  245. if (!$collection) {
  246. throw new RuntimeException('Not Found', 404);
  247. }
  248. // Check authorization.
  249. $directory = $collection->getFlexDirectory();
  250. $authorized = is_callable([$collection, 'isAuthorized'])
  251. ? $collection->isAuthorized('read', 'admin', $this->user)
  252. : $directory->isAuthorized('read', 'admin', $this->user);
  253. if (!$authorized) {
  254. throw new RuntimeException($this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' read.', 403);
  255. }
  256. $config = $collection->getFlexDirectory()->getConfig('admin.views.export') ?? $collection->getFlexDirectory()->getConfig('admin.export') ?? false;
  257. if (!$config || empty($config['enabled'])) {
  258. throw new RuntimeException($this->admin::translate('Not Found'), 404);
  259. }
  260. $queryParams = $this->getRequest()->getQueryParams();
  261. $type = $queryParams['type'] ?? null;
  262. if ($type) {
  263. $config = $config['options'][$type] ?? null;
  264. if (!$config) {
  265. throw new RuntimeException($this->admin::translate('Not Found'), 404);
  266. }
  267. }
  268. $defaultFormatter = CsvFormatter::class;
  269. $class = trim($config['formatter']['class'] ?? $defaultFormatter, '\\');
  270. $method = $config['method'] ?? ($class === $defaultFormatter ? 'csvSerialize' : 'jsonSerialize');
  271. if (!class_exists($class)) {
  272. throw new RuntimeException($this->admin::translate('Formatter Not Found'), 404);
  273. }
  274. /** @var FileFormatterInterface $formatter */
  275. $formatter = new $class($config['formatter']['options'] ?? []);
  276. $filename = ($config['filename'] ?? 'export') . $formatter->getDefaultFileExtension();
  277. if (method_exists($collection, $method)) {
  278. $list = $type ? $collection->{$method}($type) : $collection->{$method}();
  279. } else {
  280. $list = [];
  281. /** @var ObjectInterface $object */
  282. foreach ($collection as $object) {
  283. if (method_exists($object, $method)) {
  284. $data = $object->{$method}();
  285. if ($data) {
  286. $list[] = $data;
  287. }
  288. } else {
  289. $list[] = $object->jsonSerialize();
  290. }
  291. }
  292. }
  293. $response = new Response(
  294. 200,
  295. [
  296. 'Content-Type' => $formatter->getMimeType(),
  297. 'Content-Disposition' => 'inline; filename="' . $filename . '"',
  298. 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
  299. 'Last-Modified' => gmdate('D, d M Y H:i:s') . ' GMT',
  300. 'Cache-Control' => 'no-store, no-cache, must-revalidate',
  301. 'Pragma' => 'no-cache',
  302. ],
  303. $formatter->encode($list)
  304. );
  305. $this->close($response);
  306. }
  307. /**
  308. * Delete object from directory.
  309. *
  310. * @return ObjectInterface|bool
  311. */
  312. public function taskDelete()
  313. {
  314. $directory = $this->getDirectory();
  315. if (!$directory) {
  316. throw new RuntimeException('Not Found', 404);
  317. }
  318. $object = null;
  319. try {
  320. $object = $this->getObject();
  321. if ($object && $object->exists()) {
  322. $authorized = $object instanceof FlexAuthorizeInterface
  323. ? $object->isAuthorized('delete', 'admin', $this->user)
  324. : $directory->isAuthorized('delete', 'admin', $this->user);
  325. if (!$authorized) {
  326. throw new RuntimeException($this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' delete.', 403);
  327. }
  328. $object->delete();
  329. $this->admin->setMessage($this->admin::translate('PLUGIN_FLEX_OBJECTS.CONTROLLER.TASK_DELETE_SUCCESS'));
  330. if ($this->currentRoute->withoutGravParams()->getRoute() === $this->referrerRoute->getRoute()) {
  331. $redirect = dirname($this->currentRoute->withoutGravParams()->toString(true));
  332. } else {
  333. $redirect = $this->referrerRoute->toString(true);
  334. }
  335. $this->setRedirect($redirect);
  336. $this->grav->fireEvent('onFlexAfterDelete', new Event(['type' => 'flex', 'object' => $object]));
  337. }
  338. } catch (RuntimeException $e) {
  339. $this->admin->setMessage($this->admin::translate(['PLUGIN_FLEX_OBJECTS.CONTROLLER.TASK_DELETE_FAILURE', $e->getMessage()]), 'error');
  340. $this->setRedirect($this->referrerRoute->toString(true), 302);
  341. }
  342. return $object !== null;
  343. }
  344. /**
  345. * Create a new empty folder (from modal).
  346. *
  347. * TODO: Move pages specific logic
  348. *
  349. * @return void
  350. */
  351. public function taskSaveNewFolder(): void
  352. {
  353. $directory = $this->getDirectory();
  354. if (!$directory) {
  355. throw new RuntimeException('Not Found', 404);
  356. }
  357. $collection = $directory->getIndex();
  358. if (!($collection instanceof PageCollection || $collection instanceof PageIndex)) {
  359. throw new RuntimeException('Task saveNewFolder works only for pages', 400);
  360. }
  361. $data = $this->data;
  362. $route = trim($data['route'] ?? '', '/');
  363. // TODO: Folder name needs to be validated! However we test against /="' as they are dangerous characters.
  364. $folder = mb_strtolower($data['folder'] ?? '');
  365. if ($folder === '' || preg_match('![="\']!u', $folder) !== 0) {
  366. throw new RuntimeException('Creating folder failed, bad folder name', 400);
  367. }
  368. $parent = $route ? $directory->getObject($route) : $collection->getRoot();
  369. if (!$parent instanceof PageObject) {
  370. throw new RuntimeException('Creating folder failed, bad parent route', 400);
  371. }
  372. if (!$parent->isAuthorized('create', 'admin', $this->user)) {
  373. throw new RuntimeException($this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' create.', 403);
  374. }
  375. $path = $parent->getFlexDirectory()->getStorageFolder($parent->getStorageKey());
  376. if (!$path) {
  377. throw new RuntimeException('Creating folder failed, bad parent storage path', 400);
  378. }
  379. // Ordering
  380. $orders = $parent->children()->visible()->getProperty('order');
  381. $maxOrder = 0;
  382. foreach ($orders as $order) {
  383. $maxOrder = max($maxOrder, (int)$order);
  384. }
  385. $orderOfNewFolder = $maxOrder ? sprintf('%02d.', $maxOrder+1) : '';
  386. $new_path = $path . '/' . $orderOfNewFolder . $folder;
  387. /** @var UniformResourceLocator $locator */
  388. $locator = $this->grav['locator'];
  389. if ($locator->isStream($new_path)) {
  390. $new_path = $locator->findResource($new_path, true, true);
  391. } else {
  392. $new_path = GRAV_ROOT . '/' . $new_path;
  393. }
  394. Folder::create($new_path);
  395. Cache::clearCache('invalidate');
  396. $directory->getCache('index')->clear();
  397. $this->grav->fireEvent('onAdminAfterSaveAs', new Event(['path' => $new_path]));
  398. $this->admin->setMessage($this->admin::translate('PLUGIN_FLEX_OBJECTS.CONTROLLER.TASK_NEW_FOLDER_SUCCESS'));
  399. $this->setRedirect($this->referrerRoute->toString(true));
  400. }
  401. /**
  402. * Create a new object (from modal).
  403. *
  404. * TODO: Move pages specific logic
  405. *
  406. * @return void
  407. */
  408. public function taskContinue(): void
  409. {
  410. $directory = $this->getDirectory();
  411. if (!$directory) {
  412. throw new RuntimeException('Not Found', 404);
  413. }
  414. if ($directory->getFlexType() === 'pages') {
  415. $this->continuePages($directory);
  416. } else {
  417. $this->continue($directory);
  418. }
  419. }
  420. protected function continue(FlexDirectoryInterface $directory): void
  421. {
  422. $config = $directory->getConfig('admin');
  423. $supported = !empty($config['modals']['add']);
  424. if (!$supported) {
  425. throw new RuntimeException('Task continue is not supported by the type', 400);
  426. }
  427. $authorized = $directory->isAuthorized('create', 'admin', $this->user);
  428. if (!$authorized) {
  429. $this->setRedirect($this->referrerRoute->toString(true));
  430. throw new RuntimeException($this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' add.', 403);
  431. }
  432. $this->object = $directory->createObject($this->data, '');
  433. // Reset form, we are starting from scratch.
  434. /** @var FlexForm $form */
  435. $form = $this->object->getForm('', ['reset' => true]);
  436. /** @var FlexFormFlash $flash */
  437. $flash = $form->getFlash();
  438. $flash->setUrl($this->getFlex()->adminRoute($this->object));
  439. $flash->save(true);
  440. $this->setRedirect($flash->getUrl());
  441. }
  442. /**
  443. * Create a new page (from modal).
  444. *
  445. * TODO: Move pages specific logic
  446. *
  447. * @return void
  448. */
  449. protected function continuePages(FlexDirectoryInterface $directory): void
  450. {
  451. $collection = $directory->getIndex();
  452. $this->data['route'] = '/' . trim($this->data['route'] ?? '', '/');
  453. $route = trim($this->data['route'], '/');
  454. $parent = $route ? $directory->getObject($route) : $collection->getRoot();
  455. $authorized = $parent instanceof FlexAuthorizeInterface
  456. ? $parent->isAuthorized('create', 'admin', $this->user)
  457. : $directory->isAuthorized('create', 'admin', $this->user);
  458. if (!$authorized) {
  459. $this->setRedirect($this->referrerRoute->toString(true));
  460. throw new RuntimeException($this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' add.', 403);
  461. }
  462. $folder = $this->data['folder'] ?? null;
  463. $title = $this->data['title'] ?? null;
  464. if ($title) {
  465. $this->data['header']['title'] = $this->data['title'];
  466. unset($this->data['title']);
  467. }
  468. if (null !== $folder && 0 === strpos($folder, '@slugify-')) {
  469. $folder = \Grav\Plugin\Admin\Utils::slug($this->data[substr($folder, 9)] ?? '');
  470. }
  471. if (!$folder) {
  472. $folder = \Grav\Plugin\Admin\Utils::slug($title) ?: '';
  473. }
  474. $folder = ltrim($folder, '_');
  475. if ($folder === '' || mb_strpos($folder, '/') !== false) {
  476. throw new RuntimeException('Creating page failed: bad folder name', 400);
  477. }
  478. if (!isset($this->data['name'])) {
  479. // Get default child type.
  480. $this->data['name'] = $parent->header()->child_type ?? $parent->getBlueprint()->child_type ?? 'default';
  481. }
  482. if (strpos($this->data['name'], 'modular/') === 0) {
  483. $this->data['header']['body_classes'] = 'modular';
  484. $folder = '_' . $folder;
  485. }
  486. $this->data['folder'] = $folder;
  487. unset($this->data['blueprint']);
  488. $key = trim("{$route}/{$folder}", '/');
  489. if ($directory->getObject($key)) {
  490. throw new RuntimeException("Page '/{$key}' already exists!", 403);
  491. }
  492. $max = 0;
  493. if (isset($this->data['visible'])) {
  494. $auto = $this->data['visible'] === '';
  495. $visible = (bool)($this->data['visible'] ?? false);
  496. unset($this->data['visible']);
  497. // Empty string on visible means auto.
  498. if ($auto || $visible) {
  499. $children = $parent ? $parent->children()->visible() : [];
  500. $max = $auto ? 0 : 1;
  501. foreach ($children as $child) {
  502. $max = max($max, (int)$child->order());
  503. }
  504. }
  505. $this->data['order'] = $max ? $max + 1 : false;
  506. }
  507. $this->data['lang'] = $this->getLanguage();
  508. $header = $this->data['header'] ?? [];
  509. $this->grav->fireEvent('onAdminCreatePageFrontmatter', new Event(['header' => &$header,
  510. 'data' => $this->data]));
  511. $formatter = new YamlFormatter();
  512. $this->data['frontmatter'] = $formatter->encode($header);
  513. $this->data['header'] = $header;
  514. $this->object = $directory->createObject($this->data, $key);
  515. // Reset form, we are starting from scratch.
  516. /** @var FlexForm $form */
  517. $form = $this->object->getForm('', ['reset' => true]);
  518. /** @var FlexFormFlash $flash */
  519. $flash = $form->getFlash();
  520. $flash->setUrl($this->getFlex()->adminRoute($this->object));
  521. $flash->save(true);
  522. // Store the name and route of a page, to be used pre-filled defaults of the form in the future
  523. $this->admin->session()->lastPageName = $this->data['name'] ?? '';
  524. $this->admin->session()->lastPageRoute = $this->data['route'] ?? '';
  525. $this->setRedirect($flash->getUrl());
  526. }
  527. /**
  528. * Save page as a new copy.
  529. *
  530. * Route: /pages
  531. *
  532. * @return bool True if the action was performed.
  533. * @throws RuntimeException
  534. */
  535. protected function taskCopy(): bool
  536. {
  537. try {
  538. $directory = $this->getDirectory();
  539. if (!$directory) {
  540. throw new RuntimeException('Not Found', 404);
  541. }
  542. $object = $this->getObject();
  543. if (!$object || !$object->exists() || !is_callable([$object, 'createCopy'])) {
  544. throw new RuntimeException('Not Found', 404);
  545. }
  546. // Pages are a special case.
  547. $parent = $object instanceof PageInterface ? $object->parent() : $object;
  548. $authorized = $parent instanceof FlexAuthorizeInterface
  549. ? $parent->isAuthorized('create', 'admin', $this->user)
  550. : $directory->isAuthorized('create', 'admin', $this->user);
  551. if (!$authorized || !$parent) {
  552. throw new RuntimeException($this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' copy.',
  553. 403);
  554. }
  555. if ($object instanceof PageInterface && is_array($this->data)) {
  556. $data = $this->data;
  557. $blueprints = $this->admin->blueprints('admin/pages/move');
  558. $blueprints->validate($data);
  559. $data = $blueprints->filter($data, true, true);
  560. // Hack for pages
  561. $data['name'] = $data['name'] ?? $object->template();
  562. $data['ordering'] = (int)$object->order() > 0;
  563. $data['order'] = null;
  564. if (isset($data['title'])) {
  565. $data['header']['title'] = $data['title'];
  566. unset($data['title']);
  567. }
  568. $object->order(false);
  569. $object->update($data);
  570. }
  571. $object = $object->createCopy();
  572. $this->admin->setMessage($this->admin::translate('PLUGIN_FLEX_OBJECTS.CONTROLLER.TASK_COPY_SUCCESS'));
  573. $this->setRedirect($this->getFlex()->adminRoute($object));
  574. } catch (RuntimeException $e) {
  575. $this->admin->setMessage($this->admin::translate(['PLUGIN_FLEX_OBJECTS.CONTROLLER.TASK_COPY_FAILURE', $e->getMessage()]), 'error');
  576. $this->setRedirect($this->referrerRoute->toString(true), 302);
  577. }
  578. return true;
  579. }
  580. /**
  581. * $data['route'] = $this->grav['uri']->param('route');
  582. * $data['sortby'] = $this->grav['uri']->param('sortby', null);
  583. * $data['filters'] = $this->grav['uri']->param('filters', null);
  584. * $data['page'] $this->grav['uri']->param('page', true);
  585. * $data['base'] = $this->grav['uri']->param('base');
  586. * $initial = (bool) $this->grav['uri']->param('initial');
  587. *
  588. * @return ResponseInterface
  589. * @throws RequestException
  590. * @TODO: Move pages specific logic
  591. */
  592. protected function actionGetLevelListing(): ResponseInterface
  593. {
  594. /** @var PageInterface|FlexObjectInterface $object */
  595. $object = $this->getObject($this->id ?? '');
  596. if (!$object || !method_exists($object, 'getLevelListing')) {
  597. throw new RuntimeException('Not Found', 404);
  598. }
  599. $request = $this->getRequest();
  600. $data = $request->getParsedBody();
  601. if (!isset($data['field'])) {
  602. throw new RequestException($request, 'Bad Request', 400);
  603. }
  604. // Base64 decode the route
  605. $data['route'] = isset($data['route']) ? base64_decode($data['route']) : null;
  606. $data['filters'] = json_decode($options['filters'] ?? '{}', true, 512, JSON_THROW_ON_ERROR) + ['type' => ['root', 'dir']];
  607. $initial = $data['initial'] ?? null;
  608. if ($initial) {
  609. $data['leaf_route'] = $data['route'];
  610. $data['route'] = null;
  611. $data['level'] = 1;
  612. }
  613. [$status, $message, $response,$route] = $object->getLevelListing($data);
  614. $json = [
  615. 'status' => $status,
  616. 'message' => $this->admin::translate($message ?? 'PLUGIN_ADMIN.NO_ROUTE_PROVIDED'),
  617. 'route' => $route,
  618. 'initial' => (bool)$initial,
  619. 'data' => array_values($response)
  620. ];
  621. return $this->createJsonResponse($json, 200);
  622. }
  623. /**
  624. * $data['route'] = $this->grav['uri']->param('route');
  625. * $data['sortby'] = $this->grav['uri']->param('sortby', null);
  626. * $data['filters'] = $this->grav['uri']->param('filters', null);
  627. * $data['page'] $this->grav['uri']->param('page', true);
  628. * $data['base'] = $this->grav['uri']->param('base');
  629. * $initial = (bool) $this->grav['uri']->param('initial');
  630. *
  631. * @return ResponseInterface
  632. * @throws RequestException
  633. * @TODO: Move pages specific logic
  634. */
  635. protected function actionListLevel(): ResponseInterface
  636. {
  637. try {
  638. /** @var PageInterface|FlexObjectInterface $object */
  639. $object = $this->getObject('');
  640. if (!$object || !method_exists($object, 'getLevelListing')) {
  641. throw new RuntimeException('Not Found', 404);
  642. }
  643. $directory = $object->getFlexDirectory();
  644. if (!$directory->isAuthorized('list', 'admin', $this->user)) {
  645. throw new RuntimeException($this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' getLevelListing.',
  646. 403);
  647. }
  648. $request = $this->getRequest();
  649. $data = $request->getParsedBody();
  650. // Base64 decode the route
  651. $data['route'] = isset($data['route']) ? base64_decode($data['route']) : null;
  652. $data['filters'] = ($data['filters'] ?? []) + ['type' => ['dir']];
  653. $data['lang'] = $this->getLanguage();
  654. // Display root if permitted.
  655. $action = $directory->getConfig('admin.views.configure.authorize') ?? $directory->getConfig('admin.configure.authorize') ?? 'admin.super';
  656. if ($this->user->authorize($action)) {
  657. $data['filters']['type'][] = 'root';
  658. }
  659. $initial = $data['initial'] ?? null;
  660. if ($initial) {
  661. $data['leaf_route'] = $data['route'];
  662. $data['route'] = null;
  663. $data['level'] = 1;
  664. }
  665. [$status, $message, $response, $route] = $object->getLevelListing($data);
  666. $json = [
  667. 'status' => $status,
  668. 'message' => $this->admin::translate($message ?? 'PLUGIN_ADMIN.NO_ROUTE_PROVIDED'),
  669. 'route' => $route,
  670. 'initial' => (bool)$initial,
  671. 'data' => array_values($response)
  672. ];
  673. } catch (Exception $e) {
  674. return $this->createErrorResponse($e);
  675. }
  676. return $this->createJsonResponse($json, 200);
  677. }
  678. /**
  679. * @return ResponseInterface
  680. */
  681. public function taskReset(): ResponseInterface
  682. {
  683. $key = $this->id;
  684. $object = $this->getObject($key);
  685. if (!$object) {
  686. throw new RuntimeException('Not Found', 404);
  687. }
  688. /** @var FlexForm $form */
  689. $form = $this->getForm($object);
  690. $form->getFlash()->delete();
  691. return $this->createRedirectResponse($this->referrerRoute->toString(true));
  692. }
  693. /**
  694. * @return bool
  695. */
  696. public function taskSaveas(): bool
  697. {
  698. return $this->taskSave();
  699. }
  700. /**
  701. * @return bool
  702. */
  703. public function taskSave(): bool
  704. {
  705. $directory = $this->getDirectory();
  706. if (!$directory) {
  707. throw new RuntimeException('Not Found', 404);
  708. }
  709. $key = $this->id;
  710. try {
  711. $object = $this->getObject($key);
  712. if (!$object) {
  713. throw new RuntimeException('Not Found', 404);
  714. }
  715. $authorized = $object instanceof FlexAuthorizeInterface
  716. ? $object->isAuthorized('save', 'admin', $this->user)
  717. : $directory->isAuthorized($object->exists() ? 'update' : 'create', 'admin', $this->user);
  718. if (!$authorized) {
  719. throw new RuntimeException($this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' save.',
  720. 403);
  721. }
  722. /** @var ServerRequestInterface $request */
  723. $request = $this->grav['request'];
  724. /** @var FlexForm $form */
  725. $form = $this->getForm($object);
  726. $callable = function (array $data, array $files, FlexObject $object) use ($form) {
  727. if (method_exists($object, 'storeOriginal')) {
  728. $object->storeOriginal();
  729. }
  730. $object->update($data, $files);
  731. // Support for expert mode.
  732. if (str_ends_with($form->getId(), '-raw') && isset($data['frontmatter']) && is_callable([$object, 'frontmatter'])) {
  733. if (!$this->user->authorize('admin.super')) {
  734. throw new RuntimeException($this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' save raw.',
  735. 403);
  736. }
  737. $object->frontmatter($data['frontmatter']);
  738. unset($data['frontmatter']);
  739. }
  740. if (is_callable([$object, 'check'])) {
  741. $object->check($this->user);
  742. }
  743. $object->save();
  744. };
  745. $form->setSubmitMethod($callable);
  746. $form->handleRequest($request);
  747. $error = $form->getError();
  748. $errors = $form->getErrors();
  749. if ($errors) {
  750. if ($error) {
  751. $this->admin->setMessage($error, 'error');
  752. }
  753. foreach ($errors as $field => $list) {
  754. foreach ((array)$list as $message) {
  755. $this->admin->setMessage($message, 'error');
  756. }
  757. }
  758. throw new RuntimeException('Form validation failed, please check your input');
  759. }
  760. if ($error) {
  761. throw new RuntimeException($error);
  762. }
  763. $object = $form->getObject();
  764. $objectKey = $object->getKey();
  765. $this->admin->setMessage($this->admin::translate('PLUGIN_FLEX_OBJECTS.CONTROLLER.TASK_SAVE_SUCCESS'));
  766. // Set route to point to the current page.
  767. if (!$this->redirect) {
  768. $postAction = $request->getParsedBody()['_post_entries_save'] ?? 'edit';
  769. if ($postAction === 'create-new') {
  770. // Create another.
  771. $route = $this->referrerRoute->withGravParam('action', null)->withGravParam('', 'add');
  772. } elseif ($postAction === 'list') {
  773. // Back to listing.
  774. $route = $this->currentRoute;
  775. // Remove :add action.
  776. $actionAdd = $key === '' || $route->getGravParam('action') === 'add' || $route->getGravParam('') === 'add';
  777. if ($actionAdd) {
  778. $route = $route->withGravParam('action', null)->withGravParam('', null);
  779. }
  780. $len = ($key === '' ? 0 : -1) - \substr_count($key, '/');
  781. if ($len) {
  782. $route = $route->withRoute($route->getRoute(0, $len));
  783. }
  784. } else {
  785. // Back to edit.
  786. $route = $this->currentRoute;
  787. $isRoot = $object instanceof PageInterface && $object->root();
  788. $hasKeyChanged = !$isRoot && $key !== $objectKey;
  789. // Remove :add action.
  790. $actionAdd = $key === '' || $route->getGravParam('action') === 'add' || $route->getGravParam('') === 'add';
  791. if ($actionAdd) {
  792. $route = $route->withGravParam('action', null)->withGravParam('', null);
  793. }
  794. if ($hasKeyChanged) {
  795. if ($key === '') {
  796. // Append new key.
  797. $path = $route->getRoute() . '/' . $objectKey;
  798. } elseif ($objectKey === '') {
  799. // Remove old key.
  800. $path = preg_replace('|/' . preg_quote($key, '|') . '$|u', '/', $route->getRoute());
  801. } else {
  802. // Replace old key with new key.
  803. $path = preg_replace('|/' . preg_quote($key, '|') . '$|u', '/' . $objectKey, $route->getRoute());
  804. }
  805. $route = $route->withRoute($path);
  806. }
  807. // Make sure we're using the correct language.
  808. $lang = null;
  809. if ($object instanceof FlexTranslateInterface) {
  810. $lang = $object->getLanguage();
  811. $route = $route->withLanguage($lang);
  812. }
  813. }
  814. $this->setRedirect($route->toString(true));
  815. }
  816. $this->grav->fireEvent('onFlexAfterSave', new Event(['type' => 'flex', 'object' => $object]));
  817. } catch (RuntimeException $e) {
  818. $this->admin->setMessage($this->admin::translate(['PLUGIN_FLEX_OBJECTS.CONTROLLER.TASK_SAVE_FAILURE', $e->getMessage()]), 'error');
  819. if (isset($object, $form)) {
  820. $data = $form->getData();
  821. if (null !== $data) {
  822. $flash = $form->getFlash();
  823. $flash->setObject($object);
  824. if ($data instanceof Data) {
  825. $flash->setData($data->toArray());
  826. }
  827. $flash->save();
  828. }
  829. }
  830. // $this->setRedirect($this->referrerRoute->withQueryParam('uid', $flash->getUniqueId())->toString(true), 302);
  831. $this->setRedirect($this->referrerRoute->toString(true), 302);
  832. }
  833. return true;
  834. }
  835. /**
  836. * @return bool
  837. */
  838. public function taskConfigure(): bool
  839. {
  840. $directory = $this->getDirectory();
  841. if (!$directory) {
  842. throw new RuntimeException('Not Found', 404);
  843. }
  844. try {
  845. $config = $directory->getConfig('admin.views.configure.authorize') ?? $directory->getConfig('admin.configure.authorize') ?? 'admin.super';
  846. if (!$this->user->authorize($config)) {
  847. throw new RuntimeException($this->admin::translate('PLUGIN_ADMIN.INSUFFICIENT_PERMISSIONS_FOR_TASK') . ' configure.', 403);
  848. }
  849. /** @var ServerRequestInterface $request */
  850. $request = $this->grav['request'];
  851. /** @var FlexForm $form */
  852. $form = $this->getDirectoryForm();
  853. $form->handleRequest($request);
  854. $error = $form->getError();
  855. $errors = $form->getErrors();
  856. if ($errors) {
  857. if ($error) {
  858. $this->admin->setMessage($error, 'error');
  859. }
  860. foreach ($errors as $field => $list) {
  861. foreach ((array)$list as $message) {
  862. $this->admin->setMessage($message, 'error');
  863. }
  864. }
  865. throw new RuntimeException('Form validation failed, please check your input');
  866. }
  867. if ($error) {
  868. throw new RuntimeException($error);
  869. }
  870. $this->admin->setMessage($this->admin::translate('PLUGIN_FLEX_OBJECTS.CONTROLLER.TASK_CONFIGURE_SUCCESS'));
  871. if (!$this->redirect) {
  872. $this->referrerRoute = $this->currentRoute;
  873. $this->setRedirect($this->referrerRoute->toString(true));
  874. }
  875. } catch (RuntimeException $e) {
  876. $this->admin->setMessage($this->admin::translate(['PLUGIN_FLEX_OBJECTS.CONTROLLER.TASK_CONFIGURE_FAILURE', $e->getMessage()]), 'error');
  877. $this->setRedirect($this->referrerRoute->toString(true), 302);
  878. }
  879. return true;
  880. }
  881. /**
  882. * @return bool
  883. */
  884. public function taskMediaList(): bool
  885. {
  886. $directory = $this->getDirectory();
  887. if (!$directory) {
  888. throw new RuntimeException('Not Found', 404);
  889. }
  890. try {
  891. $response = $this->forwardMediaTask('action', 'media.list');
  892. $this->admin->json_response = json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);
  893. } catch (Exception $e) {
  894. die($e->getMessage());
  895. }
  896. return true;
  897. }
  898. /**
  899. * @return bool
  900. */
  901. public function taskMediaUpload(): bool
  902. {
  903. $directory = $this->getDirectory();
  904. if (!$directory) {
  905. throw new RuntimeException('Not Found', 404);
  906. }
  907. try {
  908. $response = $this->forwardMediaTask('task', 'media.upload');
  909. $this->admin->json_response = json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);
  910. } catch (Exception $e) {
  911. die($e->getMessage());
  912. }
  913. return true;
  914. }
  915. /**
  916. * @return bool
  917. */
  918. public function taskMediaDelete(): bool
  919. {
  920. $directory = $this->getDirectory();
  921. if (!$directory) {
  922. throw new RuntimeException('Not Found', 404);
  923. }
  924. try {
  925. $response = $this->forwardMediaTask('task', 'media.delete');
  926. $this->admin->json_response = json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);
  927. } catch (Exception $e) {
  928. die($e->getMessage());
  929. }
  930. return true;
  931. }
  932. /**
  933. * @return bool
  934. */
  935. public function taskListmedia(): bool
  936. {
  937. return $this->taskMediaList();
  938. }
  939. /**
  940. * @return bool
  941. */
  942. public function taskAddmedia(): bool
  943. {
  944. $directory = $this->getDirectory();
  945. if (!$directory) {
  946. throw new RuntimeException('Not Found', 404);
  947. }
  948. try {
  949. $response = $this->forwardMediaTask('task', 'media.copy');
  950. $this->admin->json_response = json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);
  951. } catch (Exception $e) {
  952. die($e->getMessage());
  953. }
  954. return true;
  955. }
  956. /**
  957. * @return bool
  958. */
  959. public function taskDelmedia(): bool
  960. {
  961. $directory = $this->getDirectory();
  962. if (!$directory) {
  963. throw new RuntimeException('Not Found', 404);
  964. }
  965. try {
  966. $response = $this->forwardMediaTask('task', 'media.remove');
  967. $this->admin->json_response = json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);
  968. } catch (Exception $e) {
  969. die($e->getMessage());
  970. }
  971. return true;
  972. }
  973. /**
  974. * @return bool
  975. * @deprecated Do not use
  976. */
  977. public function taskFilesUpload(): bool
  978. {
  979. throw new RuntimeException('Task filesUpload should not be called!');
  980. }
  981. /**
  982. * @param string|null $filename
  983. * @return bool
  984. * @deprecated Do not use
  985. */
  986. public function taskRemoveMedia($filename = null): bool
  987. {
  988. throw new RuntimeException('Task removeMedia should not be called!');
  989. }
  990. /**
  991. * @return bool
  992. */
  993. public function taskGetFilesInFolder(): bool
  994. {
  995. $directory = $this->getDirectory();
  996. if (!$directory) {
  997. throw new RuntimeException('Not Found', 404);
  998. }
  999. try {
  1000. $response = $this->forwardMediaTask('action', 'media.picker');
  1001. $this->admin->json_response = json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);
  1002. } catch (Exception $e) {
  1003. $this->admin->json_response = ['success' => false, 'error' => $e->getMessage()];
  1004. }
  1005. return true;
  1006. }
  1007. /**
  1008. * @param string $type
  1009. * @param string $name
  1010. * @return ResponseInterface
  1011. */
  1012. protected function forwardMediaTask(string $type, string $name): ResponseInterface
  1013. {
  1014. $route = Uri::getCurrentRoute()->withGravParam('task', null)->withGravParam($type, $name);
  1015. $object = $this->getObject();
  1016. /** @var ServerRequest $request */
  1017. $request = $this->grav['request'];
  1018. $request = $request
  1019. ->withAttribute('type', $this->target)
  1020. ->withAttribute('key', $this->id)
  1021. ->withAttribute('storage_key', $object && $object->exists() ? $object->getStorageKey() : null)
  1022. ->withAttribute('route', $route)
  1023. ->withAttribute('forwarded', true)
  1024. ->withAttribute('object', $object);
  1025. $controller = new MediaController();
  1026. $controller->setUser($this->user);
  1027. return $controller->handle($request);
  1028. }
  1029. /**
  1030. * @return Flex
  1031. */
  1032. protected function getFlex(): Flex
  1033. {
  1034. return Grav::instance()['flex_objects'];
  1035. }
  1036. public static function getInstance(): ?AdminController
  1037. {
  1038. return self::$instance;
  1039. }
  1040. /**
  1041. * AdminController constructor.
  1042. */
  1043. public function __construct()
  1044. {
  1045. self::$instance = $this;
  1046. $this->grav = Grav::instance();
  1047. $this->admin = $this->grav['admin'];
  1048. $this->user = $this->admin->user;
  1049. $this->active = false;
  1050. // Controller can only be run in admin.
  1051. if (!Utils::isAdminPlugin()) {
  1052. return;
  1053. }
  1054. [, $location, $target] = $this->grav['admin']->getRouteDetails();
  1055. if (!$location) {
  1056. return;
  1057. }
  1058. $target = \is_string($target) ? urldecode($target) : null;
  1059. /** @var Uri $uri */
  1060. $uri = $this->grav['uri'];
  1061. $routeObject = $uri::getCurrentRoute();
  1062. $routeObject->withExtension('');
  1063. $routes = $this->getAdminRoutes();
  1064. // Match route to the flex directory.
  1065. $path = '/' . ($target ? $location . '/' . $target : $location) . '/';
  1066. $test = $routes[$path] ?? null;
  1067. $directory = null;
  1068. if ($test) {
  1069. $directory = $test['directory'];
  1070. $location = trim($path, '/');
  1071. $target = '';
  1072. } else {
  1073. krsort($routes);
  1074. foreach ($routes as $route => $test) {
  1075. if (strpos($path, $route) === 0) {
  1076. $directory = $test['directory'];
  1077. $location = trim($route, '/');
  1078. $target = trim(substr($path, strlen($route)), '/');
  1079. break;
  1080. }
  1081. $test = null;
  1082. }
  1083. }
  1084. if ($directory) {
  1085. // Redirect aliases.
  1086. if (isset($test['redirect'])) {
  1087. $route = $test['redirect'];
  1088. // If directory route starts with alias and path continues, stop.
  1089. if ($target && strpos($route, $location) === 0) {
  1090. // We are not in a directory.
  1091. return;
  1092. }
  1093. $redirect = '/' . $route . ($target ? '/' . $target : '');
  1094. $this->setRedirect($redirect, 302);
  1095. $this->redirect();
  1096. } elseif (isset($test['action'])) {
  1097. $routeObject = $routeObject->withGravParam('', $test['action']);
  1098. }
  1099. $id = $target;
  1100. $target = $directory->getFlexType();
  1101. } else {
  1102. // We are not in a directory.
  1103. if ($location !== 'flex-objects') {
  1104. return;
  1105. }
  1106. $array = explode('/', $target, 2);
  1107. $target = array_shift($array) ?: null;
  1108. $id = array_shift($array) ?: null;
  1109. }
  1110. // Post
  1111. $post = $_POST ?? [];
  1112. if (isset($post['data'])) {
  1113. $this->data = $this->getPost($post['data']);
  1114. unset($post['data']);
  1115. }
  1116. // Task
  1117. $task = $this->grav['task'];
  1118. if ($task) {
  1119. $this->task = $task;
  1120. }
  1121. $this->post = $this->getPost($post);
  1122. $this->location = 'flex-objects';
  1123. $this->target = $target;
  1124. $this->id = $this->post['id'] ?? $id;
  1125. $this->action = $this->post['action'] ?? $uri->param('action', null) ?? $uri->param('', null) ?? $routeObject->getGravParam('');
  1126. $this->active = true;
  1127. $this->currentRoute = $uri::getCurrentRoute();
  1128. $this->route = $routeObject;
  1129. $base = $this->grav['pages']->base();
  1130. if ($base) {
  1131. // Fix referrer for sub-folder multi-site setups.
  1132. $referrer = preg_replace('`^' . $base . '`', '', $uri->referrer());
  1133. } else {
  1134. $referrer = $uri->referrer();
  1135. }
  1136. $this->referrerRoute = $referrer ? RouteFactory::createFromString($referrer) : $this->currentRoute;
  1137. }
  1138. public function getInfo(): array
  1139. {
  1140. if (!$this->isActive()) {
  1141. return [];
  1142. }
  1143. $class = AdminController::class;
  1144. return [
  1145. 'controller' => [
  1146. 'name' => $this->location,
  1147. 'instance' => [$class, 'getInstance']
  1148. ],
  1149. 'location' => $this->location,
  1150. 'type' => $this->target,
  1151. 'key' => $this->id,
  1152. 'action' => $this->action,
  1153. 'task' => $this->task
  1154. ];
  1155. }
  1156. /**
  1157. * Performs a task or action on a post or target.
  1158. *
  1159. * @return ResponseInterface|bool|null
  1160. */
  1161. public function execute()
  1162. {
  1163. if (!$this->user->authorize('admin.login')) {
  1164. // TODO: improve
  1165. return false;
  1166. }
  1167. $params = [];
  1168. $event = new Event(
  1169. [
  1170. 'type' => &$this->target,
  1171. 'key' => &$this->id,
  1172. 'directory' => &$this->directory,
  1173. 'collection' => &$this->collection,
  1174. 'object' => &$this->object
  1175. ]
  1176. );
  1177. $this->grav->fireEvent("flex.{$this->target}.admin.route", $event);
  1178. if ($this->isFormSubmit()) {
  1179. $form = $this->getForm();
  1180. $this->nonce_name = $form->getNonceName();
  1181. $this->nonce_action = $form->getNonceAction();
  1182. }
  1183. // Handle Task & Action
  1184. if ($this->task) {
  1185. // validate nonce
  1186. if (!$this->validateNonce()) {
  1187. $e = new RequestException($this->getRequest(), 'Page Expired', 400);
  1188. $this->close($this->createErrorResponse($e));
  1189. }
  1190. $method = $this->task_prefix . ucfirst(str_replace('.', '', $this->task));
  1191. if (!method_exists($this, $method)) {
  1192. $method = $this->task_prefix . 'Default';
  1193. }
  1194. } elseif ($this->target) {
  1195. if (!$this->action) {
  1196. if ($this->id) {
  1197. $this->action = 'edit';
  1198. $params[] = $this->id;
  1199. } else {
  1200. $this->action = 'list';
  1201. }
  1202. }
  1203. $method = 'action' . ucfirst(strtolower(str_replace('.', '', $this->action)));
  1204. if (!method_exists($this, $method)) {
  1205. $method = $this->action_prefix . 'Default';
  1206. }
  1207. } else {
  1208. return null;
  1209. }
  1210. if (!method_exists($this, $method)) {
  1211. return null;
  1212. }
  1213. try {
  1214. $response = $this->{$method}(...$params);
  1215. } catch (RequestException $e) {
  1216. $response = $this->createErrorResponse($e);
  1217. } catch (RuntimeException $e) {
  1218. // If task fails to run, redirect back to the previous page and display the error message.
  1219. if ($this->task && !$this->redirect) {
  1220. $this->setRedirect($this->referrerRoute->toString(true));
  1221. }
  1222. $response = null;
  1223. $this->setMessage($e->getMessage(), 'error');
  1224. }
  1225. if ($response instanceof ResponseInterface) {
  1226. $this->close($response);
  1227. }
  1228. // Grab redirect parameter.
  1229. $redirect = $this->post['_redirect'] ?? null;
  1230. unset($this->post['_redirect']);
  1231. // Redirect if requested.
  1232. if ($redirect) {
  1233. $this->setRedirect($redirect);
  1234. }
  1235. return $response;
  1236. }
  1237. /**
  1238. * @return bool
  1239. */
  1240. public function isFormSubmit(): bool
  1241. {
  1242. return (bool)($this->post['__form-name__'] ?? null);
  1243. }
  1244. /**
  1245. * @param FlexObjectInterface|null $object
  1246. * @return FlexFormInterface
  1247. */
  1248. public function getForm(FlexObjectInterface $object = null): FlexFormInterface
  1249. {
  1250. $object = $object ?? $this->getObject();
  1251. if (!$object) {
  1252. throw new RuntimeException('Not Found', 404);
  1253. }
  1254. $formName = $this->post['__form-name__'] ?? '';
  1255. $name = '';
  1256. $uniqueId = null;
  1257. // Get the form name. This defines the blueprint which is being used.
  1258. if (strpos($formName, '-')) {
  1259. $parts = explode('-', $formName);
  1260. $prefix = $parts[0] ?? '';
  1261. $type = $parts[1] ?? '';
  1262. if ($prefix === 'flex' && $type === $object->getFlexType()) {
  1263. $name = $parts[2] ?? '';
  1264. if ($name === 'object') {
  1265. $name = '';
  1266. }
  1267. $uniqueId = $this->post['__unique_form_id__'] ?? null;
  1268. }
  1269. }
  1270. $options = [
  1271. 'unique_id' => $uniqueId,
  1272. ];
  1273. return $object->getForm($name, $options);
  1274. }
  1275. /**
  1276. * @param FlexDirectoryInterface|null $directory
  1277. * @return FlexFormInterface
  1278. */
  1279. public function getDirectoryForm(FlexDirectoryInterface $directory = null): FlexFormInterface
  1280. {
  1281. $directory = $directory ?? $this->getDirectory();
  1282. if (!$directory) {
  1283. throw new RuntimeException('Not Found', 404);
  1284. }
  1285. $formName = $this->post['__form-name__'] ?? '';
  1286. $name = '';
  1287. $uniqueId = null;
  1288. // Get the form name. This defines the blueprint which is being used.
  1289. if (strpos($formName, '-')) {
  1290. $parts = explode('-', $formName);
  1291. $prefix = $parts[0] ?? '';
  1292. $type = $parts[1] ?? '';
  1293. if ($prefix === 'flex_conf' && $type === $directory->getFlexType()) {
  1294. $name = $parts[2] ?? '';
  1295. $uniqueId = $this->post['__unique_form_id__'] ?? null;
  1296. }
  1297. }
  1298. $options = [
  1299. 'unique_id' => $uniqueId,
  1300. ];
  1301. return $directory->getDirectoryForm($name, $options);
  1302. }
  1303. /**
  1304. * @param string|null $key
  1305. * @return FlexObjectInterface|null
  1306. */
  1307. public function getObject(string $key = null): ?FlexObjectInterface
  1308. {
  1309. if (null === $this->object) {
  1310. $key = $key ?? $this->id;
  1311. $object = false;
  1312. $directory = $this->getDirectory();
  1313. if ($directory) {
  1314. // FIXME: hack for pages.
  1315. if ($key === '_root') {
  1316. $index = $directory->getIndex();
  1317. if ($index instanceof PageIndex) {
  1318. $object = $index->getRoot();
  1319. }
  1320. } elseif (null !== $key) {
  1321. $object = $directory->getObject($key) ?? $directory->createObject([], $key);
  1322. } elseif ($this->action === 'add') {
  1323. $object = $directory->createObject([], '');
  1324. }
  1325. if ($object instanceof FlexTranslateInterface && $this->isMultilang()) {
  1326. $language = $this->getLanguage();
  1327. if ($object->hasTranslation($language)) {
  1328. $object = $object->getTranslation($language);
  1329. } elseif (!in_array('', $object->getLanguages(true), true)) {
  1330. $object->language($language);
  1331. }
  1332. }
  1333. if (is_callable([$object, 'refresh'])) {
  1334. $object->refresh();
  1335. }
  1336. // Get updated object via form.
  1337. $this->object = $object ? $object->getForm()->getObject() : false;
  1338. }
  1339. }
  1340. return $this->object ?: null;
  1341. }
  1342. /**
  1343. * @param string|null $type
  1344. * @return FlexDirectoryInterface|null
  1345. */
  1346. public function getDirectory(string $type = null): ?FlexDirectoryInterface
  1347. {
  1348. $type = $type ?? $this->target;
  1349. if ($type && null === $this->directory) {
  1350. $this->directory = Grav::instance()['flex_objects']->getDirectory($type);
  1351. }
  1352. return $this->directory;
  1353. }
  1354. /**
  1355. * @return FlexCollectionInterface|null
  1356. */
  1357. public function getCollection(): ?FlexCollectionInterface
  1358. {
  1359. if (null === $this->collection) {
  1360. $directory = $this->getDirectory();
  1361. $this->collection = $directory ? $directory->getCollection() : null;
  1362. }
  1363. return $this->collection;
  1364. }
  1365. /**
  1366. * @param string $msg
  1367. * @param string $type
  1368. * @return void
  1369. */
  1370. public function setMessage(string $msg, string $type = 'info'): void
  1371. {
  1372. /** @var Message $messages */
  1373. $messages = $this->grav['messages'];
  1374. $messages->add($msg, $type);
  1375. }
  1376. /**
  1377. * @return bool
  1378. */
  1379. public function isActive(): bool
  1380. {
  1381. return (bool) $this->active;
  1382. }
  1383. /**
  1384. * @param string $location
  1385. * @return void
  1386. */
  1387. public function setLocation(string $location): void
  1388. {
  1389. $this->location = $location;
  1390. }
  1391. /**
  1392. * @return string|null
  1393. */
  1394. public function getLocation(): ?string
  1395. {
  1396. return $this->location;
  1397. }
  1398. /**
  1399. * @param string $action
  1400. * @return void
  1401. */
  1402. public function setAction(string $action): void
  1403. {
  1404. $this->action = $action;
  1405. }
  1406. /**
  1407. * @return string|null
  1408. */
  1409. public function getAction(): ?string
  1410. {
  1411. return $this->action;
  1412. }
  1413. /**
  1414. * @param string $task
  1415. * @return void
  1416. */
  1417. public function setTask(string $task): void
  1418. {
  1419. $this->task = $task;
  1420. }
  1421. /**
  1422. * @return string|null
  1423. */
  1424. public function getTask(): ?string
  1425. {
  1426. return $this->task;
  1427. }
  1428. /**
  1429. * @param string $target
  1430. * @return void
  1431. */
  1432. public function setTarget(string $target): void
  1433. {
  1434. $this->target = $target;
  1435. }
  1436. /**
  1437. * @return string|null
  1438. */
  1439. public function getTarget(): ?string
  1440. {
  1441. return $this->target;
  1442. }
  1443. /**
  1444. * @param string $id
  1445. * @return void
  1446. */
  1447. public function setId(string $id): void
  1448. {
  1449. $this->id = $id;
  1450. }
  1451. /**
  1452. * @return string|null
  1453. */
  1454. public function getId(): ?string
  1455. {
  1456. return $this->id;
  1457. }
  1458. /**
  1459. * Sets the page redirect.
  1460. *
  1461. * @param string $path The path to redirect to
  1462. * @param int $code The HTTP redirect code
  1463. * @return void
  1464. */
  1465. public function setRedirect(string $path, int $code = 303): void
  1466. {
  1467. $this->redirect = $path;
  1468. $this->redirectCode = (int)$code;
  1469. }
  1470. /**
  1471. * Redirect to the route stored in $this->redirect
  1472. *
  1473. * @return void
  1474. */
  1475. public function redirect(): void
  1476. {
  1477. $this->admin->redirect($this->redirect, $this->redirectCode);
  1478. }
  1479. /**
  1480. * @return array
  1481. */
  1482. public function getAdminRoutes(): array
  1483. {
  1484. if (null === $this->adminRoutes) {
  1485. $routes = [];
  1486. /** @var FlexDirectoryInterface $directory */
  1487. foreach ($this->getFlex()->getDirectories() as $directory) {
  1488. $config = $directory->getConfig('admin');
  1489. if (!$directory->isEnabled() || !empty($config['disabled'])) {
  1490. continue;
  1491. }
  1492. // Alias under flex-objects (always exists, but can be redirected).
  1493. $routes["/flex-objects/{$directory->getFlexType()}/"] = ['directory' => $directory];
  1494. $route = $config['router']['path'] ?? $config['menu']['list']['route'] ?? null;
  1495. if ($route) {
  1496. $routes[$route . '/'] = ['directory' => $directory];
  1497. }
  1498. $redirects = (array)($config['router']['redirects'] ?? null);
  1499. foreach ($redirects as $redirectFrom => $redirectTo) {
  1500. $redirectFrom .= '/';
  1501. if (!isset($routes[$redirectFrom])) {
  1502. $routes[$redirectFrom] = ['directory' => $directory, 'redirect' => $redirectTo];
  1503. }
  1504. }
  1505. $actions = (array)($config['router']['actions'] ?? null);
  1506. foreach ($actions as $name => $action) {
  1507. if (is_array($action)) {
  1508. $path = $action['path'] ?? null;
  1509. } else {
  1510. $path = $action;
  1511. }
  1512. if ($path !== null) {
  1513. $routes[$path . '/'] = ['directory' => $directory, 'action' => $name];
  1514. }
  1515. }
  1516. }
  1517. $this->adminRoutes = $routes;
  1518. }
  1519. return $this->adminRoutes;
  1520. }
  1521. /**
  1522. * Return true if multilang is active
  1523. *
  1524. * @return bool True if multilang is active
  1525. */
  1526. protected function isMultilang(): bool
  1527. {
  1528. /** @var Language $language */
  1529. $language = $this->grav['language'];
  1530. return $language->enabled();
  1531. }
  1532. protected function validateNonce(): bool
  1533. {
  1534. $nonce_action = $this->nonce_action;
  1535. $nonce = $this->post[$this->nonce_name] ?? $this->grav['uri']->param($this->nonce_name) ?? $this->grav['uri']->query($this->nonce_name);
  1536. if (!$nonce) {
  1537. $nonce = $this->post['admin-nonce'] ?? $this->grav['uri']->param('admin-nonce') ?? $this->grav['uri']->query('admin-nonce');
  1538. $nonce_action = 'admin-form';
  1539. }
  1540. return $nonce && Utils::verifyNonce($nonce, $nonce_action);
  1541. }
  1542. /**
  1543. * Prepare and return POST data.
  1544. *
  1545. * @param array $post
  1546. * @return array
  1547. */
  1548. protected function getPost(array $post): array
  1549. {
  1550. unset($post['task']);
  1551. // Decode JSON encoded fields and merge them to data.
  1552. if (isset($post['_json'])) {
  1553. $post = array_replace_recursive($post, $this->jsonDecode($post['_json']));
  1554. unset($post['_json']);
  1555. }
  1556. $post = $this->cleanDataKeys($post);
  1557. return $post;
  1558. }
  1559. /**
  1560. * @param ResponseInterface $response
  1561. * @return never-return
  1562. */
  1563. protected function close(ResponseInterface $response): void
  1564. {
  1565. $this->grav->close($response);
  1566. }
  1567. /**
  1568. * Recursively JSON decode data.
  1569. *
  1570. * @param array $data
  1571. * @return array
  1572. */
  1573. protected function jsonDecode(array $data)
  1574. {
  1575. foreach ($data as &$value) {
  1576. if (is_array($value)) {
  1577. $value = $this->jsonDecode($value);
  1578. } else {
  1579. $value = json_decode($value, true, 512, JSON_THROW_ON_ERROR);
  1580. }
  1581. }
  1582. return $data;
  1583. }
  1584. /**
  1585. * @param array $source
  1586. * @return array
  1587. */
  1588. protected function cleanDataKeys($source = []): array
  1589. {
  1590. $out = [];
  1591. if (is_array($source)) {
  1592. foreach ($source as $key => $value) {
  1593. $key = str_replace(['%5B', '%5D'], ['[', ']'], $key);
  1594. if (is_array($value)) {
  1595. $out[$key] = $this->cleanDataKeys($value);
  1596. } else {
  1597. $out[$key] = $value;
  1598. }
  1599. }
  1600. }
  1601. return $out;
  1602. }
  1603. /**
  1604. * @return string
  1605. */
  1606. public function getLanguage(): string
  1607. {
  1608. return $this->admin->language ?? '';
  1609. }
  1610. /**
  1611. * @return Config
  1612. */
  1613. protected function getConfig(): Config
  1614. {
  1615. return $this->grav['config'];
  1616. }
  1617. /**
  1618. * @return ServerRequestInterface
  1619. */
  1620. protected function getRequest(): ServerRequestInterface
  1621. {
  1622. return $this->grav['request'];
  1623. }
  1624. }