/**
  * Check that the directory can be used for backup.
  *
  * @throws \BackupMigrate\Core\Exception\BackupMigrateException
  */
 protected function checkDirectory()
 {
     // @TODO: Figure out if the file is or might be accessible via the web.
     $dir = $this->confGet('directory');
     $is_private = strpos($dir, 'private://') === 0;
     // Attempt to create/prepare the directory if it is in the private directory
     if ($is_private) {
         if (!PrivateStream::basePath()) {
             throw new BackupMigrateException("The backup file could not be saved to '%dir' because your private files system path has not been set.", ['%dir' => $dir]);
         }
         if (!file_prepare_directory($dir, FILE_CREATE_DIRECTORY && FILE_MODIFY_PERMISSIONS)) {
             throw new BackupMigrateException("The backup file could not be saved to '%dir' because the directory could not be created or cannot be written to. Please make sure your private files directory is writable by the web server.", ['%dir' => $dir]);
         }
     } else {
         // If the file is local to the server.
         $real = \Drupal::service('file_system')->realpath($dir);
         if ($real) {
             // If the file is within the docroot.
             $in_root = strpos($real, DRUPAL_ROOT) === 0;
             if ($in_root && !$is_private) {
                 throw new BackupMigrateException("The backup file could not be saved to '%dir' because that directory may be publicly accessible via the web. Please save your backups to the private file directory or a directory outside of the web root.", ['%dir' => $dir]);
             }
         }
     }
     // Do the regular exists/writable checks
     parent::checkDirectory();
     // @TODO: Warn if the realpath cannot be resolved (because we cannot determine if the file is publicly accessible)
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     if (!PrivateStream::basePath()) {
         // if value is private and not set.
         if (strpos($form_state->getValue('private'), '//private') !== FALSE) {
             $form_state->setErrorByName('private', $this->t('Private directory location not set in settings.php.'));
         } else {
             // Warn user that it should be private.
             drupal_set_message(t('Private directory is not set and should be used for backup storage.'), 'warning');
         }
     }
 }
