UpdateProcessor.php 8.43 KB
Newer Older
1
2
3
4
5
<?php

namespace Drupal\update;

use Drupal\Component\Utility\Crypt;
6
use Drupal\Core\Config\ConfigFactoryInterface;
7
use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
8
use Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface;
9
use Drupal\Core\State\StateInterface;
10
11
12
13
14
15
16
17
18
use Drupal\Core\PrivateKey;
use Drupal\Core\Queue\QueueFactory;

/**
 * Process project update information.
 */
class UpdateProcessor implements UpdateProcessorInterface {

  /**
19
   * The update settings.
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
   *
   * @var \Drupal\Core\Config\Config
   */
  protected $updateSettings;

  /**
   * The UpdateFetcher service.
   *
   * @var \Drupal\update\UpdateFetcherInterface
   */
  protected $updateFetcher;

  /**
   * The update fetch queue.
   *
   * @var \Drupal\Core\Queue\QueueInterface
   */
  protected $fetchQueue;

  /**
40
   * Update key/value store.
41
42
43
44
45
46
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
   */
  protected $tempStore;

  /**
47
   * Update Fetch Task Store.
48
49
50
51
52
53
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface
   */
  protected $fetchTaskStore;

  /**
54
   * Update available releases store.
55
56
57
58
59
60
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
   */
  protected $availableReleasesTempStore;

  /**
61
   * Array of release history URLs that we have failed to fetch.
62
63
64
65
66
67
68
69
   *
   * @var array
   */
  protected $failed;

  /**
   * The state service.
   *
70
   * @var \Drupal\Core\State\StateInterface
71
72
73
74
75
76
77
78
79
80
81
   */
  protected $stateStore;

  /**
   * The private key.
   *
   * @var \Drupal\Core\PrivateKey
   */
  protected $privateKey;

  /**
82
   * Constructs an UpdateProcessor.
83
   *
84
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
85
86
87
88
89
   *   The config factory.
   * @param \Drupal\Core\Queue\QueueFactory $queue_factory
   *   The queue factory
   * @param \Drupal\update\UpdateFetcherInterface $update_fetcher
   *   The update fetcher service
90
   * @param \Drupal\Core\State\StateInterface $state_store
91
92
93
94
95
   *   The state service.
   * @param \Drupal\Core\PrivateKey $private_key
   *   The private key factory service.
   * @param \Drupal\Core\KeyValueStore\KeyValueFactoryInterface $key_value_factory
   *   The key/value factory.
96
   * @param \Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface $key_value_expirable_factory
97
98
   *   The expirable key/value factory.
   */
99
  public function __construct(ConfigFactoryInterface $config_factory, QueueFactory $queue_factory, UpdateFetcherInterface $update_fetcher, StateInterface $state_store, PrivateKey $private_key, KeyValueFactoryInterface $key_value_factory, KeyValueExpirableFactoryInterface $key_value_expirable_factory) {
100
101
102
103
104
105
106
107
    $this->updateFetcher = $update_fetcher;
    $this->updateSettings = $config_factory->get('update.settings');
    $this->fetchQueue = $queue_factory->get('update_fetch_tasks');
    $this->tempStore = $key_value_expirable_factory->get('update');
    $this->fetchTaskStore = $key_value_factory->get('update_fetch_task');
    $this->availableReleasesTempStore = $key_value_expirable_factory->get('update_available_releases');
    $this->stateStore = $state_store;
    $this->privateKey = $private_key;
108
109
    $this->fetchTasks = [];
    $this->failed = [];
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
  }

