summaryrefslogtreecommitdiffstatshomepage
path: root/core/modules/update/src/UpdateProcessor.php
blob: a34adb3bfd9c7c3d1dba1f3d47eaa2577fb88c19 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
<?php

namespace Drupal\update;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
use Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\PrivateKey;
use Drupal\Core\Queue\QueueFactory;

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

  /**
   * The update settings.
   *
   * @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;

  /**
   * Update key/value store.
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
   */
  protected $tempStore;

  /**
   * Update Fetch Task Store.
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface
   */
  protected $fetchTaskStore;

  /**
   * Update available releases store.
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
   */
  protected $availableReleasesTempStore;

  /**
   * Array of release history URLs that we have failed to fetch.
   *
   * @var array
   */
  protected $failed;

  /**
   * The state service.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected $stateStore;

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

  /**
   * The queue for fetching release history data.
   */
  protected array $fetchTasks;

  /**
   * Constructs an UpdateProcessor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Queue\QueueFactory $queue_factory
   *   The queue factory.
   * @param \Drupal\update\UpdateFetcherInterface $update_fetcher
   *   The update fetcher service.
   * @param \Drupal\Core\State\StateInterface $state_store
   *   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.
   * @param \Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface $key_value_expirable_factory
   *   The expirable key/value factory.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time service.
   */
  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,
    protected TimeInterface $time,
  ) {
    $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;
    $this->fetchTasks = [];
    $this->failed = [];
  }

  /**
   * {@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']] = $this->time->getRequestTime();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function fetchData() {
    $end = time() + $this->updateSettings->get('fetch.timeout');
    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');
    }
    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.
    $request_time_difference = $this->time->getCurrentTime() - $this->time->getRequestTime();
    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;
    $available = [];
    $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);
      // @todo Purge release data we don't need. See
      //   https://www.drupal.org/node/238950.
      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'] = $this->time->getRequestTime() + $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', $this->time->getRequestTime() + $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) {
      // 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;
    }
    $data = [];
    foreach ($xml as $k => $v) {
      $data[$k] = (string) $v;
    }
    $data['releases'] = [];
    if (isset($xml->releases)) {
      foreach ($xml->releases->children() as $release) {
        $version = (string) $release->version;
        $data['releases'][$version] = [];
        foreach ($release->children() as $k => $v) {
          $data['releases'][$version][$k] = (string) $v;
        }
        $data['releases'][$version]['terms'] = [];
        if ($release->terms) {
          foreach ($release->terms->children() as $term) {
            if (!isset($data['releases'][$version]['terms'][(string) $term->name])) {
              $data['releases'][$version]['terms'][(string) $term->name] = [];
            }
            $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);
  }

}