PageRenderTime 38ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/user/plugins/admin/classes/gpm.php

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