  /**
   * {@inheritdoc}
   */
  public function createFetchTask($project) {
    if (empty($this->fetchTasks)) {
      $this->fetchTasks = $this->fetchTaskStore->getAll();
    }
    if (empty($this->fetchTasks[$project['name']])) {
      $this->fetchQueue->createItem($project);
      $this->fetchTaskStore->set($project['name'], $project);
      $this->fetchTasks[$project['name']] = REQUEST_TIME;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function fetchData() {
    $end = time() + $this->updateSettings->get('fetch.timeout');
131
132
133
134
135
    if ($this->fetchQueue->numberOfItems()) {
      // Delete any stored project data as that needs refreshing when
      // update_calculate_project_data() is called.
      $this->tempStore->delete('update_project_data');
    }
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
    while (time() < $end && ($item = $this->fetchQueue->claimItem())) {
      $this->processFetchTask($item->data);
      $this->fetchQueue->deleteItem($item);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function processFetchTask($project) {
    global $base_url;

    // This can be in the middle of a long-running batch, so REQUEST_TIME won't
    // necessarily be valid.
    $request_time_difference = time() - REQUEST_TIME;
    if (empty($this->failed)) {
      // If we have valid data about release history XML servers that we have
      // failed to fetch from on previous attempts, load that.
      $this->failed = $this->tempStore->get('fetch_failures');
    }

    $max_fetch_attempts = $this->updateSettings->get('fetch.max_attempts');

    $success = FALSE;
160
    $available = [];
161
162
163
164
165
166
167
168
169
    $site_key = Crypt::hmacBase64($base_url, $this->privateKey->get());
    $fetch_url_base = $this->updateFetcher->getFetchBaseUrl($project);
    $project_name = $project['name'];

    if (empty($this->failed[$fetch_url_base]) || $this->failed[$fetch_url_base] < $max_fetch_attempts) {
      $data = $this->updateFetcher->fetchProjectData($project, $site_key);
    }
    if (!empty($data)) {
      $available = $this->parseXml($data);
170
      // @todo Purge release data we don't need. See
171
      //   https://www.drupal.org/node/238950.
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
      if (!empty($available)) {
        // Only if we fetched and parsed something sane do we return success.
        $success = TRUE;
      }
    }
    else {
      $available['project_status'] = 'not-fetched';
      if (empty($this->failed[$fetch_url_base])) {
        $this->failed[$fetch_url_base] = 1;
      }
      else {
        $this->failed[$fetch_url_base]++;
      }
    }

    $frequency = $this->updateSettings->get('check.interval_days');
    $available['last_fetch'] = REQUEST_TIME + $request_time_difference;
    $this->availableReleasesTempStore->setWithExpire($project_name, $available, $request_time_difference + (60 * 60 * 24 * $frequency));

    // Stash the $this->failed data back in the DB for the next 5 minutes.
    $this->tempStore->setWithExpire('fetch_failures', $this->failed, $request_time_difference + (60 * 5));

    // Whether this worked or not, we did just (try to) check for updates.
    $this->stateStore->set('update.last_check', REQUEST_TIME + $request_time_difference);

    // Now that we processed the fetch task for this project, clear out the
    // record for this task so we're willing to fetch again.
    $this->fetchTaskStore->delete($project_name);

    return $success;
  }

  /**
   * Parses the XML of the Drupal release history info files.
   *
   * @param string $raw_xml
   *   A raw XML string of available release data for a given project.
   *
   * @return array
   *   Array of parsed data about releases for a given project, or NULL if there
   *   was an error parsing the string.
   */
  protected function parseXml($raw_xml) {
    try {
      $xml = new \SimpleXMLElement($raw_xml);
    }
    catch (\Exception $e) {
      // SimpleXMLElement::__construct produces an E_WARNING error message for
      // each error found in the XML data and throws an exception if errors
      // were detected. Catch any exception and return failure (NULL).
      return NULL;
    }
    // If there is no valid project data, the XML is invalid, so return failure.
    if (!isset($xml->short_name)) {
      return NULL;
    }
228
    $data = [];
229
230
231
    foreach ($xml as $k => $v) {
      $data[$k] = (string) $v;
    }
232
    $data['releases'] = [];
233
234
235
    if (isset($xml->releases)) {
      foreach ($xml->releases->children() as $release) {
        $version = (string) $release->version;
236
        $data['releases'][$version] = [];
237
238
239
        foreach ($release->children() as $k => $v) {
          $data['releases'][$version][$k] = (string) $v;
        }
240
        $data['releases'][$version]['terms'] = [];
241
242
243
        if ($release->terms) {
          foreach ($release->terms->children() as $term) {
            if (!isset($data['releases'][$version]['terms'][(string) $term->name])) {
244
              $data['releases'][$version]['terms'][(string) $term->name] = [];
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
            }
            $data['releases'][$version]['terms'][(string) $term->name][] = (string) $term->value;
          }
        }
      }
    }
    return $data;
  }

  /**
   * {@inheritdoc}
   */
  public function numberOfQueueItems() {
    return $this->fetchQueue->numberOfItems();
  }

  /**
   * {@inheritdoc}
   */
  public function claimQueueItem() {
    return $this->fetchQueue->claimItem();
  }

  /**
   * {@inheritdoc}
   */
  public function deleteQueueItem($item) {
    return $this->fetchQueue->deleteItem($item);
  }

}