gpm.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. 'license_key' => $license
  237. ]));
  238. $query = '?d=' . base64_encode($query);
  239. }
  240. try {
  241. $contents = Response::get($package->zipball_url . $query, []);
  242. } catch (\Exception $e) {
  243. throw new \RuntimeException($e->getMessage());
  244. }
  245. $tmp_dir = Admin::getTempDir() . '/Grav-' . uniqid('', false);
  246. Folder::mkdir($tmp_dir);
  247. $bad_chars = array_merge(array_map('chr', range(0, 31)), ['<', '>', ':', '"', '/', '\\', '|', '?', '*']);
  248. $filename = $package->slug . str_replace($bad_chars, '', basename($package->zipball_url));
  249. $filename = preg_replace('/[\\\\\/:"*?&<>|]+/m', '-', $filename);
  250. file_put_contents($tmp_dir . DS . $filename . '.zip', $contents);
  251. return $tmp_dir . DS . $filename . '.zip';
  252. }
  253. /**
  254. * @param array $package
  255. * @param string $tmp
  256. *
  257. * @return string
  258. */
  259. private static function _downloadSelfupgrade(array $package, $tmp)
  260. {
  261. $output = Response::get($package['download'], []);
  262. Folder::mkdir($tmp);
  263. file_put_contents($tmp . DS . $package['name'], $output);
  264. return $tmp . DS . $package['name'];
  265. }
  266. /**
  267. * @return bool
  268. */
  269. public static function selfupgrade()
  270. {
  271. $upgrader = new Upgrader();
  272. if (!Installer::isGravInstance(GRAV_ROOT)) {
  273. return false;
  274. }
  275. if (is_link(GRAV_ROOT . DS . 'index.php')) {
  276. Installer::setError(Installer::IS_LINK);
  277. return false;
  278. }
  279. if (method_exists($upgrader, 'meetsRequirements') &&
  280. method_exists($upgrader, 'minPHPVersion') &&
  281. !$upgrader->meetsRequirements()) {
  282. $error = [];
  283. $error[] = '<p>Grav has increased the minimum PHP requirement.<br />';
  284. $error[] = 'You are currently running PHP <strong>' . phpversion() . '</strong>';
  285. $error[] = ', but PHP <strong>' . $upgrader->minPHPVersion() . '</strong> is required.</p>';
  286. $error[] = '<p><a href="http://getgrav.org/blog/changing-php-requirements-to-5.5" class="button button-small secondary">Additional information</a></p>';
  287. Installer::setError(implode("\n", $error));
  288. return false;
  289. }
  290. $update = $upgrader->getAssets()['grav-update'];
  291. $tmp = Admin::getTempDir() . '/Grav-' . uniqid('', false);
  292. if ($tmp) {
  293. $file = self::_downloadSelfupgrade($update, $tmp);
  294. $folder = Installer::unZip($file, $tmp . '/zip');
  295. $keepFolder = false;
  296. } else {
  297. // If you make $tmp empty, you can install your local copy of Grav (for testing purposes only).
  298. $file = 'grav.zip';
  299. $folder = '~/phpstorm/grav-clones/grav';
  300. //$folder = '/home/matias/phpstorm/rockettheme/grav-devtools/grav-clones/grav';
  301. $keepFolder = true;
  302. }
  303. static::upgradeGrav($file, $folder, $keepFolder);
  304. $errorCode = Installer::lastErrorCode();
  305. if ($tmp) {
  306. Folder::delete($tmp);
  307. }
  308. return !(is_string($errorCode) || ($errorCode & (Installer::ZIP_OPEN_ERROR | Installer::ZIP_EXTRACT_ERROR)));
  309. }
  310. private static function upgradeGrav($zip, $folder, $keepFolder = false)
  311. {
  312. static $ignores = [
  313. 'backup',
  314. 'cache',
  315. 'images',
  316. 'logs',
  317. 'tmp',
  318. 'user',
  319. '.htaccess',
  320. 'robots.txt'
  321. ];
  322. if (!is_dir($folder)) {
  323. Installer::setError('Invalid source folder');
  324. }
  325. try {
  326. $script = $folder . '/system/install.php';
  327. /** Install $installer */
  328. if ((file_exists($script) && $install = include $script) && is_callable($install)) {
  329. $install($zip);
  330. } else {
  331. Installer::install(
  332. $zip,
  333. GRAV_ROOT,
  334. ['sophisticated' => true, 'overwrite' => true, 'ignore_symlinks' => true, 'ignores' => $ignores],
  335. $folder,
  336. $keepFolder
  337. );
  338. Cache::clearCache();
  339. }
  340. } catch (\Exception $e) {
  341. Installer::setError($e->getMessage());
  342. }
  343. }
  344. }