gpm.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. <?php
  2. namespace Grav\Plugin\Admin;
  3. use Grav\Common\Cache;
  4. use Grav\Common\Grav;
  5. use Grav\Common\GPM\GPM as GravGPM;
  6. use Grav\Common\GPM\Licenses;
  7. use Grav\Common\GPM\Installer;
  8. use Grav\Common\GPM\Response;
  9. use Grav\Common\GPM\Upgrader;
  10. use Grav\Common\Filesystem\Folder;
  11. use Grav\Common\GPM\Common\Package;
  12. /**
  13. * Class Gpm
  14. *
  15. * @package Grav\Plugin\Admin
  16. */
  17. class Gpm
  18. {
  19. // Probably should move this to Grav DI container?
  20. /** @var GravGPM */
  21. protected static $GPM;
  22. public static function GPM()
  23. {
  24. if (!static::$GPM) {
  25. static::$GPM = new GravGPM();
  26. }
  27. return static::$GPM;
  28. }
  29. /**
  30. * Default options for the install
  31. *
  32. * @var array
  33. */
  34. protected static $options = [
  35. 'destination' => GRAV_ROOT,
  36. 'overwrite' => true,
  37. 'ignore_symlinks' => true,
  38. 'skip_invalid' => true,
  39. 'install_deps' => true,
  40. 'theme' => false
  41. ];
  42. /**
  43. * @param Package[]|string[]|string $packages
  44. * @param array $options
  45. *
  46. * @return string|bool
  47. */
  48. public static function install($packages, array $options)
  49. {
  50. $options = array_merge(self::$options, $options);
  51. if (!Installer::isGravInstance($options['destination']) || !Installer::isValidDestination($options['destination'],
  52. [Installer::EXISTS, Installer::IS_LINK])
  53. ) {
  54. return false;
  55. }
  56. $packages = is_array($packages) ? $packages : [$packages];
  57. $count = count($packages);
  58. $packages = array_filter(array_map(function ($p) {
  59. return !is_string($p) ? $p instanceof Package ? $p : false : self::GPM()->findPackage($p);
  60. }, $packages));
  61. if (!$options['skip_invalid'] && $count !== count($packages)) {
  62. return false;
  63. }
  64. $messages = '';
  65. foreach ($packages as $package) {
  66. if (isset($package->dependencies) && $options['install_deps']) {
  67. $result = static::install($package->dependencies, $options);
  68. if (!$result) {
  69. return false;
  70. }
  71. }
  72. // Check destination
  73. Installer::isValidDestination($options['destination'] . DS . $package->install_path);
  74. if (!$options['overwrite'] && Installer::lastErrorCode() === Installer::EXISTS) {
  75. return false;
  76. }
  77. if (!$options['ignore_symlinks'] && Installer::lastErrorCode() === Installer::IS_LINK) {
  78. return false;
  79. }
  80. $license = Licenses::get($package->slug);
  81. $local = static::download($package, $license);
  82. Installer::install($local, $options['destination'],
  83. ['install_path' => $package->install_path, 'theme' => $options['theme']]);
  84. Folder::delete(dirname($local));
  85. $errorCode = Installer::lastErrorCode();
  86. if ($errorCode) {
  87. $msg = Installer::lastErrorMsg();
  88. throw new \RuntimeException($msg);
  89. }
  90. if (count($packages) === 1) {
  91. $message = Installer::getMessage();
  92. if ($message) {
  93. return $message;
  94. }
  95. $messages .= $message;
  96. }
  97. }
  98. return $messages ?: true;
  99. }
  100. /**
  101. * @param Package[]|string[]|string $packages
  102. * @param array $options
  103. *
  104. * @return string|bool
  105. */
  106. public static function update($packages, array $options)
  107. {
  108. $options['overwrite'] = true;
  109. return static::install($packages, $options);
  110. }
  111. /**
  112. * @param Package[]|string[]|string $packages
  113. * @param array $options
  114. *
  115. * @return string|bool
  116. */
  117. public static function uninstall($packages, array $options)
  118. {
  119. $options = array_merge(self::$options, $options);
  120. $packages = (array)$packages;
  121. $count = count($packages);
  122. $packages = array_filter(array_map(function ($p) {
  123. if (is_string($p)) {
  124. $p = strtolower($p);
  125. $plugin = static::GPM()->getInstalledPlugin($p);
  126. $p = $plugin ?: static::GPM()->getInstalledTheme($p);
  127. }
  128. return $p instanceof Package ? $p : false;
  129. }, $packages));
  130. if (!$options['skip_invalid'] && $count !== count($packages)) {
  131. return false;
  132. }
  133. foreach ($packages as $package) {
  134. $location = Grav::instance()['locator']->findResource($package->package_type . '://' . $package->slug);
  135. // Check destination
  136. Installer::isValidDestination($location);
  137. if (!$options['ignore_symlinks'] && Installer::lastErrorCode() === Installer::IS_LINK) {
  138. return false;
  139. }
  140. Installer::uninstall($location);
  141. $errorCode = Installer::lastErrorCode();
  142. if ($errorCode && $errorCode !== Installer::IS_LINK && $errorCode !== Installer::EXISTS) {
  143. $msg = Installer::lastErrorMsg();
  144. throw new \RuntimeException($msg);
  145. }
  146. if (count($packages) === 1) {
  147. $message = Installer::getMessage();
  148. if ($message) {
  149. return $message;
  150. }
  151. }
  152. }
  153. return true;
  154. }
  155. /**
  156. * Direct install a file
  157. *
  158. * @param string $package_file
  159. *
  160. * @return string|bool
  161. */
  162. public static function directInstall($package_file)
  163. {
  164. if (!$package_file) {
  165. return Admin::translate('PLUGIN_ADMIN.NO_PACKAGE_NAME');
  166. }
  167. $tmp_dir = Grav::instance()['locator']->findResource('tmp://', true, true);
  168. $tmp_zip = $tmp_dir . '/Grav-' . uniqid('', false);
  169. if (Response::isRemote($package_file)) {
  170. $zip = GravGPM::downloadPackage($package_file, $tmp_zip);
  171. } else {
  172. $zip = GravGPM::copyPackage($package_file, $tmp_zip);
  173. }
  174. if (file_exists($zip)) {
  175. $tmp_source = $tmp_dir . '/Grav-' . uniqid('', false);
  176. $extracted = Installer::unZip($zip, $tmp_source);
  177. if (!$extracted) {
  178. Folder::delete($tmp_source);
  179. Folder::delete($tmp_zip);
  180. return Admin::translate('PLUGIN_ADMIN.PACKAGE_EXTRACTION_FAILED');
  181. }
  182. $type = GravGPM::getPackageType($extracted);
  183. if (!$type) {
  184. Folder::delete($tmp_source);
  185. Folder::delete($tmp_zip);
  186. return Admin::translate('PLUGIN_ADMIN.NOT_VALID_GRAV_PACKAGE');
  187. }
  188. if ($type === 'grav') {
  189. Installer::isValidDestination(GRAV_ROOT . '/system');
  190. if (Installer::IS_LINK === Installer::lastErrorCode()) {
  191. Folder::delete($tmp_source);
  192. Folder::delete($tmp_zip);
  193. return Admin::translate('PLUGIN_ADMIN.CANNOT_OVERWRITE_SYMLINKS');
  194. }
  195. static::upgradeGrav($zip, $extracted);
  196. } else {
  197. $name = GravGPM::getPackageName($extracted);
  198. if (!$name) {
  199. Folder::delete($tmp_source);
  200. Folder::delete($tmp_zip);
  201. return Admin::translate('PLUGIN_ADMIN.NAME_COULD_NOT_BE_DETERMINED');
  202. }
  203. $install_path = GravGPM::getInstallPath($type, $name);
  204. $is_update = file_exists($install_path);
  205. Installer::isValidDestination(GRAV_ROOT . DS . $install_path);
  206. if (Installer::lastErrorCode() === Installer::IS_LINK) {
  207. Folder::delete($tmp_source);
  208. Folder::delete($tmp_zip);
  209. return Admin::translate('PLUGIN_ADMIN.CANNOT_OVERWRITE_SYMLINKS');
  210. }
  211. Installer::install($zip, GRAV_ROOT,
  212. ['install_path' => $install_path, 'theme' => $type === 'theme', 'is_update' => $is_update],
  213. $extracted);
  214. }
  215. Folder::delete($tmp_source);
  216. if (Installer::lastErrorCode()) {
  217. return Installer::lastErrorMsg();
  218. }
  219. } else {
  220. return Admin::translate('PLUGIN_ADMIN.ZIP_PACKAGE_NOT_FOUND');
  221. }
  222. Folder::delete($tmp_zip);
  223. return true;
  224. }
  225. /**
  226. * @param Package $package
  227. *
  228. * @return string
  229. */
  230. private static function download(Package $package, $license = null)
  231. {
  232. $query = '';
  233. if ($package->premium) {
  234. $query = \json_encode(array_merge($package->premium, [
  235. 'slug' => $package->slug,
  236. 'filename' => $package->premium['filename'],
  237. 'license_key' => $license
  238. ]));
  239. $query = '?d=' . base64_encode($query);
  240. }
  241. try {
  242. $contents = Response::get($package->zipball_url . $query, []);
  243. } catch (\Exception $e) {
  244. throw new \RuntimeException($e->getMessage());
  245. }
  246. $tmp_dir = Admin::getTempDir() . '/Grav-' . uniqid('', false);
  247. Folder::mkdir($tmp_dir);
  248. $bad_chars = array_merge(array_map('chr', range(0, 31)), ['<', '>', ':', '"', '/', '\\', '|', '?', '*']);
  249. $filename = $package->slug . str_replace($bad_chars, '', basename($package->zipball_url));
  250. $filename = preg_replace('/[\\\\\/:"*?&<>|]+/m', '-', $filename);
  251. file_put_contents($tmp_dir . DS . $filename . '.zip', $contents);
  252. return $tmp_dir . DS . $filename . '.zip';
  253. }
  254. /**
  255. * @param array $package
  256. * @param string $tmp
  257. *
  258. * @return string
  259. */
  260. private static function _downloadSelfupgrade(array $package, $tmp)
  261. {
  262. $output = Response::get($package['download'], []);
  263. Folder::mkdir($tmp);
  264. file_put_contents($tmp . DS . $package['name'], $output);
  265. return $tmp . DS . $package['name'];
  266. }
  267. /**
  268. * @return bool
  269. */
  270. public static function selfupgrade()
  271. {
  272. $upgrader = new Upgrader();
  273. if (!Installer::isGravInstance(GRAV_ROOT)) {
  274. return false;
  275. }
  276. if (is_link(GRAV_ROOT . DS . 'index.php')) {
  277. Installer::setError(Installer::IS_LINK);
  278. return false;
  279. }
  280. if (method_exists($upgrader, 'meetsRequirements') &&
  281. method_exists($upgrader, 'minPHPVersion') &&
  282. !$upgrader->meetsRequirements()) {
  283. $error = [];
  284. $error[] = '<p>Grav has increased the minimum PHP requirement.<br />';
  285. $error[] = 'You are currently running PHP <strong>' . phpversion() . '</strong>';
  286. $error[] = ', but PHP <strong>' . $upgrader->minPHPVersion() . '</strong> is required.</p>';
  287. $error[] = '<p><a href="http://getgrav.org/blog/changing-php-requirements-to-5.5" class="button button-small secondary">Additional information</a></p>';
  288. Installer::setError(implode("\n", $error));
  289. return false;
  290. }
  291. $update = $upgrader->getAssets()['grav-update'];
  292. $tmp = Admin::getTempDir() . '/Grav-' . uniqid('', false);
  293. if ($tmp) {
  294. $file = self::_downloadSelfupgrade($update, $tmp);
  295. $folder = Installer::unZip($file, $tmp . '/zip');
  296. $keepFolder = false;
  297. } else {
  298. // If you make $tmp empty, you can install your local copy of Grav (for testing purposes only).
  299. $file = 'grav.zip';
  300. $folder = '~/phpstorm/grav-clones/grav';
  301. //$folder = '/home/matias/phpstorm/rockettheme/grav-devtools/grav-clones/grav';
  302. $keepFolder = true;
  303. }
  304. static::upgradeGrav($file, $folder, $keepFolder);
  305. $errorCode = Installer::lastErrorCode();
  306. if ($tmp) {
  307. Folder::delete($tmp);
  308. }
  309. return !(is_string($errorCode) || ($errorCode & (Installer::ZIP_OPEN_ERROR | Installer::ZIP_EXTRACT_ERROR)));
  310. }
  311. private static function upgradeGrav($zip, $folder, $keepFolder = false)
  312. {
  313. static $ignores = [
  314. 'backup',
  315. 'cache',
  316. 'images',
  317. 'logs',
  318. 'tmp',
  319. 'user',
  320. '.htaccess',
  321. 'robots.txt'
  322. ];
  323. if (!is_dir($folder)) {
  324. Installer::setError('Invalid source folder');
  325. }
  326. try {
  327. $script = $folder . '/system/install.php';
  328. /** Install $installer */
  329. if ((file_exists($script) && $install = include $script) && is_callable($install)) {
  330. $install($zip);
  331. } else {
  332. Installer::install(
  333. $zip,
  334. GRAV_ROOT,
  335. ['sophisticated' => true, 'overwrite' => true, 'ignore_symlinks' => true, 'ignores' => $ignores],
  336. $folder,
  337. $keepFolder
  338. );
  339. Cache::clearCache();
  340. }
  341. } catch (\Exception $e) {
  342. Installer::setError($e->getMessage());
  343. }
  344. }
  345. }