Пример #1
0
function file_upload($fileUrl, $file_path = "files")
{
    //echo $file_path;
    //	echo 's3://'.$fileUrl;
    $file_temp = file_get_contents('http://www.voteapps.com/' . $fileUrl);
    //print_r();
    //Saves a file to the specified destination and creates a database entry.
    if (!file_exists($public_path . '/apkfiles')) {
        drupal_mkdir($public_path . '/apkfiles');
    }
    $file_arry = file_save_data($file_temp, 's3://' . $fileUrl, FILE_EXISTS_REPLACE);
    //print_r($file_arry);
    //转存视频和图片
    if ($file_arry) {
        // echo "</br>上传成功...";
        return $file_arry;
    } else {
        //echo "</br>再次尝试上传...";
        $file_arry = file_save_data($file_temp, 's3://' . $fileUrl, FILE_EXISTS_REPLACE);
        if ($file_arry) {
            //清空视频
            //unlink($$fileUrl);
            //	echo "</br>上传成功...";
            return $file_arry;
        } else {
            //清空视频
            // unlink($$fileUrl);
            //	echo "</br>上传失败...";
            return $file_arry;
            //header('HTTP/1.1 500 Internal Server Error');
            //exit;
        }
    }
}
Пример #2
0
 /**
  * Tests the embed_button and file usage integration.
  */
 public function testEmbedButtonIconUsage()
 {
     $this->enableModules(['system', 'user', 'file']);
     $this->installSchema('file', ['file_usage']);
     $this->installConfig(['system']);
     $this->installEntitySchema('user');
     $this->installEntitySchema('file');
     $this->installEntitySchema('embed_button');
     $file1 = file_save_data(file_get_contents('core/misc/druplicon.png'));
     $file1->setTemporary();
     $file1->save();
     $file2 = file_save_data(file_get_contents('core/misc/druplicon.png'));
     $file2->setTemporary();
     $file2->save();
     $button = array('id' => 'test_button', 'label' => 'Testing embed button instance', 'type_id' => 'embed_test_default', 'icon_uuid' => $file1->uuid());
     $entity = EmbedButton::create($button);
     $entity->save();
     $this->assertTrue(File::load($file1->id())->isPermanent());
     // Delete the icon from the button.
     $entity->icon_uuid = NULL;
     $entity->save();
     $this->assertTrue(File::load($file1->id())->isTemporary());
     $entity->icon_uuid = $file1->uuid();
     $entity->save();
     $this->assertTrue(File::load($file1->id())->isPermanent());
     $entity->icon_uuid = $file2->uuid();
     $entity->save();
     $this->assertTrue(File::load($file1->id())->isTemporary());
     $this->assertTrue(File::load($file2->id())->isPermanent());
     $entity->delete();
     $this->assertTrue(File::load($file2->id())->isTemporary());
 }
Пример #3
0
 function save(FileMaterial $fileMaterial)
 {
     $wo = wechat_api_init_wechatobj();
     $file_content = $wo->getForeverMedia($fileMaterial->media_id);
     $file = file_save_data($file_content, 'public://' . $fileMaterial->name);
     dpm($file);
 }
Пример #4
0
 public static function file_save_file($src, $dest)
 {
     $data = file_get_contents($src);
     $file = file_save_data($data, $dest, FILE_EXISTS_REPLACE);
     $fid = $file->id();
     return $fid;
 }
Пример #5
0
 public function import(&$form_state, $docid = NULL)
 {
     $url = $form_state['values'][$this->fieldname];
     if (empty($url)) {
         return FALSE;
     }
     $response = drupal_http_request($url);
     // drupal_set_message("URL request ($url) returned status code $response->code.");
     if ($response->code != 200) {
         drupal_set_message("URL request ({$url}) returned unexpected status code {$response->code}.", 'error');
         return FALSE;
     }
     // else
     $content = $response->data;
     if (empty($docid)) {
         $docid = hash($this->hashAlgorithm, $content);
     }
     $pubpath = $this->constructPubPath($docid);
     file_check_directory($pubpath, FILE_CREATE_DIRECTORY);
     $savename = $this->savename;
     if (empty($savename)) {
         $savename = preg_replace('{[\\#\\?].*\\Z}', '', $url);
         $savename = preg_replace('{\\.([^.])+\\Z}', '\\#$1', $savename);
         $savename = preg_replace('/[^a-zA-Z0-9_\\#-]/', '_', $savename);
         $savename = preg_replace('/\\#/', '.', $savename);
     }
     $destfile = "{$pubpath}/{$savename}";
     file_save_data($content, $destfile, FILE_EXISTS_REPLACE);
     drupal_set_message(t("Saved !num bytes to file !file", array('!num' => strlen($content), '!file' => $destfile)));
     $this->pubpath = $pubpath;
     $this->docpath = $savename;
     return TRUE;
 }
Пример #6
0
function sunshine_build_css_cache($css_files)
{
    $data = '';
    // Create the css/ within the files folder.
    $csspath = file_create_path('css');
    $orgpath = drupal_get_path('theme', 'sunshine') . '/css/';
    file_check_directory($csspath, FILE_CREATE_DIRECTORY);
    // Build aggregate CSS file.
    foreach ($css_files as $key => $file) {
        $contents = drupal_load_stylesheet($orgpath . $file, TRUE);
        // Return the path to where this CSS file originated from.
        $base = base_path() . $orgpath;
        _drupal_build_css_path(NULL, $base);
        // Prefix all paths within this CSS file, ignoring external and absolute paths.
        $data .= preg_replace_callback('/url\\([\'"]?(?![a-z]+:|\\/+)([^\'")]+)[\'"]?\\)/i', '_drupal_build_css_path', $contents);
    }
    // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
    // @import rules must proceed any other style, so we move those to the top.
    $regexp = '/@import[^;]+;/i';
    preg_match_all($regexp, $data, $matches);
    $data = preg_replace($regexp, '', $data);
    $data = implode('', $matches[0]) . $data;
    $checksum = md5($data);
    $filename_cache = 'sunshine.cache.css';
    // Create the CSS file.
    if (!file_exists($csspath . '/' . $filename_cache) || md5(file_get_contents($csspath . '/' . $filename_cache)) != $checksum) {
        // drupal_set_message('Sunshine CSS cache has been rebuilt.');
        file_save_data($data, $csspath . '/' . $filename_cache, FILE_EXISTS_REPLACE);
    }
    return $csspath . '/' . $filename_cache;
}
Пример #7
0
function mylog($data, $file_name)
{
    if (file_destination('public://log', FILE_EXISTS_ERROR)) {
        // The file doesn't exist. do something
        drupal_mkdir('public://log');
    }
    file_save_data(print_r($data, true), "public://log/{$file_name}", FILE_EXISTS_REPLACE);
}
Пример #8
0
 public function unhandleField($entity_type, $field_type, $field_name, &$value)
 {
     if (!is_array($value)) {
         return;
     }
     if (!array_key_exists('url', $value)) {
         return;
     }
     if (!array_key_exists('original_path', $value)) {
         return;
     }
     if (!array_key_exists('uuid', $value)) {
         return;
     }
     if (!array_key_exists('uid', $value)) {
         return;
     }
     // Make sure a file doesn't already exist with that UUID.
     $entity = Entity::loadByUUID($value['uuid'], 'file');
     if ($entity) {
         $definition = $entity->definition;
     } else {
         // Make sure a file doesn't already exist with that URI.
         $query = db_select('file_managed', 'f');
         $query->addField('f', 'fid');
         $query->condition('f.uri', $value['original_path']);
         $query->range(0, 1);
         $result = $query->execute()->fetch();
         if ($result) {
             $entity = Entity::load($result->fid, 'file');
             if ($entity) {
                 $definition = $entity->definition;
             }
         }
     }
     // If we haven't found the file yet, upload it.
     if (!isset($definition)) {
         // Decode the contents of the file.
         $contents = file_get_contents($value['url']);
         if ($contents === false) {
             throw new FileHandlerException('There was an error fetching the contents of the file.');
         }
         // Save the file.
         $file = file_save_data($contents, $value['original_path']);
         if (!$file || !$file->fid) {
             throw new FileHandlerException('There was an error saving the file to the database.');
         }
         $file->uuid = $value['uuid'];
         $file->uid = $value['uid'];
         file_save($file);
         $definition = $file;
     }
     // Don't completely reset the entity.
     foreach ((array) $definition as $key => $val) {
         $this->unresolved_definition->{$key} = $val;
     }
 }
