admin.php 47 KB

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