admin.php 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794
  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($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. $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. 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. // Fix for entities in path causing looping...
  1211. $path = urldecode($path);
  1212. $page = $path ? $pages->dispatch($path, true) : $pages->root();
  1213. if (!$page) {
  1214. $slug = basename($path);
  1215. if ($slug === '') {
  1216. return null;
  1217. }
  1218. $ppath = str_replace('\\', '/', dirname($path));
  1219. // Find or create parent(s).
  1220. $parent = $this->getPage($ppath !== '/' ? $ppath : '');
  1221. // Create page.
  1222. $page = new Page;
  1223. $page->parent($parent);
  1224. $page->filePath($parent->path() . '/' . $slug . '/' . $page->name());
  1225. // Add routing information.
  1226. $pages->addPage($page, $path);
  1227. // Set if Modular
  1228. $page->modularTwig($slug[0] === '_');
  1229. // Determine page type.
  1230. if (isset($this->session->{$page->route()})) {
  1231. // Found the type and header from the session.
  1232. $data = $this->session->{$page->route()};
  1233. // Set the key header value
  1234. $header = ['title' => $data['title']];
  1235. if (isset($data['visible'])) {
  1236. if ($data['visible'] === '' || $data['visible']) {
  1237. // if auto (ie '')
  1238. $pageParent = $page->parent();
  1239. $children = $pageParent ? $pageParent->children() : [];
  1240. foreach ($children as $child) {
  1241. if ($child->order()) {
  1242. // set page order
  1243. $page->order(AdminController::getNextOrderInFolder($pageParent->path()));
  1244. break;
  1245. }
  1246. }
  1247. }
  1248. if ($data['visible'] == 1 && !$page->order()) {
  1249. $header['visible'] = $data['visible'];
  1250. }
  1251. }
  1252. if ($data['name'] === 'modular') {
  1253. $header['body_classes'] = 'modular';
  1254. }
  1255. $name = $page->modular() ? str_replace('modular/', '', $data['name']) : $data['name'];
  1256. $page->name($name . '.md');
  1257. // Fire new event to allow plugins to manipulate page frontmatter
  1258. $this->grav->fireEvent('onAdminCreatePageFrontmatter', new Event(['header' => &$header,
  1259. 'data' => $data]));
  1260. $page->header($header);
  1261. $page->frontmatter(Yaml::dump((array)$page->header(), 20));
  1262. } else {
  1263. // Find out the type by looking at the parent.
  1264. $type = $parent->childType()
  1265. ? $parent->childType()
  1266. : $parent->blueprints()->get('child_type',
  1267. 'default');
  1268. $page->name($type . CONTENT_EXT);
  1269. $page->header();
  1270. }
  1271. $page->modularTwig($slug[0] === '_');
  1272. }
  1273. return $page;
  1274. }
  1275. /**
  1276. * Get https://getgrav.org news feed
  1277. *
  1278. * @return mixed
  1279. */
  1280. public function getFeed()
  1281. {
  1282. $feed_url = 'https://getgrav.org/blog.atom';
  1283. $body = Response::get($feed_url);
  1284. $reader = new Reader();
  1285. $parser = $reader->getParser($feed_url, $body, 'utf-8');
  1286. return $parser->execute();
  1287. }
  1288. public function getRouteDetails()
  1289. {
  1290. return [$this->base, $this->location, $this->route];
  1291. }
  1292. /**
  1293. * Get the files list
  1294. *
  1295. * @todo allow pagination
  1296. * @return array
  1297. */
  1298. public function files($filtered = true, $page_index = 0)
  1299. {
  1300. $param_type = $this->grav['uri']->param('type');
  1301. $param_date = $this->grav['uri']->param('date');
  1302. $param_page = $this->grav['uri']->param('page');
  1303. $param_page = str_replace('\\', '/', $param_page);
  1304. $files_cache_key = 'media-manager-files';
  1305. if ($param_type) {
  1306. $files_cache_key .= "-{$param_type}";
  1307. }
  1308. if ($param_date) {
  1309. $files_cache_key .= "-{$param_date}";
  1310. }
  1311. if ($param_page) {
  1312. $files_cache_key .= "-{$param_page}";
  1313. }
  1314. $page_files = null;
  1315. $cache_enabled = $this->grav['config']->get('plugins.admin.cache_enabled');
  1316. if (!$cache_enabled) {
  1317. $this->grav['cache']->setEnabled(true);
  1318. }
  1319. $page_files = $this->grav['cache']->fetch(md5($files_cache_key));
  1320. if (!$cache_enabled) {
  1321. $this->grav['cache']->setEnabled(false);
  1322. }
  1323. if (!$page_files) {
  1324. $page_files = [];
  1325. $pages = $this->grav['pages'];
  1326. if ($param_page) {
  1327. $page = $pages->dispatch($param_page);
  1328. $page_files = $this->getFiles('images', $page, $page_files, $filtered);
  1329. $page_files = $this->getFiles('videos', $page, $page_files, $filtered);
  1330. $page_files = $this->getFiles('audios', $page, $page_files, $filtered);
  1331. $page_files = $this->getFiles('files', $page, $page_files, $filtered);
  1332. } else {
  1333. $allPages = $pages->all();
  1334. if ($allPages) foreach ($allPages as $page) {
  1335. $page_files = $this->getFiles('images', $page, $page_files, $filtered);
  1336. $page_files = $this->getFiles('videos', $page, $page_files, $filtered);
  1337. $page_files = $this->getFiles('audios', $page, $page_files, $filtered);
  1338. $page_files = $this->getFiles('files', $page, $page_files, $filtered);
  1339. }
  1340. }
  1341. if (count($page_files) >= self::MEDIA_PAGINATION_INTERVAL) {
  1342. $this->shouldLoadAdditionalFilesInBackground(true);
  1343. }
  1344. if (!$cache_enabled) {
  1345. $this->grav['cache']->setEnabled(true);
  1346. }
  1347. $this->grav['cache']->save(md5($files_cache_key), $page_files, 600); //cache for 10 minutes
  1348. if (!$cache_enabled) {
  1349. $this->grav['cache']->setEnabled(false);
  1350. }
  1351. }
  1352. if (count($page_files) >= self::MEDIA_PAGINATION_INTERVAL) {
  1353. $page_files = array_slice($page_files, $page_index * self::MEDIA_PAGINATION_INTERVAL, self::MEDIA_PAGINATION_INTERVAL);
  1354. }
  1355. return $page_files;
  1356. }
  1357. public function shouldLoadAdditionalFilesInBackground($status = null)
  1358. {
  1359. if ($status) {
  1360. $this->load_additional_files_in_background = true;
  1361. }
  1362. return $this->load_additional_files_in_background;
  1363. }
  1364. public function loadAdditionalFilesInBackground($status = null)
  1365. {
  1366. if (!$this->loading_additional_files_in_background) {
  1367. $this->loading_additional_files_in_background = true;
  1368. $this->files(false, false);
  1369. $this->shouldLoadAdditionalFilesInBackground(false);
  1370. $this->loading_additional_files_in_background = false;
  1371. }
  1372. }
  1373. private function getFiles($type, $page, $page_files, $filtered)
  1374. {
  1375. $page_files = $this->getMediaOfType($type, $page, $page_files);
  1376. if ($filtered) {
  1377. $page_files = $this->filterByType($page_files);
  1378. $page_files = $this->filterByDate($page_files);
  1379. }
  1380. return $page_files;
  1381. }
  1382. /**
  1383. * Get all the media of a type ('images' | 'audios' | 'videos' | 'files')
  1384. *
  1385. * @param string $type
  1386. * @param Page|null $page
  1387. * @param array $files
  1388. *
  1389. * @return array
  1390. */
  1391. private function getMediaOfType($type, Page $page = null, array $files)
  1392. {
  1393. if ($page) {
  1394. $media = $page->media();
  1395. $mediaOfType = $media->$type();
  1396. foreach($mediaOfType as $title => $file) {
  1397. $files[] = [
  1398. 'title' => $title,
  1399. 'type' => $type,
  1400. 'page_route' => $page->route(),
  1401. 'file' => $file->higherQualityAlternative()
  1402. ];
  1403. }
  1404. return $files;
  1405. }
  1406. return [];
  1407. }
  1408. /**
  1409. * Filter media by type
  1410. *
  1411. * @param array $filesFiltered
  1412. *
  1413. * @return array
  1414. */
  1415. private function filterByType($filesFiltered)
  1416. {
  1417. $filter_type = $this->grav['uri']->param('type');
  1418. if (!$filter_type) {
  1419. return $filesFiltered;
  1420. }
  1421. $filesFiltered = array_filter($filesFiltered, function ($file) use ($filter_type) {
  1422. return $file['type'] == $filter_type;
  1423. });
  1424. return $filesFiltered;
  1425. }
  1426. /**
  1427. * Filter media by date
  1428. *
  1429. * @param array $filesFiltered
  1430. *
  1431. * @return array
  1432. */
  1433. private function filterByDate($filesFiltered)
  1434. {
  1435. $filter_date = $this->grav['uri']->param('date');
  1436. if (!$filter_date) {
  1437. return $filesFiltered;
  1438. }
  1439. $year = substr($filter_date, 0, 4);
  1440. $month = substr($filter_date, 5, 2);
  1441. $filesFilteredByDate = [];
  1442. foreach($filesFiltered as $file) {
  1443. $filedate = $this->fileDate($file['file']);
  1444. $fileYear = $filedate->format('Y');
  1445. $fileMonth = $filedate->format('m');
  1446. if ($fileYear == $year && $fileMonth == $month) {
  1447. $filesFilteredByDate[] = $file;
  1448. }
  1449. }
  1450. return $filesFilteredByDate;
  1451. }
  1452. /**
  1453. * Return the DateTime object representation of a file modified date
  1454. *
  1455. * @param File $file
  1456. *
  1457. * @return DateTime
  1458. */
  1459. private function fileDate($file) {
  1460. $datetime = new \DateTime();
  1461. $datetime->setTimestamp($file->toArray()['modified']);
  1462. return $datetime;
  1463. }
  1464. /**
  1465. * Get the files dates list to be used in the Media Files filter
  1466. *
  1467. * @return array
  1468. */
  1469. public function filesDates()
  1470. {
  1471. $files = $this->files(false);
  1472. $dates = [];
  1473. foreach ($files as $file) {
  1474. $datetime = $this->fileDate($file['file']);
  1475. $year = $datetime->format('Y');
  1476. $month = $datetime->format('m');
  1477. if (!isset($dates[$year])) {
  1478. $dates[$year] = [];
  1479. }
  1480. if (!isset($dates[$year][$month])) {
  1481. $dates[$year][$month] = 1;
  1482. } else {
  1483. $dates[$year][$month]++;
  1484. }
  1485. }
  1486. return $dates;
  1487. }
  1488. /**
  1489. * Get the pages list to be used in the Media Files filter
  1490. *
  1491. * @return array
  1492. */
  1493. public function pages()
  1494. {
  1495. /** @var Collection $pages */
  1496. $pages = $this->grav['pages']->all();
  1497. $pagesWithFiles = [];
  1498. foreach ($pages as $page) {
  1499. if (count($page->media()->all())) {
  1500. $pagesWithFiles[] = $page;
  1501. }
  1502. }
  1503. return $pagesWithFiles;
  1504. }
  1505. /**
  1506. * Return HTTP_REFERRER if set
  1507. *
  1508. * @return null
  1509. */
  1510. public function getReferrer()
  1511. {
  1512. return isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
  1513. }
  1514. }