/** * Private function for creating a random image. * * This function only works with the GD toolkit. ImageMagick is not supported. */ protected function generateImage($extension = 'png', $min_resolution, $max_resolution) { if ($tmp_file = drupal_tempnam('temporary://', 'imagefield_')) { $destination = $tmp_file . '.' . $extension; file_unmanaged_move($tmp_file, $destination, FILE_CREATE_DIRECTORY); $min = explode('x', $min_resolution); $max = explode('x', $max_resolution); $width = rand((int) $min[0], (int) $max[0]); $height = rand((int) $min[1], (int) $max[1]); // Make an image split into 4 sections with random colors. $im = imagecreate($width, $height); for ($n = 0; $n < 4; $n++) { $color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255)); $x = $width / 2 * ($n % 2); $y = $height / 2 * (int) ($n >= 2); imagefilledrectangle($im, $x, $y, $x + $width / 2, $y + $height / 2, $color); } // Make a perfect circle in the image middle. $color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255)); $smaller_dimension = min($width, $height); $smaller_dimension = $smaller_dimension % 2 ? $smaller_dimension : $smaller_dimension; imageellipse($im, $width / 2, $height / 2, $smaller_dimension, $smaller_dimension, $color); $save_function = 'image' . ($extension == 'jpg' ? 'jpeg' : $extension); $save_function($im, drupal_realpath($destination)); return $destination; } }
public function generateImage($object, $field, $instance, $bundle) { $object_field = array(); static $available_images = array(); if (empty($available_images)) { $available_images = $this->getImages(); } if (empty($available_images)) { $args = func_get_args(); return call_user_func_array('_image_devel_generate', $args); } $extension = array_rand(array('jpg' => 'jpg', 'png' => 'png')); $min_resolution = empty($instance['settings']['min_resolution']) ? '100x100' : $instance['settings']['min_resolution']; $max_resolution = empty($instance['settings']['max_resolution']) ? '600x600' : $instance['settings']['max_resolution']; if (FALSE === ($tmp_file = drupal_tempnam('temporary://', 'imagefield_'))) { return FALSE; } $destination = $tmp_file . '.' . $extension; file_unmanaged_move($tmp_file, $destination, FILE_EXISTS_REPLACE); $rand_file = array_rand($available_images); if (!empty($instance['settings']['file_directory'])) { $instance['settings']['file_directory'] = $instance['settings']['file_directory'] . '/'; } $destination_dir = $field['settings']['uri_scheme'] . '://' . $instance['settings']['file_directory']; file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY); if ($this->settings['devel_image_no_alter']) { $file = $available_images[$rand_file]; $file = file_copy($file, $destination_dir); } else { $image = image_load($rand_file); $min = explode('x', $min_resolution); $max = explode('x', $max_resolution); $max[0] = $max[0] < $min[0] ? $min[0] : $max[0]; $max[1] = $max[1] < $min[1] ? $min[1] : $max[1]; $width = rand((int) $min[0], (int) $max[0]); $height = rand((int) $min[1], (int) $max[1]); if (!image_scale_and_crop($image, $width, $height)) { return FALSE; } // Use destination image type. $image->info['extension'] = $extension; if (!image_save($image, $destination)) { return FALSE; } $source = new stdClass(); $source->uri = $destination; $source->uid = 1; // TODO: randomize? Use case specific. $source->filemime = $image->info['mime_type']; $source->filename = drupal_basename($image->source); $destination = $destination_dir . basename($destination); $file = file_move($source, $destination, FILE_CREATE_DIRECTORY); } $object_field['fid'] = $file->fid; $object_field['alt'] = devel_create_greeking(4); $object_field['title'] = devel_create_greeking(4); return $object_field; }
/** * {@inheritdoc} */ public function getFilePath() { // Write to a temporary file if the parser expects a file. if ($this->filePath) { return $this->filePath; } $this->filePath = drupal_tempnam('temporary://', 'feeds-raw'); file_put_contents($this->filePath, $this->getRaw()); return $this->filePath; }
public function generateImage($object, $field, $instance, $bundle) { static $images = array(); $min_resolution = empty($instance['settings']['min_resolution']) ? '100x100' : $instance['settings']['min_resolution']; $max_resolution = empty($instance['settings']['max_resolution']) ? '600x600' : $instance['settings']['max_resolution']; $extension = 'jpg'; if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= DEVEL_GENERATE_IMAGE_MAX) { if ($tmp_file = drupal_tempnam('temporary://', 'imagefield_')) { $destination = $tmp_file . '.' . $extension; file_unmanaged_move($tmp_file, $destination, FILE_EXISTS_REPLACE); $min = explode('x', $min_resolution); $max = explode('x', $max_resolution); $max[0] = $max[0] < $min[0] ? $min[0] : $max[0]; $max[1] = $max[1] < $min[1] ? $min[1] : $max[1]; $width = rand((int) $min[0], (int) $max[0]); $height = rand((int) $min[1], (int) $max[1]); $gray = isset($this->settings['devel_image_provider_gray']) ? $this->settings['devel_image_provider_gray'] : NULL; $tags = isset($this->settings['devel_image_provider_tags']) ? $this->settings['devel_image_provider_tags'] : NULL; $url = "{$this->provider_base_url}/{$width}/{$height}"; if (!empty($tags)) { $url .= '/' . $tags; } $url = $gray ? $url . '/bw' : $url; // Generate seed value. $seed = isset($this->settings['devel_image_provider_seed']) ? $this->settings['devel_image_provider_seed'] : NULL; $rand_value = rand(0, $seed); $url .= '/' . $rand_value; $method = isset($this->settings['devel_image_provider_get_method']) ? $this->settings['devel_image_provider_get_method'] : 'file_get_contents'; $path = devel_image_provider_get_file($url, $destination, $method); $source = new stdClass(); $source->uri = $path; $source->uid = 1; // TODO: randomize? Use case specific. $source->filemime = 'image/jpg'; if (!empty($instance['settings']['file_directory'])) { $instance['settings']['file_directory'] = $instance['settings']['file_directory'] . '/'; } $destination_dir = $field['settings']['uri_scheme'] . '://' . $instance['settings']['file_directory']; file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY); $destination = $destination_dir . basename($path); $file = file_move($source, $destination, FILE_CREATE_DIRECTORY); } else { return FALSE; } } else { // Select one of the images we've already generated for this field. $file = new stdClass(); $file->fid = array_rand($images[$extension][$min_resolution][$max_resolution]); } $object_field['fid'] = $file->fid; $object_field['alt'] = devel_create_greeking(4); $object_field['title'] = devel_create_greeking(4); return $object_field; }
/** * {@inheritdoc} */ public function getFilePath() { // Write to a temporary file if the parser expects a file. if (!$this->filePath) { $this->filePath = drupal_tempnam('temporary://', 'feeds-raw'); if (file_put_contents($this->filePath, $this->getRaw()) === FALSE) { $this->error('File %filepath is not writable.'); } } return $this->filePath; }
/** * Private function for generating a random text file. */ private function generateTextFile($filesize = 1024) { if ($tmp_file = drupal_tempnam('temporary://', 'filefield_')) { $destination = $tmp_file . '.txt'; file_unmanaged_move($tmp_file, $destination); $fp = fopen($destination, 'w'); fwrite($fp, str_repeat('01', $filesize / 2)); fclose($fp); return $destination; } }
/** * {@inheritdoc} */ public function fetch(FeedInterface $feed, StateInterface $state) { $response = $this->get($feed->getSource(), $this->getCacheKey($feed)); $feed->setSource($response->getEffectiveUrl()); // 304, nothing to see here. if ($response->getStatusCode() == 304) { $state->setMessage($this->t('The feed has not been updated.')); throw new EmptyFeedException(); } // Copy the temp stream to a real file. $download_file = drupal_tempnam('temporary://', 'feeds_http_fetcher'); $dest_stream = Utils::create(fopen($download_file, 'w+')); Utils::copyToStream($response->getBody(), $dest_stream); $response->getBody()->close(); $dest_stream->close(); return new HttpFetcherResult($download_file, $response->getHeaders()); }
/** * {@inheritdoc} */ protected function connect() { try { // This doesn't actually test the connection. db_set_active(); // Now actually do a check. Database::getConnection(); $this->pass('Drupal can CONNECT to the database ok.'); } catch (\Exception $e) { // Attempt to create the database if it is not found. if ($e->getCode() == Connection::DATABASE_NOT_FOUND) { // Remove the database string from connection info. $connection_info = Database::getConnectionInfo(); $database = $connection_info['default']['database']; // We cannot use file_directory_temp() here because we haven't yet // successfully connected to the database. $connection_info['default']['database'] = drupal_tempnam(sys_get_temp_dir(), 'sqlite'); // In order to change the Database::$databaseInfo array, need to remove // the active connection, then re-add it with the new info. Database::removeConnection('default'); Database::addConnectionInfo('default', 'default', $connection_info['default']); try { Database::getConnection()->createDatabase($database); Database::closeConnection(); // Now, restore the database config. Database::removeConnection('default'); $connection_info['default']['database'] = $database; Database::addConnectionInfo('default', 'default', $connection_info['default']); // Check the database connection. Database::getConnection(); $this->pass('Drupal can CONNECT to the database ok.'); } catch (DatabaseNotFoundException $e) { // Still no dice; probably a permission issue. Raise the error to the // installer. $this->fail(t('Database %database not found. The server reports the following message when attempting to create the database: %error.', array('%database' => $database, '%error' => $e->getMessage()))); } } else { // Database connection failed for some other reason than the database // not existing. $this->fail(t('Failed to connect to your database server. The server reports the following message: %error.<ul><li>Is the database server running?</li><li>Does the database exist, and have you entered the correct database name?</li><li>Have you entered the correct username and password?</li><li>Have you entered the correct database hostname?</li></ul>', array('%error' => $e->getMessage()))); return FALSE; } } return TRUE; }
/** * {@inheritdoc} */ public function save($destination) { $scheme = file_uri_scheme($destination); // Work around lack of stream wrapper support in imagejpeg() and imagepng(). if ($scheme && file_stream_wrapper_valid_scheme($scheme)) { // If destination is not local, save image to temporary local file. $local_wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL); if (!isset($local_wrappers[$scheme])) { $permanent_destination = $destination; $destination = drupal_tempnam('temporary://', 'gd_'); } // Convert stream wrapper URI to normal path. $destination = drupal_realpath($destination); } switch ($this->getType()) { case GDToolkitWebP::IMAGETYPE_WEBP: $function = 'imagewebp'; break; default: $function = 'image' . image_type_to_extension($this->getType(), FALSE); break; } if (!function_exists($function)) { return FALSE; } if ($this->getType() == IMAGETYPE_JPEG) { $success = $function($this->getResource(), $destination, $this->configFactory->get('system.image.gd')->get('jpeg_quality')); } else { // Always save PNG images with full transparency. if ($this->getType() == IMAGETYPE_PNG) { imagealphablending($this->getResource(), FALSE); imagesavealpha($this->getResource(), TRUE); } $success = $function($this->getResource(), $destination); } // Move temporary local file to remote destination. if (isset($permanent_destination) && $success) { return (bool) file_unmanaged_move($destination, $permanent_destination, FILE_EXISTS_REPLACE); } return $success; }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $random = new Random(); $settings = $field_definition->getSettings(); static $images = array(); $min_resolution = empty($settings['min_resolution']) ? '100x100' : $settings['min_resolution']; $max_resolution = empty($settings['max_resolution']) ? '600x600' : $settings['max_resolution']; $extensions = array_intersect(explode(' ', $settings['file_extensions']), array('png', 'gif', 'jpg', 'jpeg')); $extension = array_rand(array_combine($extensions, $extensions)); // Generate a max of 5 different images. if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= 5) { $tmp_file = drupal_tempnam('temporary://', 'generateImage_'); $destination = $tmp_file . '.' . $extension; file_unmanaged_move($tmp_file, $destination, FILE_CREATE_DIRECTORY); if ($path = $random->image(drupal_realpath($destination), $min_resolution, $max_resolution)) { $image = File::create(); $image->setFileUri($path); $image->setOwnerId(\Drupal::currentUser()->id()); $image->setMimeType(\Drupal::service('file.mime_type.guesser')->guess($path)); $image->setFileName(drupal_basename($path)); $destination_dir = static::doGetUploadLocation($settings); file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY); $destination = $destination_dir . '/' . basename($path); $file = file_move($image, $destination, FILE_CREATE_DIRECTORY); $images[$extension][$min_resolution][$max_resolution][$file->id()] = $file; } else { return array(); } } else { // Select one of the images we've already generated for this field. $image_index = array_rand($images[$extension][$min_resolution][$max_resolution]); $file = $images[$extension][$min_resolution][$max_resolution][$image_index]; } list($width, $height) = getimagesize($file->getFileUri()); $values = array('target_id' => $file->id(), 'alt' => $random->sentences(4), 'title' => $random->sentences(4), 'width' => $width, 'height' => $height); return $values; }
public function generateImage($object, $field, $instance, $bundle) { static $images = array(); $min_resolution = empty($instance['settings']['min_resolution']) ? '100x100' : $instance['settings']['min_resolution']; $max_resolution = empty($instance['settings']['max_resolution']) ? '600x600' : $instance['settings']['max_resolution']; $extension = 'jpg'; if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= DEVEL_GENERATE_IMAGE_MAX) { if ($tmp_file = drupal_tempnam('temporary://', 'imagefield_')) { $destination = $tmp_file . '.' . $extension; file_unmanaged_move($tmp_file, $destination, FILE_CREATE_DIRECTORY); $min = explode('x', $min_resolution); $max = explode('x', $max_resolution); $max[0] = $max[0] < $min[0] ? $min[0] : $max[0]; $max[1] = $max[1] < $min[1] ? $min[1] : $max[1]; $width = rand((int) $min[0], (int) $max[0]); $height = rand((int) $min[1], (int) $max[1]); $gray = isset($this->settings['devel_image_provider_gray']) ? $this->settings['devel_image_provider_gray'] : NULL; $gray_part = $gray ? '/g' : ''; $url = "{$this->provider_base_url}" . $gray_part . "/{$width}/{$height}"; $categories = isset($this->settings['devel_image_provider_categories']) ? $this->settings['devel_image_provider_categories'] : array(); $category = array_rand($categories); if (!empty($category) && $category != 'any') { $url .= '/' . $category; } $include_text = isset($this->settings['devel_image_provider_include_text']) ? $this->settings['devel_image_provider_include_text'] : FALSE; switch ($include_text) { case 'custom': $custom_text = isset($this->settings['devel_image_provider_custom_text']) ? $this->settings['devel_image_provider_custom_text'] : ''; break; case 'random': $custom_text = trim(substr(devel_create_greeking(mt_rand(1, 4)), 0, 16)); break; case 'default': default: $custom_text = ''; break; } if (!empty($custom_text)) { // Replace the spaces with - as per lorempixum specifications. $custom_text = str_replace(' ', '-', check_plain($custom_text)); $url .= '/' . $custom_text; } $method = isset($this->settings['devel_image_provider_get_method']) ? $this->settings['devel_image_provider_get_method'] : 'file_get_contents'; $path = devel_image_provider_get_file($url, $destination, $method); $source = new stdClass(); $source->uri = $path; $source->uid = 1; // TODO: randomize? Use case specific. $source->filemime = 'image/jpg'; if (!empty($instance['settings']['file_directory'])) { $instance['settings']['file_directory'] = $instance['settings']['file_directory'] . '/'; } $destination_dir = $field['settings']['uri_scheme'] . '://' . $instance['settings']['file_directory']; file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY); $destination = $destination_dir . basename($path); $file = file_move($source, $destination, FILE_CREATE_DIRECTORY); } else { return FALSE; } } else { // Select one of the images we've already generated for this field. $file = new stdClass(); $file->fid = array_rand($images[$extension][$min_resolution][$max_resolution]); } $object_field['fid'] = $file->fid; $object_field['alt'] = devel_create_greeking(4); $object_field['title'] = devel_create_greeking(4); return $object_field; }
/** * 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) { $id = $message['id']; $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'); } //Hack to fix reply-to issue. $properfrom = $this->smtpConfig->get('site_mail'); if (!empty($properfrom)) { $headers['From'] = $properfrom; } if (!isset($headers['Reply-To']) || empty($headers['Reply-To'])) { if (strpos($from, '<')) { $reply = preg_replace('/>.*/', '', preg_replace('/.*</', '', $from)); } else { $reply = $from; } $headers['Reply-To'] = $reply; } // Blank value will let the e-mail address appear. if ($from == NULL || $from == '') { // If from e-mail address is blank, use smtp_from config option. if (($from = $this->smtpConfig->get('smtp_from')) == '') { // If smtp_from config option is blank, use site_email. if (($from = $this->smtpConfig->get('site_mail')) == '') { drupal_set_message(t('There is no submitted from address.'), 'error'); watchdog('smtp', 'There is no submitted from address.', array(), WATCHDOG_ERROR); return FALSE; } } } $from_comp = $this->_get_components($from); if (!valid_email_address($from_comp['email'])) { drupal_set_message(t('The submitted from address (@from) is not valid.', array('@from' => $from)), 'error'); watchdog('smtp', 'The submitted from address (@from) is not valid.', array('@from' => $from), WATCHDOG_ERROR); return FALSE; } // Defines the From value to what we expect. $mailer->From = $from; $mailer->FromName = $from_comp['name']; $mailer->Sender = $from_comp['email']; // 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_tempnam('temporary://', 'smtp'); $file_path = file_save_data($attachment, $attachment_new_filename, FILE_EXISTS_REPLACE); $real_path = drupal_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; }
/** * Performs a GET request. * * @param string $url * The URL to GET. * * @return \Guzzle\Http\Message\Response * A Guzzle response. */ protected function get($url, $cache = TRUE) { $url = strtr($url, array('feed://' => 'http://', 'webcal://' => 'http://')); $client = \Drupal::httpClient(); // Add our handy dandy cache plugin. It's magic. if ($cache) { $client->addSubscriber(new CachePlugin(\Drupal::cache())); } $request = $client->get($url); // Stream to a file to provide the best scenario for intellegent parsers. $tempname = drupal_tempnam('temporary://', 'feeds_download_cache_'); $request->setResponseBody($tempname); try { $response = $request->send(); } catch (BadResponseException $e) { $response = $e->getResponse(); $args = array('%url' => $url, '%error' => $response->getStatusCode() . ' ' . $response->getReasonPhrase()); watchdog('feeds', 'The feed %url seems to be broken due to "%error".', $args, WATCHDOG_WARNING); drupal_set_message($this->t('The feed %url seems to be broken because of error "%error".', $args, 'warning')); return FALSE; } catch (RequestException $e) { $args = array('%url' => $url, '%error' => $e->getMessage()); watchdog('feeds', 'The feed %url seems to be broken due to "%error".', $args, WATCHDOG_WARNING); drupal_set_message($this->t('The feed %url seems to be broken because of error "%error".', $args), 'warning'); return FALSE; } return $response; }
public function generateImage($object, $field, $instance, $bundle) { static $images = array(); $min_resolution = empty($instance['settings']['min_resolution']) ? '100x100' : $instance['settings']['min_resolution']; $max_resolution = empty($instance['settings']['max_resolution']) ? '600x600' : $instance['settings']['max_resolution']; $extension = 'jpg'; if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= DEVEL_GENERATE_IMAGE_MAX) { if ($tmp_file = drupal_tempnam('temporary://', 'imagefield_')) { $destination = $tmp_file . '.' . $extension; file_unmanaged_move($tmp_file, $destination, FILE_CREATE_DIRECTORY); $min = explode('x', $min_resolution); $max = explode('x', $max_resolution); $max[0] = $max[0] < $min[0] ? $min[0] : $max[0]; $max[1] = $max[1] < $min[1] ? $min[1] : $max[1]; $width = rand((int) $min[0], (int) $max[0]); $height = rand((int) $min[1], (int) $max[1]); $background_color = isset($this->settings['devel_image_provider_background_color']) ? $this->settings['devel_image_provider_background_color'] : FALSE; if ($background_color) { if (preg_match('/^#[a-f0-9]{6}$/i', $background_color)) { // Check for valid hex number $background_color = "/" . str_replace('#', '', check_plain($background_color)); // Strip out # } else { $background_color = ''; } } else { $background_color = ''; } $text_color = isset($this->settings['devel_image_provider_text_color']) ? $this->settings['devel_image_provider_text_color'] : FALSE; if ($text_color) { // Check for valid hex number. if (preg_match('/^#[a-f0-9]{6}$/i', $text_color)) { // Strip out # character. $text_color = "/" . str_replace('#', '', check_plain($text_color)); } else { $text_color = ''; } } else { $text_color = ''; } $include_text = isset($this->settings['devel_image_provider_include_text']) ? $this->settings['devel_image_provider_include_text'] : FALSE; switch ($include_text) { case 'custom': $custom_text = isset($this->settings['devel_image_provider_custom_text']) ? $this->settings['devel_image_provider_custom_text'] : ''; break; case 'random': // Small random text as text size is depending on the image size. $custom_text = trim(substr(devel_create_greeking(mt_rand(1, 3)), 0, 8)); break; case 'default': default: $custom_text = ''; break; } if (!empty($custom_text)) { //Replace the spaces with + as per provider specifications $custom_text = "&text=" . str_replace(' ', '+', check_plain($custom_text)); } $url = "{$this->provider_base_url}/" . $width . "x" . $height . '/' . $background_color . '/' . $text_color . '&text=' . $custom_text; $method = isset($this->settings['devel_image_provider_get_method']) ? $this->settings['devel_image_provider_get_method'] : 'file_get_contents'; $path = devel_image_provider_get_file($url, $destination, $method); $source = new stdClass(); $source->uri = $path; $source->uid = 1; // TODO: randomize? Use case specific. $source->filemime = 'image/jpg'; if (!empty($instance['settings']['file_directory'])) { $instance['settings']['file_directory'] = $instance['settings']['file_directory'] . '/'; } $destination_dir = $field['settings']['uri_scheme'] . '://' . $instance['settings']['file_directory']; file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY); $destination = $destination_dir . basename($path); $file = file_move($source, $destination, FILE_CREATE_DIRECTORY); } else { return FALSE; } } else { // Select one of the images we've already generated for this field. $file = new stdClass(); $file->fid = array_rand($images[$extension][$min_resolution][$max_resolution]); } $object_field['fid'] = $file->fid; $object_field['alt'] = devel_create_greeking(4); $object_field['title'] = devel_create_greeking(4); return $object_field; }