Пример #9
0
 /**
  * Helper method for saving requests coming to POETRY mock.
  *
  * @param string $message
  *    XML request.
  */
 public static function saveTranslationRequest($message, $reference)
 {
     $path = TMGMT_POETRY_MOCK_REQUESTS_PATH . $reference . '.xml';
     $dirname = dirname($path);
     if (file_prepare_directory($dirname, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
         file_save_data($message, $path);
     } else {
         watchdog('poetry_mock', 'Unable to prepare requests directory', array(), WATCHDOG_ERROR);
     }
 }
 /**
  *
  */
 public function testAdvertiserImages()
 {
     // Download an example image from the internet.
     $test_data = file_get_contents('https://www.drupal.org/sites/all/modules/drupalorg/drupalorg/images/qmark-400x684-2x.png');
     // Save the file to the temporary scheme, let's save it as a .txt so the validation fails...
     $image_file = file_save_data($test_data, 'temporary://test_test_test.txt', FILE_EXISTS_REPLACE);
     $image_file_uri = $image_file->getFileUri();
     // Create an entity and set the image file..
     $entity = Advertiser::create(['advertiser_image' => $image_file_uri]);
     $violations = $entity->validate();
     $this->assertEqual(count($violations), 1, 'Violation found when non-image filename.');
 }
Пример #11
0
function _ad_blueprint_write_css()
{
    // Set the location of the custom.css file
    $file_path = file_directory_path() . '/ad_blueprint/custom.css';
    // If the directory doesn't exist, create it
    file_check_directory(dirname($file_path), FILE_CREATE_DIRECTORY);
    // Generate the CSS
    $file_contents = _ad_blueprint_build_css();
    $output = '<div class="description">' . t('This CSS is generated by the settings chosen above and placed in the files directory: ' . l($file_path, $file_path) . '. The file is generated each time this page (and only this page) is loaded. <strong class="marker">Make sure to refresh your page to see the changes</strong>') . '</div>';
    file_save_data($file_contents, $file_path, FILE_EXISTS_REPLACE);
    return $output;
}
Пример #12
0
 /**
  * {@inheritdoc}
  */
 public function requestTranslation(JobInterface $job)
 {
     $name = "JobID" . $job->id() . '_' . $job->getSourceLangcode() . '_' . $job->getTargetLangcode();
     $export = \Drupal::service('plugin.manager.tmgmt_file.format')->createInstance($job->getSetting('export_format'));
     $path = $job->getSetting('scheme') . '://tmgmt_file/' . $name . '.' . $job->getSetting('export_format');
     $dirname = dirname($path);
     if (file_prepare_directory($dirname, FILE_CREATE_DIRECTORY)) {
         $file = file_save_data($export->export($job), $path);
         \Drupal::service('file.usage')->add($file, 'tmgmt_file', 'tmgmt_job', $job->id());
         $job->submitted('Exported file can be downloaded <a href="@link">here</a>.', array('@link' => file_create_url($path)));
     }
 }
 /**
  * Called when this activity gets activated and run by the containing
  * ConductorWorkflow's controller.
  */
 public function run()
 {
     $state = $this->getState();
     $mobile = $state->getContext('sms_number');
     // Mobile Commons sends the international code in its payload. Remove it.
     $mobile = substr($mobile, -10);
     // Get user by mobile number if it exists. Otherwise create it.
     $user = dosomething_user_get_user_by_mobile($mobile);
     if (!$user) {
         $user = dosomething_user_create_user_by_mobile($mobile);
     }
     // Initialize reportback values, defaulting to create a new reportback.
     $values = array('rbid' => 0);
     // Check for a previously submitted reportback to update instead.
     if ($rbid = dosomething_reportback_exists($this->nid, $user->uid)) {
         $values['rbid'] = $rbid;
     }
     // Get the MMS URL from the provided context.
     $pictureUrl = $state->getContext($this->mmsContext);
     // Get the location for where file should be saved to.
     $fileDest = dosomething_reportback_get_file_dest(basename($pictureUrl), $this->nid, $user->uid);
     // Download and save file to that location.
     $pictureContents = file_get_contents($pictureUrl);
     $file = file_save_data($pictureContents, $fileDest);
     // Save UID and permanent status.
     $file->uid = $user->uid;
     $file->status = FILE_STATUS_PERMANENT;
     file_save($file);
     // Get the fid to submit with the report back.
     $values['fid'] = $file->fid;
     // Get answers from context and set them to their appropriate properties.
     foreach ($this->propertyToContextMap as $property => $context) {
         $values[$property] = $state->getContext($context);
     }
     // Set nid and uid.
     $values['nid'] = $this->nid;
     $values['uid'] = $user->uid;
     // Create/update a report back submission.
     $rbid = dosomething_reportback_save($values);
     // Update user's profile if this is the first completed campaign.
     $updateArgs = array();
     if (empty($_REQUEST['profile_first_completed_campaign_id']) && !empty($this->mobileCommonsCompletedCampaignId)) {
         $updateArgs['person[first_completed_campaign_id]'] = $this->mobileCommonsCompletedCampaignId;
     }
     // Opt the user out of the main campaign.
     if (!empty($this->optOutCampaignId)) {
         dosomething_sms_mobilecommons_opt_out($mobile, $this->optOutCampaignId);
     }
     // Opt user into a path to send the confirmation message.
     dosomething_sms_mobilecommons_opt_in($mobile, $this->optInPathId, $updateArgs);
     $state->setContext('ignore_no_response_error', TRUE);
     $state->markCompleted();
 }
Пример #14
0
 /**
  * {@inheritdoc}
  */
 public function expand($values)
 {
     $data = file_get_contents($values[0]);
     if (FALSE === $data) {
         throw new \Exception("Error reading file");
     }
     /* @var \Drupal\file\FileInterface $file */
     $file = file_save_data($data, 'public://' . uniqid() . '.jpg');
     if (FALSE === $file) {
         throw new \Exception("Error saving file");
     }
     $file->save();
     $return = array('target_id' => $file->id(), 'alt' => 'Behat test image', 'title' => 'Behat test image');
     return $return;
 }
Пример #15
0
 /**
  * Creates a temporary file, for a specific user.
  *
  * @param string $data
  *   A string containing the contents of the file.
  * @param \Drupal\user\UserInterface $user
  *   The user of the file owner.
  *
  * @return \Drupal\file\FileInterface
  *   A file object, or FALSE on error.
  */
 protected function createTemporaryFile($data, UserInterface $user = NULL)
 {
     $file = file_save_data($data, NULL, NULL);
     if ($file) {
         if ($user) {
             $file->setOwner($user);
         } else {
             $file->setOwner($this->adminUser);
         }
         // Change the file status to be temporary.
         $file->setTemporary();
         // Save the changes.
         $file->save();
     }
     return $file;
 }
Пример #16
0
 /**
  * Parse attachments from message mimeparts.
  */
 function process(&$message, $source)
 {
     $message['attachments'] = array();
     foreach ($message['mimeparts'] as $attachment) {
         // 'unnamed_attachment' files are not really attachments, but mimeparts like HTML or Plain Text.
         // We only want to save real attachments, like images and files.
         if ($attachment->filename !== 'unnamed_attachment') {
             $destination = 'temporary://';
             $filename = mb_decode_mimeheader($attachment->filename);
             $file = file_save_data($attachment->data, $destination . $filename);
             $file->status = 0;
             drupal_write_record('file_managed', $file, 'fid');
             $message['attachments'][] = new FeedsEnclosure($file->uri, $attachment->filemime);
         }
     }
     unset($message['mimeparts']);
 }
 /**
  * Parse attachments from message mimeparts.
  */
 public function process(&$message, $source)
 {
     $message['attachments'] = array();
     foreach ($message['mimeparts'] as $attachment) {
         // 'unnamed_attachment' files are not really attachments, but mimeparts like HTML or Plain Text.
         // We only want to save real attachments, like images and files.
         if ($attachment->filename !== 'unnamed_attachment') {
             $destination = 'public://mailhandler_temp/';
             file_prepare_directory($destination, FILE_CREATE_DIRECTORY);
             $filename = mb_decode_mimeheader($attachment->filename);
             $file = file_save_data($attachment->data, $destination . $filename);
             $file->status = 0;
             drupal_write_record('file_managed', $file, 'fid');
             if (!empty($attachment->id)) {
                 $cid = trim($attachment->id, '<>');
                 $uri = 'cid:' . $cid;
                 $message['body_html'] = str_replace($uri, $file->uri, $message['body_html']);
             }
             $message['attachments'][] = new FeedsEnclosure($file->uri, $attachment->filemime);
         }
     }
     unset($message['mimeparts']);
 }
Пример #18
0
  /**
   * {@inheritdoc}
   */
  public function savePdfToFile(array $context, $destination_path_override = NULL) {
    /** @var FillPdfForm $fillpdf_form */
    $fillpdf_form = $context['form'];

    /** @var array $token_objects */
    $token_objects = $context['token_objects'];

    $destination_path = 'fillpdf';
    if (!empty($fillpdf_form->destination_path->value)) {
      $destination_path = "fillpdf/{$fillpdf_form->destination_path->value}";
    }
    if (!empty($destination_path_override)) {
      $destination_path = "fillpdf/{$destination_path_override}";
    }

    $resolved_destination_path = $this->processDestinationPath($destination_path, $token_objects, $fillpdf_form->scheme->value);
    $path_exists = file_prepare_directory($resolved_destination_path, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
    $saved_file = FALSE;
    if ($path_exists === FALSE) {
      $this->logger->critical($this->t("The path %destination_path does not exist and could not be
      automatically created. Therefore, the previous submission was not saved. If
      the URL contained download=1, then the PDF was still sent to the user's browser.
      If you were redirecting them to the PDF, they were sent to the homepage instead.
      If the destination path looks wrong and you have used tokens, check that you have
      used the correct token and that it is available to FillPDF at the time of PDF
      generation.",
        ['%destination_path' => $resolved_destination_path]));
    }
    else {
      // Full steam ahead!
      $saved_file = file_save_data($context['data'], "{$resolved_destination_path}/{$context['filename']}", FILE_EXISTS_RENAME);
      $this->rememberFileContext($saved_file, $context['context']);
    }

    return $saved_file;
  }
Пример #19
0
/**
 * Save page data to the specified destination as a PDF and create a database file entry.
 *
 * @param string|array $content
 *   Either of:
 *   - A string of HTML content.
 *   - A renderable array of content.
 * @param string $title
 *   Translated title for the page
 * @param $destination
 *   A string containing the destination URI. This must be a stream wrapper URI.
 *   If no value is provided, a randomized name will be generated and the file
 *   will be saved using Drupal's default files scheme, usually "public://".
 * @param $replace
 *   Replace behavior when the destination file already exists:
 *   - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
 *       the destination name exists then its database entry will be updated. If
 *       no database entry is found then a new one will be created.
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
 *       unique.
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
 *
 * @return
 *   A file object, or FALSE on error.
 *
 * @see file_save_data()
 */
function make_pdf($content, $title, $destination = NULL, $replace = FILE_EXISTS_RENAME)
{
    require_once drupal_get_path('module', CVWOBASE_MODULE) . '/tcpdf/tcpdf.php';
    require_once drupal_get_path('module', CVWOBASE_MODULE) . '/tcpdf/config/lang/eng.php';
    if (is_string($content)) {
        $content = array('main' => array('#markup' => $content));
    }
    $pdf = new TCPDF();
    // set document information
    $pdf->SetTitle($title);
    //  $pdf->SetSubject('TCPDF Tutorial');
    //  $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
    // set default header data
    $pdf->SetHeaderData('', 0, $title, '');
    // set header and footer fonts
    $pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
    // set default monospaced font
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
    // set margins
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
    //
    //set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
    //set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    //set some language-dependent strings
    $pdf->setLanguageArray($l);
    // ---------------------------------------------------------
    // set font
    $pdf->SetFont('dejavusans', '', 10);
    // add a page
    $pdf->AddPage();
    $pdf->writeHTML(drupal_render($content));
    return file_save_data($pdf->Output('', 'S'), $destination, $replace);
}
Пример #20
0
 /**
  * @param ldap entry array $ldap_entry
  *
  * @return drupal file object image user's thumbnail or FALSE if none present or ERROR happens.
  */
 public function userPictureFromLdapEntry($ldap_entry, $drupal_username = FALSE)
 {
     if ($ldap_entry && $this->picture_attr) {
         //Check if ldap entry has been provisioned.
         $thumb = isset($ldap_entry[$this->picture_attr][0]) ? $ldap_entry[$this->picture_attr][0] : FALSE;
         if (!$thumb) {
             return FALSE;
         }
         //Create md5 check.
         $md5thumb = md5($thumb);
         /**
          * If existing account already has picture check if it has changed if so remove old file and create the new one
          * If picture is not set but account has md5 something is wrong exit.
          */
         if ($drupal_username && ($account = user_load_by_name($drupal_username))) {
             if ($account->uid == 0 || $account->uid == 1) {
                 return FALSE;
             }
             if (isset($account->picture)) {
                 // Check if image has changed
                 if (isset($account->data['ldap_user']['init']['thumb5md']) && $md5thumb === $account->data['ldap_user']['init']['thumb5md']) {
                     //No change return same image
                     return $account->picture;
                 } else {
                     //Image is different check wether is obj/str and remove fileobject
                     if (is_object($account->picture)) {
                         file_delete($account->picture, TRUE);
                     } elseif (is_string($account->picture)) {
                         $file = file_load(intval($account->picture));
                         file_delete($file, TRUE);
                     }
                 }
             } elseif (isset($account->data['ldap_user']['init']['thumb5md'])) {
                 watchdog('ldap_server', "Some error happened during thumbnailPhoto sync");
                 return FALSE;
             }
         }
         //Create tmp file to get image format.
         $filename = uniqid();
         $fileuri = file_directory_temp() . '/' . $filename;
         $size = file_put_contents($fileuri, $thumb);
         $info = image_get_info($fileuri);
         unlink($fileuri);
         // create file object
         $file = file_save_data($thumb, 'public://' . variable_get('user_picture_path') . '/' . $filename . '.' . $info['extension']);
         $file->md5Sum = $md5thumb;
         // standard Drupal validators for user pictures
         $validators = array('file_validate_is_image' => array(), 'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')), 'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024));
         $errors = file_validate($file, $validators);
         if (empty($errors)) {
             return $file;
         } else {
             foreach ($errors as $err => $err_val) {
                 watchdog('ldap_server', "Error storing picture: %{$err}", "%{$err_val}", WATCHDOG_ERROR);
             }
             return FALSE;
         }
     }
 }
Пример #21
0
 /**
  * Create files for all the possible combinations of age and status.
  *
  * We are using UPDATE statements because using the API would set the
  * timestamp.
  */
 function createTempFiles()
 {
     // Temporary file that is old.
     $temp_old = file_save_data('');
     db_update('file_managed')->fields(array('status' => 0, 'changed' => REQUEST_TIME - $this->config('system.file')->get('temporary_maximum_age') - 1))->condition('fid', $temp_old->id())->execute();
     $this->assertTrue(file_exists($temp_old->getFileUri()), 'Old temp file was created correctly.');
     // Temporary file that is new.
     $temp_new = file_save_data('');
     db_update('file_managed')->fields(array('status' => 0))->condition('fid', $temp_new->id())->execute();
     $this->assertTrue(file_exists($temp_new->getFileUri()), 'New temp file was created correctly.');
     // Permanent file that is old.
     $perm_old = file_save_data('');
     db_update('file_managed')->fields(array('changed' => REQUEST_TIME - $this->config('system.file')->get('temporary_maximum_age') - 1))->condition('fid', $temp_old->id())->execute();
     $this->assertTrue(file_exists($perm_old->getFileUri()), 'Old permanent file was created correctly.');
     // Permanent file that is new.
     $perm_new = file_save_data('');
     $this->assertTrue(file_exists($perm_new->getFileUri()), 'New permanent file was created correctly.');
     return array($temp_old, $temp_new, $perm_old, $perm_new);
 }
 /**
  * {@inheritdoc}
  */
 public static function generateSampleValue(FieldDefinitionInterface $field_definition)
 {
     $random = new Random();
     $settings = $field_definition->getSettings();
     // Prepare destination.
     $dirname = static::doGetUploadLocation($settings);
     file_prepare_directory($dirname, FILE_CREATE_DIRECTORY);
     // Generate a file entity.
     $destination = $dirname . '/' . $random->name(10, TRUE) . '.txt';
     $data = $random->paragraphs(3);
     $file = file_save_data($data, $destination, FILE_EXISTS_ERROR);
     $values = array('target_id' => $file->id(), 'display' => (int) $settings['display_default'], 'description' => $random->sentences(10));
     return $values;
 }
Пример #23
0
 /**
  * Returns a Drupal file object of the enclosed resource.
  *
  * @param string $destination
  *   The path or uri specifying the target directory in which the file is
  *   expected. Don't use trailing slashes unless it's a streamwrapper scheme.
  * @param int $replace
  *   (optional) Replace behavior when the destination file already exists:
  *   - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
  *       the destination name exists then its database entry will be updated.
  *       If no database entry is found then a new one will be created.
  *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename
  *       is unique.
  *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  *   Defaults to FILE_EXISTS_RENAME.
  *
  * @return \Drupal\file\Entity\FileInterface
  *   A Drupal temporary file object of the enclosed resource.
  *
  * @throws \RuntimeException
  *   If file object could not be created.
  *
  * @todo Refactor this
  */
 public function getFile($destination, $replace = FILE_EXISTS_RENAME)
 {
     $file = FALSE;
     if (!$this->uri) {
         return $file;
     }
     // Prepare destination directory.
     file_prepare_directory($destination, FILE_MODIFY_PERMISSIONS | FILE_CREATE_DIRECTORY);
     // Copy or save file depending on whether it is remote or local.
     if (drupal_realpath($this->uri)) {
         $file = entity_create('file', ['uid' => 0, 'uri' => $this->uri, 'filemime' => $this->mimeType, 'filename' => basename($this->uri)]);
         if (drupal_dirname($file->getFileUri()) != $destination) {
             $file = file_copy($file, $destination, $replace);
         } else {
             // If file is not to be copied, check whether file already exists,
             // as file_save() won't do that for us (compare file_copy() and
             // file_save())
             $existing_files = file_load_multiple([], ['uri' => $file->getFileUri()]);
             if ($existing_files) {
                 return reset($existing_files);
             }
             $file->save();
         }
     } else {
         $filename = drupal_basename($this->uri);
         if (\Drupal::moduleHandler()->moduleExists('transliteration')) {
             require_once drupal_get_path('module', 'transliteration') . '/transliteration.inc';
             $filename = transliteration_clean_filename($filename);
         }
         if (file_uri_target($destination)) {
             $destination = trim($destination, '/') . '/';
         }
         try {
             $file = file_save_data($this->getContent(), $destination . $filename, $replace);
         } catch (\Exception $e) {
             watchdog_exception('Feeds', $e, nl2br(SafeMarkup::checkPlain($e)));
         }
     }
     // We couldn't make sense of this enclosure, throw an exception.
     if (!$file) {
         throw new \RuntimeException(SafeMarkup::format('Invalid enclosure %enclosure', ['%enclosure' => $this->uri]));
     }
     return $file;
 }
Пример #24
0
 /**
  * Send the e-mail message.
  *
  * @see drupal_mail()
  *
  * @param $message
  *   A message array, as described in hook_mail_alter().
  * @return
  *   TRUE if the mail was successfully accepted, otherwise FALSE.
  */
 public function mail(array $message)
 {
     $to = $message['to'];
     $from = $message['from'];
     $body = $message['body'];
     $headers = $message['headers'];
     $subject = $message['subject'];
     // Create a new PHPMailer object - autoloaded from registry.
     $mailer = new PHPMailer();
     // Turn on debugging, if requested.
     if ($this->smtpConfig->get('smtp_debugging') == 1) {
         $mailer->SMTPDebug = TRUE;
     }
     // Set the from name.
     $from_name = $this->smtpConfig->get('smtp_fromname');
     if (empty($from_name)) {
         // If value is not defined in settings, use site_name.
         $from_name = \Drupal::config('system.site')->get('name');
     }
     // Set SMTP module email from.
     if (\Drupal::service('email.validator')->isValid($this->smtpConfig->get('smtp_from'))) {
         $from = $this->smtpConfig->get('smtp_from');
         $headers['Sender'] = $from;
         $headers['Return-Path'] = $from;
         $headers['Reply-To'] = $from;
     }
     // Defines the From value to what we expect.
     $mailer->From = $from;
     $mailer->FromName = $from_name;
     $mailer->Sender = $from;
     // Create the list of 'To:' recipients.
     $torecipients = explode(',', $to);
     foreach ($torecipients as $torecipient) {
         $to_comp = $this->_get_components($torecipient);
         $mailer->AddAddress($to_comp['email'], $to_comp['name']);
     }
     // Parse the headers of the message and set the PHPMailer object's settings
     // accordingly.
     foreach ($headers as $key => $value) {
         //watchdog('error', 'Key: ' . $key . ' Value: ' . $value);
         switch (strtolower($key)) {
             case 'from':
                 if ($from == NULL or $from == '') {
                     // If a from value was already given, then set based on header.
                     // Should be the most common situation since drupal_mail moves the
                     // from to headers.
                     $from = $value;
                     $mailer->From = $value;
                     // then from can be out of sync with from_name !
                     $mailer->FromName = '';
                     $mailer->Sender = $value;
                 }
                 break;
             case 'content-type':
                 // Parse several values on the Content-type header, storing them in an array like
                 // key=value -> $vars['key']='value'
                 $vars = explode(';', $value);
                 foreach ($vars as $i => $var) {
                     if ($cut = strpos($var, '=')) {
                         $new_var = trim(strtolower(substr($var, $cut + 1)));
                         $new_key = trim(substr($var, 0, $cut));
                         unset($vars[$i]);
                         $vars[$new_key] = $new_var;
                     }
                 }
                 // Set the charset based on the provided value, otherwise set it to UTF-8 (which is Drupals internal default).
                 $mailer->CharSet = isset($vars['charset']) ? $vars['charset'] : 'UTF-8';
                 // If $vars is empty then set an empty value at index 0 to avoid a PHP warning in the next statement
                 $vars[0] = isset($vars[0]) ? $vars[0] : '';
                 switch ($vars[0]) {
                     case 'text/plain':
                         // The message includes only a plain text part.
                         $mailer->IsHTML(FALSE);
                         $content_type = 'text/plain';
                         break;
                     case 'text/html':
                         // The message includes only an HTML part.
                         $mailer->IsHTML(TRUE);
                         $content_type = 'text/html';
                         break;
                     case 'multipart/related':
                         // Get the boundary ID from the Content-Type header.
                         $boundary = $this->_get_substring($value, 'boundary', '"', '"');
                         // The message includes an HTML part w/inline attachments.
                         $mailer->ContentType = $content_type = 'multipart/related; boundary="' . $boundary . '"';
                         break;
                     case 'multipart/alternative':
                         // The message includes both a plain text and an HTML part.
                         $mailer->ContentType = $content_type = 'multipart/alternative';
                         // Get the boundary ID from the Content-Type header.
                         $boundary = $this->_get_substring($value, 'boundary', '"', '"');
                         break;
                     case 'multipart/mixed':
                         // The message includes one or more attachments.
                         $mailer->ContentType = $content_type = 'multipart/mixed';
                         // Get the boundary ID from the Content-Type header.
                         $boundary = $this->_get_substring($value, 'boundary', '"', '"');
                         break;
                     default:
                         // Everything else is unsuppored by PHPMailer.
                         drupal_set_message(t('The %header of your message is not supported by PHPMailer and will be sent as text/plain instead.', array('%header' => "Content-Type: {$value}")), 'error');
                         watchdog('smtp', 'The %header of your message is not supported by PHPMailer and will be sent as text/plain instead.', array('%header' => "Content-Type: {$value}"), WATCHDOG_ERROR);
                         // Force the Content-Type to be text/plain.
                         $mailer->IsHTML(FALSE);
                         $content_type = 'text/plain';
                 }
                 break;
             case 'reply-to':
                 // Only add a "reply-to" if it's not the same as "return-path".
                 if ($value != $headers['Return-Path']) {
                     $reply_to_comp = $this->_get_components($value);
                     $mailer->AddReplyTo($reply_to_comp['email'], $reply_to_comp['name']);
                 }
                 break;
             case 'content-transfer-encoding':
                 $mailer->Encoding = $value;
                 break;
             case 'return-path':
                 $mailer->Sender = $value;
                 break;
             case 'mime-version':
             case 'x-mailer':
                 // Let PHPMailer specify these.
                 break;
             case 'errors-to':
                 $mailer->AddCustomHeader('Errors-To: ' . $value);
                 break;
             case 'cc':
                 $ccrecipients = explode(',', $value);
                 foreach ($ccrecipients as $ccrecipient) {
                     $cc_comp = $this->_get_components($ccrecipient);
                     $mailer->AddCC($cc_comp['email'], $cc_comp['name']);
                 }
                 break;
             case 'bcc':
                 $bccrecipients = explode(',', $value);
                 foreach ($bccrecipients as $bccrecipient) {
                     $bcc_comp = $this->_get_components($bccrecipient);
                     $mailer->AddBCC($bcc_comp['email'], $bcc_comp['name']);
                 }
                 break;
             default:
                 // The header key is not special - add it as is.
                 $mailer->AddCustomHeader($key . ': ' . $value);
         }
     }
     /**
      * TODO
      * Need to figure out the following.
      *
      * Add one last header item, but not if it has already been added.
      * $errors_to = FALSE;
      * foreach ($mailer->CustomHeader as $custom_header) {
      *   if ($custom_header[0] = '') {
      *     $errors_to = TRUE;
      *   }
      * }
      * if ($errors_to) {
      *   $mailer->AddCustomHeader('Errors-To: '. $from);
      * }
      */
     // Add the message's subject.
     $mailer->Subject = $subject;
     // Processes the message's body.
     switch ($content_type) {
         case 'multipart/related':
             $mailer->Body = $body;
             // TODO: Figure out if there is anything more to handling this type.
             break;
         case 'multipart/alternative':
             // Split the body based on the boundary ID.
             $body_parts = $this->_boundary_split($body, $boundary);
             foreach ($body_parts as $body_part) {
                 // If plain/text within the body part, add it to $mailer->AltBody.
                 if (strpos($body_part, 'text/plain')) {
                     // Clean up the text.
                     $body_part = trim($this->_remove_headers(trim($body_part)));
                     // Include it as part of the mail object.
                     $mailer->AltBody = $body_part;
                 } elseif (strpos($body_part, 'text/html')) {
                     // Clean up the text.
                     $body_part = trim($this->_remove_headers(trim($body_part)));
                     // Include it as part of the mail object.
                     $mailer->Body = $body_part;
                 }
             }
             break;
         case 'multipart/mixed':
             // Split the body based on the boundary ID.
             $body_parts = $this->_boundary_split($body, $boundary);
             // Determine if there is an HTML part for when adding the plain text part.
             $text_plain = FALSE;
             $text_html = FALSE;
             foreach ($body_parts as $body_part) {
                 if (strpos($body_part, 'text/plain')) {
                     $text_plain = TRUE;
                 }
                 if (strpos($body_part, 'text/html')) {
                     $text_html = TRUE;
                 }
             }
             foreach ($body_parts as $body_part) {
                 // If test/plain within the body part, add it to either
                 // $mailer->AltBody or $mailer->Body, depending on whether there is
                 // also a text/html part ot not.
                 if (strpos($body_part, 'multipart/alternative')) {
                     // Get boundary ID from the Content-Type header.
                     $boundary2 = $this->_get_substring($body_part, 'boundary', '"', '"');
                     // Clean up the text.
                     $body_part = trim($this->_remove_headers(trim($body_part)));
                     // Split the body based on the boundary ID.
                     $body_parts2 = $this->_boundary_split($body_part, $boundary2);
                     foreach ($body_parts2 as $body_part2) {
                         // If plain/text within the body part, add it to $mailer->AltBody.
                         if (strpos($body_part2, 'text/plain')) {
                             // Clean up the text.
                             $body_part2 = trim($this->_remove_headers(trim($body_part2)));
                             // Include it as part of the mail object.
                             $mailer->AltBody = $body_part2;
                             $mailer->ContentType = 'multipart/mixed';
                         } elseif (strpos($body_part2, 'text/html')) {
                             // Get the encoding.
                             $body_part2_encoding = $this->_get_substring($body_part2, 'Content-Transfer-Encoding', ' ', "\n");
                             // Clean up the text.
                             $body_part2 = trim($this->_remove_headers(trim($body_part2)));
                             // Check whether the encoding is base64, and if so, decode it.
                             if (Unicode::strtolower($body_part2_encoding) == 'base64') {
                                 // Include it as part of the mail object.
                                 $mailer->Body = base64_decode($body_part2);
                                 // Ensure the whole message is recoded in the base64 format.
                                 $mailer->Encoding = 'base64';
                             } else {
                                 // Include it as part of the mail object.
                                 $mailer->Body = $body_part2;
                             }
                             $mailer->ContentType = 'multipart/mixed';
                         }
                     }
                 } elseif (strpos($body_part, 'text/plain')) {
                     // Clean up the text.
                     $body_part = trim($this->_remove_headers(trim($body_part)));
                     if ($text_html) {
                         $mailer->AltBody = $body_part;
                         $mailer->IsHTML(TRUE);
                         $mailer->ContentType = 'multipart/mixed';
                     } else {
                         $mailer->Body = $body_part;
                         $mailer->IsHTML(FALSE);
                         $mailer->ContentType = 'multipart/mixed';
                     }
                 } elseif (strpos($body_part, 'text/html')) {
                     // Clean up the text.
                     $body_part = trim($this->_remove_headers(trim($body_part)));
                     // Include it as part of the mail object.
                     $mailer->Body = $body_part;
                     $mailer->IsHTML(TRUE);
                     $mailer->ContentType = 'multipart/mixed';
                 } elseif (strpos($body_part, 'Content-Disposition: attachment;') && !isset($message['params']['attachments'])) {
                     $file_path = $this->_get_substring($body_part, 'filename=', '"', '"');
                     $file_name = $this->_get_substring($body_part, ' name=', '"', '"');
                     $file_encoding = $this->_get_substring($body_part, 'Content-Transfer-Encoding', ' ', "\n");
                     $file_type = $this->_get_substring($body_part, 'Content-Type', ' ', ';');
                     if (file_exists($file_path)) {
                         if (!$mailer->AddAttachment($file_path, $file_name, $file_encoding, $file_type)) {
                             drupal_set_message(t('Attahment could not be found or accessed.'));
                         }
                     } else {
                         // Clean up the text.
                         $body_part = trim($this->_remove_headers(trim($body_part)));
                         if (Unicode::strtolower($file_encoding) == 'base64') {
                             $attachment = base64_decode($body_part);
                         } elseif (Unicode::strtolower($file_encoding) == 'quoted-printable') {
                             $attachment = quoted_printable_decode($body_part);
                         } else {
                             $attachment = $body_part;
                         }
                         $attachment_new_filename = \Drupal::service('file_system')->tempnam('temporary://', 'smtp');
                         $file_path = file_save_data($attachment, $attachment_new_filename, FILE_EXISTS_REPLACE);
                         $real_path = \Drupal::service('file_system')->realpath($file_path->uri);
                         if (!$mailer->AddAttachment($real_path, $file_name)) {
                             drupal_set_message(t('Attachment could not be found or accessed.'));
                         }
                     }
                 }
             }
             break;
         default:
             $mailer->Body = $body;
             break;
     }
     // Process mimemail attachments, which are prepared in mimemail_mail().
     if (isset($message['params']['attachments'])) {
         foreach ($message['params']['attachments'] as $attachment) {
             if (isset($attachment['filecontent'])) {
                 $mailer->AddStringAttachment($attachment['filecontent'], $attachment['filename'], 'base64', $attachment['filemime']);
             }
             if (isset($attachment['filepath'])) {
                 $filename = isset($attachment['filename']) ? $attachment['filename'] : basename($attachment['filepath']);
                 $filemime = isset($attachment['filemime']) ? $attachment['filemime'] : file_get_mimetype($attachment['filepath']);
                 $mailer->AddAttachment($attachment['filepath'], $filename, 'base64', $filemime);
             }
         }
     }
     // Set the authentication settings.
     $username = $this->smtpConfig->get('smtp_username');
     $password = $this->smtpConfig->get('smtp_password');
     // If username and password are given, use SMTP authentication.
     if ($username != '' && $password != '') {
         $mailer->SMTPAuth = TRUE;
         $mailer->Username = $username;
         $mailer->Password = $password;
     }
     // Set the protocol prefix for the smtp host.
     switch ($this->smtpConfig->get('smtp_protocol')) {
         case 'ssl':
             $mailer->SMTPSecure = 'ssl';
             break;
         case 'tls':
             $mailer->SMTPSecure = 'tls';
             break;
         default:
             $mailer->SMTPSecure = '';
     }
     // Set other connection settings.
     $mailer->Host = $this->smtpConfig->get('smtp_host') . ';' . $this->smtpConfig->get('smtp_hostbackup');
     $mailer->Port = $this->smtpConfig->get('smtp_port');
     $mailer->Mailer = 'smtp';
     $mailerArr = array('mailer' => $mailer, 'to' => $to, 'from' => $from);
     if ($this->smtpConfig->get('smtp_queue')) {
         watchdog('smtp', 'Queue sending mail to: @to', array('@to' => $to));
         smtp_send_queue($mailerArr);
     } else {
         return _smtp_mailer_send($mailerArr);
     }
     return TRUE;
 }
Пример #25
0
 /**
  * Function for generating the external stylesheet.
  *
  * @param bool $force
  *   Force the regeneration of the CSS file.
  */
 public static function generateLanguagesCssFile($force = FALSE)
 {
     $languages = GeshiFilter::getEnabledLanguages();
     // Serialize the array of enabled languages as sort of hash.
     $languages_hash = serialize($languages);
     // Check if generation of the CSS file is needed.
     if ($force || $languages_hash != \Drupal::state()->get('geshifilter_cssfile_languages')) {
         // Build stylesheet.
         $stylesheet = self::generateLanguagesCssRules();
         // Save stylesheet.
         $stylesheet_filename = self::languageCssPath();
         $ret = file_save_data($stylesheet, $stylesheet_filename, FILE_EXISTS_REPLACE);
         if ($ret) {
             drupal_set_message(t('(Re)generated external CSS style sheet %file.', array('%file' => $ret->getFilename())));
         } else {
             drupal_set_message(t('Could not generate external CSS file. Check the settings of your <a href="!filesystem">file system</a>.', array('!filesystem' => Url::fromRoute('system.file_system_settings')->toString())), 'error');
         }
         // Remember for which list of languages the CSS file was generated.
         \Drupal::state()->set('cssfile_languages', $languages_hash);
     }
 }
Пример #26
0
 /**
  * Saves an advertiser & checks the image field is set.
  */
 public function testAdvertiserImage()
 {
     // Download an example image from the internet.
     $test_data = file_get_contents('https://www.drupal.org/sites/all/modules/drupalorg/drupalorg/images/qmark-400x684-2x.png');
     //Save the file to the temporary scheme.
     $image_file = file_save_data($test_data, 'temporary://test_test_test.png', FILE_EXISTS_REPLACE);
     $image_file_uri = $image_file->getFileUri();
     // Create an entity.
     $entity = Advertiser::create(['advertiser_image' => $image_file_uri]);
     // Save it.
     $entity->save();
     // Get the id.
     $id = $entity->id();
     // Load the saved entity.
     $saved_entity = Advertiser::load($id);
     // Get the imageUri from the entity's image field using the getImage method defined in our entity.
     $image_uri = $saved_entity->getImage();
     // Check the imageUri field matches.
     $this->assertEqual($image_file_uri, $image_uri, 'Image successfully saved', 'image');
 }
Пример #27
0
 /**
  * Test that file_save_data() fails overwriting an existing file.
  */
 function testExistingError()
 {
     $contents = $this->randomName(8);
     $existing = $this->createFile(NULL, $contents);
     // Check the overwrite error.
     $result = file_save_data('asdf', $existing->getFileUri(), FILE_EXISTS_ERROR);
     $this->assertFalse($result, 'Overwriting a file fails when FILE_EXISTS_ERROR is specified.');
     $this->assertEqual($contents, file_get_contents($existing->getFileUri()), 'Contents of existing file were unchanged.');
     // Check that no hooks were called while failing.
     $this->assertFileHooksCalled(array());
     // Ensure that the existing file wasn't overwritten.
     $this->assertFileUnchanged($existing, file_load($existing->id(), TRUE));
 }
 /**
  * Downloads and saves a file in a field
  *
  * @param mixed $field
  *   A string or an array of strings
  * @param string $path
  *   Where to save file. Default is public://
  * @param int $options
  *   Use 0 to rename existing file or 1 to replace it.
  *
  * @return mixed
  *   An object or an array of objects containing file info
  */
 public static function saveFile($field, $path = 'public://', $options = FILE_EXISTS_RENAME)
 {
     if (is_array($field)) {
         foreach ($field as &$f) {
             $f = self::saveFile($f, $path, $options);
         }
         return $field;
     }
     // Get file data.
     try {
         $image = file_get_contents($field);
     } catch (Exception $e) {
         return NULL;
     }
     $field = trim($field, '/');
     $field = drupal_substr($field, strrpos($field, '/') + 1);
     if (file_prepare_directory($path, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
         return file_save_data($image, $path . $field, (int) $options);
     }
     return NULL;
 }
Пример #29
0
/**
 * Final submit handler.
 *
 * Reports what values were finally set.
 */
function md_boom_multi_save_settings($form, &$form_state)
{
    if ($logo_normal_file = file_save_upload('logo_normal_upload')) {
        $parts = pathinfo($logo_normal_file->filename);
        $destination = 'public://' . $parts['basename'];
        $logo_normal_file->status = FILE_STATUS_PERMANENT;
        if (file_copy($logo_normal_file, $destination, FILE_EXISTS_REPLACE)) {
            $_POST['logo_normal_path'] = $form_state['values']['logo_normal_path'] = $destination;
        }
    } elseif ($logo_normal_path = $form_state['values']['logo_normal_path']) {
        $logo_normal_scheme = file_uri_scheme($logo_normal_path);
        if ($logo_normal_scheme == 'http' || $logo_normal_scheme == 'https') {
            $newimagename = basename(rawurldecode($logo_normal_path));
            $external_file = file_get_contents(rawurldecode($logo_normal_path));
            file_save_data($external_file, 'public://' . $newimagename . '', $replace = FILE_EXISTS_REPLACE);
            $form_state['values']['logo_normal_path'] = 'public://' . $newimagename;
        }
    }
    if ($logo_retina_file = file_save_upload('logo_retina_upload')) {
        $parts = pathinfo($logo_retina_file->filename);
        $destination = 'public://' . $parts['basename'];
        $logo_retina_file->status = FILE_STATUS_PERMANENT;
        if (file_copy($logo_retina_file, $destination, FILE_EXISTS_REPLACE)) {
            $_POST['logo_retina_path'] = $form_state['values']['logo_retina_path'] = $destination;
        }
    } elseif ($logo_retina_path = $form_state['values']['logo_retina_path']) {
        $logo_retina_scheme = file_uri_scheme($logo_retina_path);
        if ($logo_retina_scheme == 'http' || $logo_retina_scheme == 'https') {
            $newimagename = basename(rawurldecode($logo_retina_path));
            $external_file = file_get_contents(rawurldecode($logo_retina_path));
            file_save_data($external_file, 'public://' . $newimagename . '', $replace = FILE_EXISTS_REPLACE);
            $form_state['values']['logo_retina_path'] = 'public://' . $newimagename;
        }
    }
    if ($footer_logo_file = file_save_upload('footer_logo_upload')) {
        $parts = pathinfo($footer_logo_file->filename);
        $destination = 'public://' . $parts['basename'];
        $footer_logo_file->status = FILE_STATUS_PERMANENT;
        if (file_copy($footer_logo_file, $destination, FILE_EXISTS_REPLACE)) {
            $_POST['footer_logo_path'] = $form_state['values']['footer_logo_path'] = $destination;
        }
    } elseif ($footer_logo_path = $form_state['values']['footer_logo_path']) {
        $footer_logo_scheme = file_uri_scheme($footer_logo_path);
        if ($footer_logo_scheme == 'http' || $footer_logo_scheme == 'https') {
            $newimagename = basename(rawurldecode($footer_logo_path));
            $external_file = file_get_contents(rawurldecode($footer_logo_path));
            file_save_data($external_file, 'public://' . $newimagename . '', $replace = FILE_EXISTS_REPLACE);
            $form_state['values']['footer_logo_path'] = 'public://' . $newimagename;
        }
    }
    if ($favicon_file = file_save_upload('fvicon_upload')) {
        $parts = pathinfo($favicon_file->filename);
        $destination = 'public://' . $parts['basename'];
        $favicon_file->status = FILE_STATUS_PERMANENT;
        if (file_copy($favicon_file, $destination, FILE_EXISTS_REPLACE)) {
            $_POST['fvicon_path'] = $form_state['values']['fvicon_path'] = $destination;
        }
    } elseif ($favicon_path = $form_state['values']['favicon_path']) {
        $favicon_scheme = file_uri_scheme($favicon_path);
        if ($favicon_scheme == 'http' || $favicon_scheme == 'https') {
            $newimagename = basename(rawurldecode($favicon_path));
            $external_file = file_get_contents(rawurldecode($favicon_path));
            file_save_data($external_file, 'public://' . $newimagename . '', $replace = FILE_EXISTS_REPLACE);
            $form_state['values']['favicon_path'] = 'public://' . $newimagename;
        }
    }
    $form_state['values']['logo_path'] = $form_state['values']['logo_normal_path'];
    $form_state['values']['favicon_path'] = $form_state['values']['fvicon_path'];
    if ($form_state['values']['default_logo'] == 1) {
        $form_state['values']['logo_path'] = '';
        $form_state['values']['logo_normal_path'] = '';
        $form_state['values']['logo_retina_path'] = '';
        $form_state['values']['footer_logo_path'] = '';
    }
    if ($form_state['values']['default_favicon'] == 1) {
        $form_state['values']['favicon_path'] = '';
        $form_state['values']['fvicon_path'] = '';
    }
    if ($video_bg_file = file_save_upload('video_bg_upload', array('file_validate_extensions' => array('mov mp4 m4a m4v mpeg avi ogg oga ogv weba webp webm')))) {
        $parts = pathinfo($video_bg_file->filename);
        $destination = 'public://' . $parts['basename'];
        $video_bg_file->status = FILE_STATUS_PERMANENT;
        if (file_copy($video_bg_file, $destination, FILE_EXISTS_REPLACE)) {
            $_POST['video_bg_path'] = $form_state['values']['video_bg_path'] = $destination;
        }
    } elseif ($video_bg_path = $form_state['values']['video_bg_path']) {
        $video_bg_scheme = file_uri_scheme($video_bg_path);
        if ($video_bg_scheme == 'http' || $video_bg_scheme == 'https') {
            $newimagename = basename(rawurldecode($video_bg_path));
            $external_file = file_get_contents(rawurldecode($video_bg_path));
            file_save_data($external_file, 'public://' . $newimagename . '', $replace = FILE_EXISTS_REPLACE);
            $form_state['values']['video_bg_path'] = 'public://' . $newimagename;
        }
    }
    if ($bg_file = file_save_upload('bg_upload')) {
        $parts = pathinfo($bg_file->filename);
        $destination = 'public://' . $parts['basename'];
        $bg_file->status = FILE_STATUS_PERMANENT;
        if (file_copy($bg_file, $destination, FILE_EXISTS_REPLACE)) {
            $_POST['bg_path'] = $form_state['values']['bg_path'] = $destination;
        }
    } elseif ($bg_path = $form_state['values']['bg_path']) {
        $bg_scheme = file_uri_scheme($bg_path);
        if ($bg_scheme == 'http' || $bg_scheme == 'https') {
            $newimagename = basename(rawurldecode($bg_path));
            $external_file = file_get_contents(rawurldecode($bg_path));
            file_save_data($external_file, 'public://' . $newimagename . '', $replace = FILE_EXISTS_REPLACE);
            $form_state['values']['bg_path'] = 'public://' . $newimagename;
        }
    }
    if (theme_get_setting('slider_bg_image', 'md_boom_multi') != null || isset($form_state['values']['slider_bg_image'])) {
        $form_state['values']['slider_bg_image'] = theme_get_setting('slider_bg_image', 'md_boom_multi');
    } else {
        $form_state['values']['slider_bg_image'] = array();
    }
    if ($form_state['values']['slider_bg_upload']) {
        $slider_file = $form_state['values']['slider_bg_upload'];
        if (count($slider_file) > 1) {
            if (is_array($form_state['values']['slider_bg_image']) && !empty($form_state['values']['slider_bg_image'])) {
                foreach ($form_state['values']['slider_bg_image'] as $preview) {
                    $old_image = array($preview);
                }
            } else {
                $old_image = array();
            }
            foreach ($slider_file as $key => $file) {
                $file_save = file_get_contents($file['tmppath']);
                file_save_data($file_save, 'public://' . $file['name'], FILE_EXISTS_REPLACE);
                if (in_array('public://' . $file['name'] . '', $old_image)) {
                    drupal_set_message(t('Some images have already exist. Please change name or upload each other'), 'warning');
                } else {
                    $form_state['values']['slider_bg_image'][] = 'public://' . $file['name'] . '';
                }
            }
        } else {
            drupal_set_message(t('You must upload more than 1 image to create slider background'), 'error');
        }
    }
}
Пример #30
0
 $issue_dir = variable_get('project_directory_issues', 'issues');
 $dest = file_directory_path() . '/' . $issue_dir;
 // Drupal's standard files path
 if (!file_check_directory($dest)) {
     echo "<br>Error processing attachments.  Event has been logged and an administrator notified.\n";
     error_log("Attachment directory {$dest} does not exist or is not writable.");
     exit;
 }
 foreach (array($validation, $configcheck, $collected) as $attachment) {
     if (empty($attachment)) {
         continue;
     }
     // Generate a randomish unique file name
     $file_id = $nid . "_" . time() . posix_getpid() . ++$acount;
     // Save the file and put the path into $file
     $file = file_save_data($attachment, "{$dest}/{$file_id}", $replace = FILE_EXISTS_RENAME);
     // Make it a node in Drupal
     // Get the file size
     $details = stat($file);
     $filesize = $details['size'];
     $name = basename($file);
     // Build the file object
     $file_obj = new stdClass();
     $file_obj->filename = $name;
     $file_obj->filepath = $file;
     $file_obj->filemime = 'text/plain';
     $file_obj->filesize = $filesize;
     // You can change this to the UID you want
     $file_obj->uid = $uid;
     $file_obj->status = FILE_STATUS_TEMPORARY;
     $file_obj->timestamp = time();