GPM.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  1. <?php
  2. /**
  3. * @package Grav\Common\GPM
  4. *
  5. * @copyright Copyright (c) 2015 - 2022 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\GPM;
  9. use Exception;
  10. use Grav\Common\Grav;
  11. use Grav\Common\Filesystem\Folder;
  12. use Grav\Common\HTTP\Response;
  13. use Grav\Common\Inflector;
  14. use Grav\Common\Iterator;
  15. use Grav\Common\Utils;
  16. use RocketTheme\Toolbox\File\YamlFile;
  17. use RuntimeException;
  18. use stdClass;
  19. use function array_key_exists;
  20. use function count;
  21. use function in_array;
  22. use function is_array;
  23. use function is_object;
  24. /**
  25. * Class GPM
  26. * @package Grav\Common\GPM
  27. */
  28. class GPM extends Iterator
  29. {
  30. /** @var Local\Packages Local installed Packages */
  31. private $installed;
  32. /** @var Remote\Packages|null Remote available Packages */
  33. private $repository;
  34. /** @var Remote\GravCore|null Remove Grav Packages */
  35. private $grav;
  36. /** @var bool */
  37. private $refresh;
  38. /** @var callable|null */
  39. private $callback;
  40. /** @var array Internal cache */
  41. protected $cache;
  42. /** @var array */
  43. protected $install_paths = [
  44. 'plugins' => 'user/plugins/%name%',
  45. 'themes' => 'user/themes/%name%',
  46. 'skeletons' => 'user/'
  47. ];
  48. /**
  49. * Creates a new GPM instance with Local and Remote packages available
  50. *
  51. * @param bool $refresh Applies to Remote Packages only and forces a refetch of data
  52. * @param callable|null $callback Either a function or callback in array notation
  53. */
  54. public function __construct($refresh = false, $callback = null)
  55. {
  56. parent::__construct();
  57. Folder::create(CACHE_DIR . '/gpm');
  58. $this->cache = [];
  59. $this->installed = new Local\Packages();
  60. $this->refresh = $refresh;
  61. $this->callback = $callback;
  62. }
  63. /**
  64. * Magic getter method
  65. *
  66. * @param string $offset Asset name value
  67. * @return mixed Asset value
  68. */
  69. #[\ReturnTypeWillChange]
  70. public function __get($offset)
  71. {
  72. switch ($offset) {
  73. case 'grav':
  74. return $this->getGrav();
  75. }
  76. return parent::__get($offset);
  77. }
  78. /**
  79. * Magic method to determine if the attribute is set
  80. *
  81. * @param string $offset Asset name value
  82. * @return bool True if the value is set
  83. */
  84. #[\ReturnTypeWillChange]
  85. public function __isset($offset)
  86. {
  87. switch ($offset) {
  88. case 'grav':
  89. return $this->getGrav() !== null;
  90. }
  91. return parent::__isset($offset);
  92. }
  93. /**
  94. * Return the locally installed packages
  95. *
  96. * @return Local\Packages
  97. */
  98. public function getInstalled()
  99. {
  100. return $this->installed;
  101. }
  102. /**
  103. * Returns the Locally installable packages
  104. *
  105. * @param array $list_type_installed
  106. * @return array The installed packages
  107. */
  108. public function getInstallable($list_type_installed = ['plugins' => true, 'themes' => true])
  109. {
  110. $items = ['total' => 0];
  111. foreach ($list_type_installed as $type => $type_installed) {
  112. if ($type_installed === false) {
  113. continue;
  114. }
  115. $methodInstallableType = 'getInstalled' . ucfirst($type);
  116. $to_install = $this->$methodInstallableType();
  117. $items[$type] = $to_install;
  118. $items['total'] += count($to_install);
  119. }
  120. return $items;
  121. }
  122. /**
  123. * Returns the amount of locally installed packages
  124. *
  125. * @return int Amount of installed packages
  126. */
  127. public function countInstalled()
  128. {
  129. $installed = $this->getInstalled();
  130. return count($installed['plugins']) + count($installed['themes']);
  131. }
  132. /**
  133. * Return the instance of a specific Package
  134. *
  135. * @param string $slug The slug of the Package
  136. * @return Local\Package|null The instance of the Package
  137. */
  138. public function getInstalledPackage($slug)
  139. {
  140. return $this->getInstalledPlugin($slug) ?? $this->getInstalledTheme($slug);
  141. }
  142. /**
  143. * Return the instance of a specific Plugin
  144. *
  145. * @param string $slug The slug of the Plugin
  146. * @return Local\Package|null The instance of the Plugin
  147. */
  148. public function getInstalledPlugin($slug)
  149. {
  150. return $this->installed['plugins'][$slug] ?? null;
  151. }
  152. /**
  153. * Returns the Locally installed plugins
  154. * @return Iterator The installed plugins
  155. */
  156. public function getInstalledPlugins()
  157. {
  158. return $this->installed['plugins'];
  159. }
  160. /**
  161. * Returns the plugin's enabled state
  162. *
  163. * @param string $slug
  164. * @return bool True if the Plugin is Enabled. False if manually set to enable:false. Null otherwise.
  165. */
  166. public function isPluginEnabled($slug): bool
  167. {
  168. $grav = Grav::instance();
  169. return ($grav['config']['plugins'][$slug]['enabled'] ?? false) === true;
  170. }
  171. /**
  172. * Checks if a Plugin is installed
  173. *
  174. * @param string $slug The slug of the Plugin
  175. * @return bool True if the Plugin has been installed. False otherwise
  176. */
  177. public function isPluginInstalled($slug): bool
  178. {
  179. return isset($this->installed['plugins'][$slug]);
  180. }
  181. /**
  182. * @param string $slug
  183. * @return bool
  184. */
  185. public function isPluginInstalledAsSymlink($slug)
  186. {
  187. $plugin = $this->getInstalledPlugin($slug);
  188. return (bool)($plugin->symlink ?? false);
  189. }
  190. /**
  191. * Return the instance of a specific Theme
  192. *
  193. * @param string $slug The slug of the Theme
  194. * @return Local\Package|null The instance of the Theme
  195. */
  196. public function getInstalledTheme($slug)
  197. {
  198. return $this->installed['themes'][$slug] ?? null;
  199. }
  200. /**
  201. * Returns the Locally installed themes
  202. *
  203. * @return Iterator The installed themes
  204. */
  205. public function getInstalledThemes()
  206. {
  207. return $this->installed['themes'];
  208. }
  209. /**
  210. * Checks if a Theme is enabled
  211. *
  212. * @param string $slug The slug of the Theme
  213. * @return bool True if the Theme has been set to the default theme. False if installed, but not enabled. Null otherwise.
  214. */
  215. public function isThemeEnabled($slug): bool
  216. {
  217. $grav = Grav::instance();
  218. $current_theme = $grav['config']['system']['pages']['theme'] ?? null;
  219. return $current_theme === $slug;
  220. }
  221. /**
  222. * Checks if a Theme is installed
  223. *
  224. * @param string $slug The slug of the Theme
  225. * @return bool True if the Theme has been installed. False otherwise
  226. */
  227. public function isThemeInstalled($slug): bool
  228. {
  229. return isset($this->installed['themes'][$slug]);
  230. }
  231. /**
  232. * Returns the amount of updates available
  233. *
  234. * @return int Amount of available updates
  235. */
  236. public function countUpdates()
  237. {
  238. return count($this->getUpdatablePlugins()) + count($this->getUpdatableThemes());
  239. }
  240. /**
  241. * Returns an array of Plugins and Themes that can be updated.
  242. * Plugins and Themes are extended with the `available` property that relies to the remote version
  243. *
  244. * @param array $list_type_update specifies what type of package to update
  245. * @return array Array of updatable Plugins and Themes.
  246. * Format: ['total' => int, 'plugins' => array, 'themes' => array]
  247. */
  248. public function getUpdatable($list_type_update = ['plugins' => true, 'themes' => true])
  249. {
  250. $items = ['total' => 0];
  251. foreach ($list_type_update as $type => $type_updatable) {
  252. if ($type_updatable === false) {
  253. continue;
  254. }
  255. $methodUpdatableType = 'getUpdatable' . ucfirst($type);
  256. $to_update = $this->$methodUpdatableType();
  257. $items[$type] = $to_update;
  258. $items['total'] += count($to_update);
  259. }
  260. return $items;
  261. }
  262. /**
  263. * Returns an array of Plugins that can be updated.
  264. * The Plugins are extended with the `available` property that relies to the remote version
  265. *
  266. * @return array Array of updatable Plugins
  267. */
  268. public function getUpdatablePlugins()
  269. {
  270. $items = [];
  271. $repository = $this->getRepository();
  272. if (null === $repository) {
  273. return $items;
  274. }
  275. $plugins = $repository['plugins'];
  276. // local cache to speed things up
  277. if (isset($this->cache[__METHOD__])) {
  278. return $this->cache[__METHOD__];
  279. }
  280. foreach ($this->installed['plugins'] as $slug => $plugin) {
  281. if (!isset($plugins[$slug]) || $plugin->symlink || !$plugin->version || $plugin->gpm === false) {
  282. continue;
  283. }
  284. $local_version = $plugin->version ?? 'Unknown';
  285. $remote_version = $plugins[$slug]->version;
  286. if (version_compare($local_version, $remote_version) < 0) {
  287. $plugins[$slug]->available = $remote_version;
  288. $plugins[$slug]->version = $local_version;
  289. $plugins[$slug]->type = $plugins[$slug]->release_type;
  290. $items[$slug] = $plugins[$slug];
  291. }
  292. }
  293. $this->cache[__METHOD__] = $items;
  294. return $items;
  295. }
  296. /**
  297. * Get the latest release of a package from the GPM
  298. *
  299. * @param string $package_name
  300. * @return string|null
  301. */
  302. public function getLatestVersionOfPackage($package_name)
  303. {
  304. $repository = $this->getRepository();
  305. if (null === $repository) {
  306. return null;
  307. }
  308. $plugins = $repository['plugins'];
  309. if (isset($plugins[$package_name])) {
  310. return $plugins[$package_name]->available ?: $plugins[$package_name]->version;
  311. }
  312. //Not a plugin, it's a theme?
  313. $themes = $repository['themes'];
  314. if (isset($themes[$package_name])) {
  315. return $themes[$package_name]->available ?: $themes[$package_name]->version;
  316. }
  317. return null;
  318. }
  319. /**
  320. * Check if a Plugin or Theme is updatable
  321. *
  322. * @param string $slug The slug of the package
  323. * @return bool True if updatable. False otherwise or if not found
  324. */
  325. public function isUpdatable($slug)
  326. {
  327. return $this->isPluginUpdatable($slug) || $this->isThemeUpdatable($slug);
  328. }
  329. /**
  330. * Checks if a Plugin is updatable
  331. *
  332. * @param string $plugin The slug of the Plugin
  333. * @return bool True if the Plugin is updatable. False otherwise
  334. */
  335. public function isPluginUpdatable($plugin)
  336. {
  337. return array_key_exists($plugin, (array)$this->getUpdatablePlugins());
  338. }
  339. /**
  340. * Returns an array of Themes that can be updated.
  341. * The Themes are extended with the `available` property that relies to the remote version
  342. *
  343. * @return array Array of updatable Themes
  344. */
  345. public function getUpdatableThemes()
  346. {
  347. $items = [];
  348. $repository = $this->getRepository();
  349. if (null === $repository) {
  350. return $items;
  351. }
  352. $themes = $repository['themes'];
  353. // local cache to speed things up
  354. if (isset($this->cache[__METHOD__])) {
  355. return $this->cache[__METHOD__];
  356. }
  357. foreach ($this->installed['themes'] as $slug => $plugin) {
  358. if (!isset($themes[$slug]) || $plugin->symlink || !$plugin->version || $plugin->gpm === false) {
  359. continue;
  360. }
  361. $local_version = $plugin->version ?? 'Unknown';
  362. $remote_version = $themes[$slug]->version;
  363. if (version_compare($local_version, $remote_version) < 0) {
  364. $themes[$slug]->available = $remote_version;
  365. $themes[$slug]->version = $local_version;
  366. $themes[$slug]->type = $themes[$slug]->release_type;
  367. $items[$slug] = $themes[$slug];
  368. }
  369. }
  370. $this->cache[__METHOD__] = $items;
  371. return $items;
  372. }
  373. /**
  374. * Checks if a Theme is Updatable
  375. *
  376. * @param string $theme The slug of the Theme
  377. * @return bool True if the Theme is updatable. False otherwise
  378. */
  379. public function isThemeUpdatable($theme)
  380. {
  381. return array_key_exists($theme, (array)$this->getUpdatableThemes());
  382. }
  383. /**
  384. * Get the release type of a package (stable / testing)
  385. *
  386. * @param string $package_name
  387. * @return string|null
  388. */
  389. public function getReleaseType($package_name)
  390. {
  391. $repository = $this->getRepository();
  392. if (null === $repository) {
  393. return null;
  394. }
  395. $plugins = $repository['plugins'];
  396. if (isset($plugins[$package_name])) {
  397. return $plugins[$package_name]->release_type;
  398. }
  399. //Not a plugin, it's a theme?
  400. $themes = $repository['themes'];
  401. if (isset($themes[$package_name])) {
  402. return $themes[$package_name]->release_type;
  403. }
  404. return null;
  405. }
  406. /**
  407. * Returns true if the package latest release is stable
  408. *
  409. * @param string $package_name
  410. * @return bool
  411. */
  412. public function isStableRelease($package_name)
  413. {
  414. return $this->getReleaseType($package_name) === 'stable';
  415. }
  416. /**
  417. * Returns true if the package latest release is testing
  418. *
  419. * @param string $package_name
  420. * @return bool
  421. */
  422. public function isTestingRelease($package_name)
  423. {
  424. $package = $this->getInstalledPackage($package_name);
  425. $testing = $package->testing ?? false;
  426. return $this->getReleaseType($package_name) === 'testing' || $testing;
  427. }
  428. /**
  429. * Returns a Plugin from the repository
  430. *
  431. * @param string $slug The slug of the Plugin
  432. * @return Remote\Package|null Package if found, NULL if not
  433. */
  434. public function getRepositoryPlugin($slug)
  435. {
  436. $packages = $this->getRepositoryPlugins();
  437. return $packages ? ($packages[$slug] ?? null) : null;
  438. }
  439. /**
  440. * Returns the list of Plugins available in the repository
  441. *
  442. * @return Iterator|null The Plugins remotely available
  443. */
  444. public function getRepositoryPlugins()
  445. {
  446. return $this->getRepository()['plugins'] ?? null;
  447. }
  448. /**
  449. * Returns a Theme from the repository
  450. *
  451. * @param string $slug The slug of the Theme
  452. * @return Remote\Package|null Package if found, NULL if not
  453. */
  454. public function getRepositoryTheme($slug)
  455. {
  456. $packages = $this->getRepositoryThemes();
  457. return $packages ? ($packages[$slug] ?? null) : null;
  458. }
  459. /**
  460. * Returns the list of Themes available in the repository
  461. *
  462. * @return Iterator|null The Themes remotely available
  463. */
  464. public function getRepositoryThemes()
  465. {
  466. return $this->getRepository()['themes'] ?? null;
  467. }
  468. /**
  469. * Returns the list of Plugins and Themes available in the repository
  470. *
  471. * @return Remote\Packages|null Available Plugins and Themes
  472. * Format: ['plugins' => array, 'themes' => array]
  473. */
  474. public function getRepository()
  475. {
  476. if (null === $this->repository) {
  477. try {
  478. $this->repository = new Remote\Packages($this->refresh, $this->callback);
  479. } catch (Exception $e) {}
  480. }
  481. return $this->repository;
  482. }
  483. /**
  484. * Returns Grav version available in the repository
  485. *
  486. * @return Remote\GravCore|null
  487. */
  488. public function getGrav()
  489. {
  490. if (null === $this->grav) {
  491. try {
  492. $this->grav = new Remote\GravCore($this->refresh, $this->callback);
  493. } catch (Exception $e) {}
  494. }
  495. return $this->grav;
  496. }
  497. /**
  498. * Searches for a Package in the repository
  499. *
  500. * @param string $search Can be either the slug or the name
  501. * @param bool $ignore_exception True if should not fire an exception (for use in Twig)
  502. * @return Remote\Package|false Package if found, FALSE if not
  503. */
  504. public function findPackage($search, $ignore_exception = false)
  505. {
  506. $search = strtolower($search);
  507. $found = $this->getRepositoryPlugin($search) ?? $this->getRepositoryTheme($search);
  508. if ($found) {
  509. return $found;
  510. }
  511. $themes = $this->getRepositoryThemes();
  512. $plugins = $this->getRepositoryPlugins();
  513. if (null === $themes || null === $plugins) {
  514. if (!is_writable(GRAV_ROOT . '/cache/gpm')) {
  515. throw new RuntimeException('The cache/gpm folder is not writable. Please check the folder permissions.');
  516. }
  517. if ($ignore_exception) {
  518. return false;
  519. }
  520. throw new RuntimeException('GPM not reachable. Please check your internet connection or check the Grav site is reachable');
  521. }
  522. foreach ($themes as $slug => $theme) {
  523. if ($search === $slug || $search === $theme->name) {
  524. return $theme;
  525. }
  526. }
  527. foreach ($plugins as $slug => $plugin) {
  528. if ($search === $slug || $search === $plugin->name) {
  529. return $plugin;
  530. }
  531. }
  532. return false;
  533. }
  534. /**
  535. * Download the zip package via the URL
  536. *
  537. * @param string $package_file
  538. * @param string $tmp
  539. * @return string|null
  540. */
  541. public static function downloadPackage($package_file, $tmp)
  542. {
  543. $package = parse_url($package_file);
  544. if (!is_array($package)) {
  545. throw new \RuntimeException("Malformed GPM URL: {$package_file}");
  546. }
  547. $filename = Utils::basename($package['path'] ?? '');
  548. if (Grav::instance()['config']->get('system.gpm.official_gpm_only') && ($package['host'] ?? null) !== 'getgrav.org') {
  549. throw new RuntimeException('Only official GPM URLs are allowed. You can modify this behavior in the System configuration.');
  550. }
  551. $output = Response::get($package_file, []);
  552. if ($output) {
  553. Folder::create($tmp);
  554. file_put_contents($tmp . DS . $filename, $output);
  555. return $tmp . DS . $filename;
  556. }
  557. return null;
  558. }
  559. /**
  560. * Copy the local zip package to tmp
  561. *
  562. * @param string $package_file
  563. * @param string $tmp
  564. * @return string|null
  565. */
  566. public static function copyPackage($package_file, $tmp)
  567. {
  568. $package_file = realpath($package_file);
  569. if ($package_file && file_exists($package_file)) {
  570. $filename = Utils::basename($package_file);
  571. Folder::create($tmp);
  572. copy($package_file, $tmp . DS . $filename);
  573. return $tmp . DS . $filename;
  574. }
  575. return null;
  576. }
  577. /**
  578. * Try to guess the package type from the source files
  579. *
  580. * @param string $source
  581. * @return string|false
  582. */
  583. public static function getPackageType($source)
  584. {
  585. $plugin_regex = '/^class\\s{1,}[a-zA-Z0-9]{1,}\\s{1,}extends.+Plugin/m';
  586. $theme_regex = '/^class\\s{1,}[a-zA-Z0-9]{1,}\\s{1,}extends.+Theme/m';
  587. if (file_exists($source . 'system/defines.php') &&
  588. file_exists($source . 'system/config/system.yaml')
  589. ) {
  590. return 'grav';
  591. }
  592. // must have a blueprint
  593. if (!file_exists($source . 'blueprints.yaml')) {
  594. return false;
  595. }
  596. // either theme or plugin
  597. $name = Utils::basename($source);
  598. if (Utils::contains($name, 'theme')) {
  599. return 'theme';
  600. }
  601. if (Utils::contains($name, 'plugin')) {
  602. return 'plugin';
  603. }
  604. $glob = glob($source . '*.php') ?: [];
  605. foreach ($glob as $filename) {
  606. $contents = file_get_contents($filename);
  607. if (!$contents) {
  608. continue;
  609. }
  610. if (preg_match($theme_regex, $contents)) {
  611. return 'theme';
  612. }
  613. if (preg_match($plugin_regex, $contents)) {
  614. return 'plugin';
  615. }
  616. }
  617. // Assume it's a theme
  618. return 'theme';
  619. }
  620. /**
  621. * Try to guess the package name from the source files
  622. *
  623. * @param string $source
  624. * @return string|false
  625. */
  626. public static function getPackageName($source)
  627. {
  628. $ignore_yaml_files = ['blueprints', 'languages'];
  629. $glob = glob($source . '*.yaml') ?: [];
  630. foreach ($glob as $filename) {
  631. $name = strtolower(Utils::basename($filename, '.yaml'));
  632. if (in_array($name, $ignore_yaml_files)) {
  633. continue;
  634. }
  635. return $name;
  636. }
  637. return false;
  638. }
  639. /**
  640. * Find/Parse the blueprint file
  641. *
  642. * @param string $source
  643. * @return array|false
  644. */
  645. public static function getBlueprints($source)
  646. {
  647. $blueprint_file = $source . 'blueprints.yaml';
  648. if (!file_exists($blueprint_file)) {
  649. return false;
  650. }
  651. $file = YamlFile::instance($blueprint_file);
  652. $blueprint = (array)$file->content();
  653. $file->free();
  654. return $blueprint;
  655. }
  656. /**
  657. * Get the install path for a name and a particular type of package
  658. *
  659. * @param string $type
  660. * @param string $name
  661. * @return string
  662. */
  663. public static function getInstallPath($type, $name)
  664. {
  665. $locator = Grav::instance()['locator'];
  666. if ($type === 'theme') {
  667. $install_path = $locator->findResource('themes://', false) . DS . $name;
  668. } else {
  669. $install_path = $locator->findResource('plugins://', false) . DS . $name;
  670. }
  671. return $install_path;
  672. }
  673. /**
  674. * Searches for a list of Packages in the repository
  675. *
  676. * @param array $searches An array of either slugs or names
  677. * @return array Array of found Packages
  678. * Format: ['total' => int, 'not_found' => array, <found-slugs>]
  679. */
  680. public function findPackages($searches = [])
  681. {
  682. $packages = ['total' => 0, 'not_found' => []];
  683. $inflector = new Inflector();
  684. foreach ($searches as $search) {
  685. $repository = '';
  686. // if this is an object, get the search data from the key
  687. if (is_object($search)) {
  688. $search = (array)$search;
  689. $key = key($search);
  690. $repository = $search[$key];
  691. $search = $key;
  692. }
  693. $found = $this->findPackage($search);
  694. if ($found) {
  695. // set override repository if provided
  696. if ($repository) {
  697. $found->override_repository = $repository;
  698. }
  699. if (!isset($packages[$found->package_type])) {
  700. $packages[$found->package_type] = [];
  701. }
  702. $packages[$found->package_type][$found->slug] = $found;
  703. $packages['total']++;
  704. } else {
  705. // make a best guess at the type based on the repo URL
  706. if (Utils::contains($repository, '-theme')) {
  707. $type = 'themes';
  708. } else {
  709. $type = 'plugins';
  710. }
  711. $not_found = new stdClass();
  712. $not_found->name = $inflector::camelize($search);
  713. $not_found->slug = $search;
  714. $not_found->package_type = $type;
  715. $not_found->install_path = str_replace('%name%', $search, $this->install_paths[$type]);
  716. $not_found->override_repository = $repository;
  717. $packages['not_found'][$search] = $not_found;
  718. }
  719. }
  720. return $packages;
  721. }
  722. /**
  723. * Return the list of packages that have the passed one as dependency
  724. *
  725. * @param string $slug The slug name of the package
  726. * @return array
  727. */
  728. public function getPackagesThatDependOnPackage($slug)
  729. {
  730. $plugins = $this->getInstalledPlugins();
  731. $themes = $this->getInstalledThemes();
  732. $packages = array_merge($plugins->toArray(), $themes->toArray());
  733. $list = [];
  734. foreach ($packages as $package_name => $package) {
  735. $dependencies = $package['dependencies'] ?? [];
  736. foreach ($dependencies as $dependency) {
  737. if (is_array($dependency) && isset($dependency['name'])) {
  738. $dependency = $dependency['name'];
  739. }
  740. if ($dependency === $slug) {
  741. $list[] = $package_name;
  742. }
  743. }
  744. }
  745. return $list;
  746. }
  747. /**
  748. * Get the required version of a dependency of a package
  749. *
  750. * @param string $package_slug
  751. * @param string $dependency_slug
  752. * @return mixed|null
  753. */
  754. public function getVersionOfDependencyRequiredByPackage($package_slug, $dependency_slug)
  755. {
  756. $dependencies = $this->getInstalledPackage($package_slug)->dependencies ?? [];
  757. foreach ($dependencies as $dependency) {
  758. if (isset($dependency[$dependency_slug])) {
  759. return $dependency[$dependency_slug];
  760. }
  761. }
  762. return null;
  763. }
  764. /**
  765. * Check the package identified by $slug can be updated to the version passed as argument.
  766. * Thrown an exception if it cannot be updated because another package installed requires it to be at an older version.
  767. *
  768. * @param string $slug
  769. * @param string $version_with_operator
  770. * @param array $ignore_packages_list
  771. * @return bool
  772. * @throws RuntimeException
  773. */
  774. public function checkNoOtherPackageNeedsThisDependencyInALowerVersion($slug, $version_with_operator, $ignore_packages_list)
  775. {
  776. // check if any of the currently installed package need this in a lower version than the one we need. In case, abort and tell which package
  777. $dependent_packages = $this->getPackagesThatDependOnPackage($slug);
  778. $version = $this->calculateVersionNumberFromDependencyVersion($version_with_operator);
  779. if (count($dependent_packages)) {
  780. foreach ($dependent_packages as $dependent_package) {
  781. $other_dependency_version_with_operator = $this->getVersionOfDependencyRequiredByPackage($dependent_package, $slug);
  782. $other_dependency_version = $this->calculateVersionNumberFromDependencyVersion($other_dependency_version_with_operator);
  783. // check version is compatible with the one needed by the current package
  784. if ($this->versionFormatIsNextSignificantRelease($other_dependency_version_with_operator)) {
  785. $compatible = $this->checkNextSignificantReleasesAreCompatible($version, $other_dependency_version);
  786. if (!$compatible && !in_array($dependent_package, $ignore_packages_list, true)) {
  787. throw new RuntimeException(
  788. "Package <cyan>$slug</cyan> is required in an older version by package <cyan>$dependent_package</cyan>. This package needs a newer version, and because of this it cannot be installed. The <cyan>$dependent_package</cyan> package must be updated to use a newer release of <cyan>$slug</cyan>.",
  789. 2
  790. );
  791. }
  792. }
  793. }
  794. }
  795. return true;
  796. }
  797. /**
  798. * Check the passed packages list can be updated
  799. *
  800. * @param array $packages_names_list
  801. * @return void
  802. * @throws Exception
  803. */
  804. public function checkPackagesCanBeInstalled($packages_names_list)
  805. {
  806. foreach ($packages_names_list as $package_name) {
  807. $latest = $this->getLatestVersionOfPackage($package_name);
  808. $this->checkNoOtherPackageNeedsThisDependencyInALowerVersion($package_name, $latest, $packages_names_list);
  809. }
  810. }
  811. /**
  812. * Fetch the dependencies, check the installed packages and return an array with
  813. * the list of packages with associated an information on what to do: install, update or ignore.
  814. *
  815. * `ignore` means the package is already installed and can be safely left as-is.
  816. * `install` means the package is not installed and must be installed.
  817. * `update` means the package is already installed and must be updated as a dependency needs a higher version.
  818. *
  819. * @param array $packages
  820. * @return array
  821. * @throws RuntimeException
  822. */
  823. public function getDependencies($packages)
  824. {
  825. $dependencies = $this->calculateMergedDependenciesOfPackages($packages);
  826. foreach ($dependencies as $dependency_slug => $dependencyVersionWithOperator) {
  827. $dependency_slug = (string)$dependency_slug;
  828. if (in_array($dependency_slug, $packages, true)) {
  829. unset($dependencies[$dependency_slug]);
  830. continue;
  831. }
  832. // Check PHP version
  833. if ($dependency_slug === 'php') {
  834. $testVersion = $this->calculateVersionNumberFromDependencyVersion($dependencyVersionWithOperator);
  835. if (version_compare($testVersion, PHP_VERSION) === 1) {
  836. //Needs a Grav update first
  837. throw new RuntimeException("<red>One of the packages require PHP {$dependencies['php']}. Please update PHP to resolve this");
  838. }
  839. unset($dependencies[$dependency_slug]);
  840. continue;
  841. }
  842. //First, check for Grav dependency. If a dependency requires Grav > the current version, abort and tell.
  843. if ($dependency_slug === 'grav') {
  844. $testVersion = $this->calculateVersionNumberFromDependencyVersion($dependencyVersionWithOperator);
  845. if (version_compare($testVersion, GRAV_VERSION) === 1) {
  846. //Needs a Grav update first
  847. throw new RuntimeException("<red>One of the packages require Grav {$dependencies['grav']}. Please update Grav to the latest release.");
  848. }
  849. unset($dependencies[$dependency_slug]);
  850. continue;
  851. }
  852. if ($this->isPluginInstalled($dependency_slug)) {
  853. if ($this->isPluginInstalledAsSymlink($dependency_slug)) {
  854. unset($dependencies[$dependency_slug]);
  855. continue;
  856. }
  857. $dependencyVersion = $this->calculateVersionNumberFromDependencyVersion($dependencyVersionWithOperator);
  858. // get currently installed version
  859. $locator = Grav::instance()['locator'];
  860. $blueprints_path = $locator->findResource('plugins://' . $dependency_slug . DS . 'blueprints.yaml');
  861. $file = YamlFile::instance($blueprints_path);
  862. $package_yaml = $file->content();
  863. $file->free();
  864. $currentlyInstalledVersion = $package_yaml['version'];
  865. // if requirement is next significant release, check is compatible with currently installed version, might not be
  866. if ($this->versionFormatIsNextSignificantRelease($dependencyVersionWithOperator)
  867. && $this->firstVersionIsLower($dependencyVersion, $currentlyInstalledVersion)) {
  868. $compatible = $this->checkNextSignificantReleasesAreCompatible($dependencyVersion, $currentlyInstalledVersion);
  869. if (!$compatible) {
  870. throw new RuntimeException(
  871. 'Dependency <cyan>' . $dependency_slug . '</cyan> is required in an older version than the one installed. This package must be updated. Please get in touch with its developer.',
  872. 2
  873. );
  874. }
  875. }
  876. //if I already have the latest release, remove the dependency
  877. $latestRelease = $this->getLatestVersionOfPackage($dependency_slug);
  878. if ($this->firstVersionIsLower($latestRelease, $dependencyVersion)) {
  879. //throw an exception if a required version cannot be found in the GPM yet
  880. throw new RuntimeException(
  881. 'Dependency <cyan>' . $package_yaml['name'] . '</cyan> is required in version <cyan>' . $dependencyVersion . '</cyan> which is higher than the latest release, <cyan>' . $latestRelease . '</cyan>. Try running `bin/gpm -f index` to force a refresh of the GPM cache',
  882. 1
  883. );
  884. }
  885. if ($this->firstVersionIsLower($currentlyInstalledVersion, $dependencyVersion)) {
  886. $dependencies[$dependency_slug] = 'update';
  887. } elseif ($currentlyInstalledVersion === $latestRelease) {
  888. unset($dependencies[$dependency_slug]);
  889. } else {
  890. // an update is not strictly required mark as 'ignore'
  891. $dependencies[$dependency_slug] = 'ignore';
  892. }
  893. } else {
  894. $dependencyVersion = $this->calculateVersionNumberFromDependencyVersion($dependencyVersionWithOperator);
  895. // if requirement is next significant release, check is compatible with latest available version, might not be
  896. if ($this->versionFormatIsNextSignificantRelease($dependencyVersionWithOperator)) {
  897. $latestVersionOfPackage = $this->getLatestVersionOfPackage($dependency_slug);
  898. if ($this->firstVersionIsLower($dependencyVersion, $latestVersionOfPackage)) {
  899. $compatible = $this->checkNextSignificantReleasesAreCompatible(
  900. $dependencyVersion,
  901. $latestVersionOfPackage
  902. );
  903. if (!$compatible) {
  904. throw new RuntimeException(
  905. 'Dependency <cyan>' . $dependency_slug . '</cyan> is required in an older version than the latest release available, and it cannot be installed. This package must be updated. Please get in touch with its developer.',
  906. 2
  907. );
  908. }
  909. }
  910. }
  911. $dependencies[$dependency_slug] = 'install';
  912. }
  913. }
  914. $dependencies_slugs = array_keys($dependencies);
  915. $this->checkNoOtherPackageNeedsTheseDependenciesInALowerVersion(array_merge($packages, $dependencies_slugs));
  916. return $dependencies;
  917. }
  918. /**
  919. * @param array $dependencies_slugs
  920. * @return void
  921. */
  922. public function checkNoOtherPackageNeedsTheseDependenciesInALowerVersion($dependencies_slugs)
  923. {
  924. foreach ($dependencies_slugs as $dependency_slug) {
  925. $this->checkNoOtherPackageNeedsThisDependencyInALowerVersion(
  926. $dependency_slug,
  927. $this->getLatestVersionOfPackage($dependency_slug),
  928. $dependencies_slugs
  929. );
  930. }
  931. }
  932. /**
  933. * @param string $firstVersion
  934. * @param string $secondVersion
  935. * @return bool
  936. */
  937. private function firstVersionIsLower($firstVersion, $secondVersion)
  938. {
  939. return version_compare($firstVersion, $secondVersion) === -1;
  940. }
  941. /**
  942. * Calculates and merges the dependencies of a package
  943. *
  944. * @param string $packageName The package information
  945. * @param array $dependencies The dependencies array
  946. * @return array
  947. */
  948. private function calculateMergedDependenciesOfPackage($packageName, $dependencies)
  949. {
  950. $packageData = $this->findPackage($packageName);
  951. if (empty($packageData->dependencies)) {
  952. return $dependencies;
  953. }
  954. foreach ($packageData->dependencies as $dependency) {
  955. $dependencyName = $dependency['name'] ?? null;
  956. if (!$dependencyName) {
  957. continue;
  958. }
  959. $dependencyVersion = $dependency['version'] ?? '*';
  960. if (!isset($dependencies[$dependencyName])) {
  961. // Dependency added for the first time
  962. $dependencies[$dependencyName] = $dependencyVersion;
  963. //Factor in the package dependencies too
  964. $dependencies = $this->calculateMergedDependenciesOfPackage($dependencyName, $dependencies);
  965. } elseif ($dependencyVersion !== '*') {
  966. // Dependency already added by another package
  967. // If this package requires a version higher than the currently stored one, store this requirement instead
  968. $currentDependencyVersion = $dependencies[$dependencyName];
  969. $currently_stored_version_number = $this->calculateVersionNumberFromDependencyVersion($currentDependencyVersion);
  970. $currently_stored_version_is_in_next_significant_release_format = false;
  971. if ($this->versionFormatIsNextSignificantRelease($currentDependencyVersion)) {
  972. $currently_stored_version_is_in_next_significant_release_format = true;
  973. }
  974. if (!$currently_stored_version_number) {
  975. $currently_stored_version_number = '*';
  976. }
  977. $current_package_version_number = $this->calculateVersionNumberFromDependencyVersion($dependencyVersion);
  978. if (!$current_package_version_number) {
  979. throw new RuntimeException("Bad format for version of dependency {$dependencyName} for package {$packageName}", 1);
  980. }
  981. $current_package_version_is_in_next_significant_release_format = false;
  982. if ($this->versionFormatIsNextSignificantRelease($dependencyVersion)) {
  983. $current_package_version_is_in_next_significant_release_format = true;
  984. }
  985. //If I had stored '*', change right away with the more specific version required
  986. if ($currently_stored_version_number === '*') {
  987. $dependencies[$dependencyName] = $dependencyVersion;
  988. } elseif (!$currently_stored_version_is_in_next_significant_release_format && !$current_package_version_is_in_next_significant_release_format) {
  989. //Comparing versions equals or higher, a simple version_compare is enough
  990. if (version_compare($currently_stored_version_number, $current_package_version_number) === -1) {
  991. //Current package version is higher
  992. $dependencies[$dependencyName] = $dependencyVersion;
  993. }
  994. } else {
  995. $compatible = $this->checkNextSignificantReleasesAreCompatible($currently_stored_version_number, $current_package_version_number);
  996. if (!$compatible) {
  997. throw new RuntimeException("Dependency {$dependencyName} is required in two incompatible versions", 2);
  998. }
  999. }
  1000. }
  1001. }
  1002. return $dependencies;
  1003. }
  1004. /**
  1005. * Calculates and merges the dependencies of the passed packages
  1006. *
  1007. * @param array $packages
  1008. * @return array
  1009. */
  1010. public function calculateMergedDependenciesOfPackages($packages)
  1011. {
  1012. $dependencies = [];
  1013. foreach ($packages as $package) {
  1014. $dependencies = $this->calculateMergedDependenciesOfPackage($package, $dependencies);
  1015. }
  1016. return $dependencies;
  1017. }
  1018. /**
  1019. * Returns the actual version from a dependency version string.
  1020. * Examples:
  1021. * $versionInformation == '~2.0' => returns '2.0'
  1022. * $versionInformation == '>=2.0.2' => returns '2.0.2'
  1023. * $versionInformation == '2.0.2' => returns '2.0.2'
  1024. * $versionInformation == '*' => returns null
  1025. * $versionInformation == '' => returns null
  1026. *
  1027. * @param string $version
  1028. * @return string|null
  1029. */
  1030. public function calculateVersionNumberFromDependencyVersion($version)
  1031. {
  1032. if ($version === '*') {
  1033. return null;
  1034. }
  1035. if ($version === '') {
  1036. return null;
  1037. }
  1038. if ($this->versionFormatIsNextSignificantRelease($version)) {
  1039. return trim(substr($version, 1));
  1040. }
  1041. if ($this->versionFormatIsEqualOrHigher($version)) {
  1042. return trim(substr($version, 2));
  1043. }
  1044. return $version;
  1045. }
  1046. /**
  1047. * Check if the passed version information contains next significant release (tilde) operator
  1048. *
  1049. * Example: returns true for $version: '~2.0'
  1050. *
  1051. * @param string $version
  1052. * @return bool
  1053. */
  1054. public function versionFormatIsNextSignificantRelease($version): bool
  1055. {
  1056. return strpos($version, '~') === 0;
  1057. }
  1058. /**
  1059. * Check if the passed version information contains equal or higher operator
  1060. *
  1061. * Example: returns true for $version: '>=2.0'
  1062. *
  1063. * @param string $version
  1064. * @return bool
  1065. */
  1066. public function versionFormatIsEqualOrHigher($version): bool
  1067. {
  1068. return strpos($version, '>=') === 0;
  1069. }
  1070. /**
  1071. * Check if two releases are compatible by next significant release
  1072. *
  1073. * ~1.2 is equivalent to >=1.2 <2.0.0
  1074. * ~1.2.3 is equivalent to >=1.2.3 <1.3.0
  1075. *
  1076. * In short, allows the last digit specified to go up
  1077. *
  1078. * @param string $version1 the version string (e.g. '2.0.0' or '1.0')
  1079. * @param string $version2 the version string (e.g. '2.0.0' or '1.0')
  1080. * @return bool
  1081. */
  1082. public function checkNextSignificantReleasesAreCompatible($version1, $version2): bool
  1083. {
  1084. $version1array = explode('.', $version1);
  1085. $version2array = explode('.', $version2);
  1086. if (count($version1array) > count($version2array)) {
  1087. [$version1array, $version2array] = [$version2array, $version1array];
  1088. }
  1089. $i = 0;
  1090. while ($i < count($version1array) - 1) {
  1091. if ($version1array[$i] !== $version2array[$i]) {
  1092. return false;
  1093. }
  1094. $i++;
  1095. }
  1096. return true;
  1097. }
  1098. }