Gpm.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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\Upgrader;
  9. use Grav\Common\HTTP\Response;
  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. Cache::clearCache();
  99. return $messages ?: true;
  100. }
  101. /**
  102. * @param Package[]|string[]|string $packages
  103. * @param array $options
  104. *
  105. * @return string|bool
  106. */
  107. public static function update($packages, array $options)
  108. {
  109. $options['overwrite'] = true;
  110. return static::install($packages, $options);
  111. }
  112. /**
  113. * @param Package[]|string[]|string $packages
  114. * @param array $options
  115. *
  116. * @return string|bool
  117. */
  118. public static function uninstall($packages, array $options)
  119. {
  120. $options = array_merge(self::$options, $options);
  121. $packages = (array)$packages;
  122. $count = count($packages);
  123. $packages = array_filter(array_map(function ($p) {
  124. if (is_string($p)) {
  125. $p = strtolower($p);
  126. $plugin = static::GPM()->getInstalledPlugin($p);
  127. $p = $plugin ?: static::GPM()->getInstalledTheme($p);
  128. }
  129. return $p instanceof Package ? $p : false;
  130. }, $packages));
  131. if (!$options['skip_invalid'] && $count !== count($packages)) {
  132. return false;
  133. }
  134. foreach ($packages as $package) {
  135. $location = Grav::instance()['locator']->findResource($package->package_type . '://' . $package->slug);
  136. // Check destination
  137. Installer::isValidDestination($location);
  138. if (!$options['ignore_symlinks'] && Installer::lastErrorCode() === Installer::IS_LINK) {
  139. return false;
  140. }
  141. Installer::uninstall($location);
  142. $errorCode = Installer::lastErrorCode();
  143. if ($errorCode && $errorCode !== Installer::IS_LINK && $errorCode !== Installer::EXISTS) {
  144. $msg = Installer::lastErrorMsg();
  145. throw new \RuntimeException($msg);
  146. }
  147. if (count($packages) === 1) {
  148. $message = Installer::getMessage();
  149. if ($message) {
  150. return $message;
  151. }
  152. }
  153. }
  154. Cache::clearCache();
  155. return true;
  156. }
  157. /**
  158. * Direct install a file
  159. *
  160. * @param string $package_file
  161. *
  162. * @return string|bool
  163. */
  164. public static function directInstall($package_file)
  165. {
  166. if (!$package_file) {
  167. return Admin::translate('PLUGIN_ADMIN.NO_PACKAGE_NAME');
  168. }
  169. $tmp_dir = Grav::instance()['locator']->findResource('tmp://', true, true);
  170. $tmp_zip = $tmp_dir . '/Grav-' . uniqid('', false);
  171. if (Response::isRemote($package_file)) {
  172. $zip = GravGPM::downloadPackage($package_file, $tmp_zip);
  173. } else {
  174. $zip = GravGPM::copyPackage($package_file, $tmp_zip);
  175. }
  176. if (file_exists($zip)) {
  177. $tmp_source = $tmp_dir . '/Grav-' . uniqid('', false);
  178. $extracted = Installer::unZip($zip, $tmp_source);
  179. if (!$extracted) {
  180. Folder::delete($tmp_source);
  181. Folder::delete($tmp_zip);
  182. return Admin::translate('PLUGIN_ADMIN.PACKAGE_EXTRACTION_FAILED');
  183. }
  184. $type = GravGPM::getPackageType($extracted);
  185. if (!$type) {
  186. Folder::delete($tmp_source);
  187. Folder::delete($tmp_zip);
  188. return Admin::translate('PLUGIN_ADMIN.NOT_VALID_GRAV_PACKAGE');
  189. }
  190. if ($type === 'grav') {
  191. Installer::isValidDestination(GRAV_ROOT . '/system');
  192. if (Installer::IS_LINK === Installer::lastErrorCode()) {
  193. Folder::delete($tmp_source);
  194. Folder::delete($tmp_zip);
  195. return Admin::translate('PLUGIN_ADMIN.CANNOT_OVERWRITE_SYMLINKS');
  196. }
  197. static::upgradeGrav($zip, $extracted);
  198. } else {
  199. $name = GravGPM::getPackageName($extracted);
  200. if (!$name) {
  201. Folder::delete($tmp_source);
  202. Folder::delete($tmp_zip);
  203. return Admin::translate('PLUGIN_ADMIN.NAME_COULD_NOT_BE_DETERMINED');
  204. }
  205. $install_path = GravGPM::getInstallPath($type, $name);
  206. $is_update = file_exists($install_path);
  207. Installer::isValidDestination(GRAV_ROOT . DS . $install_path);
  208. if (Installer::lastErrorCode() === Installer::IS_LINK) {
  209. Folder::delete($tmp_source);
  210. Folder::delete($tmp_zip);
  211. return Admin::translate('PLUGIN_ADMIN.CANNOT_OVERWRITE_SYMLINKS');
  212. }
  213. Installer::install($zip, GRAV_ROOT,
  214. ['install_path' => $install_path, 'theme' => $type === 'theme', 'is_update' => $is_update],
  215. $extracted);
  216. }
  217. Folder::delete($tmp_source);
  218. if (Installer::lastErrorCode()) {
  219. return Installer::lastErrorMsg();
  220. }
  221. } else {
  222. return Admin::translate('PLUGIN_ADMIN.ZIP_PACKAGE_NOT_FOUND');
  223. }
  224. Folder::delete($tmp_zip);
  225. Cache::clearCache();
  226. return true;
  227. }
  228. /**
  229. * @param Package $package
  230. *
  231. * @return string
  232. */
  233. private static function download(Package $package, $license = null)
  234. {
  235. $query = '';
  236. if ($package->premium) {
  237. $query = \json_encode(array_merge($package->premium, [
  238. 'slug' => $package->slug,
  239. 'license_key' => $license,
  240. 'sid' => md5(GRAV_ROOT)
  241. ]));
  242. $query = '?d=' . base64_encode($query);
  243. }
  244. try {
  245. $contents = Response::get($package->zipball_url . $query, []);
  246. } catch (\Exception $e) {
  247. throw new \RuntimeException($e->getMessage());
  248. }
  249. $tmp_dir = Admin::getTempDir() . '/Grav-' . uniqid('', false);
  250. Folder::mkdir($tmp_dir);
  251. $bad_chars = array_merge(array_map('chr', range(0, 31)), ['<', '>', ':', '"', '/', '\\', '|', '?', '*']);
  252. $filename = $package->slug . str_replace($bad_chars, '', basename($package->zipball_url));
  253. $filename = preg_replace('/[\\\\\/:"*?&<>|]+/m', '-', $filename);
  254. file_put_contents($tmp_dir . DS . $filename . '.zip', $contents);
  255. return $tmp_dir . DS . $filename . '.zip';
  256. }
  257. /**
  258. * @param array $package
  259. * @param string $tmp
  260. *
  261. * @return string
  262. */
  263. private static function _downloadSelfupgrade(array $package, $tmp)
  264. {
  265. $output = Response::get($package['download'], []);
  266. Folder::mkdir($tmp);
  267. file_put_contents($tmp . DS . $package['name'], $output);
  268. return $tmp . DS . $package['name'];
  269. }
  270. /**
  271. * @return bool
  272. */
  273. public static function selfupgrade()
  274. {
  275. $upgrader = new Upgrader();
  276. if (!Installer::isGravInstance(GRAV_ROOT)) {
  277. return false;
  278. }
  279. if (is_link(GRAV_ROOT . DS . 'index.php')) {
  280. Installer::setError(Installer::IS_LINK);
  281. return false;
  282. }
  283. if (method_exists($upgrader, 'meetsRequirements') &&
  284. method_exists($upgrader, 'minPHPVersion') &&
  285. !$upgrader->meetsRequirements()) {
  286. $error = [];
  287. $error[] = '<p>Grav has increased the minimum PHP requirement.<br />';
  288. $error[] = 'You are currently running PHP <strong>' . phpversion() . '</strong>';
  289. $error[] = ', but PHP <strong>' . $upgrader->minPHPVersion() . '</strong> is required.</p>';
  290. $error[] = '<p><a href="http://getgrav.org/blog/changing-php-requirements-to-5.5" class="button button-small secondary">Additional information</a></p>';
  291. Installer::setError(implode("\n", $error));
  292. return false;
  293. }
  294. $update = $upgrader->getAssets()['grav-update'];
  295. $tmp = Admin::getTempDir() . '/Grav-' . uniqid('', false);
  296. if ($tmp) {
  297. $file = self::_downloadSelfupgrade($update, $tmp);
  298. $folder = Installer::unZip($file, $tmp . '/zip');
  299. $keepFolder = false;
  300. } else {
  301. // If you make $tmp empty, you can install your local copy of Grav (for testing purposes only).
  302. $file = 'grav.zip';
  303. $folder = '~/phpstorm/grav-clones/grav';
  304. //$folder = '/home/matias/phpstorm/rockettheme/grav-devtools/grav-clones/grav';
  305. $keepFolder = true;
  306. }
  307. static::upgradeGrav($file, $folder, $keepFolder);
  308. $errorCode = Installer::lastErrorCode();
  309. if ($tmp) {
  310. Folder::delete($tmp);
  311. }
  312. return !(is_string($errorCode) || ($errorCode & (Installer::ZIP_OPEN_ERROR | Installer::ZIP_EXTRACT_ERROR)));
  313. }
  314. private static function upgradeGrav($zip, $folder, $keepFolder = false)
  315. {
  316. static $ignores = [
  317. 'backup',
  318. 'cache',
  319. 'images',
  320. 'logs',
  321. 'tmp',
  322. 'user',
  323. '.htaccess',
  324. 'robots.txt'
  325. ];
  326. if (!is_dir($folder)) {
  327. Installer::setError('Invalid source folder');
  328. }
  329. try {
  330. $script = $folder . '/system/install.php';
  331. /** Install $installer */
  332. if ((file_exists($script) && $install = include $script) && is_callable($install)) {
  333. $install($zip);
  334. } else {
  335. Installer::install(
  336. $zip,
  337. GRAV_ROOT,
  338. ['sophisticated' => true, 'overwrite' => true, 'ignore_symlinks' => true, 'ignores' => $ignores],
  339. $folder,
  340. $keepFolder
  341. );
  342. Cache::clearCache();
  343. }
  344. } catch (\Exception $e) {
  345. Installer::setError($e->getMessage());
  346. }
  347. }
  348. }