Project.php

  1. 8.0.x lib/Drush/UpdateService/Project.php
  2. 7.x lib/Drush/UpdateService/Project.php
  3. master lib/Drush/UpdateService/Project.php

Namespace

Drush\UpdateService

Classes

Namesort descending Description
Project Representation of a project's release info from the update service.

File

lib/Drush/UpdateService/Project.php
View source
  1. <?php
  2. namespace Drush\UpdateService;
  3. use Drush\Log\LogLevel;
  4. /**
  5. * Representation of a project's release info from the update service.
  6. */
  7. class Project {
  8. private $parsed;
  9. /**
  10. * Constructor.
  11. *
  12. * @param string $project_name
  13. * Project name.
  14. *
  15. * @param \SimpleXMLElement $xml
  16. * XML data.
  17. */
  18. function __construct(\SimpleXMLElement $xml) {
  19. // Check if the xml contains an error on the project.
  20. if ($error = $xml->xpath('/error')) {
  21. $error = (string)$error[0];
  22. if (strpos($error, 'No release history available for') === 0) {
  23. $project_status = 'unsupported';
  24. }
  25. elseif (strpos($error, 'No release history was found for the requested project') === 0) {
  26. $project_status = 'unknown';
  27. }
  28. // Any other error we are not aware of.
  29. else {
  30. $project_status = 'unknown';
  31. }
  32. }
  33. // The xml has a project, but still it can have errors.
  34. else {
  35. $this->parsed = self::parseXml($xml);
  36. if (empty($this->parsed['releases'])) {
  37. $error = dt('No available releases found for the requested project (!name).', array('!name' => $this->parsed['short_name']));
  38. $project_status = 'unknown';
  39. }
  40. else {
  41. $error = FALSE;
  42. $project_status = $xml->xpath('/project/project_status');
  43. $project_status = (string)$project_status[0];
  44. }
  45. }
  46. $this->project_status = $project_status;
  47. $this->error = $error;
  48. if ($error) {
  49. drush_set_error('DRUSH_RELEASE_INFO_ERROR', $error);
  50. }
  51. }
  52. /**
  53. * Downloads release info xml from update service.
  54. *
  55. * @param array $request
  56. * A request array.
  57. * @param int $cache_duration
  58. * Cache lifetime.
  59. *
  60. * @return \Drush\UpdateService\Project
  61. */
  62. public static function getInstance(array $request, $cache_duration = ReleaseInfo::CACHE_LIFETIME) {
  63. $url = self::buildFetchUrl($request);
  64. drush_log(dt('Downloading release history from !url', array('!url' => $url)));
  65. $path = drush_download_file($url, drush_tempnam($request['name']), $cache_duration);
  66. $xml = simplexml_load_file($path);
  67. if (!$xml) {
  68. $error = dt('Failed to get available update data from !url', array('!url' => $url));
  69. return drush_set_error('DRUSH_RELEASE_INFO_ERROR', $error);
  70. }
  71. return new Project($xml);
  72. }
  73. /**
  74. * Returns URL to the updates service for the given request.
  75. *
  76. * @param array $request
  77. * A request array.
  78. *
  79. * @return string
  80. * URL to the updates service.
  81. *
  82. * @see \Drupal\update\UpdateFetcher::buildFetchUrl()
  83. */
  84. public static function buildFetchUrl(array $request) {
  85. $status_url = isset($request['status url']) ? $request['status url'] : ReleaseInfo::DEFAULT_URL;
  86. return $status_url . '/' . $request['name'] . '/' . $request['drupal_version'];
  87. }
  88. /**
  89. * Parses update service xml.
  90. *
  91. * @param \SimpleXMLElement $xml
  92. * XML element from the updates service.
  93. *
  94. * @return array
  95. * Project update information.
  96. */
  97. private static function parseXml(\SimpleXMLElement $xml) {
  98. $project_info = array();
  99. // Extract general project info.
  100. $items = array('title', 'short_name', 'dc:creator', 'type', 'api_version',
  101. 'recommended_major', 'supported_majors', 'default_major',
  102. 'project_status', 'link',
  103. );
  104. foreach ($items as $item) {
  105. if (array_key_exists($item, (array)$xml)) {
  106. $value = $xml->xpath($item);
  107. $project_info[$item] = (string)$value[0];
  108. }
  109. }
  110. // Parse project type.
  111. $project_types = array(
  112. 'core' => 'project_core',
  113. 'profile' => 'project_distribution',
  114. 'module' => 'project_module',
  115. 'theme' => 'project_theme',
  116. 'theme engine' => 'project_theme_engine',
  117. 'translation' => 'project_translation',
  118. 'utility' => 'project_drupalorg',
  119. );
  120. $type = $project_info['type'];
  121. // Probably unused but kept for possible legacy compat.
  122. $type = ($type == 'profile-legacy') ? 'profile' : $type;
  123. $project_info['project_type'] = array_search($type, $project_types);
  124. // Extract project terms.
  125. $project_info['terms'] = array();
  126. if ($xml->terms) {
  127. foreach ($xml->terms->children() as $term) {
  128. $term_name = (string) $term->name;
  129. $term_value = (string) $term->value;
  130. if (!isset($project_info[$term_name])) {
  131. $project_info['terms'][$term_name] = array();
  132. }
  133. $project_info['terms'][$term_name][] = $term_value;
  134. }
  135. }
  136. // Extract and parse releases info.
  137. // In addition to the info in the update service, here we calculate
  138. // release statuses as Recommended, Security, etc.
  139. $recommended_major = empty($project_info['recommended_major']) ? '' : $project_info['recommended_major'];
  140. $supported_majors = empty($project_info['supported_majors']) ? array() : array_flip(explode(',', $project_info['supported_majors']));
  141. $items = array(
  142. 'name', 'date', 'status', 'type',
  143. 'version', 'tag', 'version_major', 'version_patch', 'version_extra',
  144. 'release_link', 'download_link', 'mdhash', 'filesize',
  145. );
  146. $releases = array();
  147. $releases_xml = @$xml->xpath("/project/releases/release[status='published']");
  148. foreach ($releases_xml as $release) {
  149. $release_info = array();
  150. $statuses = array();
  151. // Extract general release info.
  152. foreach ($items as $item) {
  153. if (array_key_exists($item, $release)) {
  154. $value = $release->xpath($item);
  155. $release_info[$item] = (string)$value[0];
  156. }
  157. }
  158. // Extract release terms.
  159. $release_info['terms'] = array();
  160. if ($release->terms) {
  161. foreach ($release->terms->children() as $term) {
  162. $term_name = (string) $term->name;
  163. $term_value = (string) $term->value;
  164. if (!isset($release_info['terms'][$term_name])) {
  165. $release_info['terms'][$term_name] = array();
  166. }
  167. $release_info['terms'][$term_name][] = $term_value;
  168. // Add "Security" for security updates, and nothing
  169. // for the other kinds.
  170. if (strpos($term_value, "Security") !== FALSE) {
  171. $statuses[] = "Security";
  172. }
  173. }
  174. }
  175. // Extract files.
  176. $release_info['files'] = array();
  177. foreach ($release->files->children() as $file) {
  178. // Normalize keys to match the ones in the release info.
  179. $item = array(
  180. 'download_link' => (string) $file->url,
  181. 'date' => (string) $file->filedate,
  182. 'mdhash' => (string) $file->md5,
  183. 'filesize' => (string) $file->size,
  184. 'archive_type' => (string) $file->archive_type,
  185. );
  186. if (!empty($file->variant)) {
  187. $item['variant'] = (string) $file->variant;
  188. }
  189. $release_info['files'][] = $item;
  190. }
  191. // Calculate statuses.
  192. if (array_key_exists($release_info['version_major'], $supported_majors)) {
  193. $statuses[] = "Supported";
  194. unset($supported_majors[$release_info['version_major']]);
  195. }
  196. if ($release_info['version_major'] == $recommended_major) {
  197. if (!isset($latest_version)) {
  198. $latest_version = $release_info['version'];
  199. }
  200. // The first stable version (no 'version extra') in the recommended major
  201. // is the recommended release
  202. if (empty($release_info['version_extra']) && (!isset($recommended_version))) {
  203. $statuses[] = "Recommended";
  204. $recommended_version = $release_info['version'];
  205. }
  206. }
  207. if (!empty($release_info['version_extra']) && ($release_info['version_extra'] == "dev")) {
  208. $statuses[] = "Development";
  209. }
  210. $release_info['release_status'] = $statuses;
  211. $releases[$release_info['version']] = $release_info;
  212. }
  213. // If there is no -stable- release in the recommended major,
  214. // then take the latest version in the recommended major to be
  215. // the recommended release.
  216. if (!isset($recommended_version) && isset($latest_version)) {
  217. $recommended_version = $latest_version;
  218. $releases[$recommended_version]['release_status'][] = "Recommended";
  219. }
  220. $project_info['releases'] = $releases;
  221. if (isset($recommended_version)) {
  222. $project_info['recommended'] = $recommended_version;
  223. }
  224. return $project_info;
  225. }
  226. /**
  227. * Gets the project type.
  228. *
  229. * @return string
  230. * Type of the project.
  231. */
  232. public function getType() {
  233. return $this->parsed['project_type'];
  234. }
  235. /**
  236. * Gets the project status in the update service.
  237. *
  238. * This is the project status in drupal.org: insecure, revoked, published etc.
  239. *
  240. * @return string
  241. */
  242. public function getStatus() {
  243. return $this->project_status;
  244. }
  245. /**
  246. * Whether this object represents a project in the update service or an error.
  247. */
  248. public function isValid() {
  249. return ($this->error === FALSE);
  250. }
  251. /**
  252. * Gets the parsed xml.
  253. *
  254. * @return array or FALSE if the xml has an error.
  255. */
  256. public function getInfo() {
  257. return (!$this->error) ? $this->parsed : FALSE;
  258. }
  259. /**
  260. * Helper to pick the best release in a list of candidates.
  261. *
  262. * The best one is the first stable release if there are stable
  263. * releases; otherwise, it will be the first of the candidates.
  264. *
  265. * @param array $releases
  266. * Array of release arrays.
  267. *
  268. * @return array|bool
  269. */
  270. private static function getBestRelease(array $releases) {
  271. if (empty($releases)) {
  272. return FALSE;
  273. }
  274. else {
  275. // If there are releases found, let's try first to fetch one with no
  276. // 'version_extra'. Otherwise, use all.
  277. $stable_releases = array();
  278. foreach ($releases as $one_release) {
  279. if (!array_key_exists('version_extra', $one_release)) {
  280. $stable_releases[] = $one_release;
  281. }
  282. }
  283. if (!empty($stable_releases)) {
  284. $releases = $stable_releases;
  285. }
  286. }
  287. // First published release is just the first value in $releases.
  288. return reset($releases);
  289. }
  290. private function searchReleases($key, $value) {
  291. $releases = array();
  292. foreach ($this->parsed['releases'] as $version => $release) {
  293. if ($release['status'] == 'published' && isset($release[$key]) && $release[$key] == $value) {
  294. $releases[$version] = $release;
  295. }
  296. }
  297. return $releases;
  298. }
  299. /**
  300. * Returns the specific release that matches the request version.
  301. *
  302. * @param string $version
  303. * Version of the release to pick.
  304. * @return array|bool
  305. * The release or FALSE if no version specified or no release found.
  306. */
  307. public function getSpecificRelease($version = NULL) {
  308. if (!empty($version)) {
  309. $matches = array();
  310. // See if we only have a branch version.
  311. if (preg_match('/^\d+\.x-(\d+)$/', $version, $matches)) {
  312. $releases = $this->searchReleases('version_major', $matches[1]);
  313. }
  314. else {
  315. // In some cases, the request only says something like '7.x-3.x' but the
  316. // version strings include '-dev' on the end, so we need to append that
  317. // here for the xpath to match below.
  318. if (substr($version, -2) == '.x') {
  319. $version .= '-dev';
  320. }
  321. $releases = $this->searchReleases('version', $version);
  322. }
  323. if (empty($releases)) {
  324. return FALSE;
  325. }
  326. return self::getBestRelease($releases);
  327. }
  328. return array();
  329. }
  330. /**
  331. * Pick the first dev release from XML list.
  332. *
  333. * @return array|bool
  334. * The selected release xml object or FALSE.
  335. */
  336. public function getDevRelease() {
  337. $releases = $this->searchReleases('version_extra', 'dev');
  338. return self::getBestRelease($releases);
  339. }
  340. /**
  341. * Pick most appropriate release from XML list.
  342. *
  343. * @return array|bool
  344. * The selected release xml object or FALSE.
  345. */
  346. public function getRecommendedOrSupportedRelease() {
  347. $majors = array();
  348. $recommended_major = empty($this->parsed['recommended_major']) ? 0 : $this->parsed['recommended_major'];
  349. if ($recommended_major != 0) {
  350. $majors[] = $this->parsed['recommended_major'];
  351. }
  352. $supported = explode(',', $this->parsed['supported_majors']);
  353. foreach ($supported as $v) {
  354. if ($v != $recommended_major) {
  355. $majors[] = $v;
  356. }
  357. }
  358. $releases = array();
  359. foreach ($majors as $major) {
  360. $releases = $this->searchReleases('version_major', $major);
  361. if (!empty($releases)) {
  362. break;
  363. }
  364. }
  365. return self::getBestRelease($releases);
  366. }
  367. /**
  368. * Comparison routine to order releases by date.
  369. *
  370. * @param array $a
  371. * Release to compare.
  372. * @param array $b
  373. * Release to compare.
  374. *
  375. * @return int
  376. * -1, 0 or 1 whether $a is greater, equal or lower than $b.
  377. */
  378. private static function compareDates(array $a, array $b) {
  379. if ($a['date'] == $b['date']) {
  380. return ($a['version_major'] > $b['version_major']) ? -1 : 1;
  381. }
  382. if ($a['version_major'] == $b['version_major']) {
  383. return ($a['date'] > $b['date']) ? -1 : 1;
  384. }
  385. return ($a['version_major'] > $b['version_major']) ? -1 : 1;
  386. }
  387. /**
  388. * Comparison routine to order releases by version.
  389. *
  390. * @param array $a
  391. * Release to compare.
  392. * @param array $b
  393. * Release to compare.
  394. *
  395. * @return int
  396. * -1, 0 or 1 whether $a is greater, equal or lower than $b.
  397. */
  398. private static function compareVersions(array $a, array $b) {
  399. $defaults = array(
  400. 'version_patch' => '',
  401. 'version_extra' => '',
  402. 'date' => 0,
  403. );
  404. $a += $defaults;
  405. $b += $defaults;
  406. if ($a['version_major'] != $b['version_major']) {
  407. return ($a['version_major'] > $b['version_major']) ? -1 : 1;
  408. }
  409. else if ($a['version_patch'] != $b['version_patch']) {
  410. return ($a['version_patch'] > $b['version_patch']) ? -1 : 1;
  411. }
  412. else if ($a['version_extra'] != $b['version_extra']) {
  413. // Don't rely on version_extra alphabetical order.
  414. return ($a['date'] > $b['date']) ? -1 : 1;
  415. }
  416. return 0;
  417. }
  418. /**
  419. * Filter project releases by a criteria and returns a list.
  420. *
  421. * If no filter is provided, the first Recommended, Supported, Security
  422. * or Development release on each major version will be shown.
  423. *
  424. * @param string $filter
  425. * Valid values:
  426. * - 'all': Select all releases.
  427. * - 'dev': Select all development releases.
  428. * @param string $installed_version
  429. * Version string. If provided, Select all releases in the same
  430. * version_major branch until the provided one is found.
  431. * On any other branch, the default behaviour will be applied.
  432. *
  433. * @return array
  434. * List of releases matching the filter criteria.
  435. */
  436. function filterReleases($filter = '', $installed_version = NULL) {
  437. $releases = $this->parsed['releases'];
  438. usort($releases, array($this, 'compareDates'));
  439. $installed_version = pm_parse_version($installed_version);
  440. // Iterate through and filter out the releases we're interested in.
  441. $options = array();
  442. $limits_list = array();
  443. foreach ($releases as $release) {
  444. $eligible = FALSE;
  445. // Mark as eligible if the filter criteria matches.
  446. if ($filter == 'all') {
  447. $eligible = TRUE;
  448. }
  449. elseif ($filter == 'dev') {
  450. if (!empty($release['version_extra']) && ($release['version_extra'] == 'dev')) {
  451. $eligible = TRUE;
  452. }
  453. }
  454. // The Drupal core version scheme (ex: 7.31) is different to
  455. // other projects (ex 7.x-3.2). We need to manage this special case.
  456. elseif (($this->getType() != 'core') && ($installed_version['version_major'] == $release['version_major'])) {
  457. // In case there's no filter, select all releases until the installed one.
  458. // Always show the dev release.
  459. if (isset($release['version_extra']) && ($release['version_extra'] == 'dev')) {
  460. $eligible = TRUE;
  461. }
  462. else {
  463. if (self::compareVersions($release, $installed_version) < 1) {
  464. $eligible = TRUE;
  465. }
  466. }
  467. }
  468. // Otherwise, pick only the first release in each status.
  469. // For example after we pick out the first security release,
  470. // we won't pick any other. We do this on a per-major-version basis,
  471. // though, so if a project has three major versions, then we will
  472. // pick out the first security release from each.
  473. else {
  474. foreach ($release['release_status'] as $one_status) {
  475. $test_key = $release['version_major'] . $one_status;
  476. if (empty($limits_list[$test_key])) {
  477. $limits_list[$test_key] = TRUE;
  478. $eligible = TRUE;
  479. }
  480. }
  481. }
  482. if ($eligible) {
  483. $options[$release['version']] = $release;
  484. }
  485. }
  486. // Add Installed status.
  487. if (!is_null($installed_version) && isset($options[$installed_version['version']])) {
  488. $options[$installed_version['version']]['release_status'][] = 'Installed';
  489. }
  490. return $options;
  491. }
  492. /**
  493. * Prints release notes for given projects.
  494. *
  495. * @param string $version
  496. * Version of the release to get notes.
  497. * @param bool $print_status
  498. * Whether to print a informative note.
  499. * @param string $tmpfile
  500. * If provided, a file that contains contents to show before the
  501. * release notes.
  502. */
  503. function getReleaseNotes($version = NULL, $print_status = TRUE, $tmpfile = NULL) {
  504. $project_name = $this->parsed['short_name'];
  505. if (!isset($tmpfile)) {
  506. $tmpfile = drush_tempnam('rln-' . $project_name . '.');
  507. }
  508. // Select versions to show.
  509. $versions = array();
  510. if (!is_null($version)) {
  511. $versions[] = $version;
  512. }
  513. else {
  514. // If requested project is installed,
  515. // show release notes for the installed version and all newer versions.
  516. if (isset($this->parsed['recommended'], $this->parsed['installed'])) {
  517. $releases = array_reverse($this->parsed['releases']);
  518. foreach($releases as $version => $release) {
  519. if ($release['date'] >= $this->parsed['releases'][$this->parsed['installed']]['date']) {
  520. $release += array('version_extra' => '');
  521. $this->parsed['releases'][$this->parsed['installed']] += array('version_extra' => '');
  522. if ($release['version_extra'] == 'dev' && $this->parsed['releases'][$this->parsed['installed']]['version_extra'] != 'dev') {
  523. continue;
  524. }
  525. $versions[] = $version;
  526. }
  527. }
  528. }
  529. else {
  530. // Project is not installed and user did not specify a version,
  531. // so show the release notes for the recommended version.
  532. $versions[] = $this->parsed['recommended'];
  533. }
  534. }
  535. foreach ($versions as $version) {
  536. if (!isset($this->parsed['releases'][$version]['release_link'])) {
  537. drush_log(dt("Project !project does not have release notes for version !version.", array('!project' => $project_name, '!version' => $version)), LogLevel::WARNING);
  538. continue;
  539. }
  540. // Download the release node page and get the html as xml to explore it.
  541. $release_link = $this->parsed['releases'][$version]['release_link'];
  542. $filename = drush_download_file($release_link, drush_tempnam($project_name));
  543. @$dom = \DOMDocument::loadHTMLFile($filename);
  544. if ($dom) {
  545. drush_log(dt("Successfully parsed and loaded the HTML contained in the release notes' page for !project (!version) project.", array('!project' => $project_name, '!version' => $version)), LogLevel::NOTICE);
  546. }
  547. else {
  548. drush_log(dt("Error while requesting the release notes page for !project project.", array('!project' => $project_name)), LogLevel::ERROR);
  549. continue;
  550. }
  551. $xml = simplexml_import_dom($dom);
  552. // Extract last update time and the notes.
  553. $last_updated = $xml->xpath('//div[contains(@class,"views-field-changed")]');
  554. $last_updated = $last_updated[0]->asXML();
  555. $notes = $xml->xpath('//div[contains(@class,"field-name-body")]');
  556. $notes = (!empty($notes)) ? $notes[0]->asXML() : dt("There're no release notes.");
  557. // Build the notes header.
  558. $header = array();
  559. $header[] = '<hr>';
  560. $header[] = dt("> RELEASE NOTES FOR '!name' PROJECT, VERSION !version:", array('!name' => strtoupper($project_name), '!version' => $version));
  561. $header[] = dt("> !last_updated.", array('!last_updated' => trim(drush_html_to_text($last_updated))));
  562. if ($print_status) {
  563. $header[] = '> ' . implode(', ', $this->parsed['releases'][$version]['release_status']);
  564. }
  565. $header[] = '<hr>';
  566. // Finally add the release notes for the requested project to the tmpfile.
  567. $content = implode("\n", $header) . "\n" . $notes . "\n";
  568. #TODO# accept $html as a method argument
  569. if (!drush_get_option('html', FALSE)) {
  570. $content = drush_html_to_text($content, array('br', 'p', 'ul', 'ol', 'li', 'hr'));
  571. }
  572. file_put_contents($tmpfile, $content, FILE_APPEND);
  573. }
  574. #TODO# don't print! Just return the filename
  575. drush_print_file($tmpfile);
  576. }
  577. }