admin.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792
  1. <?php
  2. namespace Grav\Plugin\Admin;
  3. use DateTime;
  4. use Grav\Common\Data;
  5. use Grav\Common\File\CompiledYamlFile;
  6. use Grav\Common\GPM\GPM;
  7. use Grav\Common\GPM\Licenses;
  8. use Grav\Common\GPM\Response;
  9. use Grav\Common\Grav;
  10. use Grav\Common\Language\LanguageCodes;
  11. use Grav\Common\Page\Collection;
  12. use Grav\Common\Page\Page;
  13. use Grav\Common\Page\Pages;
  14. use Grav\Common\Plugins;
  15. use Grav\Common\Themes;
  16. use Grav\Common\Uri;
  17. use Grav\Common\User\User;
  18. use Grav\Common\Utils;
  19. use Grav\Plugin\Admin\Twig\AdminTwigExtension;
  20. use Grav\Plugin\Login\Login;
  21. use Grav\Plugin\Login\TwoFactorAuth\TwoFactorAuth;
  22. use RocketTheme\Toolbox\Event\Event;
  23. use RocketTheme\Toolbox\File\File;
  24. use RocketTheme\Toolbox\File\JsonFile;
  25. use RocketTheme\Toolbox\ResourceLocator\UniformResourceIterator;
  26. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  27. use RocketTheme\Toolbox\Session\Message;
  28. use RocketTheme\Toolbox\Session\Session;
  29. use Symfony\Component\Yaml\Yaml;
  30. use Composer\Semver\Semver;
  31. use PicoFeed\Reader\Reader;
  32. define('LOGIN_REDIRECT_COOKIE', 'grav-login-redirect');
  33. class Admin
  34. {
  35. const MEDIA_PAGINATION_INTERVAL = 20;
  36. const TMP_COOKIE_NAME = 'tmp-admin-message';
  37. /**
  38. * @var Grav
  39. */
  40. public $grav;
  41. /**
  42. * @var string
  43. */
  44. public $base;
  45. /**
  46. * @var string
  47. */
  48. public $location;
  49. /**
  50. * @var string
  51. */
  52. public $route;
  53. /**
  54. * @var User
  55. */
  56. public $user;
  57. /**
  58. * @var array
  59. */
  60. public $forgot;
  61. /**
  62. * @var string
  63. */
  64. public $task;
  65. /**
  66. * @var array
  67. */
  68. public $json_response;
  69. /**
  70. * @var Uri $uri
  71. */
  72. protected $uri;
  73. /**
  74. * @var array
  75. */
  76. protected $pages = [];
  77. /**
  78. * @var Session
  79. */
  80. protected $session;
  81. /**
  82. * @var Data\Blueprints
  83. */
  84. protected $blueprints;
  85. /**
  86. * @var GPM
  87. */
  88. protected $gpm;
  89. /**
  90. * @var int
  91. */
  92. protected $pages_count;
  93. /**
  94. * @var array
  95. */
  96. protected $permissions;
  97. /**
  98. * @var bool
  99. */
  100. protected $load_additional_files_in_background = false;
  101. /**
  102. * @var bool
  103. */
  104. protected $loading_additional_files_in_background = false;
  105. /**
  106. * @var array
  107. */
  108. protected $temp_messages = [];
  109. /**
  110. * Constructor.
  111. *
  112. * @param Grav $grav
  113. * @param string $base
  114. * @param string $location
  115. * @param string $route
  116. */
  117. public function __construct(Grav $grav, $base, $location, $route)
  118. {
  119. $this->grav = $grav;
  120. $this->base = $base;
  121. $this->location = $location;
  122. $this->route = $route;
  123. $this->uri = $this->grav['uri'];
  124. $this->session = $this->grav['session'];
  125. $this->user = $this->grav['user'];
  126. $this->permissions = [];
  127. $language = $this->grav['language'];
  128. // Load utility class
  129. if ($language->enabled()) {
  130. $this->multilang = true;
  131. $this->languages_enabled = $this->grav['config']->get('system.languages.supported', []);
  132. //Set the currently active language for the admin
  133. $language = $this->grav['uri']->param('lang');
  134. if (!$language) {
  135. if (!$this->session->admin_lang) {
  136. $this->session->admin_lang = $this->grav['language']->getLanguage();
  137. }
  138. $language = $this->session->admin_lang;
  139. }
  140. $this->grav['language']->setActive($language ?: 'en');
  141. } else {
  142. $this->grav['language']->setActive('en');
  143. $this->multilang = false;
  144. }
  145. }
  146. /**
  147. * Return the languages available in the admin
  148. *
  149. * @return array
  150. */
  151. public static function adminLanguages()
  152. {
  153. $languages = [];
  154. $path = Grav::instance()['locator']->findResource('plugins://admin/languages');
  155. /** @var \DirectoryIterator $directory */
  156. foreach (new \DirectoryIterator($path) as $file) {
  157. if ($file->isDir() || $file->isDot() || Utils::startsWith($file->getBasename(), '.')) {
  158. continue;
  159. }
  160. $lang = basename($file->getBasename(), '.yaml');
  161. $languages[$lang] = LanguageCodes::getNativeName($lang);
  162. }
  163. // sort languages
  164. asort($languages);
  165. return $languages;
  166. }
  167. /**
  168. * Return the found configuration blueprints
  169. *
  170. * @return array
  171. */
  172. public static function configurations()
  173. {
  174. $configurations = [];
  175. /** @var UniformResourceIterator $iterator */
  176. $iterator = Grav::instance()['locator']->getIterator('blueprints://config');
  177. foreach ($iterator as $file) {
  178. if ($file->isDir() || !preg_match('/^[^.].*.yaml$/', $file->getFilename())) {
  179. continue;
  180. }
  181. $configurations[] = basename($file->getBasename(), '.yaml');
  182. }
  183. return $configurations;
  184. }
  185. /**
  186. * Return the tools found
  187. *
  188. * @return array
  189. */
  190. public static function tools()
  191. {
  192. $tools = [];
  193. Grav::instance()->fireEvent('onAdminTools', new Event(['tools' => &$tools]));
  194. return $tools;
  195. }
  196. /**
  197. * Return the languages available in the site
  198. *
  199. * @return array
  200. */
  201. public static function siteLanguages()
  202. {
  203. $languages = [];
  204. $lang_data = (array) Grav::instance()['config']->get('system.languages.supported', []);
  205. foreach ($lang_data as $index => $lang) {
  206. $languages[$lang] = LanguageCodes::getNativeName($lang);
  207. }
  208. return $languages;
  209. }
  210. /**
  211. * Static helper method to return the admin form nonce
  212. *
  213. * @return string
  214. */
  215. public static function getNonce()
  216. {
  217. $action = 'admin-form';
  218. return Utils::getNonce($action);
  219. }
  220. /**
  221. * Static helper method to return the last used page name
  222. *
  223. * @return string
  224. */
  225. public static function getLastPageName()
  226. {
  227. return Grav::instance()['session']->lastPageName ?: 'default';
  228. }
  229. /**
  230. * Static helper method to return the last used page route
  231. *
  232. * @return string
  233. */
  234. public static function getLastPageRoute()
  235. {
  236. return Grav::instance()['session']->lastPageRoute ?: self::route();
  237. }
  238. /**
  239. * Static helper method to return current route.
  240. *
  241. * @return string
  242. */
  243. public static function route()
  244. {
  245. $pages = Grav::instance()['pages'];
  246. $route = '/' . ltrim(Grav::instance()['admin']->route, '/');
  247. /** @var Page $page */
  248. $page = $pages->dispatch($route);
  249. $parent_route = null;
  250. if ($page) {
  251. /** @var Page $parent */
  252. $parent = $page->parent();
  253. $parent_route = $parent->rawRoute();
  254. }
  255. return $parent_route;
  256. }
  257. public static function getTempDir()
  258. {
  259. try {
  260. $tmp_dir = Grav::instance()['locator']->findResource('tmp://', true, true);
  261. } catch (\Exception $e) {
  262. $tmp_dir = Grav::instance()['locator']->findResource('cache://', true, true) . '/tmp';
  263. }
  264. return $tmp_dir;
  265. }
  266. public static function getPageMedia()
  267. {
  268. $files = [];
  269. $grav = Grav::instance();
  270. $pages = $grav['pages'];
  271. $route = '/' . ltrim($grav['admin']->route, '/');
  272. /** @var Page $page */
  273. $page = $pages->dispatch($route);
  274. $parent_route = null;
  275. if ($page) {
  276. $media = $page->media()->all();
  277. $files = array_keys($media);
  278. }
  279. return $files;
  280. }
  281. /**
  282. * Get current session.
  283. *
  284. * @return Session
  285. */
  286. public function session()
  287. {
  288. return $this->session;
  289. }
  290. /**
  291. * Fetch and delete messages from the session queue.
  292. *
  293. * @param string $type
  294. *
  295. * @return array
  296. */
  297. public function messages($type = null)
  298. {
  299. /** @var Message $messages */
  300. $messages = $this->grav['messages'];
  301. return $messages->fetch($type);
  302. }
  303. /**
  304. * Authenticate user.
  305. *
  306. * @param array $credentials User credentials.
  307. */
  308. public function authenticate($credentials, $post)
  309. {
  310. /** @var Login $login */
  311. $login = $this->grav['login'];
  312. // Remove login nonce from the form.
  313. $credentials = array_diff_key($credentials, ['admin-nonce' => true]);
  314. $twofa = $this->grav['config']->get('plugins.admin.twofa_enabled', false);
  315. $rateLimiter = $login->getRateLimiter('login_attempts');
  316. $userKey = isset($credentials['username']) ? (string)$credentials['username'] : '';
  317. $ipKey = Uri::ip();
  318. $redirect = isset($post['redirect']) ? $post['redirect'] : $this->uri->route();
  319. // Check if the current IP has been used in failed login attempts.
  320. $attempts = count($rateLimiter->getAttempts($ipKey, 'ip'));
  321. $rateLimiter->registerRateLimitedAction($ipKey, 'ip')->registerRateLimitedAction($userKey);
  322. // Check rate limit for both IP and user, but allow each IP a single try even if user is already rate limited.
  323. if ($rateLimiter->isRateLimited($ipKey, 'ip') || ($attempts && $rateLimiter->isRateLimited($userKey))) {
  324. $this->setMessage($this->translate(['PLUGIN_LOGIN.TOO_MANY_LOGIN_ATTEMPTS', $rateLimiter->getInterval()]), 'error');
  325. $this->grav->redirect('/');
  326. }
  327. // Fire Login process.
  328. $event = $login->login(
  329. $credentials,
  330. ['admin' => true, 'twofa' => $twofa],
  331. ['authorize' => 'admin.login', 'return_event' => true]
  332. );
  333. $user = $event->getUser();
  334. if ($user->authenticated) {
  335. $rateLimiter->resetRateLimit($ipKey, 'ip')->resetRateLimit($userKey);
  336. if ($user->authorized) {
  337. $event->defMessage('PLUGIN_ADMIN.LOGIN_LOGGED_IN', 'info');
  338. $event->defRedirect($redirect);
  339. } else {
  340. $this->session->redirect = $redirect;
  341. $event->defRedirect($this->uri->route());
  342. }
  343. } else {
  344. if ($user->authorized) {
  345. $event->defMessage('PLUGIN_LOGIN.ACCESS_DENIED', 'error');
  346. } else {
  347. $event->defMessage('PLUGIN_LOGIN.LOGIN_FAILED', 'error');
  348. }
  349. }
  350. $event->defRedirect($this->uri->route());
  351. $message = $event->getMessage();
  352. if ($message) {
  353. $this->setMessage($this->translate($message), $event->getMessageType());
  354. }
  355. $redirect = $event->getRedirect();
  356. $this->grav->redirect($redirect, $event->getRedirectCode());
  357. }
  358. /**
  359. * Check Two-Factor Authentication.
  360. */
  361. public function twoFa($data, $post)
  362. {
  363. /** @var Login $login */
  364. $login = $this->grav['login'];
  365. /** @var TwoFactorAuth $twoFa */
  366. $twoFa = $login->twoFactorAuth();
  367. $user = $this->grav['user'];
  368. $code = isset($data['2fa_code']) ? $data['2fa_code'] : null;
  369. $secret = isset($user->twofa_secret) ? $user->twofa_secret : null;
  370. if (!$code || !$secret || !$twoFa->verifyCode($secret, $code)) {
  371. $login->logout(['admin' => true]);
  372. $this->grav['session']->setFlashCookieObject(Admin::TMP_COOKIE_NAME, ['message' => $this->translate('PLUGIN_ADMIN.2FA_FAILED'), 'status' => 'error']);
  373. $this->grav->redirect($this->uri->route(), 303);
  374. }
  375. $this->setMessage($this->translate('PLUGIN_ADMIN.LOGIN_LOGGED_IN'), 'info');
  376. $user->authorized = true;
  377. $this->grav->redirect($post['redirect']);
  378. }
  379. /**
  380. * Logout from admin.
  381. */
  382. public function Logout($data, $post)
  383. {
  384. /** @var Login $login */
  385. $login = $this->grav['login'];
  386. $event = $login->logout(['admin' => true], ['return_event' => true]);
  387. $event->defMessage('PLUGIN_ADMIN.LOGGED_OUT', 'info');
  388. $message = $event->getMessage();
  389. if ($message) {
  390. $this->grav['session']->setFlashCookieObject(Admin::TMP_COOKIE_NAME, ['message' => $this->translate($message), 'status' => $event->getMessageType()]);
  391. }
  392. $this->grav->redirect($this->base);
  393. }
  394. /**
  395. * @return bool
  396. */
  397. public static function doAnyUsersExist()
  398. {
  399. // check for existence of a user account
  400. $account_dir = $file_path = Grav::instance()['locator']->findResource('account://');
  401. $user_check = glob($account_dir . '/*.yaml');
  402. return $user_check ? true : false;
  403. }
  404. /**
  405. * Add message into the session queue.
  406. *
  407. * @param string $msg
  408. * @param string $type
  409. */
  410. public function setMessage($msg, $type = 'info')
  411. {
  412. /** @var Message $messages */
  413. $messages = $this->grav['messages'];
  414. $messages->add($msg, $type);
  415. }
  416. public function addTempMessage($msg, $type)
  417. {
  418. $this->temp_messages[] = ['message' => $msg, 'scope' => $type];
  419. }
  420. public function getTempMessages()
  421. {
  422. return $this->temp_messages;
  423. }
  424. /**
  425. * Translate a string to the user-defined language
  426. *
  427. * @param array|mixed $args
  428. *
  429. * @param mixed $languages
  430. *
  431. * @return string
  432. */
  433. public static function translate($args, $languages = null)
  434. {
  435. $grav = Grav::instance();
  436. if (is_array($args)) {
  437. $lookup = array_shift($args);
  438. } else {
  439. $lookup = $args;
  440. $args = [];
  441. }
  442. if (!$languages) {
  443. if ($grav['config']->get('system.languages.translations_fallback', true)) {
  444. $languages = $grav['language']->getFallbackLanguages();
  445. } else {
  446. $languages = (array)$grav['language']->getDefault();
  447. }
  448. $languages = $grav['user']->authenticated ? [ $grav['user']->language ] : $languages;
  449. } else {
  450. $languages = (array)$languages;
  451. }
  452. foreach ((array)$languages as $lang) {
  453. $translation = $grav['language']->getTranslation($lang, $lookup);
  454. if (!$translation) {
  455. $language = $grav['language']->getDefault() ?: 'en';
  456. $translation = $grav['language']->getTranslation($language, $lookup);
  457. }
  458. if (!$translation) {
  459. $language = 'en';
  460. $translation = $grav['language']->getTranslation($language, $lookup);
  461. }
  462. if ($translation) {
  463. if (count($args) >= 1) {
  464. return vsprintf($translation, $args);
  465. }
  466. return $translation;
  467. }
  468. }
  469. return $lookup;
  470. }
  471. /**
  472. * Checks user authorisation to the action.
  473. *
  474. * @param string|string[] $action
  475. *
  476. * @return bool
  477. */
  478. public function authorize($action = 'admin.login')
  479. {
  480. $action = (array)$action;
  481. foreach ($action as $a) {
  482. if ($this->user->authorize($a)) {
  483. return true;
  484. }
  485. }
  486. return false;
  487. }
  488. /**
  489. * Gets configuration data.
  490. *
  491. * @param string $type
  492. * @param array $post
  493. *
  494. * @return mixed
  495. * @throws \RuntimeException
  496. */
  497. public function data($type, array $post = [])
  498. {
  499. static $data = [];
  500. if (isset($data[$type])) {
  501. return $data[$type];
  502. }
  503. if (!$post) {
  504. $post = isset($_POST['data']) ? $_POST['data'] : [];
  505. }
  506. // Check to see if a data type is plugin-provided, before looking into core ones
  507. $event = $this->grav->fireEvent('onAdminData', new Event(['type' => &$type]));
  508. if ($event && isset($event['data_type'])) {
  509. return $event['data_type'];
  510. }
  511. /** @var UniformResourceLocator $locator */
  512. $locator = $this->grav['locator'];
  513. $filename = $locator->findResource("config://{$type}.yaml", true, true);
  514. $file = CompiledYamlFile::instance($filename);
  515. if (preg_match('|plugins/|', $type)) {
  516. /** @var Plugins $plugins */
  517. $plugins = $this->grav['plugins'];
  518. $obj = $plugins->get(preg_replace('|plugins/|', '', $type));
  519. if (!$obj) {
  520. return [];
  521. }
  522. $obj->merge($post);
  523. $obj->file($file);
  524. $data[$type] = $obj;
  525. } elseif (preg_match('|themes/|', $type)) {
  526. /** @var Themes $themes */
  527. $themes = $this->grav['themes'];
  528. $obj = $themes->get(preg_replace('|themes/|', '', $type));
  529. if (!$obj) {
  530. return [];
  531. }
  532. $obj->merge($post);
  533. $obj->file($file);
  534. $data[$type] = $obj;
  535. } elseif (preg_match('|users/|', $type)) {
  536. $obj = User::load(preg_replace('|users/|', '', $type));
  537. $obj->merge($post);
  538. $data[$type] = $obj;
  539. } elseif (preg_match('|user/|', $type)) {
  540. $obj = User::load(preg_replace('|user/|', '', $type));
  541. $obj->merge($post);
  542. $data[$type] = $obj;
  543. } elseif (preg_match('|config/|', $type)) {
  544. $type = preg_replace('|config/|', '', $type);
  545. $blueprints = $this->blueprints("config/{$type}");
  546. $config = $this->grav['config'];
  547. $obj = new Data\Data($config->get($type, []), $blueprints);
  548. $obj->merge($post);
  549. // FIXME: We shouldn't allow user to change configuration files in system folder!
  550. $filename = $this->grav['locator']->findResource("config://{$type}.yaml")
  551. ?: $this->grav['locator']->findResource("config://{$type}.yaml", true, true);
  552. $file = CompiledYamlFile::instance($filename);
  553. $obj->file($file);
  554. $data[$type] = $obj;
  555. } elseif (preg_match('|media-manager/|', $type)) {
  556. $filename = base64_decode(preg_replace('|media-manager/|', '', $type));
  557. $file = File::instance($filename);
  558. $obj = new \StdClass();
  559. $obj->title = $file->basename();
  560. $obj->path = $file->filename();
  561. $obj->file = $file;
  562. $obj->page = $this->grav['pages']->get(dirname($obj->path));
  563. $filename = pathinfo($obj->title)['filename'];
  564. $filename = str_replace(['@3x', '@2x'], '', $filename);
  565. if (isset(pathinfo($obj->title)['extension'])) {
  566. $filename .= '.' . pathinfo($obj->title)['extension'];
  567. }
  568. if ($obj->page && isset($obj->page->media()[$filename])) {
  569. $obj->metadata = new Data\Data($obj->page->media()[$filename]->metadata());
  570. }
  571. $data[$type] = $obj;
  572. } else {
  573. throw new \RuntimeException("Data type '{$type}' doesn't exist!");
  574. }
  575. return $data[$type];
  576. }
  577. protected function hasErrorMessage()
  578. {
  579. $msgs = $this->grav['messages']->all();
  580. foreach ($msgs as $msg) {
  581. if (isset($msg['scope']) && $msg['scope'] === 'error') {
  582. return true;
  583. }
  584. }
  585. return false;
  586. }
  587. /**
  588. * Returns blueprints for the given type.
  589. *
  590. * @param string $type
  591. *
  592. * @return Data\Blueprint
  593. */
  594. public function blueprints($type)
  595. {
  596. if ($this->blueprints === null) {
  597. $this->blueprints = new Data\Blueprints('blueprints://');
  598. }
  599. return $this->blueprints->get($type);
  600. }
  601. /**
  602. * Converts dot notation to array notation.
  603. *
  604. * @param string $name
  605. *
  606. * @return string
  607. */
  608. public function field($name)
  609. {
  610. $path = explode('.', $name);
  611. return array_shift($path) . ($path ? '[' . implode('][', $path) . ']' : '');
  612. }
  613. /**
  614. * Get all routes.
  615. *
  616. * @param bool $unique
  617. *
  618. * @return array
  619. */
  620. public function routes($unique = false)
  621. {
  622. /** @var Pages $pages */
  623. $pages = $this->grav['pages'];
  624. if ($unique) {
  625. $routes = array_unique($pages->routes());
  626. } else {
  627. $routes = $pages->routes();
  628. }
  629. return $routes;
  630. }
  631. /**
  632. * Count the pages
  633. *
  634. * @return array
  635. */
  636. public function pagesCount()
  637. {
  638. if (!$this->pages_count) {
  639. $this->pages_count = count($this->grav['pages']->all());
  640. }
  641. return $this->pages_count;
  642. }
  643. /**
  644. * Get all template types
  645. *
  646. * @return array
  647. */
  648. public function types()
  649. {
  650. return Pages::types();
  651. }
  652. /**
  653. * Get all modular template types
  654. *
  655. * @return array
  656. */
  657. public function modularTypes()
  658. {
  659. return Pages::modularTypes();
  660. }
  661. /**
  662. * Get all access levels
  663. *
  664. * @return array
  665. */
  666. public function accessLevels()
  667. {
  668. if (method_exists($this->grav['pages'], 'accessLevels')) {
  669. return $this->grav['pages']->accessLevels();
  670. }
  671. return [];
  672. }
  673. public function license($package_slug)
  674. {
  675. return Licenses::get($package_slug);
  676. }
  677. /**
  678. * Generate an array of dependencies for a package, used to generate a list of
  679. * packages that can be removed when removing a package.
  680. *
  681. * @param string $slug The package slug
  682. *
  683. * @return array|bool
  684. */
  685. public function dependenciesThatCanBeRemovedWhenRemoving($slug)
  686. {
  687. $gpm = $this->gpm();
  688. if (!$gpm) {
  689. return false;
  690. }
  691. $dependencies = [];
  692. $package = $this->getPackageFromGPM($slug);
  693. if ($package) {
  694. if ($package->dependencies) {
  695. foreach ($package->dependencies as $dependency) {
  696. // if (count($gpm->getPackagesThatDependOnPackage($dependency)) > 1) {
  697. // continue;
  698. // }
  699. if (isset($dependency['name'])) {
  700. $dependency = $dependency['name'];
  701. }
  702. if (!in_array($dependency, $dependencies, true)) {
  703. if (!in_array($dependency, ['admin', 'form', 'login', 'email', 'php'])) {
  704. $dependencies[] = $dependency;
  705. }
  706. }
  707. }
  708. }
  709. }
  710. return $dependencies;
  711. }
  712. /**
  713. * Get the GPM instance
  714. *
  715. * @return GPM The GPM instance
  716. */
  717. public function gpm()
  718. {
  719. if (!$this->gpm) {
  720. try {
  721. $this->gpm = new GPM();
  722. } catch (\Exception $e) {
  723. }
  724. }
  725. return $this->gpm;
  726. }
  727. public function getPackageFromGPM($package_slug)
  728. {
  729. $package = $this->plugins(true)[$package_slug];
  730. if (!$package) {
  731. $package = $this->themes(true)[$package_slug];
  732. }
  733. return $package;
  734. }
  735. /**
  736. * Get all plugins.
  737. *
  738. * @param bool $local
  739. *
  740. * @return mixed
  741. */
  742. public function plugins($local = true)
  743. {
  744. $gpm = $this->gpm();
  745. if (!$gpm) {
  746. return false;
  747. }
  748. if ($local) {
  749. return $gpm->getInstalledPlugins();
  750. }
  751. $plugins = $gpm->getRepositoryPlugins();
  752. if ($plugins) {
  753. return $plugins->filter(function ($package, $slug) use ($gpm) {
  754. return !$gpm->isPluginInstalled($slug);
  755. });
  756. }
  757. return [];
  758. }
  759. /**
  760. * Get all themes.
  761. *
  762. * @param bool $local
  763. *
  764. * @return mixed
  765. */
  766. public function themes($local = true)
  767. {
  768. $gpm = $this->gpm();
  769. if (!$gpm) {
  770. return false;
  771. }
  772. if ($local) {
  773. return $gpm->getInstalledThemes();
  774. }
  775. $themes = $gpm->getRepositoryThemes();
  776. if ($themes) {
  777. return $themes->filter(function ($package, $slug) use ($gpm) {
  778. return !$gpm->isThemeInstalled($slug);
  779. });
  780. }
  781. return [];
  782. }
  783. /**
  784. * Get list of packages that depend on the passed package slug
  785. *
  786. * @param string $slug The package slug
  787. *
  788. * @return array|bool
  789. */
  790. public function getPackagesThatDependOnPackage($slug)
  791. {
  792. $gpm = $this->gpm();
  793. if (!$gpm) {
  794. return false;
  795. }
  796. return $gpm->getPackagesThatDependOnPackage($slug);
  797. }
  798. /**
  799. * Check the passed packages list can be updated
  800. *
  801. * @param $packages
  802. *
  803. * @throws \Exception
  804. * @return bool
  805. */
  806. public function checkPackagesCanBeInstalled($packages)
  807. {
  808. $gpm = $this->gpm();
  809. if (!$gpm) {
  810. return false;
  811. }
  812. $this->gpm->checkPackagesCanBeInstalled($packages);
  813. return true;
  814. }
  815. /**
  816. * Get an array of dependencies needed to be installed or updated for a list of packages
  817. * to be installed.
  818. *
  819. * @param array $packages The packages slugs
  820. *
  821. * @return array|bool
  822. */
  823. public function getDependenciesNeededToInstall($packages)
  824. {
  825. $gpm = $this->gpm();
  826. if (!$gpm) {
  827. return false;
  828. }
  829. return $this->gpm->getDependencies($packages);
  830. }
  831. /**
  832. * Used by the Dashboard in the admin to display the X latest pages
  833. * that have been modified
  834. *
  835. * @param integer $count number of pages to pull back
  836. *
  837. * @return array|null
  838. */
  839. public function latestPages($count = 10)
  840. {
  841. /** @var Pages $pages */
  842. $pages = $this->grav['pages'];
  843. $latest = [];
  844. if (null === $pages->routes()) {
  845. return null;
  846. }
  847. foreach ($pages->routes() as $url => $path) {
  848. $page = $pages->dispatch($url, true);
  849. if ($page && $page->routable()) {
  850. $latest[$page->route()] = ['modified' => $page->modified(), 'page' => $page];
  851. }
  852. }
  853. // sort based on modified
  854. uasort($latest, function ($a, $b) {
  855. if ($a['modified'] == $b['modified']) {
  856. return 0;
  857. }
  858. return ($a['modified'] > $b['modified']) ? -1 : 1;
  859. });
  860. // build new array with just pages in it
  861. $list = [];
  862. foreach ($latest as $item) {
  863. $list[] = $item['page'];
  864. }
  865. return array_slice($list, 0, $count);
  866. }
  867. /**
  868. * Get log file for fatal errors.
  869. *
  870. * @return string
  871. */
  872. public function logEntry()
  873. {
  874. $file = File::instance($this->grav['locator']->findResource("log://{$this->route}.html"));
  875. $content = $file->content();
  876. $file->free();
  877. return $content;
  878. }
  879. /**
  880. * Search in the logs when was the latest backup made
  881. *
  882. * @return array Array containing the latest backup information
  883. */
  884. public function lastBackup()
  885. {
  886. $file = JsonFile::instance($this->grav['locator']->findResource("log://backup.log"));
  887. $content = $file->content();
  888. if (empty($content)) {
  889. return [
  890. 'days' => '&infin;',
  891. 'chart_fill' => 100,
  892. 'chart_empty' => 0
  893. ];
  894. }
  895. $backup = new \DateTime();
  896. $backup->setTimestamp($content['time']);
  897. $diff = $backup->diff(new \DateTime());
  898. $days = $diff->days;
  899. $chart_fill = $days > 30 ? 100 : round($days / 30 * 100);
  900. return [
  901. 'days' => $days,
  902. 'chart_fill' => $chart_fill,
  903. 'chart_empty' => 100 - $chart_fill
  904. ];
  905. }
  906. /**
  907. * Determine if the plugin or theme info passed is from Team Grav
  908. *
  909. * @param object $info Plugin or Theme info object
  910. *
  911. * @return bool
  912. */
  913. public function isTeamGrav($info)
  914. {
  915. return isset($info['author']['name']) && ($info['author']['name'] === 'Team Grav' || Utils::contains($info['author']['name'], 'Trilby Media'));
  916. }
  917. /**
  918. * Determine if the plugin or theme info passed is premium
  919. *
  920. * @param object $info Plugin or Theme info object
  921. *
  922. * @return bool
  923. */
  924. public function isPremiumProduct($info)
  925. {
  926. return isset($info['premium']);
  927. }
  928. /**
  929. * Renders phpinfo
  930. *
  931. * @return string The phpinfo() output
  932. */
  933. function phpinfo()
  934. {
  935. if (function_exists('phpinfo')) {
  936. ob_start();
  937. phpinfo();
  938. $pinfo = ob_get_contents();
  939. ob_end_clean();
  940. $pinfo = preg_replace('%^.*<body>(.*)</body>.*$%ms', '$1', $pinfo);
  941. return $pinfo;
  942. }
  943. return 'phpinfo() method is not available on this server.';
  944. }
  945. /**
  946. * Guest date format based on euro/US
  947. *
  948. * @param $date
  949. *
  950. * @return string
  951. */
  952. public function guessDateFormat($date)
  953. {
  954. static $guess;
  955. $date_formats = [
  956. 'm/d/y',
  957. 'm/d/Y',
  958. 'n/d/y',
  959. 'n/d/Y',
  960. 'd-m-Y',
  961. 'd-m-y',
  962. ];
  963. $time_formats = [
  964. 'H:i',
  965. 'G:i',
  966. 'h:ia',
  967. 'g:ia'
  968. ];
  969. if (!isset($guess[$date])) {
  970. foreach ($date_formats as $date_format) {
  971. foreach ($time_formats as $time_format) {
  972. if ($this->validateDate($date, "$date_format $time_format")) {
  973. $guess[$date] = "$date_format $time_format";
  974. break 2;
  975. }
  976. if ($this->validateDate($date, "$time_format $date_format")) {
  977. $guess[$date] = "$time_format $date_format";
  978. break 2;
  979. }
  980. }
  981. }
  982. if (!isset($guess[$date])) {
  983. $guess[$date] = 'd-m-Y H:i';
  984. }
  985. }
  986. return $guess[$date];
  987. }
  988. public function validateDate($date, $format)
  989. {
  990. $d = DateTime::createFromFormat($format, $date);
  991. return $d && $d->format($format) == $date;
  992. }
  993. /**
  994. * @param string $php_format
  995. *
  996. * @return string
  997. */
  998. public function dateformatToMomentJS($php_format)
  999. {
  1000. $SYMBOLS_MATCHING = [
  1001. // Day
  1002. 'd' => 'DD',
  1003. 'D' => 'ddd',
  1004. 'j' => 'D',
  1005. 'l' => 'dddd',
  1006. 'N' => 'E',
  1007. 'S' => 'Do',
  1008. 'w' => 'd',
  1009. 'z' => 'DDD',
  1010. // Week
  1011. 'W' => 'W',
  1012. // Month
  1013. 'F' => 'MMMM',
  1014. 'm' => 'MM',
  1015. 'M' => 'MMM',
  1016. 'n' => 'M',
  1017. 't' => '',
  1018. // Year
  1019. 'L' => '',
  1020. 'o' => 'GGGG',
  1021. 'Y' => 'YYYY',
  1022. 'y' => 'yy',
  1023. // Time
  1024. 'a' => 'a',
  1025. 'A' => 'A',
  1026. 'B' => 'SSS',
  1027. 'g' => 'h',
  1028. 'G' => 'H',
  1029. 'h' => 'hh',
  1030. 'H' => 'HH',
  1031. 'i' => 'mm',
  1032. 's' => 'ss',
  1033. 'u' => '',
  1034. // Timezone
  1035. 'e' => '',
  1036. 'I' => '',
  1037. 'O' => 'ZZ',
  1038. 'P' => 'Z',
  1039. 'T' => 'z',
  1040. 'Z' => '',
  1041. // Full Date/Time
  1042. 'c' => '',
  1043. 'r' => 'llll ZZ',
  1044. 'U' => 'X'
  1045. ];
  1046. $js_format = '';
  1047. $escaping = false;
  1048. $len = strlen($php_format);
  1049. for ($i = 0; $i < $len; $i++) {
  1050. $char = $php_format[$i];
  1051. if ($char === '\\') // PHP date format escaping character
  1052. {
  1053. $i++;
  1054. if ($escaping) {
  1055. $js_format .= $php_format[$i];
  1056. } else {
  1057. $js_format .= '\'' . $php_format[$i];
  1058. }
  1059. $escaping = true;
  1060. } else {
  1061. if ($escaping) {
  1062. $js_format .= "'";
  1063. $escaping = false;
  1064. }
  1065. if (isset($SYMBOLS_MATCHING[$char])) {
  1066. $js_format .= $SYMBOLS_MATCHING[$char];
  1067. } else {
  1068. $js_format .= $char;
  1069. }
  1070. }
  1071. }
  1072. return $js_format;
  1073. }
  1074. /**
  1075. * Gets the entire permissions array
  1076. *
  1077. * @return array
  1078. */
  1079. public function getPermissions()
  1080. {
  1081. return $this->permissions;
  1082. }
  1083. /**
  1084. * Sets the entire permissions array
  1085. *
  1086. * @param $permissions
  1087. */
  1088. public function setPermissions($permissions)
  1089. {
  1090. $this->permissions = $permissions;
  1091. }
  1092. /**
  1093. * Adds a permission to the permissions array
  1094. *
  1095. * @param $permissions
  1096. */
  1097. public function addPermissions($permissions)
  1098. {
  1099. $this->permissions = array_merge($this->permissions, $permissions);
  1100. }
  1101. public function processNotifications($notifications)
  1102. {
  1103. // Sort by date
  1104. usort($notifications, function ($a, $b) {
  1105. return strcmp($a->date, $b->date);
  1106. });
  1107. $notifications = array_reverse($notifications);
  1108. // Make adminNicetimeFilter available
  1109. require_once __DIR__ . '/../classes/Twig/AdminTwigExtension.php';
  1110. $adminTwigExtension = new AdminTwigExtension;
  1111. $filename = $this->grav['locator']->findResource('user://data/notifications/' . $this->grav['user']->username . YAML_EXT,
  1112. true, true);
  1113. $read_notifications = (array)CompiledYamlFile::instance($filename)->content();
  1114. $notifications_processed = [];
  1115. foreach ($notifications as $key => $notification) {
  1116. $is_valid = true;
  1117. if (in_array($notification->id, $read_notifications, true)) {
  1118. $notification->read = true;
  1119. }
  1120. if ($is_valid && isset($notification->permissions) && !$this->authorize($notification->permissions)) {
  1121. $is_valid = false;
  1122. }
  1123. if ($is_valid && isset($notification->dependencies)) {
  1124. foreach ($notification->dependencies as $dependency => $constraints) {
  1125. if ($dependency === 'grav') {
  1126. if (!Semver::satisfies(GRAV_VERSION, $constraints)) {
  1127. $is_valid = false;
  1128. }
  1129. } else {
  1130. $packages = array_merge($this->plugins()->toArray(), $this->themes()->toArray());
  1131. if (!isset($packages[$dependency])) {
  1132. $is_valid = false;
  1133. } else {
  1134. $version = $packages[$dependency]['version'];
  1135. if (!Semver::satisfies($version, $constraints)) {
  1136. $is_valid = false;
  1137. }
  1138. }
  1139. }
  1140. if (!$is_valid) {
  1141. break;
  1142. }
  1143. }
  1144. }
  1145. if ($is_valid) {
  1146. $notifications_processed[] = $notification;
  1147. }
  1148. }
  1149. // Process notifications
  1150. $notifications_processed = array_map(function ($notification) use ($adminTwigExtension) {
  1151. $notification->date = $adminTwigExtension->adminNicetimeFilter($notification->date);
  1152. return $notification;
  1153. }, $notifications_processed);
  1154. return $notifications_processed;
  1155. }
  1156. public function findFormFields($type, $fields, $found_fields = [])
  1157. {
  1158. foreach ($fields as $key => $field) {
  1159. if (isset($field['type']) && $field['type'] == $type) {
  1160. $found_fields[$key] = $field;
  1161. } elseif (isset($field['fields'])) {
  1162. $result = $this->findFormFields($type, $field['fields'], $found_fields);
  1163. if (!empty($result)) {
  1164. $found_fields = array_merge($found_fields, $result);
  1165. }
  1166. }
  1167. }
  1168. return $found_fields;
  1169. }
  1170. public function getPagePathFromToken($path)
  1171. {
  1172. return Utils::getPagePathFromToken($path, $this->page(true));
  1173. }
  1174. /**
  1175. * Returns edited page.
  1176. *
  1177. * @param bool $route
  1178. *
  1179. * @param null $path
  1180. *
  1181. * @return Page
  1182. */
  1183. public function page($route = false, $path = null)
  1184. {
  1185. if (!$path) {
  1186. $path = $this->route;
  1187. }
  1188. if ($route && !$path) {
  1189. $path = '/';
  1190. }
  1191. if (!isset($this->pages[$path])) {
  1192. $this->pages[$path] = $this->getPage($path);
  1193. }
  1194. return $this->pages[$path];
  1195. }
  1196. /**
  1197. * Returns the page creating it if it does not exist.
  1198. *
  1199. * @param $path
  1200. *
  1201. * @return Page
  1202. */
  1203. public function getPage($path)
  1204. {
  1205. /** @var Pages $pages */
  1206. $pages = $this->grav['pages'];
  1207. if ($path && $path[0] !== '/') {
  1208. $path = "/{$path}";
  1209. }
  1210. $page = $path ? $pages->dispatch($path, true) : $pages->root();
  1211. if (!$page) {
  1212. $slug = basename($path);
  1213. if ($slug === '') {
  1214. return null;
  1215. }
  1216. $ppath = str_replace('\\', '/', dirname($path));
  1217. // Find or create parent(s).
  1218. $parent = $this->getPage($ppath !== '/' ? $ppath : '');
  1219. // Create page.
  1220. $page = new Page;
  1221. $page->parent($parent);
  1222. $page->filePath($parent->path() . '/' . $slug . '/' . $page->name());
  1223. // Add routing information.
  1224. $pages->addPage($page, $path);
  1225. // Set if Modular
  1226. $page->modularTwig($slug[0] === '_');
  1227. // Determine page type.
  1228. if (isset($this->session->{$page->route()})) {
  1229. // Found the type and header from the session.
  1230. $data = $this->session->{$page->route()};
  1231. // Set the key header value
  1232. $header = ['title' => $data['title']];
  1233. if (isset($data['visible'])) {
  1234. if ($data['visible'] === '' || $data['visible']) {
  1235. // if auto (ie '')
  1236. $pageParent = $page->parent();
  1237. $children = $pageParent ? $pageParent->children() : [];
  1238. foreach ($children as $child) {
  1239. if ($child->order()) {
  1240. // set page order
  1241. $page->order(AdminController::getNextOrderInFolder($pageParent->path()));
  1242. break;
  1243. }
  1244. }
  1245. }
  1246. if ($data['visible'] == 1 && !$page->order()) {
  1247. $header['visible'] = $data['visible'];
  1248. }
  1249. }
  1250. if ($data['name'] === 'modular') {
  1251. $header['body_classes'] = 'modular';
  1252. }
  1253. $name = $page->modular() ? str_replace('modular/', '', $data['name']) : $data['name'];
  1254. $page->name($name . '.md');
  1255. // Fire new event to allow plugins to manipulate page frontmatter
  1256. $this->grav->fireEvent('onAdminCreatePageFrontmatter', new Event(['header' => &$header,
  1257. 'data' => $data]));
  1258. $page->header($header);
  1259. $page->frontmatter(Yaml::dump((array)$page->header(), 20));
  1260. } else {
  1261. // Find out the type by looking at the parent.
  1262. $type = $parent->childType()
  1263. ? $parent->childType()
  1264. : $parent->blueprints()->get('child_type',
  1265. 'default');
  1266. $page->name($type . CONTENT_EXT);
  1267. $page->header();
  1268. }
  1269. $page->modularTwig($slug[0] === '_');
  1270. }
  1271. return $page;
  1272. }
  1273. /**
  1274. * Get https://getgrav.org news feed
  1275. *
  1276. * @return mixed
  1277. */
  1278. public function getFeed()
  1279. {
  1280. $feed_url = 'https://getgrav.org/blog.atom';
  1281. $body = Response::get($feed_url);
  1282. $reader = new Reader();
  1283. $parser = $reader->getParser($feed_url, $body, 'utf-8');
  1284. return $parser->execute();
  1285. }
  1286. public function getRouteDetails()
  1287. {
  1288. return [$this->base, $this->location, $this->route];
  1289. }
  1290. /**
  1291. * Get the files list
  1292. *
  1293. * @todo allow pagination
  1294. * @return array
  1295. */
  1296. public function files($filtered = true, $page_index = 0)
  1297. {
  1298. $param_type = $this->grav['uri']->param('type');
  1299. $param_date = $this->grav['uri']->param('date');
  1300. $param_page = $this->grav['uri']->param('page');
  1301. $param_page = str_replace('\\', '/', $param_page);
  1302. $files_cache_key = 'media-manager-files';
  1303. if ($param_type) {
  1304. $files_cache_key .= "-{$param_type}";
  1305. }
  1306. if ($param_date) {
  1307. $files_cache_key .= "-{$param_date}";
  1308. }
  1309. if ($param_page) {
  1310. $files_cache_key .= "-{$param_page}";
  1311. }
  1312. $page_files = null;
  1313. $cache_enabled = $this->grav['config']->get('plugins.admin.cache_enabled');
  1314. if (!$cache_enabled) {
  1315. $this->grav['cache']->setEnabled(true);
  1316. }
  1317. $page_files = $this->grav['cache']->fetch(md5($files_cache_key));
  1318. if (!$cache_enabled) {
  1319. $this->grav['cache']->setEnabled(false);
  1320. }
  1321. if (!$page_files) {
  1322. $page_files = [];
  1323. $pages = $this->grav['pages'];
  1324. if ($param_page) {
  1325. $page = $pages->dispatch($param_page);
  1326. $page_files = $this->getFiles('images', $page, $page_files, $filtered);
  1327. $page_files = $this->getFiles('videos', $page, $page_files, $filtered);
  1328. $page_files = $this->getFiles('audios', $page, $page_files, $filtered);
  1329. $page_files = $this->getFiles('files', $page, $page_files, $filtered);
  1330. } else {
  1331. $allPages = $pages->all();
  1332. if ($allPages) foreach ($allPages as $page) {
  1333. $page_files = $this->getFiles('images', $page, $page_files, $filtered);
  1334. $page_files = $this->getFiles('videos', $page, $page_files, $filtered);
  1335. $page_files = $this->getFiles('audios', $page, $page_files, $filtered);
  1336. $page_files = $this->getFiles('files', $page, $page_files, $filtered);
  1337. }
  1338. }
  1339. if (count($page_files) >= self::MEDIA_PAGINATION_INTERVAL) {
  1340. $this->shouldLoadAdditionalFilesInBackground(true);
  1341. }
  1342. if (!$cache_enabled) {
  1343. $this->grav['cache']->setEnabled(true);
  1344. }
  1345. $this->grav['cache']->save(md5($files_cache_key), $page_files, 600); //cache for 10 minutes
  1346. if (!$cache_enabled) {
  1347. $this->grav['cache']->setEnabled(false);
  1348. }
  1349. }
  1350. if (count($page_files) >= self::MEDIA_PAGINATION_INTERVAL) {
  1351. $page_files = array_slice($page_files, $page_index * self::MEDIA_PAGINATION_INTERVAL, self::MEDIA_PAGINATION_INTERVAL);
  1352. }
  1353. return $page_files;
  1354. }
  1355. public function shouldLoadAdditionalFilesInBackground($status = null)
  1356. {
  1357. if ($status) {
  1358. $this->load_additional_files_in_background = true;
  1359. }
  1360. return $this->load_additional_files_in_background;
  1361. }
  1362. public function loadAdditionalFilesInBackground($status = null)
  1363. {
  1364. if (!$this->loading_additional_files_in_background) {
  1365. $this->loading_additional_files_in_background = true;
  1366. $this->files(false, false);
  1367. $this->shouldLoadAdditionalFilesInBackground(false);
  1368. $this->loading_additional_files_in_background = false;
  1369. }
  1370. }
  1371. private function getFiles($type, $page, $page_files, $filtered)
  1372. {
  1373. $page_files = $this->getMediaOfType($type, $page, $page_files);
  1374. if ($filtered) {
  1375. $page_files = $this->filterByType($page_files);
  1376. $page_files = $this->filterByDate($page_files);
  1377. }
  1378. return $page_files;
  1379. }
  1380. /**
  1381. * Get all the media of a type ('images' | 'audios' | 'videos' | 'files')
  1382. *
  1383. * @param string $type
  1384. * @param Page|null $page
  1385. * @param array $files
  1386. *
  1387. * @return array
  1388. */
  1389. private function getMediaOfType($type, Page $page = null, array $files)
  1390. {
  1391. if ($page) {
  1392. $media = $page->media();
  1393. $mediaOfType = $media->$type();
  1394. foreach($mediaOfType as $title => $file) {
  1395. $files[] = [
  1396. 'title' => $title,
  1397. 'type' => $type,
  1398. 'page_route' => $page->route(),
  1399. 'file' => $file->higherQualityAlternative()
  1400. ];
  1401. }
  1402. return $files;
  1403. }
  1404. return [];
  1405. }
  1406. /**
  1407. * Filter media by type
  1408. *
  1409. * @param array $filesFiltered
  1410. *
  1411. * @return array
  1412. */
  1413. private function filterByType($filesFiltered)
  1414. {
  1415. $filter_type = $this->grav['uri']->param('type');
  1416. if (!$filter_type) {
  1417. return $filesFiltered;
  1418. }
  1419. $filesFiltered = array_filter($filesFiltered, function ($file) use ($filter_type) {
  1420. return $file['type'] == $filter_type;
  1421. });
  1422. return $filesFiltered;
  1423. }
  1424. /**
  1425. * Filter media by date
  1426. *
  1427. * @param array $filesFiltered
  1428. *
  1429. * @return array
  1430. */
  1431. private function filterByDate($filesFiltered)
  1432. {
  1433. $filter_date = $this->grav['uri']->param('date');
  1434. if (!$filter_date) {
  1435. return $filesFiltered;
  1436. }
  1437. $year = substr($filter_date, 0, 4);
  1438. $month = substr($filter_date, 5, 2);
  1439. $filesFilteredByDate = [];
  1440. foreach($filesFiltered as $file) {
  1441. $filedate = $this->fileDate($file['file']);
  1442. $fileYear = $filedate->format('Y');
  1443. $fileMonth = $filedate->format('m');
  1444. if ($fileYear == $year && $fileMonth == $month) {
  1445. $filesFilteredByDate[] = $file;
  1446. }
  1447. }
  1448. return $filesFilteredByDate;
  1449. }
  1450. /**
  1451. * Return the DateTime object representation of a file modified date
  1452. *
  1453. * @param File $file
  1454. *
  1455. * @return DateTime
  1456. */
  1457. private function fileDate($file) {
  1458. $datetime = new \DateTime();
  1459. $datetime->setTimestamp($file->toArray()['modified']);
  1460. return $datetime;
  1461. }
  1462. /**
  1463. * Get the files dates list to be used in the Media Files filter
  1464. *
  1465. * @return array
  1466. */
  1467. public function filesDates()
  1468. {
  1469. $files = $this->files(false);
  1470. $dates = [];
  1471. foreach ($files as $file) {
  1472. $datetime = $this->fileDate($file['file']);
  1473. $year = $datetime->format('Y');
  1474. $month = $datetime->format('m');
  1475. if (!isset($dates[$year])) {
  1476. $dates[$year] = [];
  1477. }
  1478. if (!isset($dates[$year][$month])) {
  1479. $dates[$year][$month] = 1;
  1480. } else {
  1481. $dates[$year][$month]++;
  1482. }
  1483. }
  1484. return $dates;
  1485. }
  1486. /**
  1487. * Get the pages list to be used in the Media Files filter
  1488. *
  1489. * @return array
  1490. */
  1491. public function pages()
  1492. {
  1493. /** @var Collection $pages */
  1494. $pages = $this->grav['pages']->all();
  1495. $pagesWithFiles = [];
  1496. foreach ($pages as $page) {
  1497. if (count($page->media()->all())) {
  1498. $pagesWithFiles[] = $page;
  1499. }
  1500. }
  1501. return $pagesWithFiles;
  1502. }
  1503. /**
  1504. * Return HTTP_REFERRER if set
  1505. *
  1506. * @return null
  1507. */
  1508. public function getReferrer()
  1509. {
  1510. return isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
  1511. }
  1512. }