Projet

Général

Profil

Paste
Télécharger (20,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / l10n_update / l10n_update.inc @ 64ad485a

1
<?php
2

    
3
/**
4
 * @file
5
 *   Reusable API for l10n remote updates.
6
 */
7

    
8
include_once DRUPAL_ROOT . '/includes/locale.inc';
9
module_load_include('locale.inc', 'l10n_update');
10

    
11
/**
12
 * Default update server, filename and URL.
13
 */
14
define('L10N_UPDATE_DEFAULT_SERVER', 'localize.drupal.org');
15
define('L10N_UPDATE_DEFAULT_SERVER_URL', 'http://localize.drupal.org/l10n_server.xml');
16
define('L10N_UPDATE_DEFAULT_UPDATE_URL', 'http://ftp.drupal.org/files/translations/%core/%project/%project-%release.%language.po');
17

    
18
// Translation filename, will be used just for local imports
19
define('L10N_UPDATE_DEFAULT_FILENAME', '%project-%release.%language.po');
20

    
21
// Translation status: String imported from po
22
define('L10N_UPDATE_STRING_DEFAULT', 0);
23

    
24
// Translation status: Custom string, overridden original import
25
define('L10N_UPDATE_STRING_CUSTOM', 1);
26

    
27
/**
28
 * Retrieve data for default server.
29
 *
30
 * @return array
31
 *   Server parameters:
32
 *     name :       Localization server name
33
 *     server_url : Localization server URL where language list can be retrieved.
34
 *     update_url : URL containing po file pattern.
35
 */
36
function l10n_update_default_server() {
37
  return array(
38
    'name' => variable_get('l10n_update_default_server', L10N_UPDATE_DEFAULT_SERVER),
39
    'server_url' => variable_get('l10n_update_default_server_url', L10N_UPDATE_DEFAULT_SERVER_URL),
40
    'update_url' => variable_get('l10n_update_default_update_url', L10N_UPDATE_DEFAULT_UPDATE_URL),
41
  );
42
}
43

    
44
/**
45
 * Download and import remote translation file.
46
 *
47
 * @param $download_url
48
 *   Download URL.
49
 * @param $locale
50
 *   Language code.
51
 * @param $mode
52
 *   Download mode. How to treat exising and modified translations.
53
 *
54
 * @return boolean
55
 *   TRUE on success.
56
 */
57
function l10n_update_download_import($download_url, $locale, $mode = LOCALE_IMPORT_OVERWRITE) {
58
  if ($file = l10n_update_download_file($download_url)) {
59
    $result = l10n_update_import_file($file, $locale, $mode);
60
    return $result;
61
  }
62
}
63

    
64
/**
65
 * Import local file into the database.
66
 *
67
 * @param $file
68
 *   File object of localy stored file
69
 *   or path to localy stored file.
70
 * @param $locale
71
 *   Language code.
72
 * @param $mode
73
 *   Download mode. How to treat exising and modified translations.
74
 *
75
 * @return boolean
76
 *   Result array on success. FALSE on failure
77
 */
78
function l10n_update_import_file($file, $locale, $mode = LOCALE_IMPORT_OVERWRITE) {
79
  // If the file is a uri, create a $file object
80
  if (is_string($file)) {
81
    $uri = $file;
82
    $file = new stdClass();
83
    $file->uri = $uri;
84
    $file->filename = $uri;
85
  }
86
  return _l10n_update_locale_import_po($file, $locale, $mode, 'default');
87
}
88

    
89
/**
90
 * Get remote file and download it to a temporary path.
91
 *
92
 * @param $download_url
93
 *   URL of remote file.
94
 * @param $destination
95
 *   URL of local destination file. By default the download will be stored
96
 *   in a temporary file.
97
 */
98
function l10n_update_download_file($download_url, $destination = NULL) {
99
  $t = get_t();
100
  $variables['%download_link'] = $download_url;
101

    
102
  // Create temporary file or use specified file destination.
103
  // Temporary files get a 'translation-' file name prefix.
104
  $file = $destination ? $destination : drupal_tempnam(file_directory_temp(), 'translation-');
105

    
106
  if ($file) {
107
    $variables['%tmpfile'] = $file;
108
    // We download and store the file (in one if statement! Isnt't that neat ;) ).
109
    // @todo remove the timeout once we use the batch API to download the files.
110
    if (($contents = drupal_http_request($download_url, array('timeout' => 90))) && $contents->code == 200 && $file_result = file_put_contents($file, $contents->data)) {
111
      watchdog('l10n_update', 'Successfully downloaded %download_link to %tmpfile', $variables);
112
      return $file;
113
    }
114
    else {
115
      if (isset($contents->error)) {
116
        watchdog('l10n_update', 'An error occured during the download operation: %error.', array('%error' => $contents->error), WATCHDOG_ERROR);
117
      }
118
      elseif (isset($contents->code) && $contents->code != 200) {
119
        watchdog('l10n_update', 'An error occured during the download operation: HTTP status code %code.', array('%code' => $contents->code), WATCHDOG_ERROR);
120
      }
121
      if (isset($file_result)) {
122
        // file_put_contents() was called but returned FALSE.
123
        watchdog('l10n_update', 'Unable to save %download_link file to %tmpfile.', $variables, WATCHDOG_ERROR);
124
      }
125
    }
126

    
127
  }
128
  else {
129
    $variables['%tmpdir'] = file_directory_temp();
130
    watchdog('l10n_update', 'Error creating temporary file for download in %tmpdir. Remote file is %download_link.', $variables, WATCHDOG_ERROR);
131
  }
132
}
133

    
134
/**
135
 * Get names for the language list from locale system.
136
 *
137
 * @param $string_list
138
 *   Comma separated list of language codes.
139
 *   Language codes must exist in languages from _locale_get_predefined_list().
140
 * @return array
141
 *   Array of language names keyed by language code.
142
 */
143
function l10n_update_get_language_names($string_list) {
144
  $t = get_t();
145
  $language_codes = array_map('trim', explode(',', $string_list));
146
  $languages = _locale_get_predefined_list();
147
  $result = array();
148
  foreach ($language_codes as $lang) {
149
    if (array_key_exists($lang, $languages)) {
150
      // Try to use verbose locale name
151
      $name = $lang;
152
      $name = $languages[$name][0] . (isset($languages[$name][1]) ? ' ' . $t('(@language)', array('@language' => $languages[$name][1])) : '');
153
      $result[$lang] = $name;
154
    }
155
  }
156
  return $result;
157
}
158

    
159
/**
160
 * Build project data as an object.
161
 *
162
 * @param $name
163
 *   Project name.
164
 * @param $version
165
 *   Project version.
166
 * @param $server
167
 *   Localisation server name.
168
 * @param $path
169
 *   Localisation server URL.
170
 * @return object
171
 *   Project object containing the supplied data.
172
 */
173
function _l10n_update_build_project($name, $version = NULL, $server = L10N_UPDATE_DEFAULT_SERVER, $path = L10N_UPDATE_DEFAULT_SERVER_URL) {
174
  $project = new stdClass();
175
  $project->name = $name;
176
  $project->version = $version;
177
  $project->l10n_server = $server;
178
  $project->l10n_path = $path;
179
  return $project;
180
}
181

    
182
/**
183
 * Update the file history table.
184
 *
185
 * @param $file
186
 *   Object representing the file just imported or downloaded.
187
 * @return integer
188
 *   FALSE on failure. Otherwise SAVED_NEW or SAVED_UPDATED.
189
 *   @see drupal_write_record()
190
 */
191
function l10n_update_file_history($file) {
192
  // Update or write new record
193
  if (db_query("SELECT project FROM {l10n_update_file} WHERE project = :project AND language = :language", array(':project' => $file->project, ':language' => $file->language))->fetchField()) {
194
    $update = array('project', 'language');
195
  }
196
  else {
197
    $update = array();
198
  }
199
  return drupal_write_record('l10n_update_file', $file, $update);
200
}
201

    
202
/**
203
 * Delete the history of downloaded translations.
204
 *
205
 * @param string $langcode
206
 *   Language code of the file history to be deleted.
207
 */
208
function l10n_update_delete_file_history($langcode) {
209
  db_delete('l10n_update_file')
210
    ->condition('language', $langcode)
211
    ->execute();
212
}
213

    
214
/**
215
 * Flag the file history as up to date.
216
 *
217
 * Compare history data in the {l10n_update_file} table with translations
218
 * available at translations server(s). Update the 'last_checked' timestamp of
219
 * the files which are up to date.
220
 *
221
 * @param $available
222
 *   Available translations as retreived from remote server.
223
 */
224
function l10n_update_flag_history($available) {
225
  if ($history = l10n_update_get_history()) {
226
    foreach($history as $name => $project) {
227
      foreach ($project as $langcode => $current) {
228
        if (isset($available[$name][$langcode])) {
229
          $update = $available[$name][$langcode];
230
          // When the available update is equal to the current translation the current
231
          // is marked checked in the {l10n_update_file} table.
232
          if (_l10n_update_source_compare($current, $update) == 0 && $current->version == $update->version) {
233
            db_update('l10n_update_file')
234
              ->fields(array(
235
                'last_checked' => REQUEST_TIME,
236
              ))
237
              ->condition('project', $current->project)
238
              ->condition('language', $current->language)
239
              ->execute();
240
          }
241
        }
242
      }
243
    }
244
  }
245
}
246

    
247
/**
248
 * Check if remote file exists and when it was last updated.
249
 *
250
 * @param $url
251
 *   URL of remote file.
252
 * @param $headers
253
 *   HTTP request headers.
254
 * @return object
255
 *   Result object containing the HTTP request headers, response code, headers,
256
 *   data, redirect status and updated timestamp.
257
 *   @see l10n_update_http_request()
258
 */
259
function l10n_update_http_check($url, $headers = array()) {
260
  $result = l10n_update_http_request($url, array('headers' => $headers, 'method' => 'HEAD'));
261
  if ($result && $result->code == '200') {
262
    $result->updated = isset($result->headers['last-modified']) ? strtotime($result->headers['last-modified']) : 0;
263
  }
264
  return $result;
265
}
266

    
267
/**
268
 * Perform an HTTP request.
269
 *
270
 * We cannot use drupal_http_request() at install, see http://drupal.org/node/527484
271
 *
272
 * This is a flexible and powerful HTTP client implementation. Correctly
273
 * handles GET, POST, PUT or any other HTTP requests. Handles redirects.
274
 *
275
 * @param $url
276
 *   A string containing a fully qualified URI.
277
 * @param array $options
278
 *   (optional) An array that can have one or more of the following elements:
279
 *   - headers: An array containing request headers to send as name/value pairs.
280
 *   - method: A string containing the request method. Defaults to 'GET'.
281
 *   - data: A string containing the request body, formatted as
282
 *     'param=value&param=value&...'. Defaults to NULL.
283
 *   - max_redirects: An integer representing how many times a redirect
284
 *     may be followed. Defaults to 3.
285
 *   - timeout: A float representing the maximum number of seconds the function
286
 *     call may take. The default is 30 seconds. If a timeout occurs, the error
287
 *     code is set to the HTTP_REQUEST_TIMEOUT constant.
288
 *   - context: A context resource created with stream_context_create().
289
 *
290
 * @return object
291
 *   An object that can have one or more of the following components:
292
 *   - request: A string containing the request body that was sent.
293
 *   - code: An integer containing the response status code, or the error code
294
 *     if an error occurred.
295
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
296
 *   - status_message: The status message from the response, if a response was
297
 *     received.
298
 *   - redirect_code: If redirected, an integer containing the initial response
299
 *     status code.
300
 *   - redirect_url: If redirected, a string containing the redirection location.
301
 *   - error: If an error occurred, the error message. Otherwise not set.
302
 *   - headers: An array containing the response headers as name/value pairs.
303
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
304
 *     easy access the array keys are returned in lower case.
305
 *   - data: A string containing the response body that was received.
306
 */
307
function l10n_update_http_request($url, array $options = array()) {
308
  $result = new stdClass();
309

    
310
  // Parse the URL and make sure we can handle the schema.
311
  $uri = @parse_url($url);
312

    
313
  if ($uri == FALSE) {
314
    $result->error = 'unable to parse URL';
315
    $result->code = -1001;
316
    return $result;
317
  }
318

    
319
  if (!isset($uri['scheme'])) {
320
    $result->error = 'missing schema';
321
    $result->code = -1002;
322
    return $result;
323
  }
324

    
325
  timer_start(__FUNCTION__);
326

    
327
  // Merge the default options.
328
  $options += array(
329
    'headers' => array(),
330
    'method' => 'GET',
331
    'data' => NULL,
332
    'max_redirects' => 3,
333
    'timeout' => 30.0,
334
    'context' => NULL,
335
  );
336
  // stream_socket_client() requires timeout to be a float.
337
  $options['timeout'] = (float) $options['timeout'];
338

    
339
  switch ($uri['scheme']) {
340
    case 'http':
341
    case 'feed':
342
      $port = isset($uri['port']) ? $uri['port'] : 80;
343
      $socket = 'tcp://' . $uri['host'] . ':' . $port;
344
      // RFC 2616: "non-standard ports MUST, default ports MAY be included".
345
      // We don't add the standard port to prevent from breaking rewrite rules
346
      // checking the host that do not take into account the port number.
347
      $options['headers']['Host'] = $uri['host'] . ($port != 80 ? ':' . $port : '');
348
      break;
349
    case 'https':
350
      // Note: Only works when PHP is compiled with OpenSSL support.
351
      $port = isset($uri['port']) ? $uri['port'] : 443;
352
      $socket = 'ssl://' . $uri['host'] . ':' . $port;
353
      $options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
354
      break;
355
    default:
356
      $result->error = 'invalid schema ' . $uri['scheme'];
357
      $result->code = -1003;
358
      return $result;
359
  }
360

    
361
  if (empty($options['context'])) {
362
    $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout']);
363
  }
364
  else {
365
    // Create a stream with context. Allows verification of a SSL certificate.
366
    $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
367
  }
368

    
369
  // Make sure the socket opened properly.
370
  if (!$fp) {
371
    // When a network error occurs, we use a negative number so it does not
372
    // clash with the HTTP status codes.
373
    $result->code = -$errno;
374
    $result->error = trim($errstr) ? trim($errstr) : t('Error opening socket @socket', array('@socket' => $socket));
375

    
376
    // Mark that this request failed. This will trigger a check of the web
377
    // server's ability to make outgoing HTTP requests the next time that
378
    // requirements checking is performed.
379
    // See system_requirements()
380
    // variable_set('drupal_http_request_fails', TRUE);
381

    
382
    return $result;
383
  }
384

    
385
  // Construct the path to act on.
386
  $path = isset($uri['path']) ? $uri['path'] : '/';
387
  if (isset($uri['query'])) {
388
    $path .= '?' . $uri['query'];
389
  }
390

    
391
  // Merge the default headers.
392
  $options['headers'] += array(
393
    'User-Agent' => 'Drupal (+http://drupal.org/)',
394
  );
395

    
396
  // Only add Content-Length if we actually have any content or if it is a POST
397
  // or PUT request. Some non-standard servers get confused by Content-Length in
398
  // at least HEAD/GET requests, and Squid always requires Content-Length in
399
  // POST/PUT requests.
400
  $content_length = strlen($options['data']);
401
  if ($content_length > 0 || $options['method'] == 'POST' || $options['method'] == 'PUT') {
402
    $options['headers']['Content-Length'] = $content_length;
403
  }
404

    
405
  // If the server URL has a user then attempt to use basic authentication.
406
  if (isset($uri['user'])) {
407
    $options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (!empty($uri['pass']) ? ":" . $uri['pass'] : ''));
408
  }
409

    
410
  // If the database prefix is being used by SimpleTest to run the tests in a copied
411
  // database then set the user-agent header to the database prefix so that any
412
  // calls to other Drupal pages will run the SimpleTest prefixed database. The
413
  // user-agent is used to ensure that multiple testing sessions running at the
414
  // same time won't interfere with each other as they would if the database
415
  // prefix were stored statically in a file or database variable.
416
  $test_info = &$GLOBALS['drupal_test_info'];
417
  if (!empty($test_info['test_run_id'])) {
418
    $options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
419
  }
420

    
421
  $request = $options['method'] . ' ' . $path . " HTTP/1.0\r\n";
422
  foreach ($options['headers'] as $name => $value) {
423
    $request .= $name . ': ' . trim($value) . "\r\n";
424
  }
425
  $request .= "\r\n" . $options['data'];
426
  $result->request = $request;
427
  // Calculate how much time is left of the original timeout value.
428
  $timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
429
  if ($timeout > 0) {
430
    stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
431
    fwrite($fp, $request);
432
  }
433

    
434
  // Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
435
  // and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
436
  // instead must invoke stream_get_meta_data() each iteration.
437
  $info = stream_get_meta_data($fp);
438
  $alive = !$info['eof'] && !$info['timed_out'];
439
  $response = '';
440

    
441
  while ($alive) {
442
    // Calculate how much time is left of the original timeout value.
443
    $timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
444
    if ($timeout <= 0) {
445
      $info['timed_out'] = TRUE;
446
      break;
447
    }
448
    stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
449
    $chunk = fread($fp, 1024);
450
    $response .= $chunk;
451
    $info = stream_get_meta_data($fp);
452
    $alive = !$info['eof'] && !$info['timed_out'] && $chunk;
453
  }
454
  fclose($fp);
455

    
456
  if ($info['timed_out']) {
457
    $result->code = HTTP_REQUEST_TIMEOUT;
458
    $result->error = 'request timed out';
459
    return $result;
460
  }
461
  // Parse response headers from the response body.
462
  list($response, $result->data) = explode("\r\n\r\n", $response, 2);
463
  $response = preg_split("/\r\n|\n|\r/", $response);
464

    
465
  // Parse the response status line.
466
  list($protocol, $code, $status_message) = explode(' ', trim(array_shift($response)), 3);
467
  $result->protocol = $protocol;
468
  $result->status_message = $status_message;
469

    
470
  $result->headers = array();
471

    
472
  // Parse the response headers.
473
  while ($line = trim(array_shift($response))) {
474
    list($name, $value) = explode(':', $line, 2);
475
    $name = strtolower($name);
476
    if (isset($result->headers[$name]) && $name == 'set-cookie') {
477
      // RFC 2109: the Set-Cookie response header comprises the token Set-
478
      // Cookie:, followed by a comma-separated list of one or more cookies.
479
      $result->headers[$name] .= ',' . trim($value);
480
    }
481
    else {
482
      $result->headers[$name] = trim($value);
483
    }
484
  }
485

    
486
  $responses = array(
487
    100 => 'Continue',
488
    101 => 'Switching Protocols',
489
    200 => 'OK',
490
    201 => 'Created',
491
    202 => 'Accepted',
492
    203 => 'Non-Authoritative Information',
493
    204 => 'No Content',
494
    205 => 'Reset Content',
495
    206 => 'Partial Content',
496
    300 => 'Multiple Choices',
497
    301 => 'Moved Permanently',
498
    302 => 'Found',
499
    303 => 'See Other',
500
    304 => 'Not Modified',
501
    305 => 'Use Proxy',
502
    307 => 'Temporary Redirect',
503
    400 => 'Bad Request',
504
    401 => 'Unauthorized',
505
    402 => 'Payment Required',
506
    403 => 'Forbidden',
507
    404 => 'Not Found',
508
    405 => 'Method Not Allowed',
509
    406 => 'Not Acceptable',
510
    407 => 'Proxy Authentication Required',
511
    408 => 'Request Time-out',
512
    409 => 'Conflict',
513
    410 => 'Gone',
514
    411 => 'Length Required',
515
    412 => 'Precondition Failed',
516
    413 => 'Request Entity Too Large',
517
    414 => 'Request-URI Too Large',
518
    415 => 'Unsupported Media Type',
519
    416 => 'Requested range not satisfiable',
520
    417 => 'Expectation Failed',
521
    500 => 'Internal Server Error',
522
    501 => 'Not Implemented',
523
    502 => 'Bad Gateway',
524
    503 => 'Service Unavailable',
525
    504 => 'Gateway Time-out',
526
    505 => 'HTTP Version not supported',
527
  );
528
  // RFC 2616 states that all unknown HTTP codes must be treated the same as the
529
  // base code in their class.
530
  if (!isset($responses[$code])) {
531
    $code = floor($code / 100) * 100;
532
  }
533
  $result->code = $code;
534

    
535
  switch ($code) {
536
    case 200: // OK
537
    case 304: // Not modified
538
      break;
539
    case 301: // Moved permanently
540
    case 302: // Moved temporarily
541
    case 307: // Moved temporarily
542
      $location = $result->headers['location'];
543
      $options['timeout'] -= timer_read(__FUNCTION__) / 1000;
544
      if ($options['timeout'] <= 0) {
545
        $result->code = HTTP_REQUEST_TIMEOUT;
546
        $result->error = 'request timed out';
547
      }
548
      elseif ($options['max_redirects']) {
549
        // Redirect to the new location.
550
        $options['max_redirects']--;
551
        $result = l10n_update_http_request($location, $options);
552
        $result->redirect_code = $code;
553
      }
554
      $result->redirect_url = $location;
555
      break;
556
    default:
557
      $result->error = $status_message;
558
  }
559

    
560
  return $result;
561
}
562

    
563
/**
564
 * Build abstract translation source, to be mapped to a file or a download.
565
 *
566
 * @param $project
567
 *   Project object containing data to be inserted in the template.
568
 * @param $template
569
 *   String containing place holders. Available place holders:
570
 *   - '%project': Project name.
571
 *   - '%release': Poject version.
572
 *   - '%core': Project core version.
573
 *   - '%language': Language code.
574
 *   - '%filename': Project file name.
575
 * @return string
576
 *   String with replaced place holders.
577
 */
578
function l10n_update_build_string($project, $template) {
579
  $variables = array(
580
    '%project' => $project->name,
581
    '%release' => $project->version,
582
    '%core' => $project->core,
583
    '%language' => isset($project->language) ? $project->language : '%language',
584
    '%filename' => isset($project->filename) ? $project->filename : '%filename',
585
  );
586
  return strtr($template, $variables);
587
}