示例#3
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $config = $this->config('system.file');
     $form['file_public_path'] = array('#type' => 'item', '#title' => t('Public file system path'), '#markup' => PublicStream::basePath(), '#description' => t('A local file system path where public files will be stored. This directory must exist and be writable by Drupal. This directory must be relative to the Drupal installation directory and be accessible over the web. This must be changed in settings.php'));
     $form['file_private_path'] = array('#type' => 'item', '#title' => t('Private file system path'), '#markup' => PrivateStream::basePath() ? PrivateStream::basePath() : t('Not set'), '#description' => t('An existing local file system path for storing private files. It should be writable by Drupal and not accessible over the web. This must be changed in settings.php'));
     $form['file_temporary_path'] = array('#type' => 'textfield', '#title' => t('Temporary directory'), '#default_value' => $config->get('path.temporary'), '#maxlength' => 255, '#description' => t('A local file system path where temporary files will be stored. This directory should not be accessible over the web.'), '#after_build' => array('system_check_directory'));
     // Any visible, writeable wrapper can potentially be used for the files
     // directory, including a remote file system that integrates with a CDN.
     $options = $this->streamWrapperManager->getDescriptions(StreamWrapperInterface::WRITE_VISIBLE);
     if (!empty($options)) {
         $form['file_default_scheme'] = array('#type' => 'radios', '#title' => t('Default download method'), '#default_value' => $config->get('default_scheme'), '#options' => $options, '#description' => t('This setting is used as the preferred download method. The use of public files is more efficient, but does not provide any access control.'));
     }
     $intervals = array(0, 21600, 43200, 86400, 604800, 2419200, 7776000);
     $period = array_combine($intervals, array_map(array($this->dateFormatter, 'formatInterval'), $intervals));
     $period[0] = t('Never');
     $form['temporary_maximum_age'] = array('#type' => 'select', '#title' => t('Delete orphaned files after'), '#default_value' => $config->get('temporary_maximum_age'), '#options' => $period, '#description' => t('Orphaned files are not referenced from any content but remain in the file system and may appear in administrative listings. <strong>Warning:</strong> If enabled, orphaned files will be permanently deleted and may not be recoverable.'));
     return parent::buildForm($form, $form_state);
 }
  /**
   * {@inheritdoc}.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    // Build $photos_size array().
    $size = array();
    for ($i = 0; $i < $form_state->getValue('photos_thumb_count'); $i++) {
      if ($form_state->getValue('photos_size_' . $i)) {
        $size[$form_state->getValue('photos_size_' . $i)] = $form_state->getValue('photos_name_' . $i);
      }
    }
    $photos_size = $size;

    // Set number of albums per role.
    $num = $form_state->getValue('num');
    foreach ($num as $rnum => $rcount) {
      $this->config('photos.settings')->set($rnum, $rcount);
    }

    $this->config('photos.settings')
      ->set('photos_access_photos', $form_state->getValue('photos_access_photos'))
      ->set('photos_additional_sizes', $form_state->getValue('photos_additional_sizes'))
      ->set('photos_comment', $form_state->getValue('photos_comment'))
      ->set('photos_cover_imagesize', $form_state->getValue('photos_cover_imagesize'))
      ->set('photos_display_full_imagesize', $form_state->getValue('photos_display_full_imagesize'))
      ->set('photos_display_full_viewnum', $form_state->getValue('photos_display_full_viewnum'))
      ->set('photos_display_imageorder', $form_state->getValue('photos_display_imageorder'))
      ->set('photos_display_list_imagesize', $form_state->getValue('photos_display_list_imagesize'))
      ->set('photos_display_page_display', $form_state->getValue('photos_display_page_display'))
      ->set('photos_display_page_user', $form_state->getValue('photos_display_page_user'))
      ->set('photos_display_teaser_display', $form_state->getValue('photos_display_teaser_display'))
      ->set('photos_display_teaser_imagesize', $form_state->getValue('photos_display_teaser_imagesize'))
      ->set('photos_display_teaser_user', $form_state->getValue('photos_display_teaser_user'))
      ->set('photos_display_teaser_viewnum', $form_state->getValue('photos_display_teaser_viewnum'))
      ->set('photos_display_user', $form_state->getValue('photos_display_user'))
      ->set('photos_display_view_imagesize', $form_state->getValue('photos_display_view_imagesize'))
      ->set('photos_display_viewpager', $form_state->getValue('photos_display_viewpager'))
      ->set('photos_exif', $form_state->getValue('photos_exif'))
      ->set('photos_exif_cache', $form_state->getValue('photos_exif_cache'))
      ->set('photos_image_count', $form_state->getValue('photos_image_count'))
      ->set('photos_num', $form_state->getValue('photos_num'))
      ->set('photos_pager_imagesize', $form_state->getValue('photos_pager_imagesize'))
      ->set('photos_path', $form_state->getValue('photos_path'))
      ->set('photos_plupload_status', $form_state->getValue('photos_plupload_status'))
      ->set('photos_print_sizes', $form_state->getValue('photos_print_sizes'))
      ->set('photos_rname', $form_state->getValue('photos_rname'))
      ->set('photos_size', $photos_size)
      ->set('photos_size_max', $form_state->getValue('photos_size_max'))
      ->set('photos_upzip', $form_state->getValue('photos_upzip'))
      ->set('photos_user_count_cron', $form_state->getValue('photos_user_count_cron'))
      ->set('photos_vote', $form_state->getValue('photos_vote'))
      ->save();

    // Set warning if private file path is not set.
    if (!PrivateStream::basePath() && $form_state->getValue('photos_access_photos')) {
      drupal_set_message(t('Warning: image files can still be accessed by visiting the direct URL.
        For better security, ask your website admin to setup a private file path.'), 'warning');
    }
  }
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $user_value = $form_state->getValue('user');
    if ($user_value) {
      $form_state->setRebuild();
    }
    else {
      // @todo check if file is already in use before moving?
      // - If in use copy?
      $album = $form_state->getValue('album');
      $directory = $form_state->getValue('directory');
      $user = \Drupal::currentUser();
      $validators = array(
        'file_validate_is_image' => array()
      );
      $count = 0;
      $files_uploaded = array();
      $nid = $album;
      $album_uid = $form_state->getValue('uid');
      // If photos_access is enabled check viewid.
      $scheme = 'default';
      $album_viewid = 0;
      if (\Drupal::moduleHandler()->moduleExists('photos_access')) {
        $node = \Drupal\node\Entity\Node::load($nid);
        if (isset($node->privacy) && isset($node->privacy['viewid'])) {
          $album_viewid = $node->privacy['viewid'];
          if ($album_viewid > 0) {
            // Check for private file path.
            if (PrivateStream::basePath()) {
              $scheme = 'private';
            }
            else {
              // Set warning message.
              drupal_set_message(t('Warning: image files can still be accessed by visiting the direct URL.
                For better security, ask your website admin to setup a private file path.'), 'warning');
            }
          }
        }
      }
      $account = \Drupal::entityManager()->getStorage('user')->load($album_uid);
      // Check if zip is included.
      $allow_zip = \Drupal::config('photos.settings')->get('photos_upzip') ? '|zip|ZIP' : '';
      $file_extensions = 'png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF' . $allow_zip;
      $files = file_scan_directory($directory, '/^.*\.(' . $file_extensions . ')$/');
      foreach ($files as $dir_file) {
        $ext = \Drupal\Component\Utility\Unicode::substr($dir_file->uri, -3);
        if ($ext <> 'zip' && $ext <> 'ZIP') {
          // Prepare directory.
          $photos_path = photos_check_path($scheme, '', $account);
          $photos_name = _photos_rename($dir_file->filename);
          $file_uri = file_destination($photos_path . '/' . $photos_name, FILE_EXISTS_RENAME);
          if (file_unmanaged_move($dir_file->uri, $file_uri)) {
            // Save file to album. Include title and description.
            $image = \Drupal::service('image.factory')->get($file_uri);
            if ($image->getWidth()) {
              // Create a file entity.
              $file = entity_create('file', array(
                'uri' => $file_uri,
                'uid' => $user->id(),
                'status' => FILE_STATUS_PERMANENT,
                'pid' => $nid,
                'nid' => $nid,
                'filename' => $photos_name,
                'filesize' => $image->getFileSize(),
                'filemime' => $image->getMimeType()
              ));

              if ($file_fid = _photos_save_data($file)) {
                $files_uploaded[] = photos_image_date($file);
              }
              $count++;
            }
          }
        }
        else {
          // Zip upload from manual upload form.
          if (!\Drupal::config('photos.settings')->get('photos_upzip')) {
            return form_set_error('error', t('Please update settings to allow zip uploads.'));
          }
          $directory = photos_check_path();
          file_prepare_directory($directory);
          $zip = file_destination($directory . '/' . trim(basename($dir_file->uri)), FILE_EXISTS_RENAME);
          if (file_unmanaged_move($dir_file->uri, $zip)) {
            $value = new \stdClass();
            $value->pid = $nid;
            $value->nid = $nid;
            $value->des = '';
            $value->title = $dir_file->filename;
            if (!$file_count = _photos_unzip($zip, $value, $scheme, $account)) {
            $msg = t('Upload failed.');
            }
            else {
              $count = $count+$file_count;
            }
          }
        }
      }
      // Clear node and album page cache.
      Cache::invalidateTags(array('node:' . $nid, 'photos:album:' . $nid));
      $message = \Drupal::translation()->formatPlural($count, '1 image moved to selected album.', '@count images moved to selected album.');
      drupal_set_message($message);
    }
  }
 public function latest_tweet(\Twig_Environment $env, array $context)
 {
     $filepath = DRUPAL_ROOT . '/' . \Drupal\Core\StreamWrapper\PrivateStream::basePath() . '/social.twitter.json';
     if (file_exists($filepath)) {
         $filecontents = file_get_contents($filepath);
         if (empty($filecontents)) {
             return '';
         } else {
             $tweets = json_decode($filecontents, TRUE);
             foreach ($tweets as $tweet) {
                 if ($tweet['user']['handle'] === 'BateauxLondon') {
                     return $this->static_block($env, [], 'latest_tweet', array('tweet' => $tweet));
                 }
             }
             return '';
         }
     } else {
         return '';
     }
 }
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $user = \Drupal::currentUser();
    $validators = array(
      'file_validate_is_image' => array()
    );
    $count = 0;
    $files_uploaded = array();
    $nid = $form_state->getValue('nid');
    $album_uid = db_query("SELECT uid FROM {node_field_data} WHERE nid = :nid", array(':nid' => $nid))->fetchField();
    // If photos_access is enabled check viewid.
    $scheme = 'default';
    $album_viewid = 0;
    if (\Drupal::moduleHandler()->moduleExists('photos_access')) {
      $node = \Drupal\node\Entity\Node::load($nid);
      if (isset($node->privacy) && isset($node->privacy['viewid'])) {
        $album_viewid = $node->privacy['viewid'];
        if ($album_viewid > 0) {
          // Check for private file path.
          if (PrivateStream::basePath()) {
            $scheme = 'private';
          }
          else {
            // Set warning message.
            drupal_set_message(t('Warning: image files can still be accessed by visiting the direct URL.
              For better security, ask your website admin to setup a private file path.'), 'warning');
          }
        }
      }
    }
    if (empty($album_uid)) {
      $album_uid = $user->id();
    }
    // \Drupal\user\Entity\User::load($album_uid);
    $account = \Drupal::entityManager()->getStorage('user')->load($album_uid);
    // Check if plupload is enabled.
    // @todo check for plupload library?
    if (\Drupal::config('photos.settings')->get('photos_plupload_status')) {
      $plupload_files = $form_state->getValue('plupload');
      foreach ($plupload_files as $uploaded_file) {
        if ($uploaded_file['status'] == 'done') {
          // Check for zip files.
          $ext = \Drupal\Component\Utility\Unicode::substr($uploaded_file['name'], -3);
          if ($ext <> 'zip' && $ext <> 'ZIP') {
            // Prepare directory.
            $photos_path = photos_check_path($scheme, '', $account);
            $photos_name = _photos_rename($uploaded_file['name']);
            $file_uri = file_destination($photos_path . '/' . $photos_name, FILE_EXISTS_RENAME);
            if (file_unmanaged_move($uploaded_file['tmppath'], $file_uri)) {
              $path_parts = pathinfo($file_uri);
              $image = \Drupal::service('image.factory')->get($file_uri);
              if ($path_parts['extension'] && $image->getWidth()) {
                // Create a file entity.
                $file = entity_create('file', array(
                  'uri' => $file_uri,
                  'uid' => $user->id(),
                  'status' => FILE_STATUS_PERMANENT,
                  'pid' => $form_state->getValue('pid'),
                  'nid' => $form_state->getValue('nid'),
                  'filename' => $photos_name,
                  'filesize' => $image->getFileSize(),
                  'filemime' => $image->getMimeType()
                ));

                if ($file_fid = _photos_save_data($file)) {
                  $files_uploaded[] = photos_image_date($file);
                }
                $count++;
              }
              else {
                file_delete($file_uri);
                \Drupal::logger('photos')->notice('Wrong file type');
              }
            }
            else {
              \Drupal::logger('photos')->notice('Upload error. Could not move temp file.');
            }
          }
          else {
            if (!\Drupal::config('photos.settings')->get('photos_upzip')) {
              drupal_set_message(t('Please set Album photos to open zip uploads.'), 'error');
            }
            $directory = photos_check_path();
            file_prepare_directory($directory);
            $zip = file_destination($directory . '/' . $uploaded_file['name'], FILE_EXISTS_RENAME);
            if (file_unmanaged_move($uploaded_file['tmppath'], $zip)) {
              $value = new \StdClass();
              $value->pid = $form_state->getValue('pid');
              $value->nid = $form_state->getValue('nid');
              $value->title = $uploaded_file['name'];
              $value->des = '';
              // Unzip it.
              if (!$file_count = _photos_unzip($zip, $value, $scheme, $account)) {
                drupal_set_message(t('Zip upload failed.'), 'error');
              }
              else {
                // Update image upload count.
                $count = $count+$file_count;
              }
            }
          }
        }
        else {
          drupal_set_message(t('Error uploading some photos.'), 'error');
        }
      }
    }
    else {
      // Manual upload form.
      $pid = $form_state->getValue('pid');
      $photos_num = \Drupal::config('photos.settings')->get('photos_num');
      for ($i = 0; $i < $photos_num; ++$i) {
        if ($_FILES['files']['name']['images_' . $i]) {
          $ext = \Drupal\Component\Utility\Unicode::substr($_FILES['files']['name']['images_' . $i], -3);
          if ($ext <> 'zip' && $ext <> 'ZIP') {
            // Prepare directory.
            $photos_path = photos_check_path($scheme, '', $account);
            if ($file = file_save_upload('images_' . $i, $validators, $photos_path, 0)) {
              // Save file to album. Include title and description.
              $file->pid = $pid;
              $file->nid = $form_state->getValue('nid');
              $file->des = $form_state->getValue('des_' . $i);
              $file->title = $form_state->getValue('title_' . $i);
              $files_uploaded[] = photos_image_date($file);
              $count++;
            }
          }
          else {
            // Zip upload from manual upload form.
            if (!\Drupal::config('photos.settings')->get('photos_upzip')) {
              return form_set_error('error', t('Please update settings to allow zip uploads.'));
            }
            $directory = photos_check_path();
            file_prepare_directory($directory);
            $zip = file_destination($directory . '/' . trim(basename($_FILES['files']['name']['images_' . $i])), FILE_EXISTS_RENAME);
            if (file_unmanaged_move($_FILES['files']['tmp_name']['images_' . $i], $zip)) {
              $value = new \stdClass();
              $value->pid = $pid;
              $value->nid = $form_state->getValue('nid') ? $form_state->getValue('nid') : $form_state->getValue('pid');
              $value->des = $form_state->getValue('des_' . $i);
              $value->title = $form_state->getValue('title_' . $i);
              if (!$file_count = _photos_unzip($zip, $value, $scheme, $account)) {
                $msg = t('Upload failed.');
              }
              else {
                $count = $count+$file_count;
              }
            }
          }
        }
      }
    }
    // Clear node and album page cache.
    Cache::invalidateTags(array('node:' . $nid, 'photos:album:' . $nid));
    $message = \Drupal::translation()->formatPlural($count, '1 image uploaded.', '@count images uploaded.');
    drupal_set_message($message);
  }