admin.php 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790
  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->getBasename(), '.')) {
  158. continue;
  159. }
  160. $lang = basename($file->getBasename(), '.yaml');
  161. $languages[$lang] = LanguageCodes::getNativeName($lang);
  162. }
  163. // sort languages
  164. asort($languages);
  165. return $languages;
  166. }
  167. /**
  168. * Return the found configuration blueprints
  169. *
  170. * @return array
  171. */
  172. public static function configurations()
  173. {
  174. $configurations = [];
  175. /** @var UniformResourceIterator $iterator */
  176. $iterator = Grav::instance()['locator']->getIterator('blueprints://config');
  177. foreach ($iterator as $file) {
  178. if ($file->isDir() || !preg_match('/^[^.].*.yaml$/', $file->getFilename())) {
  179. continue;
  180. }
  181. $configurations[] = basename($file->getBasename(), '.yaml');
  182. }
  183. return $configurations;
  184. }
  185. /**
  186. * Return the tools found
  187. *
  188. * @return array
  189. */
  190. public static function tools()
  191. {
  192. $tools = [];
  193. Grav::instance()->fireEvent('onAdminTools', new Event(['tools' => &$tools]));
  194. return $tools;
  195. }
  196. /**
  197. * Return the languages available in the site
  198. *
  199. * @return array
  200. */
  201. public static function siteLanguages()
  202. {
  203. $languages = [];
  204. $lang_data = (array) Grav::instance()['config']->get('system.languages.supported', []);
  205. foreach ($lang_data as $index => $lang) {
  206. $languages[$lang] = LanguageCodes::getNativeName($lang);
  207. }
  208. return $languages;
  209. }
  210. /**
  211. * Static helper method to return the admin form nonce
  212. *
  213. * @return string
  214. */
  215. public static function getNonce()
  216. {
  217. $action = 'admin-form';
  218. return Utils::getNonce($action);
  219. }
  220. /**
  221. * Static helper method to return the last used page name
  222. *
  223. * @return string
  224. */
  225. public static function getLastPageName()
  226. {
  227. return Grav::instance()['session']->lastPageName ?: 'default';
  228. }
  229. /**
  230. * Static helper method to return the last used page route
  231. *
  232. * @return string
  233. */
  234. public static function getLastPageRoute()
  235. {
  236. return Grav::instance()['session']->lastPageRoute ?: self::route();
  237. }
  238. /**
  239. * Static helper method to return current route.
  240. *
  241. * @return string
  242. */
  243. public static function route()
  244. {
  245. $pages = Grav::instance()['pages'];
  246. $route = '/' . ltrim(Grav::instance()['admin']->route, '/');
  247. /** @var Page $page */
  248. $page = $pages->dispatch($route);
  249. $parent_route = null;
  250. if ($page) {
  251. /** @var Page $parent */
  252. $parent = $page->parent();
  253. $parent_route = $parent->rawRoute();
  254. }
  255. return $parent_route;
  256. }
  257. public static function getTempDir()
  258. {
  259. try {
  260. $tmp_dir = Grav::instance()['locator']->findResource('tmp://', true, true);
  261. } catch (\Exception $e) {
  262. $tmp_dir = Grav::instance()['locator']->findResource('cache://', true, true) . '/tmp';
  263. }
  264. return $tmp_dir;
  265. }
  266. public static function getPageMedia()
  267. {
  268. $files = [];
  269. $grav = Grav::instance();
  270. $pages = $grav['pages'];
  271. $route = '/' . ltrim($grav['admin']->route, '/');
  272. /** @var Page $page */
  273. $page = $pages->dispatch($route);
  274. $parent_route = null;
  275. if ($page) {
  276. $media = $page->media()->all();
  277. $files = array_keys($media);
  278. }
  279. return $files;
  280. }
  281. /**
  282. * Get current session.
  283. *
  284. * @return Session
  285. */
  286. public function session()
  287. {
  288. return $this->session;
  289. }
  290. /**
  291. * Fetch and delete messages from the session queue.
  292. *
  293. * @param string $type
  294. *
  295. * @return array
  296. */
  297. public function messages($type = null)
  298. {
  299. /** @var Message $messages */
  300. $messages = $this->grav['messages'];
  301. return $messages->fetch($type);
  302. }
  303. /**
  304. * Authenticate user.
  305. *
  306. * @param array $credentials User credentials.
  307. */
  308. public function authenticate($credentials, $post)
  309. {
  310. /** @var Login $login */
  311. $login = $this->grav['login'];
  312. // Remove login nonce from the form.
  313. $credentials = array_diff_key($credentials, ['admin-nonce' => true]);
  314. $twofa = $this->grav['config']->get('plugins.admin.twofa_enabled', false);
  315. $rateLimiter = $login->getRateLimiter('login_attempts');
  316. $userKey = isset($credentials['username']) ? (string)$credentials['username'] : '';
  317. $ipKey = Uri::ip();
  318. $redirect = $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 = isset($_POST['data']) ? $_POST['data'] : [];
  504. }
  505. // Check to see if a data type is plugin-provided, before looking into core ones
  506. $event = $this->grav->fireEvent('onAdminData', new Event(['type' => &$type]));
  507. if ($event && isset($event['data_type'])) {
  508. return $event['data_type'];
  509. }
  510. /** @var UniformResourceLocator $locator */
  511. $locator = $this->grav['locator'];
  512. $filename = $locator->findResource("config://{$type}.yaml", true, true);
  513. $file = CompiledYamlFile::instance($filename);
  514. if (preg_match('|plugins/|', $type)) {
  515. /** @var Plugins $plugins */
  516. $plugins = $this->grav['plugins'];
  517. $obj = $plugins->get(preg_replace('|plugins/|', '', $type));
  518. if (!$obj) {
  519. return [];
  520. }
  521. $obj->merge($post);
  522. $obj->file($file);
  523. $data[$type] = $obj;
  524. } elseif (preg_match('|themes/|', $type)) {
  525. /** @var Themes $themes */
  526. $themes = $this->grav['themes'];
  527. $obj = $themes->get(preg_replace('|themes/|', '', $type));
  528. if (!$obj) {
  529. return [];
  530. }
  531. $obj->merge($post);
  532. $obj->file($file);
  533. $data[$type] = $obj;
  534. } elseif (preg_match('|users/|', $type)) {
  535. $obj = User::load(preg_replace('|users/|', '', $type));
  536. $obj->merge($post);
  537. $data[$type] = $obj;
  538. } elseif (preg_match('|user/|', $type)) {
  539. $obj = User::load(preg_replace('|user/|', '', $type));
  540. $obj->merge($post);
  541. $data[$type] = $obj;
  542. } elseif (preg_match('|config/|', $type)) {
  543. $type = preg_replace('|config/|', '', $type);
  544. $blueprints = $this->blueprints("config/{$type}");
  545. $config = $this->grav['config'];
  546. $obj = new Data\Data($config->get($type, []), $blueprints);
  547. $obj->merge($post);
  548. // FIXME: We shouldn't allow user to change configuration files in system folder!
  549. $filename = $this->grav['locator']->findResource("config://{$type}.yaml")
  550. ?: $this->grav['locator']->findResource("config://{$type}.yaml", true, true);
  551. $file = CompiledYamlFile::instance($filename);
  552. $obj->file($file);
  553. $data[$type] = $obj;
  554. } elseif (preg_match('|media-manager/|', $type)) {
  555. $filename = base64_decode(preg_replace('|media-manager/|', '', $type));
  556. $file = File::instance($filename);
  557. $obj = new \StdClass();
  558. $obj->title = $file->basename();
  559. $obj->path = $file->filename();
  560. $obj->file = $file;
  561. $obj->page = $this->grav['pages']->get(dirname($obj->path));
  562. $filename = pathinfo($obj->title)['filename'];
  563. $filename = str_replace(['@3x', '@2x'], '', $filename);
  564. if (isset(pathinfo($obj->title)['extension'])) {
  565. $filename .= '.' . pathinfo($obj->title)['extension'];
  566. }
  567. if ($obj->page && isset($obj->page->media()[$filename])) {
  568. $obj->metadata = new Data\Data($obj->page->media()[$filename]->metadata());
  569. }
  570. $data[$type] = $obj;
  571. } else {
  572. throw new \RuntimeException("Data type '{$type}' doesn't exist!");
  573. }
  574. return $data[$type];
  575. }
  576. protected function hasErrorMessage()
  577. {
  578. $msgs = $this->grav['messages']->all();
  579. foreach ($msgs as $msg) {
  580. if (isset($msg['scope']) && $msg['scope'] === 'error') {
  581. return true;
  582. }
  583. }
  584. return false;
  585. }
  586. /**
  587. * Returns blueprints for the given type.
  588. *
  589. * @param string $type
  590. *
  591. * @return Data\Blueprint
  592. */
  593. public function blueprints($type)
  594. {
  595. if ($this->blueprints === null) {
  596. $this->blueprints = new Data\Blueprints('blueprints://');
  597. }
  598. return $this->blueprints->get($type);
  599. }
  600. /**
  601. * Converts dot notation to array notation.
  602. *
  603. * @param string $name
  604. *
  605. * @return string
  606. */
  607. public function field($name)
  608. {
  609. $path = explode('.', $name);
  610. return array_shift($path) . ($path ? '[' . implode('][', $path) . ']' : '');
  611. }
  612. /**
  613. * Get all routes.
  614. *
  615. * @param bool $unique
  616. *
  617. * @return array
  618. */
  619. public function routes($unique = false)
  620. {
  621. /** @var Pages $pages */
  622. $pages = $this->grav['pages'];
  623. if ($unique) {
  624. $routes = array_unique($pages->routes());
  625. } else {
  626. $routes = $pages->routes();
  627. }
  628. return $routes;
  629. }
  630. /**
  631. * Count the pages
  632. *
  633. * @return array
  634. */
  635. public function pagesCount()
  636. {
  637. if (!$this->pages_count) {
  638. $this->pages_count = count($this->grav['pages']->all());
  639. }
  640. return $this->pages_count;
  641. }
  642. /**
  643. * Get all template types
  644. *
  645. * @return array
  646. */
  647. public function types()
  648. {
  649. return Pages::types();
  650. }
  651. /**
  652. * Get all modular template types
  653. *
  654. * @return array
  655. */
  656. public function modularTypes()
  657. {
  658. return Pages::modularTypes();
  659. }
  660. /**
  661. * Get all access levels
  662. *
  663. * @return array
  664. */
  665. public function accessLevels()
  666. {
  667. if (method_exists($this->grav['pages'], 'accessLevels')) {
  668. return $this->grav['pages']->accessLevels();
  669. }
  670. return [];
  671. }
  672. public function license($package_slug)
  673. {
  674. return Licenses::get($package_slug);
  675. }
  676. /**
  677. * Generate an array of dependencies for a package, used to generate a list of
  678. * packages that can be removed when removing a package.
  679. *
  680. * @param string $slug The package slug
  681. *
  682. * @return array|bool
  683. */
  684. public function dependenciesThatCanBeRemovedWhenRemoving($slug)
  685. {
  686. $gpm = $this->gpm();
  687. if (!$gpm) {
  688. return false;
  689. }
  690. $dependencies = [];
  691. $package = $this->getPackageFromGPM($slug);
  692. if ($package) {
  693. if ($package->dependencies) {
  694. foreach ($package->dependencies as $dependency) {
  695. // if (count($gpm->getPackagesThatDependOnPackage($dependency)) > 1) {
  696. // continue;
  697. // }
  698. if (isset($dependency['name'])) {
  699. $dependency = $dependency['name'];
  700. }
  701. if (!in_array($dependency, $dependencies, true)) {
  702. if (!in_array($dependency, ['admin', 'form', 'login', 'email', 'php'])) {
  703. $dependencies[] = $dependency;
  704. }
  705. }
  706. }
  707. }
  708. }
  709. return $dependencies;
  710. }
  711. /**
  712. * Get the GPM instance
  713. *
  714. * @return GPM The GPM instance
  715. */
  716. public function gpm()
  717. {
  718. if (!$this->gpm) {
  719. try {
  720. $this->gpm = new GPM();
  721. } catch (\Exception $e) {
  722. }
  723. }
  724. return $this->gpm;
  725. }
  726. public function getPackageFromGPM($package_slug)
  727. {
  728. $package = $this->plugins(true)[$package_slug];
  729. if (!$package) {
  730. $package = $this->themes(true)[$package_slug];
  731. }
  732. return $package;
  733. }
  734. /**
  735. * Get all plugins.
  736. *
  737. * @param bool $local
  738. *
  739. * @return mixed
  740. */
  741. public function plugins($local = true)
  742. {
  743. $gpm = $this->gpm();
  744. if (!$gpm) {
  745. return false;
  746. }
  747. if ($local) {
  748. return $gpm->getInstalledPlugins();
  749. }
  750. $plugins = $gpm->getRepositoryPlugins();
  751. if ($plugins) {
  752. return $plugins->filter(function ($package, $slug) use ($gpm) {
  753. return !$gpm->isPluginInstalled($slug);
  754. });
  755. }
  756. return [];
  757. }
  758. /**
  759. * Get all themes.
  760. *
  761. * @param bool $local
  762. *
  763. * @return mixed
  764. */
  765. public function themes($local = true)
  766. {
  767. $gpm = $this->gpm();
  768. if (!$gpm) {
  769. return false;
  770. }
  771. if ($local) {
  772. return $gpm->getInstalledThemes();
  773. }
  774. $themes = $gpm->getRepositoryThemes();
  775. if ($themes) {
  776. return $themes->filter(function ($package, $slug) use ($gpm) {
  777. return !$gpm->isThemeInstalled($slug);
  778. });
  779. }
  780. return [];
  781. }
  782. /**
  783. * Get list of packages that depend on the passed package slug
  784. *
  785. * @param string $slug The package slug
  786. *
  787. * @return array|bool
  788. */
  789. public function getPackagesThatDependOnPackage($slug)
  790. {
  791. $gpm = $this->gpm();
  792. if (!$gpm) {
  793. return false;
  794. }
  795. return $gpm->getPackagesThatDependOnPackage($slug);
  796. }
  797. /**
  798. * Check the passed packages list can be updated
  799. *
  800. * @param $packages
  801. *
  802. * @throws \Exception
  803. * @return bool
  804. */
  805. public function checkPackagesCanBeInstalled($packages)
  806. {
  807. $gpm = $this->gpm();
  808. if (!$gpm) {
  809. return false;
  810. }
  811. $this->gpm->checkPackagesCanBeInstalled($packages);
  812. return true;
  813. }
  814. /**
  815. * Get an array of dependencies needed to be installed or updated for a list of packages
  816. * to be installed.
  817. *
  818. * @param array $packages The packages slugs
  819. *
  820. * @return array|bool
  821. */
  822. public function getDependenciesNeededToInstall($packages)
  823. {
  824. $gpm = $this->gpm();
  825. if (!$gpm) {
  826. return false;
  827. }
  828. return $this->gpm->getDependencies($packages);
  829. }
  830. /**
  831. * Used by the Dashboard in the admin to display the X latest pages
  832. * that have been modified
  833. *
  834. * @param integer $count number of pages to pull back
  835. *
  836. * @return array|null
  837. */
  838. public function latestPages($count = 10)
  839. {
  840. /** @var Pages $pages */
  841. $pages = $this->grav['pages'];
  842. $latest = [];
  843. if (null === $pages->routes()) {
  844. return null;
  845. }
  846. foreach ($pages->routes() as $url => $path) {
  847. $page = $pages->dispatch($url, true);
  848. if ($page && $page->routable()) {
  849. $latest[$page->route()] = ['modified' => $page->modified(), 'page' => $page];
  850. }
  851. }
  852. // sort based on modified
  853. uasort($latest, function ($a, $b) {
  854. if ($a['modified'] == $b['modified']) {
  855. return 0;
  856. }
  857. return ($a['modified'] > $b['modified']) ? -1 : 1;
  858. });
  859. // build new array with just pages in it
  860. $list = [];
  861. foreach ($latest as $item) {
  862. $list[] = $item['page'];
  863. }
  864. return array_slice($list, 0, $count);
  865. }
  866. /**
  867. * Get log file for fatal errors.
  868. *
  869. * @return string
  870. */
  871. public function logEntry()
  872. {
  873. $file = File::instance($this->grav['locator']->findResource("log://{$this->route}.html"));
  874. $content = $file->content();
  875. $file->free();
  876. return $content;
  877. }
  878. /**
  879. * Search in the logs when was the latest backup made
  880. *
  881. * @return array Array containing the latest backup information
  882. */
  883. public function lastBackup()
  884. {
  885. $file = JsonFile::instance($this->grav['locator']->findResource("log://backup.log"));
  886. $content = $file->content();
  887. if (empty($content)) {
  888. return [
  889. 'days' => '&infin;',
  890. 'chart_fill' => 100,
  891. 'chart_empty' => 0
  892. ];
  893. }
  894. $backup = new \DateTime();
  895. $backup->setTimestamp($content['time']);
  896. $diff = $backup->diff(new \DateTime());
  897. $days = $diff->days;
  898. $chart_fill = $days > 30 ? 100 : round($days / 30 * 100);
  899. return [
  900. 'days' => $days,
  901. 'chart_fill' => $chart_fill,
  902. 'chart_empty' => 100 - $chart_fill
  903. ];
  904. }
  905. /**
  906. * Determine if the plugin or theme info passed is from Team Grav
  907. *
  908. * @param object $info Plugin or Theme info object
  909. *
  910. * @return bool
  911. */
  912. public function isTeamGrav($info)
  913. {
  914. return isset($info['author']['name']) && ($info['author']['name'] === 'Team Grav' || Utils::contains($info['author']['name'], 'Trilby Media'));
  915. }
  916. /**
  917. * Determine if the plugin or theme info passed is premium
  918. *
  919. * @param object $info Plugin or Theme info object
  920. *
  921. * @return bool
  922. */
  923. public function isPremiumProduct($info)
  924. {
  925. return isset($info['premium']);
  926. }
  927. /**
  928. * Renders phpinfo
  929. *
  930. * @return string The phpinfo() output
  931. */
  932. function phpinfo()
  933. {
  934. if (function_exists('phpinfo')) {
  935. ob_start();
  936. phpinfo();
  937. $pinfo = ob_get_contents();
  938. ob_end_clean();
  939. $pinfo = preg_replace('%^.*<body>(.*)</body>.*$%ms', '$1', $pinfo);
  940. return $pinfo;
  941. }
  942. return 'phpinfo() method is not available on this server.';
  943. }
  944. /**
  945. * Guest date format based on euro/US
  946. *
  947. * @param $date
  948. *
  949. * @return string
  950. */
  951. public function guessDateFormat($date)
  952. {
  953. static $guess;
  954. $date_formats = [
  955. 'm/d/y',
  956. 'm/d/Y',
  957. 'n/d/y',
  958. 'n/d/Y',
  959. 'd-m-Y',
  960. 'd-m-y',
  961. ];
  962. $time_formats = [
  963. 'H:i',
  964. 'G:i',
  965. 'h:ia',
  966. 'g:ia'
  967. ];
  968. if (!isset($guess[$date])) {
  969. foreach ($date_formats as $date_format) {
  970. foreach ($time_formats as $time_format) {
  971. if ($this->validateDate($date, "$date_format $time_format")) {
  972. $guess[$date] = "$date_format $time_format";
  973. break 2;
  974. }
  975. if ($this->validateDate($date, "$time_format $date_format")) {
  976. $guess[$date] = "$time_format $date_format";
  977. break 2;
  978. }
  979. }
  980. }
  981. if (!isset($guess[$date])) {
  982. $guess[$date] = 'd-m-Y H:i';
  983. }
  984. }
  985. return $guess[$date];
  986. }
  987. public function validateDate($date, $format)
  988. {
  989. $d = DateTime::createFromFormat($format, $date);
  990. return $d && $d->format($format) == $date;
  991. }
  992. /**
  993. * @param string $php_format
  994. *
  995. * @return string
  996. */
  997. public function dateformatToMomentJS($php_format)
  998. {
  999. $SYMBOLS_MATCHING = [
  1000. // Day
  1001. 'd' => 'DD',
  1002. 'D' => 'ddd',
  1003. 'j' => 'D',
  1004. 'l' => 'dddd',
  1005. 'N' => 'E',
  1006. 'S' => 'Do',
  1007. 'w' => 'd',
  1008. 'z' => 'DDD',
  1009. // Week
  1010. 'W' => 'W',
  1011. // Month
  1012. 'F' => 'MMMM',
  1013. 'm' => 'MM',
  1014. 'M' => 'MMM',
  1015. 'n' => 'M',
  1016. 't' => '',
  1017. // Year
  1018. 'L' => '',
  1019. 'o' => 'GGGG',
  1020. 'Y' => 'YYYY',
  1021. 'y' => 'yy',
  1022. // Time
  1023. 'a' => 'a',
  1024. 'A' => 'A',
  1025. 'B' => 'SSS',
  1026. 'g' => 'h',
  1027. 'G' => 'H',
  1028. 'h' => 'hh',
  1029. 'H' => 'HH',
  1030. 'i' => 'mm',
  1031. 's' => 'ss',
  1032. 'u' => '',
  1033. // Timezone
  1034. 'e' => '',
  1035. 'I' => '',
  1036. 'O' => 'ZZ',
  1037. 'P' => 'Z',
  1038. 'T' => 'z',
  1039. 'Z' => '',
  1040. // Full Date/Time
  1041. 'c' => '',
  1042. 'r' => 'llll ZZ',
  1043. 'U' => 'X'
  1044. ];
  1045. $js_format = '';
  1046. $escaping = false;
  1047. $len = strlen($php_format);
  1048. for ($i = 0; $i < $len; $i++) {
  1049. $char = $php_format[$i];
  1050. if ($char === '\\') // PHP date format escaping character
  1051. {
  1052. $i++;
  1053. if ($escaping) {
  1054. $js_format .= $php_format[$i];
  1055. } else {
  1056. $js_format .= '\'' . $php_format[$i];
  1057. }
  1058. $escaping = true;
  1059. } else {
  1060. if ($escaping) {
  1061. $js_format .= "'";
  1062. $escaping = false;
  1063. }
  1064. if (isset($SYMBOLS_MATCHING[$char])) {
  1065. $js_format .= $SYMBOLS_MATCHING[$char];
  1066. } else {
  1067. $js_format .= $char;
  1068. }
  1069. }
  1070. }
  1071. return $js_format;
  1072. }
  1073. /**
  1074. * Gets the entire permissions array
  1075. *
  1076. * @return array
  1077. */
  1078. public function getPermissions()
  1079. {
  1080. return $this->permissions;
  1081. }
  1082. /**
  1083. * Sets the entire permissions array
  1084. *
  1085. * @param $permissions
  1086. */
  1087. public function setPermissions($permissions)
  1088. {
  1089. $this->permissions = $permissions;
  1090. }
  1091. /**
  1092. * Adds a permission to the permissions array
  1093. *
  1094. * @param $permissions
  1095. */
  1096. public function addPermissions($permissions)
  1097. {
  1098. $this->permissions = array_merge($this->permissions, $permissions);
  1099. }
  1100. public function processNotifications($notifications)
  1101. {
  1102. // Sort by date
  1103. usort($notifications, function ($a, $b) {
  1104. return strcmp($a->date, $b->date);
  1105. });
  1106. $notifications = array_reverse($notifications);
  1107. // Make adminNicetimeFilter available
  1108. require_once __DIR__ . '/../classes/Twig/AdminTwigExtension.php';
  1109. $adminTwigExtension = new AdminTwigExtension;
  1110. $filename = $this->grav['locator']->findResource('user://data/notifications/' . $this->grav['user']->username . YAML_EXT,
  1111. true, true);
  1112. $read_notifications = (array)CompiledYamlFile::instance($filename)->content();
  1113. $notifications_processed = [];
  1114. foreach ($notifications as $key => $notification) {
  1115. $is_valid = true;
  1116. if (in_array($notification->id, $read_notifications, true)) {
  1117. $notification->read = true;
  1118. }
  1119. if ($is_valid && isset($notification->permissions) && !$this->authorize($notification->permissions)) {
  1120. $is_valid = false;
  1121. }
  1122. if ($is_valid && isset($notification->dependencies)) {
  1123. foreach ($notification->dependencies as $dependency => $constraints) {
  1124. if ($dependency === 'grav') {
  1125. if (!Semver::satisfies(GRAV_VERSION, $constraints)) {
  1126. $is_valid = false;
  1127. }
  1128. } else {
  1129. $packages = array_merge($this->plugins()->toArray(), $this->themes()->toArray());
  1130. if (!isset($packages[$dependency])) {
  1131. $is_valid = false;
  1132. } else {
  1133. $version = $packages[$dependency]['version'];
  1134. if (!Semver::satisfies($version, $constraints)) {
  1135. $is_valid = false;
  1136. }
  1137. }
  1138. }
  1139. if (!$is_valid) {
  1140. break;
  1141. }
  1142. }
  1143. }
  1144. if ($is_valid) {
  1145. $notifications_processed[] = $notification;
  1146. }
  1147. }
  1148. // Process notifications
  1149. $notifications_processed = array_map(function ($notification) use ($adminTwigExtension) {
  1150. $notification->date = $adminTwigExtension->adminNicetimeFilter($notification->date);
  1151. return $notification;
  1152. }, $notifications_processed);
  1153. return $notifications_processed;
  1154. }
  1155. public function findFormFields($type, $fields, $found_fields = [])
  1156. {
  1157. foreach ($fields as $key => $field) {
  1158. if (isset($field['type']) && $field['type'] == $type) {
  1159. $found_fields[$key] = $field;
  1160. } elseif (isset($field['fields'])) {
  1161. $result = $this->findFormFields($type, $field['fields'], $found_fields);
  1162. if (!empty($result)) {
  1163. $found_fields = array_merge($found_fields, $result);
  1164. }
  1165. }
  1166. }
  1167. return $found_fields;
  1168. }
  1169. public function getPagePathFromToken($path)
  1170. {
  1171. return Utils::getPagePathFromToken($path, $this->page(true));
  1172. }
  1173. /**
  1174. * Returns edited page.
  1175. *
  1176. * @param bool $route
  1177. *
  1178. * @param null $path
  1179. *
  1180. * @return Page
  1181. */
  1182. public function page($route = false, $path = null)
  1183. {
  1184. if (!$path) {
  1185. $path = $this->route;
  1186. }
  1187. if ($route && !$path) {
  1188. $path = '/';
  1189. }
  1190. if (!isset($this->pages[$path])) {
  1191. $this->pages[$path] = $this->getPage($path);
  1192. }
  1193. return $this->pages[$path];
  1194. }
  1195. /**
  1196. * Returns the page creating it if it does not exist.
  1197. *
  1198. * @param $path
  1199. *
  1200. * @return Page
  1201. */
  1202. public function getPage($path)
  1203. {
  1204. /** @var Pages $pages */
  1205. $pages = $this->grav['pages'];
  1206. if ($path && $path[0] !== '/') {
  1207. $path = "/{$path}";
  1208. }
  1209. $page = $path ? $pages->dispatch($path, true) : $pages->root();
  1210. if (!$page) {
  1211. $slug = basename($path);
  1212. if ($slug === '') {
  1213. return null;
  1214. }
  1215. $ppath = str_replace('\\', '/', dirname($path));
  1216. // Find or create parent(s).
  1217. $parent = $this->getPage($ppath !== '/' ? $ppath : '');
  1218. // Create page.
  1219. $page = new Page;
  1220. $page->parent($parent);
  1221. $page->filePath($parent->path() . '/' . $slug . '/' . $page->name());
  1222. // Add routing information.
  1223. $pages->addPage($page, $path);
  1224. // Set if Modular
  1225. $page->modularTwig($slug[0] === '_');
  1226. // Determine page type.
  1227. if (isset($this->session->{$page->route()})) {
  1228. // Found the type and header from the session.
  1229. $data = $this->session->{$page->route()};
  1230. // Set the key header value
  1231. $header = ['title' => $data['title']];
  1232. if (isset($data['visible'])) {
  1233. if ($data['visible'] === '' || $data['visible']) {
  1234. // if auto (ie '')
  1235. $pageParent = $page->parent();
  1236. $children = $pageParent ? $pageParent->children() : [];
  1237. foreach ($children as $child) {
  1238. if ($child->order()) {
  1239. // set page order
  1240. $page->order(AdminController::getNextOrderInFolder($pageParent->path()));
  1241. break;
  1242. }
  1243. }
  1244. }
  1245. if ($data['visible'] == 1 && !$page->order()) {
  1246. $header['visible'] = $data['visible'];
  1247. }
  1248. }
  1249. if ($data['name'] === 'modular') {
  1250. $header['body_classes'] = 'modular';
  1251. }
  1252. $name = $page->modular() ? str_replace('modular/', '', $data['name']) : $data['name'];
  1253. $page->name($name . '.md');
  1254. // Fire new event to allow plugins to manipulate page frontmatter
  1255. $this->grav->fireEvent('onAdminCreatePageFrontmatter', new Event(['header' => &$header,
  1256. 'data' => $data]));
  1257. $page->header($header);
  1258. $page->frontmatter(Yaml::dump((array)$page->header(), 20));
  1259. } else {
  1260. // Find out the type by looking at the parent.
  1261. $type = $parent->childType()
  1262. ? $parent->childType()
  1263. : $parent->blueprints()->get('child_type',
  1264. 'default');
  1265. $page->name($type . CONTENT_EXT);
  1266. $page->header();
  1267. }
  1268. $page->modularTwig($slug[0] === '_');
  1269. }
  1270. return $page;
  1271. }
  1272. /**
  1273. * Get https://getgrav.org news feed
  1274. *
  1275. * @return mixed
  1276. */
  1277. public function getFeed()
  1278. {
  1279. $feed_url = 'https://getgrav.org/blog.atom';
  1280. $body = Response::get($feed_url);
  1281. $reader = new Reader();
  1282. $parser = $reader->getParser($feed_url, $body, 'utf-8');
  1283. return $parser->execute();
  1284. }
  1285. public function getRouteDetails()
  1286. {
  1287. return [$this->base, $this->location, $this->route];
  1288. }
  1289. /**
  1290. * Get the files list
  1291. *
  1292. * @todo allow pagination
  1293. * @return array
  1294. */
  1295. public function files($filtered = true, $page_index = 0)
  1296. {
  1297. $param_type = $this->grav['uri']->param('type');
  1298. $param_date = $this->grav['uri']->param('date');
  1299. $param_page = $this->grav['uri']->param('page');
  1300. $param_page = str_replace('\\', '/', $param_page);
  1301. $files_cache_key = 'media-manager-files';
  1302. if ($param_type) {
  1303. $files_cache_key .= "-{$param_type}";
  1304. }
  1305. if ($param_date) {
  1306. $files_cache_key .= "-{$param_date}";
  1307. }
  1308. if ($param_page) {
  1309. $files_cache_key .= "-{$param_page}";
  1310. }
  1311. $page_files = null;
  1312. $cache_enabled = $this->grav['config']->get('plugins.admin.cache_enabled');
  1313. if (!$cache_enabled) {
  1314. $this->grav['cache']->setEnabled(true);
  1315. }
  1316. $page_files = $this->grav['cache']->fetch(md5($files_cache_key));
  1317. if (!$cache_enabled) {
  1318. $this->grav['cache']->setEnabled(false);
  1319. }
  1320. if (!$page_files) {
  1321. $page_files = [];
  1322. $pages = $this->grav['pages'];
  1323. if ($param_page) {
  1324. $page = $pages->dispatch($param_page);
  1325. $page_files = $this->getFiles('images', $page, $page_files, $filtered);
  1326. $page_files = $this->getFiles('videos', $page, $page_files, $filtered);
  1327. $page_files = $this->getFiles('audios', $page, $page_files, $filtered);
  1328. $page_files = $this->getFiles('files', $page, $page_files, $filtered);
  1329. } else {
  1330. $allPages = $pages->all();
  1331. if ($allPages) foreach ($allPages as $page) {
  1332. $page_files = $this->getFiles('images', $page, $page_files, $filtered);
  1333. $page_files = $this->getFiles('videos', $page, $page_files, $filtered);
  1334. $page_files = $this->getFiles('audios', $page, $page_files, $filtered);
  1335. $page_files = $this->getFiles('files', $page, $page_files, $filtered);
  1336. }
  1337. }
  1338. if (count($page_files) >= self::MEDIA_PAGINATION_INTERVAL) {
  1339. $this->shouldLoadAdditionalFilesInBackground(true);
  1340. }
  1341. if (!$cache_enabled) {
  1342. $this->grav['cache']->setEnabled(true);
  1343. }
  1344. $this->grav['cache']->save(md5($files_cache_key), $page_files, 600); //cache for 10 minutes
  1345. if (!$cache_enabled) {
  1346. $this->grav['cache']->setEnabled(false);
  1347. }
  1348. }
  1349. if (count($page_files) >= self::MEDIA_PAGINATION_INTERVAL) {
  1350. $page_files = array_slice($page_files, $page_index * self::MEDIA_PAGINATION_INTERVAL, self::MEDIA_PAGINATION_INTERVAL);
  1351. }
  1352. return $page_files;
  1353. }
  1354. public function shouldLoadAdditionalFilesInBackground($status = null)
  1355. {
  1356. if ($status) {
  1357. $this->load_additional_files_in_background = true;
  1358. }
  1359. return $this->load_additional_files_in_background;
  1360. }
  1361. public function loadAdditionalFilesInBackground($status = null)
  1362. {
  1363. if (!$this->loading_additional_files_in_background) {
  1364. $this->loading_additional_files_in_background = true;
  1365. $this->files(false, false);
  1366. $this->shouldLoadAdditionalFilesInBackground(false);
  1367. $this->loading_additional_files_in_background = false;
  1368. }
  1369. }
  1370. private function getFiles($type, $page, $page_files, $filtered)
  1371. {
  1372. $page_files = $this->getMediaOfType($type, $page, $page_files);
  1373. if ($filtered) {
  1374. $page_files = $this->filterByType($page_files);
  1375. $page_files = $this->filterByDate($page_files);
  1376. }
  1377. return $page_files;
  1378. }
  1379. /**
  1380. * Get all the media of a type ('images' | 'audios' | 'videos' | 'files')
  1381. *
  1382. * @param string $type
  1383. * @param Page|null $page
  1384. * @param array $files
  1385. *
  1386. * @return array
  1387. */
  1388. private function getMediaOfType($type, Page $page = null, array $files)
  1389. {
  1390. if ($page) {
  1391. $media = $page->media();
  1392. $mediaOfType = $media->$type();
  1393. foreach($mediaOfType as $title => $file) {
  1394. $files[] = [
  1395. 'title' => $title,
  1396. 'type' => $type,
  1397. 'page_route' => $page->route(),
  1398. 'file' => $file->higherQualityAlternative()
  1399. ];
  1400. }
  1401. return $files;
  1402. }
  1403. return [];
  1404. }
  1405. /**
  1406. * Filter media by type
  1407. *
  1408. * @param array $filesFiltered
  1409. *
  1410. * @return array
  1411. */
  1412. private function filterByType($filesFiltered)
  1413. {
  1414. $filter_type = $this->grav['uri']->param('type');
  1415. if (!$filter_type) {
  1416. return $filesFiltered;
  1417. }
  1418. $filesFiltered = array_filter($filesFiltered, function ($file) use ($filter_type) {
  1419. return $file['type'] == $filter_type;
  1420. });
  1421. return $filesFiltered;
  1422. }
  1423. /**
  1424. * Filter media by date
  1425. *
  1426. * @param array $filesFiltered
  1427. *
  1428. * @return array
  1429. */
  1430. private function filterByDate($filesFiltered)
  1431. {
  1432. $filter_date = $this->grav['uri']->param('date');
  1433. if (!$filter_date) {
  1434. return $filesFiltered;
  1435. }
  1436. $year = substr($filter_date, 0, 4);
  1437. $month = substr($filter_date, 5, 2);
  1438. $filesFilteredByDate = [];
  1439. foreach($filesFiltered as $file) {
  1440. $filedate = $this->fileDate($file['file']);
  1441. $fileYear = $filedate->format('Y');
  1442. $fileMonth = $filedate->format('m');
  1443. if ($fileYear == $year && $fileMonth == $month) {
  1444. $filesFilteredByDate[] = $file;
  1445. }
  1446. }
  1447. return $filesFilteredByDate;
  1448. }
  1449. /**
  1450. * Return the DateTime object representation of a file modified date
  1451. *
  1452. * @param File $file
  1453. *
  1454. * @return DateTime
  1455. */
  1456. private function fileDate($file) {
  1457. $datetime = new \DateTime();
  1458. $datetime->setTimestamp($file->toArray()['modified']);
  1459. return $datetime;
  1460. }
  1461. /**
  1462. * Get the files dates list to be used in the Media Files filter
  1463. *
  1464. * @return array
  1465. */
  1466. public function filesDates()
  1467. {
  1468. $files = $this->files(false);
  1469. $dates = [];
  1470. foreach ($files as $file) {
  1471. $datetime = $this->fileDate($file['file']);
  1472. $year = $datetime->format('Y');
  1473. $month = $datetime->format('m');
  1474. if (!isset($dates[$year])) {
  1475. $dates[$year] = [];
  1476. }
  1477. if (!isset($dates[$year][$month])) {
  1478. $dates[$year][$month] = 1;
  1479. } else {
  1480. $dates[$year][$month]++;
  1481. }
  1482. }
  1483. return $dates;
  1484. }
  1485. /**
  1486. * Get the pages list to be used in the Media Files filter
  1487. *
  1488. * @return array
  1489. */
  1490. public function pages()
  1491. {
  1492. /** @var Collection $pages */
  1493. $pages = $this->grav['pages']->all();
  1494. $pagesWithFiles = [];
  1495. foreach ($pages as $page) {
  1496. if (count($page->media()->all())) {
  1497. $pagesWithFiles[] = $page;
  1498. }
  1499. }
  1500. return $pagesWithFiles;
  1501. }
  1502. /**
  1503. * Return HTTP_REFERRER if set
  1504. *
  1505. * @return null
  1506. */
  1507. public function getReferrer()
  1508. {
  1509. return isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
  1510. }
  1511. }