admin.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813
  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 Grav\Common\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->getFilename(), '.')) {
  158. continue;
  159. }
  160. $lang = $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[] = $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->base . $this->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(isset($post['redirect']) ? $post['redirect'] : $redirect);
  339. } else {
  340. $this->session->redirect = $redirect;
  341. }
  342. } else {
  343. if ($user->authorized) {
  344. $event->defMessage('PLUGIN_LOGIN.ACCESS_DENIED', 'error');
  345. } else {
  346. $event->defMessage('PLUGIN_LOGIN.LOGIN_FAILED', 'error');
  347. }
  348. }
  349. $event->defRedirect($redirect);
  350. $message = $event->getMessage();
  351. if ($message) {
  352. $this->setMessage($this->translate($message), $event->getMessageType());
  353. }
  354. $redirect = $event->getRedirect();
  355. $this->grav->redirect($redirect, $event->getRedirectCode());
  356. }
  357. /**
  358. * Check Two-Factor Authentication.
  359. */
  360. public function twoFa($data, $post)
  361. {
  362. /** @var Login $login */
  363. $login = $this->grav['login'];
  364. /** @var TwoFactorAuth $twoFa */
  365. $twoFa = $login->twoFactorAuth();
  366. $user = $this->grav['user'];
  367. $code = isset($data['2fa_code']) ? $data['2fa_code'] : null;
  368. $secret = isset($user->twofa_secret) ? $user->twofa_secret : null;
  369. if (!$code || !$secret || !$twoFa->verifyCode($secret, $code)) {
  370. $login->logout(['admin' => true]);
  371. $this->grav['session']->setFlashCookieObject(Admin::TMP_COOKIE_NAME, ['message' => $this->translate('PLUGIN_ADMIN.2FA_FAILED'), 'status' => 'error']);
  372. $this->grav->redirect($this->uri->route(), 303);
  373. }
  374. $this->setMessage($this->translate('PLUGIN_ADMIN.LOGIN_LOGGED_IN'), 'info');
  375. $user->authorized = true;
  376. $this->grav->redirect($post['redirect']);
  377. }
  378. /**
  379. * Logout from admin.
  380. */
  381. public function Logout($data, $post)
  382. {
  383. /** @var Login $login */
  384. $login = $this->grav['login'];
  385. $event = $login->logout(['admin' => true], ['return_event' => true]);
  386. $event->defMessage('PLUGIN_ADMIN.LOGGED_OUT', 'info');
  387. $message = $event->getMessage();
  388. if ($message) {
  389. $this->grav['session']->setFlashCookieObject(Admin::TMP_COOKIE_NAME, ['message' => $this->translate($message), 'status' => $event->getMessageType()]);
  390. }
  391. $this->grav->redirect($this->base);
  392. }
  393. /**
  394. * @return bool
  395. */
  396. public static function doAnyUsersExist()
  397. {
  398. // check for existence of a user account
  399. $account_dir = $file_path = Grav::instance()['locator']->findResource('account://');
  400. $user_check = glob($account_dir . '/*.yaml');
  401. return $user_check ? true : false;
  402. }
  403. /**
  404. * Add message into the session queue.
  405. *
  406. * @param string $msg
  407. * @param string $type
  408. */
  409. public function setMessage($msg, $type = 'info')
  410. {
  411. /** @var Message $messages */
  412. $messages = $this->grav['messages'];
  413. $messages->add($msg, $type);
  414. }
  415. public function addTempMessage($msg, $type)
  416. {
  417. $this->temp_messages[] = ['message' => $msg, 'scope' => $type];
  418. }
  419. public function getTempMessages()
  420. {
  421. return $this->temp_messages;
  422. }
  423. /**
  424. * Translate a string to the user-defined language
  425. *
  426. * @param array|mixed $args
  427. *
  428. * @param mixed $languages
  429. *
  430. * @return string
  431. */
  432. public static function translate($args, $languages = null)
  433. {
  434. $grav = Grav::instance();
  435. if (is_array($args)) {
  436. $lookup = array_shift($args);
  437. } else {
  438. $lookup = $args;
  439. $args = [];
  440. }
  441. if (!$languages) {
  442. if ($grav['config']->get('system.languages.translations_fallback', true)) {
  443. $languages = $grav['language']->getFallbackLanguages();
  444. } else {
  445. $languages = (array)$grav['language']->getDefault();
  446. }
  447. $languages = $grav['user']->authenticated ? [ $grav['user']->language ] : $languages;
  448. } else {
  449. $languages = (array)$languages;
  450. }
  451. foreach ((array)$languages as $lang) {
  452. $translation = $grav['language']->getTranslation($lang, $lookup);
  453. if (!$translation) {
  454. $language = $grav['language']->getDefault() ?: 'en';
  455. $translation = $grav['language']->getTranslation($language, $lookup);
  456. }
  457. if (!$translation) {
  458. $language = 'en';
  459. $translation = $grav['language']->getTranslation($language, $lookup);
  460. }
  461. if ($translation) {
  462. if (count($args) >= 1) {
  463. return vsprintf($translation, $args);
  464. }
  465. return $translation;
  466. }
  467. }
  468. return $lookup;
  469. }
  470. /**
  471. * Checks user authorisation to the action.
  472. *
  473. * @param string|string[] $action
  474. *
  475. * @return bool
  476. */
  477. public function authorize($action = 'admin.login')
  478. {
  479. $action = (array)$action;
  480. foreach ($action as $a) {
  481. if ($this->user->authorize($a)) {
  482. return true;
  483. }
  484. }
  485. return false;
  486. }
  487. /**
  488. * Gets configuration data.
  489. *
  490. * @param string $type
  491. * @param array $post
  492. *
  493. * @return mixed
  494. * @throws \RuntimeException
  495. */
  496. public function data($type, array $post = [])
  497. {
  498. static $data = [];
  499. if (isset($data[$type])) {
  500. return $data[$type];
  501. }
  502. if (!$post) {
  503. $post = $this->grav['uri']->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($this->cleanUserPost($post));
  538. $data[$type] = $obj;
  539. } elseif (preg_match('|user/|', $type)) {
  540. $obj = User::load(preg_replace('|user/|', '', $type));
  541. $obj->merge($this->cleanUserPost($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. $fileInfo = pathinfo($obj->title);
  564. $filename = str_replace(['@3x', '@2x'], '', $fileInfo['filename']);
  565. if (isset($fileInfo['extension'])) {
  566. $filename .= '.' . $fileInfo['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. /**
  578. * Clean user form post and remove extra stuff that may be passed along
  579. *
  580. * @param $post
  581. * @return array
  582. */
  583. protected function cleanUserPost($post)
  584. {
  585. // Clean fields for all users
  586. unset($post['hashed_password']);
  587. // Clean field for users who shouldn't be able to modify these fields
  588. if (!$this->authorize(['admin.user', 'admin.super'])) {
  589. unset($post['access']);
  590. }
  591. return $post;
  592. }
  593. protected function hasErrorMessage()
  594. {
  595. $msgs = $this->grav['messages']->all();
  596. foreach ($msgs as $msg) {
  597. if (isset($msg['scope']) && $msg['scope'] === 'error') {
  598. return true;
  599. }
  600. }
  601. return false;
  602. }
  603. /**
  604. * Returns blueprints for the given type.
  605. *
  606. * @param string $type
  607. *
  608. * @return Data\Blueprint
  609. */
  610. public function blueprints($type)
  611. {
  612. if ($this->blueprints === null) {
  613. $this->blueprints = new Data\Blueprints('blueprints://');
  614. }
  615. return $this->blueprints->get($type);
  616. }
  617. /**
  618. * Converts dot notation to array notation.
  619. *
  620. * @param string $name
  621. *
  622. * @return string
  623. */
  624. public function field($name)
  625. {
  626. $path = explode('.', $name);
  627. return array_shift($path) . ($path ? '[' . implode('][', $path) . ']' : '');
  628. }
  629. /**
  630. * Get all routes.
  631. *
  632. * @param bool $unique
  633. *
  634. * @return array
  635. */
  636. public function routes($unique = false)
  637. {
  638. /** @var Pages $pages */
  639. $pages = $this->grav['pages'];
  640. if ($unique) {
  641. $routes = array_unique($pages->routes());
  642. } else {
  643. $routes = $pages->routes();
  644. }
  645. return $routes;
  646. }
  647. /**
  648. * Count the pages
  649. *
  650. * @return array
  651. */
  652. public function pagesCount()
  653. {
  654. if (!$this->pages_count) {
  655. $this->pages_count = count($this->grav['pages']->all());
  656. }
  657. return $this->pages_count;
  658. }
  659. /**
  660. * Get all template types
  661. *
  662. * @return array
  663. */
  664. public function types()
  665. {
  666. return Pages::types();
  667. }
  668. /**
  669. * Get all modular template types
  670. *
  671. * @return array
  672. */
  673. public function modularTypes()
  674. {
  675. return Pages::modularTypes();
  676. }
  677. /**
  678. * Get all access levels
  679. *
  680. * @return array
  681. */
  682. public function accessLevels()
  683. {
  684. if (method_exists($this->grav['pages'], 'accessLevels')) {
  685. return $this->grav['pages']->accessLevels();
  686. }
  687. return [];
  688. }
  689. public function license($package_slug)
  690. {
  691. return Licenses::get($package_slug);
  692. }
  693. /**
  694. * Generate an array of dependencies for a package, used to generate a list of
  695. * packages that can be removed when removing a package.
  696. *
  697. * @param string $slug The package slug
  698. *
  699. * @return array|bool
  700. */
  701. public function dependenciesThatCanBeRemovedWhenRemoving($slug)
  702. {
  703. $gpm = $this->gpm();
  704. if (!$gpm) {
  705. return false;
  706. }
  707. $dependencies = [];
  708. $package = $this->getPackageFromGPM($slug);
  709. if ($package) {
  710. if ($package->dependencies) {
  711. foreach ($package->dependencies as $dependency) {
  712. // if (count($gpm->getPackagesThatDependOnPackage($dependency)) > 1) {
  713. // continue;
  714. // }
  715. if (isset($dependency['name'])) {
  716. $dependency = $dependency['name'];
  717. }
  718. if (!in_array($dependency, $dependencies, true)) {
  719. if (!in_array($dependency, ['admin', 'form', 'login', 'email', 'php'])) {
  720. $dependencies[] = $dependency;
  721. }
  722. }
  723. }
  724. }
  725. }
  726. return $dependencies;
  727. }
  728. /**
  729. * Get the GPM instance
  730. *
  731. * @return GPM The GPM instance
  732. */
  733. public function gpm()
  734. {
  735. if (!$this->gpm) {
  736. try {
  737. $this->gpm = new GPM();
  738. } catch (\Exception $e) {
  739. }
  740. }
  741. return $this->gpm;
  742. }
  743. public function getPackageFromGPM($package_slug)
  744. {
  745. $package = $this->plugins(true)[$package_slug];
  746. if (!$package) {
  747. $package = $this->themes(true)[$package_slug];
  748. }
  749. return $package;
  750. }
  751. /**
  752. * Get all plugins.
  753. *
  754. * @param bool $local
  755. *
  756. * @return mixed
  757. */
  758. public function plugins($local = true)
  759. {
  760. $gpm = $this->gpm();
  761. if (!$gpm) {
  762. return false;
  763. }
  764. if ($local) {
  765. return $gpm->getInstalledPlugins();
  766. }
  767. $plugins = $gpm->getRepositoryPlugins();
  768. if ($plugins) {
  769. return $plugins->filter(function ($package, $slug) use ($gpm) {
  770. return !$gpm->isPluginInstalled($slug);
  771. });
  772. }
  773. return [];
  774. }
  775. /**
  776. * Get all themes.
  777. *
  778. * @param bool $local
  779. *
  780. * @return mixed
  781. */
  782. public function themes($local = true)
  783. {
  784. $gpm = $this->gpm();
  785. if (!$gpm) {
  786. return false;
  787. }
  788. if ($local) {
  789. return $gpm->getInstalledThemes();
  790. }
  791. $themes = $gpm->getRepositoryThemes();
  792. if ($themes) {
  793. return $themes->filter(function ($package, $slug) use ($gpm) {
  794. return !$gpm->isThemeInstalled($slug);
  795. });
  796. }
  797. return [];
  798. }
  799. /**
  800. * Get list of packages that depend on the passed package slug
  801. *
  802. * @param string $slug The package slug
  803. *
  804. * @return array|bool
  805. */
  806. public function getPackagesThatDependOnPackage($slug)
  807. {
  808. $gpm = $this->gpm();
  809. if (!$gpm) {
  810. return false;
  811. }
  812. return $gpm->getPackagesThatDependOnPackage($slug);
  813. }
  814. /**
  815. * Check the passed packages list can be updated
  816. *
  817. * @param $packages
  818. *
  819. * @throws \Exception
  820. * @return bool
  821. */
  822. public function checkPackagesCanBeInstalled($packages)
  823. {
  824. $gpm = $this->gpm();
  825. if (!$gpm) {
  826. return false;
  827. }
  828. $this->gpm->checkPackagesCanBeInstalled($packages);
  829. return true;
  830. }
  831. /**
  832. * Get an array of dependencies needed to be installed or updated for a list of packages
  833. * to be installed.
  834. *
  835. * @param array $packages The packages slugs
  836. *
  837. * @return array|bool
  838. */
  839. public function getDependenciesNeededToInstall($packages)
  840. {
  841. $gpm = $this->gpm();
  842. if (!$gpm) {
  843. return false;
  844. }
  845. return $this->gpm->getDependencies($packages);
  846. }
  847. /**
  848. * Used by the Dashboard in the admin to display the X latest pages
  849. * that have been modified
  850. *
  851. * @param integer $count number of pages to pull back
  852. *
  853. * @return array|null
  854. */
  855. public function latestPages($count = 10)
  856. {
  857. /** @var Pages $pages */
  858. $pages = $this->grav['pages'];
  859. $latest = [];
  860. if (null === $pages->routes()) {
  861. return null;
  862. }
  863. foreach ($pages->routes() as $url => $path) {
  864. $page = $pages->dispatch($url, true);
  865. if ($page && $page->routable()) {
  866. $latest[$page->route()] = ['modified' => $page->modified(), 'page' => $page];
  867. }
  868. }
  869. // sort based on modified
  870. uasort($latest, function ($a, $b) {
  871. if ($a['modified'] == $b['modified']) {
  872. return 0;
  873. }
  874. return ($a['modified'] > $b['modified']) ? -1 : 1;
  875. });
  876. // build new array with just pages in it
  877. $list = [];
  878. foreach ($latest as $item) {
  879. $list[] = $item['page'];
  880. }
  881. return array_slice($list, 0, $count);
  882. }
  883. /**
  884. * Get log file for fatal errors.
  885. *
  886. * @return string
  887. */
  888. public function logEntry()
  889. {
  890. $file = File::instance($this->grav['locator']->findResource("log://{$this->route}.html"));
  891. $content = $file->content();
  892. $file->free();
  893. return $content;
  894. }
  895. /**
  896. * Search in the logs when was the latest backup made
  897. *
  898. * @return array Array containing the latest backup information
  899. */
  900. public function lastBackup()
  901. {
  902. $file = JsonFile::instance($this->grav['locator']->findResource("log://backup.log"));
  903. $content = $file->content();
  904. if (empty($content)) {
  905. return [
  906. 'days' => '&infin;',
  907. 'chart_fill' => 100,
  908. 'chart_empty' => 0
  909. ];
  910. }
  911. $backup = new \DateTime();
  912. $backup->setTimestamp($content['time']);
  913. $diff = $backup->diff(new \DateTime());
  914. $days = $diff->days;
  915. $chart_fill = $days > 30 ? 100 : round($days / 30 * 100);
  916. return [
  917. 'days' => $days,
  918. 'chart_fill' => $chart_fill,
  919. 'chart_empty' => 100 - $chart_fill
  920. ];
  921. }
  922. /**
  923. * Determine if the plugin or theme info passed is from Team Grav
  924. *
  925. * @param object $info Plugin or Theme info object
  926. *
  927. * @return bool
  928. */
  929. public function isTeamGrav($info)
  930. {
  931. return isset($info['author']['name']) && ($info['author']['name'] === 'Team Grav' || Utils::contains($info['author']['name'], 'Trilby Media'));
  932. }
  933. /**
  934. * Determine if the plugin or theme info passed is premium
  935. *
  936. * @param object $info Plugin or Theme info object
  937. *
  938. * @return bool
  939. */
  940. public function isPremiumProduct($info)
  941. {
  942. return isset($info['premium']);
  943. }
  944. /**
  945. * Renders phpinfo
  946. *
  947. * @return string The phpinfo() output
  948. */
  949. function phpinfo()
  950. {
  951. if (function_exists('phpinfo')) {
  952. ob_start();
  953. phpinfo();
  954. $pinfo = ob_get_contents();
  955. ob_end_clean();
  956. $pinfo = preg_replace('%^.*<body>(.*)</body>.*$%ms', '$1', $pinfo);
  957. return $pinfo;
  958. }
  959. return 'phpinfo() method is not available on this server.';
  960. }
  961. /**
  962. * Guest date format based on euro/US
  963. *
  964. * @param $date
  965. *
  966. * @return string
  967. */
  968. public function guessDateFormat($date)
  969. {
  970. static $guess;
  971. $date_formats = [
  972. 'm/d/y',
  973. 'm/d/Y',
  974. 'n/d/y',
  975. 'n/d/Y',
  976. 'd-m-Y',
  977. 'd-m-y',
  978. ];
  979. $time_formats = [
  980. 'H:i',
  981. 'G:i',
  982. 'h:ia',
  983. 'g:ia'
  984. ];
  985. if (!isset($guess[$date])) {
  986. foreach ($date_formats as $date_format) {
  987. foreach ($time_formats as $time_format) {
  988. if ($this->validateDate($date, "$date_format $time_format")) {
  989. $guess[$date] = "$date_format $time_format";
  990. break 2;
  991. }
  992. if ($this->validateDate($date, "$time_format $date_format")) {
  993. $guess[$date] = "$time_format $date_format";
  994. break 2;
  995. }
  996. }
  997. }
  998. if (!isset($guess[$date])) {
  999. $guess[$date] = 'd-m-Y H:i';
  1000. }
  1001. }
  1002. return $guess[$date];
  1003. }
  1004. public function validateDate($date, $format)
  1005. {
  1006. $d = DateTime::createFromFormat($format, $date);
  1007. return $d && $d->format($format) == $date;
  1008. }
  1009. /**
  1010. * @param string $php_format
  1011. *
  1012. * @return string
  1013. */
  1014. public function dateformatToMomentJS($php_format)
  1015. {
  1016. $SYMBOLS_MATCHING = [
  1017. // Day
  1018. 'd' => 'DD',
  1019. 'D' => 'ddd',
  1020. 'j' => 'D',
  1021. 'l' => 'dddd',
  1022. 'N' => 'E',
  1023. 'S' => 'Do',
  1024. 'w' => 'd',
  1025. 'z' => 'DDD',
  1026. // Week
  1027. 'W' => 'W',
  1028. // Month
  1029. 'F' => 'MMMM',
  1030. 'm' => 'MM',
  1031. 'M' => 'MMM',
  1032. 'n' => 'M',
  1033. 't' => '',
  1034. // Year
  1035. 'L' => '',
  1036. 'o' => 'GGGG',
  1037. 'Y' => 'YYYY',
  1038. 'y' => 'yy',
  1039. // Time
  1040. 'a' => 'a',
  1041. 'A' => 'A',
  1042. 'B' => 'SSS',
  1043. 'g' => 'h',
  1044. 'G' => 'H',
  1045. 'h' => 'hh',
  1046. 'H' => 'HH',
  1047. 'i' => 'mm',
  1048. 's' => 'ss',
  1049. 'u' => '',
  1050. // Timezone
  1051. 'e' => '',
  1052. 'I' => '',
  1053. 'O' => 'ZZ',
  1054. 'P' => 'Z',
  1055. 'T' => 'z',
  1056. 'Z' => '',
  1057. // Full Date/Time
  1058. 'c' => '',
  1059. 'r' => 'llll ZZ',
  1060. 'U' => 'X'
  1061. ];
  1062. $js_format = '';
  1063. $escaping = false;
  1064. $len = strlen($php_format);
  1065. for ($i = 0; $i < $len; $i++) {
  1066. $char = $php_format[$i];
  1067. if ($char === '\\') // PHP date format escaping character
  1068. {
  1069. $i++;
  1070. if ($escaping) {
  1071. $js_format .= $php_format[$i];
  1072. } else {
  1073. $js_format .= '\'' . $php_format[$i];
  1074. }
  1075. $escaping = true;
  1076. } else {
  1077. if ($escaping) {
  1078. $js_format .= "'";
  1079. $escaping = false;
  1080. }
  1081. if (isset($SYMBOLS_MATCHING[$char])) {
  1082. $js_format .= $SYMBOLS_MATCHING[$char];
  1083. } else {
  1084. $js_format .= $char;
  1085. }
  1086. }
  1087. }
  1088. return $js_format;
  1089. }
  1090. /**
  1091. * Gets the entire permissions array
  1092. *
  1093. * @return array
  1094. */
  1095. public function getPermissions()
  1096. {
  1097. return $this->permissions;
  1098. }
  1099. /**
  1100. * Sets the entire permissions array
  1101. *
  1102. * @param $permissions
  1103. */
  1104. public function setPermissions($permissions)
  1105. {
  1106. $this->permissions = $permissions;
  1107. }
  1108. /**
  1109. * Adds a permission to the permissions array
  1110. *
  1111. * @param $permissions
  1112. */
  1113. public function addPermissions($permissions)
  1114. {
  1115. $this->permissions = array_merge($this->permissions, $permissions);
  1116. }
  1117. public function processNotifications($notifications)
  1118. {
  1119. // Sort by date
  1120. usort($notifications, function ($a, $b) {
  1121. return strcmp($a->date, $b->date);
  1122. });
  1123. $notifications = array_reverse($notifications);
  1124. // Make adminNicetimeFilter available
  1125. require_once __DIR__ . '/../classes/Twig/AdminTwigExtension.php';
  1126. $adminTwigExtension = new AdminTwigExtension;
  1127. $filename = $this->grav['locator']->findResource('user://data/notifications/' . $this->grav['user']->username . YAML_EXT,
  1128. true, true);
  1129. $read_notifications = (array)CompiledYamlFile::instance($filename)->content();
  1130. $notifications_processed = [];
  1131. foreach ($notifications as $key => $notification) {
  1132. $is_valid = true;
  1133. if (in_array($notification->id, $read_notifications, true)) {
  1134. $notification->read = true;
  1135. }
  1136. if ($is_valid && isset($notification->permissions) && !$this->authorize($notification->permissions)) {
  1137. $is_valid = false;
  1138. }
  1139. if ($is_valid && isset($notification->dependencies)) {
  1140. foreach ($notification->dependencies as $dependency => $constraints) {
  1141. if ($dependency === 'grav') {
  1142. if (!Semver::satisfies(GRAV_VERSION, $constraints)) {
  1143. $is_valid = false;
  1144. }
  1145. } else {
  1146. $packages = array_merge($this->plugins()->toArray(), $this->themes()->toArray());
  1147. if (!isset($packages[$dependency])) {
  1148. $is_valid = false;
  1149. } else {
  1150. $version = $packages[$dependency]['version'];
  1151. if (!Semver::satisfies($version, $constraints)) {
  1152. $is_valid = false;
  1153. }
  1154. }
  1155. }
  1156. if (!$is_valid) {
  1157. break;
  1158. }
  1159. }
  1160. }
  1161. if ($is_valid) {
  1162. $notifications_processed[] = $notification;
  1163. }
  1164. }
  1165. // Process notifications
  1166. $notifications_processed = array_map(function ($notification) use ($adminTwigExtension) {
  1167. $notification->date = $adminTwigExtension->adminNicetimeFilter($notification->date);
  1168. return $notification;
  1169. }, $notifications_processed);
  1170. return $notifications_processed;
  1171. }
  1172. public function findFormFields($type, $fields, $found_fields = [])
  1173. {
  1174. foreach ($fields as $key => $field) {
  1175. if (isset($field['type']) && $field['type'] == $type) {
  1176. $found_fields[$key] = $field;
  1177. } elseif (isset($field['fields'])) {
  1178. $result = $this->findFormFields($type, $field['fields'], $found_fields);
  1179. if (!empty($result)) {
  1180. $found_fields = array_merge($found_fields, $result);
  1181. }
  1182. }
  1183. }
  1184. return $found_fields;
  1185. }
  1186. public function getPagePathFromToken($path)
  1187. {
  1188. return Utils::getPagePathFromToken($path, $this->page(true));
  1189. }
  1190. /**
  1191. * Returns edited page.
  1192. *
  1193. * @param bool $route
  1194. *
  1195. * @param null $path
  1196. *
  1197. * @return Page
  1198. */
  1199. public function page($route = false, $path = null)
  1200. {
  1201. if (!$path) {
  1202. $path = $this->route;
  1203. }
  1204. if ($route && !$path) {
  1205. $path = '/';
  1206. }
  1207. if (!isset($this->pages[$path])) {
  1208. $this->pages[$path] = $this->getPage($path);
  1209. }
  1210. return $this->pages[$path];
  1211. }
  1212. /**
  1213. * Returns the page creating it if it does not exist.
  1214. *
  1215. * @param $path
  1216. *
  1217. * @return Page
  1218. */
  1219. public function getPage($path)
  1220. {
  1221. /** @var Pages $pages */
  1222. $pages = $this->grav['pages'];
  1223. if ($path && $path[0] !== '/') {
  1224. $path = "/{$path}";
  1225. }
  1226. // Fix for entities in path causing looping...
  1227. $path = urldecode($path);
  1228. $page = $path ? $pages->dispatch($path, true) : $pages->root();
  1229. if (!$page) {
  1230. $slug = basename($path);
  1231. if ($slug === '') {
  1232. return null;
  1233. }
  1234. $ppath = str_replace('\\', '/', dirname($path));
  1235. // Find or create parent(s).
  1236. $parent = $this->getPage($ppath !== '/' ? $ppath : '');
  1237. // Create page.
  1238. $page = new Page;
  1239. $page->parent($parent);
  1240. $page->filePath($parent->path() . '/' . $slug . '/' . $page->name());
  1241. // Add routing information.
  1242. $pages->addPage($page, $path);
  1243. // Set if Modular
  1244. $page->modularTwig($slug[0] === '_');
  1245. // Determine page type.
  1246. if (isset($this->session->{$page->route()})) {
  1247. // Found the type and header from the session.
  1248. $data = $this->session->{$page->route()};
  1249. // Set the key header value
  1250. $header = ['title' => $data['title']];
  1251. if (isset($data['visible'])) {
  1252. if ($data['visible'] === '' || $data['visible']) {
  1253. // if auto (ie '')
  1254. $pageParent = $page->parent();
  1255. $children = $pageParent ? $pageParent->children() : [];
  1256. foreach ($children as $child) {
  1257. if ($child->order()) {
  1258. // set page order
  1259. $page->order(AdminController::getNextOrderInFolder($pageParent->path()));
  1260. break;
  1261. }
  1262. }
  1263. }
  1264. if ($data['visible'] == 1 && !$page->order()) {
  1265. $header['visible'] = $data['visible'];
  1266. }
  1267. }
  1268. if ($data['name'] === 'modular') {
  1269. $header['body_classes'] = 'modular';
  1270. }
  1271. $name = $page->modular() ? str_replace('modular/', '', $data['name']) : $data['name'];
  1272. $page->name($name . '.md');
  1273. // Fire new event to allow plugins to manipulate page frontmatter
  1274. $this->grav->fireEvent('onAdminCreatePageFrontmatter', new Event(['header' => &$header,
  1275. 'data' => $data]));
  1276. $page->header($header);
  1277. $page->frontmatter(Yaml::dump((array)$page->header(), 20));
  1278. } else {
  1279. // Find out the type by looking at the parent.
  1280. $type = $parent->childType()
  1281. ? $parent->childType()
  1282. : $parent->blueprints()->get('child_type',
  1283. 'default');
  1284. $page->name($type . CONTENT_EXT);
  1285. $page->header();
  1286. }
  1287. $page->modularTwig($slug[0] === '_');
  1288. }
  1289. return $page;
  1290. }
  1291. /**
  1292. * Get https://getgrav.org news feed
  1293. *
  1294. * @return mixed
  1295. */
  1296. public function getFeed()
  1297. {
  1298. $feed_url = 'https://getgrav.org/blog.atom';
  1299. $body = Response::get($feed_url);
  1300. $reader = new Reader();
  1301. $parser = $reader->getParser($feed_url, $body, 'utf-8');
  1302. return $parser->execute();
  1303. }
  1304. public function getRouteDetails()
  1305. {
  1306. return [$this->base, $this->location, $this->route];
  1307. }
  1308. /**
  1309. * Get the files list
  1310. *
  1311. * @todo allow pagination
  1312. * @return array
  1313. */
  1314. public function files($filtered = true, $page_index = 0)
  1315. {
  1316. $param_type = $this->grav['uri']->param('type');
  1317. $param_date = $this->grav['uri']->param('date');
  1318. $param_page = $this->grav['uri']->param('page');
  1319. $param_page = str_replace('\\', '/', $param_page);
  1320. $files_cache_key = 'media-manager-files';
  1321. if ($param_type) {
  1322. $files_cache_key .= "-{$param_type}";
  1323. }
  1324. if ($param_date) {
  1325. $files_cache_key .= "-{$param_date}";
  1326. }
  1327. if ($param_page) {
  1328. $files_cache_key .= "-{$param_page}";
  1329. }
  1330. $page_files = null;
  1331. $cache_enabled = $this->grav['config']->get('plugins.admin.cache_enabled');
  1332. if (!$cache_enabled) {
  1333. $this->grav['cache']->setEnabled(true);
  1334. }
  1335. $page_files = $this->grav['cache']->fetch(md5($files_cache_key));
  1336. if (!$cache_enabled) {
  1337. $this->grav['cache']->setEnabled(false);
  1338. }
  1339. if (!$page_files) {
  1340. $page_files = [];
  1341. $pages = $this->grav['pages'];
  1342. if ($param_page) {
  1343. $page = $pages->dispatch($param_page);
  1344. $page_files = $this->getFiles('images', $page, $page_files, $filtered);
  1345. $page_files = $this->getFiles('videos', $page, $page_files, $filtered);
  1346. $page_files = $this->getFiles('audios', $page, $page_files, $filtered);
  1347. $page_files = $this->getFiles('files', $page, $page_files, $filtered);
  1348. } else {
  1349. $allPages = $pages->all();
  1350. if ($allPages) foreach ($allPages as $page) {
  1351. $page_files = $this->getFiles('images', $page, $page_files, $filtered);
  1352. $page_files = $this->getFiles('videos', $page, $page_files, $filtered);
  1353. $page_files = $this->getFiles('audios', $page, $page_files, $filtered);
  1354. $page_files = $this->getFiles('files', $page, $page_files, $filtered);
  1355. }
  1356. }
  1357. if (count($page_files) >= self::MEDIA_PAGINATION_INTERVAL) {
  1358. $this->shouldLoadAdditionalFilesInBackground(true);
  1359. }
  1360. if (!$cache_enabled) {
  1361. $this->grav['cache']->setEnabled(true);
  1362. }
  1363. $this->grav['cache']->save(md5($files_cache_key), $page_files, 600); //cache for 10 minutes
  1364. if (!$cache_enabled) {
  1365. $this->grav['cache']->setEnabled(false);
  1366. }
  1367. }
  1368. if (count($page_files) >= self::MEDIA_PAGINATION_INTERVAL) {
  1369. $page_files = array_slice($page_files, $page_index * self::MEDIA_PAGINATION_INTERVAL, self::MEDIA_PAGINATION_INTERVAL);
  1370. }
  1371. return $page_files;
  1372. }
  1373. public function shouldLoadAdditionalFilesInBackground($status = null)
  1374. {
  1375. if ($status) {
  1376. $this->load_additional_files_in_background = true;
  1377. }
  1378. return $this->load_additional_files_in_background;
  1379. }
  1380. public function loadAdditionalFilesInBackground($status = null)
  1381. {
  1382. if (!$this->loading_additional_files_in_background) {
  1383. $this->loading_additional_files_in_background = true;
  1384. $this->files(false, false);
  1385. $this->shouldLoadAdditionalFilesInBackground(false);
  1386. $this->loading_additional_files_in_background = false;
  1387. }
  1388. }
  1389. private function getFiles($type, $page, $page_files, $filtered)
  1390. {
  1391. $page_files = $this->getMediaOfType($type, $page, $page_files);
  1392. if ($filtered) {
  1393. $page_files = $this->filterByType($page_files);
  1394. $page_files = $this->filterByDate($page_files);
  1395. }
  1396. return $page_files;
  1397. }
  1398. /**
  1399. * Get all the media of a type ('images' | 'audios' | 'videos' | 'files')
  1400. *
  1401. * @param string $type
  1402. * @param Page|null $page
  1403. * @param array $files
  1404. *
  1405. * @return array
  1406. */
  1407. private function getMediaOfType($type, Page $page = null, array $files)
  1408. {
  1409. if ($page) {
  1410. $media = $page->media();
  1411. $mediaOfType = $media->$type();
  1412. foreach($mediaOfType as $title => $file) {
  1413. $files[] = [
  1414. 'title' => $title,
  1415. 'type' => $type,
  1416. 'page_route' => $page->route(),
  1417. 'file' => $file->higherQualityAlternative()
  1418. ];
  1419. }
  1420. return $files;
  1421. }
  1422. return [];
  1423. }
  1424. /**
  1425. * Filter media by type
  1426. *
  1427. * @param array $filesFiltered
  1428. *
  1429. * @return array
  1430. */
  1431. private function filterByType($filesFiltered)
  1432. {
  1433. $filter_type = $this->grav['uri']->param('type');
  1434. if (!$filter_type) {
  1435. return $filesFiltered;
  1436. }
  1437. $filesFiltered = array_filter($filesFiltered, function ($file) use ($filter_type) {
  1438. return $file['type'] == $filter_type;
  1439. });
  1440. return $filesFiltered;
  1441. }
  1442. /**
  1443. * Filter media by date
  1444. *
  1445. * @param array $filesFiltered
  1446. *
  1447. * @return array
  1448. */
  1449. private function filterByDate($filesFiltered)
  1450. {
  1451. $filter_date = $this->grav['uri']->param('date');
  1452. if (!$filter_date) {
  1453. return $filesFiltered;
  1454. }
  1455. $year = substr($filter_date, 0, 4);
  1456. $month = substr($filter_date, 5, 2);
  1457. $filesFilteredByDate = [];
  1458. foreach($filesFiltered as $file) {
  1459. $filedate = $this->fileDate($file['file']);
  1460. $fileYear = $filedate->format('Y');
  1461. $fileMonth = $filedate->format('m');
  1462. if ($fileYear == $year && $fileMonth == $month) {
  1463. $filesFilteredByDate[] = $file;
  1464. }
  1465. }
  1466. return $filesFilteredByDate;
  1467. }
  1468. /**
  1469. * Return the DateTime object representation of a file modified date
  1470. *
  1471. * @param File $file
  1472. *
  1473. * @return DateTime
  1474. */
  1475. private function fileDate($file) {
  1476. $datetime = new \DateTime();
  1477. $datetime->setTimestamp($file->toArray()['modified']);
  1478. return $datetime;
  1479. }
  1480. /**
  1481. * Get the files dates list to be used in the Media Files filter
  1482. *
  1483. * @return array
  1484. */
  1485. public function filesDates()
  1486. {
  1487. $files = $this->files(false);
  1488. $dates = [];
  1489. foreach ($files as $file) {
  1490. $datetime = $this->fileDate($file['file']);
  1491. $year = $datetime->format('Y');
  1492. $month = $datetime->format('m');
  1493. if (!isset($dates[$year])) {
  1494. $dates[$year] = [];
  1495. }
  1496. if (!isset($dates[$year][$month])) {
  1497. $dates[$year][$month] = 1;
  1498. } else {
  1499. $dates[$year][$month]++;
  1500. }
  1501. }
  1502. return $dates;
  1503. }
  1504. /**
  1505. * Get the pages list to be used in the Media Files filter
  1506. *
  1507. * @return array
  1508. */
  1509. public function pages()
  1510. {
  1511. /** @var Collection $pages */
  1512. $pages = $this->grav['pages']->all();
  1513. $pagesWithFiles = [];
  1514. foreach ($pages as $page) {
  1515. if (count($page->media()->all())) {
  1516. $pagesWithFiles[] = $page;
  1517. }
  1518. }
  1519. return $pagesWithFiles;
  1520. }
  1521. /**
  1522. * Return HTTP_REFERRER if set
  1523. *
  1524. * @return null
  1525. */
  1526. public function getReferrer()
  1527. {
  1528. return isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
  1529. }
  1530. }