You are here

protected static function Remote::curlWrite in FileField Sources 8

Save the file to disk. Also updates progress bar.

File

src/Plugin/FilefieldSource/Remote.php, line 204

Class

Remote
A FileField source plugin to allow downloading a file from a remote server.

Namespace

Drupal\filefield_sources\Plugin\FilefieldSource

Code

protected static function curlWrite(&$ch, $data) {
  $progress_update = 0;
  $options = static::getTransferOptions();

  // Get the current progress and update the progress value.
  // Only update every 64KB to reduce Drupal::cache()->set() calls.
  // cURL usually writes in 16KB chunks.
  if (curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD) / 65536 > $progress_update) {
    $progress_update++;
    $progress = [
      'current' => curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD),
      'total' => curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD),
    ];

    // Set a cache so that we can retrieve this value from the progress bar.
    $cid = 'filefield_transfer:' . session_id() . ':' . $options['key'];
    if ($progress['current'] != $progress['total']) {
      \Drupal::cache()
        ->set($cid, $progress, time() + 300);
    }
    else {
      \Drupal::cache()
        ->delete($cid);
    }
  }
  $data_length = 0;
  if ($fp = @fopen($options['filepath'], 'a')) {
    fwrite($fp, $data);
    fclose($fp);
    $data_length = strlen($data);
  }
  return $data_length;
}