You are here

function backup_migrate_destination_nodesquirrel::_post_file in Backup and Migrate 6.2

Same name and namespace in other branches
  1. 8.3 includes/destinations.nodesquirrel.inc \backup_migrate_destination_nodesquirrel::_post_file()
  2. 6.3 includes/destinations.nodesquirrel.inc \backup_migrate_destination_nodesquirrel::_post_file()
  3. 7.2 includes/destinations.nodesquirrel.inc \backup_migrate_destination_nodesquirrel::_post_file()

Post a file via http.

This looks a lot like a clone of drupal_http_request but it can post a large file without reading the whole file into memory.

1 call to backup_migrate_destination_nodesquirrel::_post_file()
backup_migrate_destination_nodesquirrel::save_file in includes/destinations.nodesquirrel.inc
Save to the NodeSquirrel destination.

File

includes/destinations.nodesquirrel.inc, line 534
Functions to handle the NodeSquirrel backup destination.

Class

backup_migrate_destination_nodesquirrel
A destination for sending database backups to the NodeSquirel backup service.

Code

function _post_file($url, $method = 'GET', $params = array(), $file = NULL, $retry = 3) {
  global $db_prefix;
  $result = new stdClass();

  // Parse the URL and make sure we can handle the schema.
  $uri = parse_url($url);
  if ($uri == FALSE) {
    $result->error = 'unable to parse URL';
    $result->code = -1001;
    return $result;
  }
  if (!isset($uri['scheme'])) {
    $result->error = 'missing schema';
    $result->code = -1002;
    return $result;
  }
  switch ($uri['scheme']) {
    case 'http':
    case 'feed':
      $port = isset($uri['port']) ? $uri['port'] : 80;
      $host = $uri['host'] . ($port != 80 ? ':' . $port : '');
      $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
      break;
    case 'https':

      // Note: Only works for PHP 4.3 compiled with OpenSSL.
      $port = isset($uri['port']) ? $uri['port'] : 443;
      $host = $uri['host'] . ($port != 443 ? ':' . $port : '');
      $fp = @fsockopen('ssl://' . $uri['host'], $port, $errno, $errstr, 20);
      break;
    default:
      $result->error = 'invalid schema ' . $uri['scheme'];
      $result->code = -1003;
      return $result;
  }

  // Make sure the socket opened properly.
  if (!$fp) {

    // When a network error occurs, we use a negative number so it does not
    // clash with the HTTP status codes.
    $result->code = -$errno;
    $result->error = trim($errstr);

    // Mark that this request failed. This will trigger a check of the web
    // server's ability to make outgoing HTTP requests the next time that
    // requirements checking is performed.
    // @see system_requirements()
    variable_set('drupal_http_request_fails', TRUE);
    return $result;
  }

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

  // Prepare the data payload.
  $boundary = '---------------------------' . substr(md5(rand(0, 32000)), 0, 10);
  $data_footer = "\r\n--{$boundary}--\r\n";
  $data_header = '';
  foreach ($params as $key => $value) {
    $data_header .= "--{$boundary}\r\n";
    $data_header .= "Content-Disposition: form-data; name=\"" . $key . "\"\r\n";
    $data_header .= "\r\n" . $value . "\r\n";
    $data_header .= "--{$boundary}\r\n";
  }

  // Add the file header to the post payload.
  $data_header .= "--{$boundary}\r\n";
  $data_header .= "Content-Disposition: form-data; name=\"file\"; filename=\"" . $file
    ->filename() . "\"\r\n";
  $data_header .= "Content-Type: application/octet-stream;\r\n";
  $data_header .= "\r\n";

  // Calculate the content length.
  $content_length = strlen($data_header . $data_footer) + filesize($file
    ->filepath());

  //file_get_contents($file->filepath()));

  // Create HTTP request.
  $defaults = array(
    // RFC 2616: "non-standard ports MUST, default ports MAY be included".
    // We don't add the port to prevent from breaking rewrite rules checking the
    // host that do not take into account the port number.
    'Host' => "Host: {$host}",
    'Content-type' => "Content-type: multipart/form-data, boundary={$boundary}",
    'User-Agent' => 'User-Agent: NodeSquirrel Client/1.x (+http://www.nodesquirrel.com) (Drupal ' . VERSION . '; Backup and Migrate 2.x)',
    'Content-Length' => 'Content-Length: ' . $content_length,
  );

  // If the server url has a user then attempt to use basic authentication
  if (isset($uri['user'])) {
    $defaults['Authorization'] = 'Authorization: Basic ' . base64_encode($uri['user'] . (!empty($uri['pass']) ? ":" . $uri['pass'] : ''));
  }
  $request = $method . ' ' . $path . " HTTP/1.0\r\n";
  $request .= implode("\r\n", $defaults);
  $request .= "\r\n\r\n";
  $result->request = $request;

  // Write the headers and start of the headers
  fwrite($fp, $request);
  fwrite($fp, $data_header);

  // Copy the file 512k at a time to prevent memory issues.
  if ($fp_in = fopen($file
    ->filepath(), 'rb')) {
    while (!feof($fp_in)) {
      fwrite($fp, fread($fp_in, 1024 * 512));
    }
    $success = TRUE;
  }
  @fclose($fp_in);

  // Finish the write.
  fwrite($fp, $data_footer);

  // Fetch response.
  $response = '';
  while (!feof($fp) && ($chunk = fread($fp, 1024))) {
    $response .= $chunk;
  }
  fclose($fp);

  // Parse response.
  list($split, $result->data) = explode("\r\n\r\n", $response, 2);
  $split = preg_split("/\r\n|\n|\r/", $split);
  list($protocol, $code, $status_message) = explode(' ', trim(array_shift($split)), 3);
  $result->protocol = $protocol;
  $result->status_message = $status_message;
  $result->headers = array();

  // Parse headers.
  while ($line = trim(array_shift($split))) {
    list($header, $value) = explode(':', $line, 2);
    if (isset($result->headers[$header]) && $header == 'Set-Cookie') {

      // RFC 2109: the Set-Cookie response header comprises the token Set-
      // Cookie:, followed by a comma-separated list of one or more cookies.
      $result->headers[$header] .= ',' . trim($value);
    }
    else {
      $result->headers[$header] = trim($value);
    }
  }
  $responses = array(
    100 => 'Continue',
    101 => 'Switching Protocols',
    200 => 'OK',
    201 => 'Created',
    202 => 'Accepted',
    203 => 'Non-Authoritative Information',
    204 => 'No Content',
    205 => 'Reset Content',
    206 => 'Partial Content',
    300 => 'Multiple Choices',
    301 => 'Moved Permanently',
    302 => 'Found',
    303 => 'See Other',
    304 => 'Not Modified',
    305 => 'Use Proxy',
    307 => 'Temporary Redirect',
    400 => 'Bad Request',
    401 => 'Unauthorized',
    402 => 'Payment Required',
    403 => 'Forbidden',
    404 => 'Not Found',
    405 => 'Method Not Allowed',
    406 => 'Not Acceptable',
    407 => 'Proxy Authentication Required',
    408 => 'Request Time-out',
    409 => 'Conflict',
    410 => 'Gone',
    411 => 'Length Required',
    412 => 'Precondition Failed',
    413 => 'Request Entity Too Large',
    414 => 'Request-URI Too Large',
    415 => 'Unsupported Media Type',
    416 => 'Requested range not satisfiable',
    417 => 'Expectation Failed',
    500 => 'Internal Server Error',
    501 => 'Not Implemented',
    502 => 'Bad Gateway',
    503 => 'Service Unavailable',
    504 => 'Gateway Time-out',
    505 => 'HTTP Version not supported',
  );

  // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  // base code in their class.
  if (!isset($responses[$code])) {
    $code = floor($code / 100) * 100;
  }
  switch ($code) {
    case 200:

    // OK
    case 304:

      // Not modified
      break;
    case 301:

    // Moved permanently
    case 302:

    // Moved temporarily
    case 307:

      // Moved temporarily
      $location = $result->headers['Location'];
      if ($retry) {
        $result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
        $result->redirect_code = $result->code;
      }
      $result->redirect_url = $location;
      break;
    default:
      $result->error = $status_message;
  }
  $result->code = $code;
  return $result;
}