GPM.php 39 KB

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