function gevent_service() { global $calendar; $info = libraries_load('google-api-php-client'); if (!$info['loaded']) { drupal_set_message(t('Can`t authenticate with google as library is missing check Status report or Readme for requirements, download from') . l('https://github.com/google/google-api-php-client/archive/master.zip', 'https://github.com/google/google-api-php-client/archive/master.zip'), 'error'); return FALSE; } $client_email = variable_get('gapps_service_client_email'); $file = file_load(variable_get('gapps_service_private_key')); $private_key = file_get_contents(drupal_realpath($file->uri)); $user_to_impersonate = variable_get('gevent_admin'); $scopes = array('https://www.googleapis.com/auth/calendar'); $credentials = new Google_Auth_AssertionCredentials($client_email, $scopes, $private_key, 'notasecret', 'http://oauth.net/grant_type/jwt/1.0/bearer', $user_to_impersonate); $client = new Google_Client(); $client->setApplicationName('Drupal gevent module'); $client->setAssertionCredentials($credentials); while ($client->getAuth()->isAccessTokenExpired()) { $client->getAuth()->refreshTokenWithAssertion(); } $calendar = new Google_Service_Calendar($client); $_SESSION['gevent_access_token'] = $client->getAccessToken(); if ($_SESSION['gevent_access_token']) { return $calendar; } else { return NULL; } }
function gapps_service($domain) { global $directory; $info = libraries_load('google-api-php-client'); if (!$info['loaded']) { drupal_set_message(t('Can`t authenticate with google as library is missing check Status report or Readme for requirements, download from') . l('https://github.com/google/google-api-php-client/archive/master.zip', 'https://github.com/google/google-api-php-client/archive/master.zip'), 'error'); return FALSE; } $client_email = variable_get('gapps_service_client_email'); $file = file_load(variable_get('gapps_service_private_key')); $private_key = file_get_contents(drupal_realpath($file->uri)); if ($domain == 'teacher') { $user_to_impersonate = variable_get('gapps_teacher_admin'); } else { $user_to_impersonate = variable_get('gapps_student_admin'); } $scopes = array('https://www.googleapis.com/auth/admin.directory.orgunit', 'https://www.googleapis.com/auth/admin.directory.group', 'https://www.googleapis.com/auth/admin.directory.group.member', 'https://www.googleapis.com/auth/admin.directory.user', 'https://www.googleapis.com/auth/admin.directory.user.alias'); $credentials = new Google_Auth_AssertionCredentials($client_email, $scopes, $private_key); $credentials->sub = $user_to_impersonate; $client = new Google_Client(); $client->setApplicationName('Drupal gapps module'); $client->setAssertionCredentials($credentials); while ($client->getAuth()->isAccessTokenExpired()) { $client->getAuth()->refreshTokenWithAssertion($credentials); } $directory = new Google_Service_Directory($client); $_SESSION['gapps_' . $domain . '_access_token'] = $client->getAccessToken(); if ($_SESSION['gapps_' . $domain . '_access_token']) { return $directory; } else { return NULL; } }
/** * Test local directory handling functions. */ function testFileCheckLocalDirectoryHandling() { $site_path = $this->container->get('site.path'); $directory = $site_path . '/files'; // Check a new recursively created local directory for correct file system // permissions. $parent = $this->randomMachineName(); $child = $this->randomMachineName(); // Files directory already exists. $this->assertTrue(is_dir($directory), t('Files directory already exists.'), 'File'); // Make files directory writable only. $old_mode = fileperms($directory); // Create the directories. $parent_path = $directory . DIRECTORY_SEPARATOR . $parent; $child_path = $parent_path . DIRECTORY_SEPARATOR . $child; $this->assertTrue(drupal_mkdir($child_path, 0775, TRUE), t('No error reported when creating new local directories.'), 'File'); // Ensure new directories also exist. $this->assertTrue(is_dir($parent_path), t('New parent directory actually exists.'), 'File'); $this->assertTrue(is_dir($child_path), t('New child directory actually exists.'), 'File'); // Check that new directory permissions were set properly. $this->assertDirectoryPermissions($parent_path, 0775); $this->assertDirectoryPermissions($child_path, 0775); // Check that existing directory permissions were not modified. $this->assertDirectoryPermissions($directory, $old_mode); // Check creating a directory using an absolute path. $absolute_path = drupal_realpath($directory) . DIRECTORY_SEPARATOR . $this->randomMachineName() . DIRECTORY_SEPARATOR . $this->randomMachineName(); $this->assertTrue(drupal_mkdir($absolute_path, 0775, TRUE), 'No error reported when creating new absolute directories.', 'File'); $this->assertDirectoryPermissions($absolute_path, 0775); }
protected function urlToFileEntity($url) { $url = urldecode(DRUPAL_ROOT . EntityPathHelper::normalizeUrl($url)); if (file_exists($url)) { // Get the filename. $filename = pathinfo($url, PATHINFO_FILENAME) . '.' . pathinfo($url, PATHINFO_EXTENSION); $filesize = filesize($url); $files = db_select('file_managed', 'f')->fields('f', array('fid', 'uri', 'filesize'))->condition('filename', $filename)->condition('filesize', $filesize)->execute(); $found_fid = -1; while ($row = $files->fetch()) { $result_uri = drupal_realpath($row->uri); if ($result_uri == drupal_realpath($url)) { $found_fid = $row->fid; break; } } if ($found_fid !== -1) { return Entity::load($found_fid, 'file'); } else { // Create the file entity. if ($contents = file_get_contents($url)) { $public_files_directory = DRUPAL_ROOT . '/' . variable_get('file_public_path', conf_path() . '/files') . '/'; $schema_url = 'public://' . str_replace($public_files_directory, '', $url); // This will basically re-create the same file with the same filename, so we don't // need to check to see if the file already exists because we don't care to replace // the file with itself. $file = file_save_data($contents, $schema_url, FILE_EXISTS_REPLACE); return Entity::load($file->fid, 'file'); } } } return false; }
/** * Add a new slide and ensure that it was created successfully. */ function testSlideTest() { // Check to ensure that the slider is not displayed. $this->drupalGet('<front>'); $this->assertNoRaw('//div[@id="slider"]', 'There is no slider on the front page.'); // Load the slider slides administration page. $this->drupalGet('admin/structure/nivo-slider'); $this->assertResponse(200, t('The privileged user can access the slider slides administration page.')); $file = $this->getTestImage(); // Create five new slide. for ($i = 0; $i <= 5; $i++) { $edit = array(); $edit['files[upload]'] = drupal_realpath($file->uri); $this->drupalPost('admin/structure/nivo-slider', $edit, t('Save configuration')); $this->assertText(t('The configuration options have been saved.')); } // Check to ensure that the slider is displayed. $this->drupalGet('<front>'); $elements = $this->xpath('//div[@id="slider"]'); $this->assertEqual(count($elements), 1, t('There is exactly one slider on the front page.')); // Delete the five existing slides. for ($i = 5; $i <= 0; $i--) { $edit = array(); $edit["images[{$i}][delete]"] = TRUE; $this->drupalPost('admin/structure/nivo-slider', $edit, t('Save configuration')); $this->assertText(t('The configuration options have been saved.')); } }
/** * Tests comment preview. */ function testCommentPreview() { // As admin user, configure comment settings. $this->drupalLogin($this->adminUser); $this->setCommentPreview(DRUPAL_OPTIONAL); $this->setCommentForm(TRUE); $this->setCommentSubject(TRUE); $this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.'); $this->drupalLogout(); // Login as web user and add a user picture. $this->drupalLogin($this->webUser); $image = current($this->drupalGetTestFiles('image')); $edit['files[user_picture_0]'] = drupal_realpath($image->uri); $this->drupalPostForm('user/' . $this->webUser->id() . '/edit', $edit, t('Save')); // As the web user, fill in the comment form and preview the comment. $edit = array(); $edit['subject[0][value]'] = $this->randomMachineName(8); $edit['comment_body[0][value]'] = $this->randomMachineName(16); $this->drupalPostForm('node/' . $this->node->id(), $edit, t('Preview')); // Check that the preview is displaying the title and body. $this->assertTitle(t('Preview comment | Drupal'), 'Page title is "Preview comment".'); $this->assertText($edit['subject[0][value]'], 'Subject displayed.'); $this->assertText($edit['comment_body[0][value]'], 'Comment displayed.'); // Check that the title and body fields are displayed with the correct values. $this->assertFieldByName('subject[0][value]', $edit['subject[0][value]'], 'Subject field displayed.'); $this->assertFieldByName('comment_body[0][value]', $edit['comment_body[0][value]'], 'Comment field displayed.'); // Check that the user picture is displayed. $this->assertFieldByXPath("//article[contains(@class, 'preview')]//div[contains(@class, 'user-picture')]//img", NULL, 'User picture displayed.'); }
/** * 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 testTaxonomyImageAccess() { $user = $this->drupalCreateUser(array('administer site configuration', 'administer taxonomy', 'access user profiles')); $this->drupalLogin($user); // Create a term and upload the image. $files = $this->drupalGetTestFiles('image'); $image = array_pop($files); $edit['name[0][value]'] = $this->randomMachineName(); $edit['files[field_test_0]'] = drupal_realpath($image->uri); $this->drupalPostForm('admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/add', $edit, t('Save')); $this->drupalPostForm(NULL, ['field_test[0][alt]' => $this->randomMachineName()], t('Save')); $terms = entity_load_multiple_by_properties('taxonomy_term', array('name' => $edit['name[0][value]'])); $term = reset($terms); $this->assertText(t('Created new term @name.', array('@name' => $term->getName()))); // Create a user that should have access to the file and one that doesn't. $access_user = $this->drupalCreateUser(array('access content')); $no_access_user = $this->drupalCreateUser(); $image = File::load($term->field_test->target_id); $this->drupalLogin($access_user); $this->drupalGet(file_create_url($image->getFileUri())); $this->assertResponse(200, 'Private image on term is accessible with right permission'); $this->drupalLogin($no_access_user); $this->drupalGet(file_create_url($image->getFileUri())); $this->assertResponse(403, 'Private image on term not accessible without right permission'); }
/** * Helper to create a node and upload a file to it. */ protected function createNodeWithFile($file_type = 'image', $multivalue = TRUE, $add_title_caption = TRUE) { $file = current($this->drupalGetTestFiles($file_type)); $edit = array('title[0][value]' => 'Test Juicebox Gallery Node', 'files[' . $this->instFieldName . '_0]' . ($multivalue ? '[]' : '') => drupal_realpath($file->uri)); $this->drupalPostForm('node/add/' . $this->instBundle, $edit, t('Save and publish')); // Get ID of the newly created node from the current URL. $matches = array(); preg_match('/node\\/([0-9]+)/', $this->getUrl(), $matches); if (isset($matches[1])) { $nid = $matches[1]; // Now re-edit the node to add title and caption values for the newly // uploaded image. This could probably also be done above with // DrupalWebTestCase::drupalPostAJAX(), but this works too. $edit = array('body[0][value]' => 'Some body content on node ' . $nid . ' <strong>with formatting</strong>'); if ($add_title_caption) { if ($this->instFieldType == 'image') { $edit[$this->instFieldName . '[0][title]'] = 'Some title text for field ' . $this->instFieldName . ' on node ' . $nid; $edit[$this->instFieldName . '[0][alt]'] = 'Some alt text for field ' . $this->instFieldName . ' on node ' . $nid . ' <strong>with formatting</strong>'; } if ($this->instFieldType == 'file') { $edit[$this->instFieldName . '[0][description]'] = 'Some description text for field ' . $this->instFieldName . ' on node ' . $nid . ' <strong>with formatting</strong>'; } } $this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published')); // Clear some caches for good measure and save the node object for // reference during tests. $node_storage = $this->container->get('entity.manager')->getStorage('node'); $node_storage->resetCache(array($nid)); $this->node = $node_storage->load($nid); return TRUE; } return FALSE; }
function testUserTokens() { // Add a user picture to the account. $image = current($this->drupalGetTestFiles('image')); $edit = array('files[user_picture_0]' => drupal_realpath($image->uri)); $this->drupalPostForm('user/' . $this->account->id() . '/edit', $edit, t('Save')); $storage = \Drupal::entityManager()->getStorage('user'); // Load actual user data from database. $storage->resetCache(); $this->account = $storage->load($this->account->id()); $this->assertTrue(!empty($this->account->user_picture->target_id), 'User picture uploaded.'); $picture = ['#theme' => 'user_picture', '#account' => $this->account]; /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = \Drupal::service('renderer'); $user_tokens = array('picture' => $renderer->render($picture), 'picture:fid' => $this->account->user_picture->target_id, 'picture:size-raw' => 125, 'ip-address' => NULL, 'roles' => implode(', ', $this->account->getRoles())); $this->assertTokens('user', array('user' => $this->account), $user_tokens); // Remove the simpletest-created user role. $roles = $this->account->getRoles(); $this->account->removeRole(end($roles)); $this->account->save(); // Remove the user picture field and reload the user. FieldStorageConfig::loadByName('user', 'user_picture')->delete(); $storage->resetCache(); $this->account = $storage->load($this->account->id()); $user_tokens = array('picture' => NULL, 'picture:fid' => NULL, 'ip-address' => NULL, 'roles' => 'authenticated', 'roles:keys' => (string) DRUPAL_AUTHENTICATED_RID); $this->assertTokens('user', array('user' => $this->account), $user_tokens); // The ip address token should work for the current user token type. $tokens = array('ip-address' => \Drupal::request()->getClientIp()); $this->assertTokens('current-user', array(), $tokens); $anonymous = new AnonymousUserSession(); $tokens = array('roles' => 'anonymous', 'roles:keys' => (string) DRUPAL_ANONYMOUS_RID); $this->assertTokens('user', array('user' => $anonymous), $tokens); }
/** This is for Export content, we may alter $content, and $zip file before user download it * Hook_builder_content_export($zip , $content) */ function HOOK_builder_content_export_alter(&$zip, &$content) { if ($content['module'] == 'builder' && $content['delta'] == 'image') { if (!empty($content['settings']['image'])) { $file = file_load($content['settings']['image']); $filename = $file->filename; $zip->addFile(drupal_realpath($file->uri), $filename); } } }
/** * Tests importing configuration. */ function testImport() { // Verify access to the config upload form. $this->drupalGet('admin/config/development/configuration/full/import'); $this->assertResponse(200); // Attempt to upload a non-tar file. $text_file = current($this->drupalGetTestFiles('text')); $edit = array('files[import_tarball]' => drupal_realpath($text_file->uri)); $this->drupalPostForm('admin/config/development/configuration/full/import', $edit, t('Upload')); $this->assertText(t('Could not extract the contents of the tar file')); }
/** * Manually imports an archive XML file. * * @param array &$form The brafton config form. * @param object $form_state The current state of the brafton config form. * * @return void */ static function manual_import_archive(array &$form, FormStateInterface $form_state) { $file_value = $form_state->getValue('brafton_archive_file'); $file_id = $file_value[0]; $file = file_load($file_id); $file_uri = $file->getFileUri(); $file_url = drupal_realpath($file_uri); // $article_loader = new \Drupal\brafton_importer\Model\BraftonArticleLoader(); // $article_loader->import_articles($file_url); $controller = new \Drupal\brafton_importer\Controller\BraftonImporterController(); $controller->import_articles($file_url); }
/** * Tests that the autocomplete input element does not cause ajax fatal. */ public function testFileUpload() { $user1 = $this->drupalCreateUser(array('access content', "create {$this->referencingType} content")); $this->drupalLogin($user1); $test_file = current($this->drupalGetTestFiles('text')); $edit['files[file_field_0]'] = drupal_realpath($test_file->uri); $this->drupalPostForm('node/add/' . $this->referencingType, $edit, 'Upload'); $this->assertResponse(200); $edit = array('title[0][value]' => $this->randomMachineName(), 'test_field[0][target_id]' => $this->nodeId); $this->drupalPostForm(NULL, $edit, 'Save'); $this->assertResponse(200); }
/** * Tests normal formatter display on node display. */ function testNodeDisplay() { $field_name = strtolower($this->randomMachineName()); $type_name = 'article'; $field_storage_settings = array('display_field' => '1', 'display_default' => '1', 'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED); $field_settings = array('description_field' => '1'); $widget_settings = array(); $this->createFileField($field_name, 'node', $type_name, $field_storage_settings, $field_settings, $widget_settings); // Create a new node *without* the file field set, and check that the field // is not shown for each node display. $node = $this->drupalCreateNode(array('type' => $type_name)); // Check file_default last as the assertions below assume that this is the // case. $file_formatters = array('file_table', 'file_url_plain', 'hidden', 'file_default'); foreach ($file_formatters as $formatter) { $edit = array("fields[{$field_name}][type]" => $formatter); $this->drupalPostForm("admin/structure/types/manage/{$type_name}/display", $edit, t('Save')); $this->drupalGet('node/' . $node->id()); $this->assertNoText($field_name, format_string('Field label is hidden when no file attached for formatter %formatter', array('%formatter' => $formatter))); } $test_file = $this->getTestFile('text'); // Create a new node with the uploaded file. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); // Check that the default formatter is displaying with the file name. $node_storage = $this->container->get('entity.manager')->getStorage('node'); $node_storage->resetCache(array($nid)); $node = $node_storage->load($nid); $node_file = file_load($node->{$field_name}->target_id); $file_link = array('#theme' => 'file_link', '#file' => $node_file); $default_output = drupal_render($file_link); $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.'); // Turn the "display" option off and check that the file is no longer displayed. $edit = array($field_name . '[0][display]' => FALSE); $this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published')); $this->assertNoRaw($default_output, 'Field is hidden when "display" option is unchecked.'); // Add a description and make sure that it is displayed. $description = $this->randomMachineName(); $edit = array($field_name . '[0][description]' => $description, $field_name . '[0][display]' => TRUE); $this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published')); $this->assertText($description); // Test that fields appear as expected after during the preview. // Add a second file. $name = 'files[' . $field_name . '_1][]'; $edit[$name] = drupal_realpath($test_file->getFileUri()); // Uncheck the display checkboxes and go to the preview. $edit[$field_name . '[0][display]'] = FALSE; $edit[$field_name . '[1][display]'] = FALSE; $this->drupalPostForm("node/{$nid}/edit", $edit, t('Preview')); $this->clickLink(t('Back to content editing')); $this->assertRaw($field_name . '[0][display]', 'First file appears as expected.'); $this->assertRaw($field_name . '[1][display]', 'Second file appears as expected.'); }
/** * Tests the deletion of stale files. */ function testUpdateDeleteFileIfStale() { $file_name = file_unmanaged_save_data($this->randomMachineName()); $this->assertNotNull($file_name); // During testing the file change and the stale checking occurs in the same // request, so the beginning of request will be before the file changes and // REQUEST_TIME - $filectime is negative. Set the maximum age to a number // even smaller than that. $this->container->get('config.factory')->get('system.file')->set('temporary_maximum_age', -100000)->save(); $file_path = drupal_realpath($file_name); update_delete_file_if_stale($file_path); $this->assertFalse(is_file($file_path)); }
/** * Upload an image to a node. * * @param $image * A file object representing the image to upload. * @param $field_name * Name of the image field the image should be attached to. * @param $type * The type of node to create. * @param $alt * The alt text for the image. Use if the field settings require alt text. */ function uploadNodeImage($image, $field_name, $type, $alt = '') { $edit = array('title[0][value]' => $this->randomMachineName()); $edit['files[' . $field_name . '_0]'] = drupal_realpath($image->uri); $this->drupalPostForm('node/add/' . $type, $edit, t('Save and publish')); if ($alt) { // Add alt text. $this->drupalPostForm(NULL, [$field_name . '[0][alt]' => $alt], t('Save and publish')); } // Retrieve ID of the newly created node from the current URL. $matches = array(); preg_match('/node\\/([0-9]+)/', $this->getUrl(), $matches); return isset($matches[1]) ? $matches[1] : FALSE; }
/** * Prepares the parameters to publish to Facebook, this means settings any * field or destination dependent configuration. */ protected function publishParameterPrepare(&$publication) { parent::publishParameterPrepare($publication); // Add facebook support for uploading files $this->setFileUploadSupport(true); // Add @ in front of upload URL if (!empty($publication['params']['source'])) { $image = $publication['params']['source']; $uri = empty($image['uri']) ? file_load($image['fid'])->uri : $image['uri']; $publication['params']['source'] = '@' . drupal_realpath($uri); if (empty($publication['params']['name']) && !empty($image['title'])) { $publication['params']['name'] = check_plain($image['title']); } } }
/** * Tests \Drupal\Core\Form\FormState::cleanValues(). */ function testFormStateValuesCleanAdvanced() { // Get an image for uploading. $image_files = $this->drupalGetTestFiles('image'); $this->image = current($image_files); // Check if the physical file is there. $this->assertTrue(is_file($this->image->uri), "The image file we're going to upload exists."); // "Browse" for the desired file. $edit = array('files[image]' => drupal_realpath($this->image->uri)); // Post the form. $this->drupalPostForm('form_test/form-state-values-clean-advanced', $edit, t('Submit')); // Expecting a 200 HTTP code. $this->assertResponse(200, 'Received a 200 response for posted test file.'); $this->assertRaw(t('You WIN!'), 'Found the success message.'); }
public function handleField($entity_type, $field_type, $field_name, &$value) { $original_value = $value; $file_path = drupal_realpath($value); if (file_exists($file_path)) { $url = file_create_url($value); if ($url) { $value = array('original_path' => $original_value, 'url' => $url, 'uuid' => $this->entity->uuid(), 'uid' => $this->entity->definition->uid); } else { throw new FileHandlerException('The specified file ' . $file_path . ' could not be read.'); } } else { throw new FileHandlerException('The specified file ' . $file_path . ' does not exist.'); } }
/** * {@inheritdoc} */ public static function value(array &$element, &$input, FormStateInterface $form_state) { if (!empty($input['filefield_flysystem']['filename'])) { $instance = entity_load('field_config', $element['#entity_type'] . '.' . $element['#bundle'] . '.' . $element['#field_name']); $filepath = $input['filefield_flysystem']['filename']; $directory = $element['#upload_location']; $mode = Settings::get('file_chmod_directory', FILE_CHMOD_DIRECTORY); if (!drupal_chmod($directory, $mode) && !file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) { \Drupal::logger('filefield_sources')->log(E_NOTICE, 'File %file could not be copied, because the destination directory %destination is not configured correctly.', array('%file' => $filepath, '%destination' => drupal_realpath($directory))); drupal_set_message(t('The specified file %file could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.', array('%file' => $filepath)), 'error'); return; } // Clean up the file name extensions and transliterate. $original_filepath = $filepath; $new_filepath = filefield_sources_clean_filename($filepath, $instance->getSetting('file_extensions')); rename($filepath, $new_filepath); $filepath = $new_filepath; // Run all the normal validations, minus file size restrictions. $validators = $element['#upload_validators']; if (isset($validators['file_validate_size'])) { unset($validators['file_validate_size']); } // Serve files from source folder directly. if ($element['#filefield_sources_settings']['flysystem']['attach_mode'] == FILEFIELD_SOURCE_FLYSYSTEM_ATTACH_MODE_SERVEFROMFOLDER) { $directory = $filepath; if ($file = filefield_sources_flysystem_save_file_servefromattach($filepath, $validators, $directory)) { if (!in_array($file->id(), $input['fids'])) { $input['fids'][] = $file->id(); } } } else { if ($file = filefield_sources_save_file($filepath, $validators, $directory)) { if (!in_array($file->id(), $input['fids'])) { $input['fids'][] = $file->id(); } // Delete the original file if "moving" the file instead of copying. if ($element['#filefield_sources_settings']['flysystem']['attach_mode'] !== FILEFIELD_SOURCE_FLYSYSTEM_ATTACH_MODE_COPY) { @unlink($filepath); } } } // Restore the original file name if the file still exists. if (file_exists($filepath) && $filepath != $original_filepath) { rename($filepath, $original_filepath); } $input['filefield_flysystem']['filename'] = ''; } }
/** * {@inheritdoc} */ public static function value(array &$element, &$input, FormStateInterface $form_state) { if (isset($input['filefield_clipboard']['contents']) && strlen($input['filefield_clipboard']['contents']) > 0) { // Check that the destination is writable. $temporary_directory = 'temporary://'; if (!file_prepare_directory($temporary_directory, FILE_MODIFY_PERMISSIONS)) { \Drupal::logger('filefield_sources')->log(E_NOTICE, 'The directory %directory is not writable, because it does not have the correct permissions set.', array('%directory' => drupal_realpath($temporary_directory))); drupal_set_message(t('The file could not be transferred because the temporary directory is not writable.'), 'error'); return; } // Check that the destination is writable. $directory = $element['#upload_location']; $mode = Settings::get('file_chmod_directory', FILE_CHMOD_DIRECTORY); // This first chmod check is for other systems such as S3, which don't // work with file_prepare_directory(). if (!drupal_chmod($directory, $mode) && !file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) { $url = $input['filefield_clipboard']['filename']; \Drupal::logger('filefield_sources')->log(E_NOTICE, 'File %file could not be copied, because the destination directory %destination is not configured correctly.', array('%file' => $url, '%destination' => drupal_realpath($directory))); drupal_set_message(t('The specified file %file could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.', array('%file' => $url)), 'error'); return; } // Split the file information in mimetype and base64 encoded binary. $base64_data = $input['filefield_clipboard']['contents']; $comma_position = strpos($base64_data, ','); $semicolon_position = strpos($base64_data, ';'); $file_contents = base64_decode(substr($base64_data, $comma_position + 1)); $mimetype = substr($base64_data, 5, $semicolon_position - 5); $extension = \Drupal::service('file.mime_type.guesser.extension')->convertMimeTypeToExtension($mimetype); $filename = trim($input['filefield_clipboard']['filename']); $filename = preg_replace('/\\.[a-z0-9]{3,4}$/', '', $filename); $filename = (empty($filename) ? 'paste_' . REQUEST_TIME : $filename) . '.' . $extension; $filepath = file_create_filename($filename, $temporary_directory); $copy_success = FALSE; if ($fp = @fopen($filepath, 'w')) { fwrite($fp, $file_contents); fclose($fp); $copy_success = TRUE; } if ($copy_success && ($file = filefield_sources_save_file($filepath, $element['#upload_validators'], $element['#upload_location']))) { if (!in_array($file->id(), $input['fids'])) { $input['fids'][] = $file->id(); } } // Remove the temporary file generated from paste. @unlink($filepath); } }
/** * Test for transliteration of file name. */ public function testFileTransliteration() { $account = $this->drupalCreateUser(array('access site reports')); $this->drupalLogin($account); $original = drupal_get_path('module', 'simpletest') . '/files'; file_unmanaged_copy($original . '/image-1.png', PublicStream::basePath() . '/foo°.png'); // Upload with replace to guarantee there's something there. $edit = array('file_test_replace' => FILE_EXISTS_RENAME, 'files[file_test_upload]' => drupal_realpath('public://foo°.png')); $this->drupalPostForm('file-test/upload', $edit, t('Submit')); $this->assertResponse(200, 'Received a 200 response for posted test file.'); $this->assertRaw(t('You WIN!'), 'Found the success message.'); $this->assertTrue(file_exists('temporary://foodeg.png')); $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField(); $file = file_load($max_fid_after); $this->assertIdentical('foodeg.png', $file->getFilename()); $this->assertIdentical('temporary://foodeg.png', $file->getFileUri()); }
private static function _gen($str, $dest, $w, $h, $fontsize, $t = 'caption', $gravity = 'center', $verticle = false) { if ($verticle) { $str = preg_replace('%(.)%u', '$1\\n', $str); } $uri_font = 'public://font/GenShinGothic-Monospace-Bold.ttf'; $font = drupal_realpath($uri_font); $background = '#fcfc84'; $fill = '#000'; $cmd = "convert "; $cmd .= "-background '{$background}' -fill '{$fill}' "; $cmd .= "-size {$w}x{$h} "; $cmd .= "-gravity {$gravity} "; $cmd .= "-pointsize {$fontsize} "; $cmd .= "-font {$font} "; $cmd .= "{$t}:'{$str}' {$dest}"; shell_exec($cmd); }
/** * Tests private file fields on translated nodes. */ public function testPrivateLanguageFile() { // Verify that the file field on the "Basic page" node type is translatable. $definitions = \Drupal::entityManager()->getFieldDefinitions('node', 'page'); $this->assertTrue($definitions[$this->fieldName]->isTranslatable(), 'Node file field is translatable.'); // Create a default language node. $default_language_node = $this->drupalCreateNode(array('type' => 'page')); // Edit the node to upload a file. $edit = array(); $name = 'files[' . $this->fieldName . '_0]'; $edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[0]->uri); $this->drupalPostForm('node/' . $default_language_node->id() . '/edit', $edit, t('Save')); $last_fid_prior = $this->getLastFileId(); // Languages are cached on many levels, and we need to clear those caches. $this->rebuildContainer(); // Ensure the file can be downloaded. \Drupal::entityManager()->getStorage('node')->resetCache(array($default_language_node->id())); $node = Node::load($default_language_node->id()); $node_file = File::load($node->{$this->fieldName}->target_id); $this->drupalGet(file_create_url($node_file->getFileUri())); $this->assertResponse(200, 'Confirmed that the file attached to the English node can be downloaded.'); // Translate the node into French. $this->drupalGet('node/' . $default_language_node->id() . '/translations'); $this->clickLink(t('Add')); // Remove the existing file. $this->drupalPostForm(NULL, array(), t('Remove')); // Upload a different file. $edit = array(); $edit['title[0][value]'] = $this->randomMachineName(); $name = 'files[' . $this->fieldName . '_0]'; $edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[1]->uri); $this->drupalPostForm(NULL, $edit, t('Save (this translation)')); $last_fid = $this->getLastFileId(); // Verify the translation was created. \Drupal::entityManager()->getStorage('node')->resetCache(array($default_language_node->id())); $default_language_node = Node::load($default_language_node->id()); $this->assertTrue($default_language_node->hasTranslation('fr'), 'Node found in database.'); $this->assertTrue($last_fid > $last_fid_prior, 'New file got saved.'); // Ensure the file attached to the translated node can be downloaded. $french_node = $default_language_node->getTranslation('fr'); $node_file = File::load($french_node->{$this->fieldName}->target_id); $this->drupalGet(file_create_url($node_file->getFileUri())); $this->assertResponse(200, 'Confirmed that the file attached to the French node can be downloaded.'); }
/** * {@inheritdoc} */ protected function setUpSyncForm() { // Create a new sync directory. drupal_mkdir($this->sync_dir); // Extract the tarball into the sync directory. $archiver = new ArchiveTar($this->tarball, 'gz'); $files = array(); foreach ($archiver->listContent() as $file) { $files[] = $file['filename']; } $archiver->extractList($files, $this->sync_dir); // Change the user.settings::register so that we can test that // standard_install() does not override it. $sync = new FileStorage($this->sync_dir); $user_settings = $sync->read('user.settings'); $user_settings['register'] = USER_REGISTER_ADMINISTRATORS_ONLY; $sync->write('user.settings', $user_settings); $this->drupalPostForm(NULL, array('sync_directory' => drupal_realpath($this->sync_dir)), 'Save and continue'); }
/** * Tests importing configuration. */ function testImport() { // Verify access to the config upload form. $this->drupalGet('admin/config/development/configuration/full/import'); $this->assertResponse(200); // Attempt to upload a non-tar file. $text_file = current($this->drupalGetTestFiles('text')); $edit = array('files[import_tarball]' => drupal_realpath($text_file->uri)); $this->drupalPostForm('admin/config/development/configuration/full/import', $edit, t('Upload')); $this->assertText(t('Could not extract the contents of the tar file')); // Make the sync directory read-only. $directory = config_get_config_directory(CONFIG_SYNC_DIRECTORY); \Drupal::service('file_system')->chmod($directory, 0555); $this->drupalGet('admin/config/development/configuration/full/import'); $this->assertRaw(t('The directory %directory is not writable.', ['%directory' => $directory])); // Ensure submit button for \Drupal\config\Form\ConfigImportForm is // disabled. $submit_is_disabled = $this->cssSelect('form.config-import-form input[type="submit"]:disabled'); $this->assertTrue(count($submit_is_disabled) === 1, 'The submit button is disabled.'); }
/** * {@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 function import(Row $row, array $old_destination_id_values = array()) { $file = $row->getSourceProperty($this->configuration['source_path_property']); $destination = $row->getDestinationProperty($this->configuration['destination_path_property']); // We check the destination to see if this is a temporary file. If it is // then we do not prepend the source_base_path because temporary files are // already absolute. $source = $this->isTempFile($destination) ? $file : $this->configuration['source_base_path'] . $file; $dirname = drupal_dirname($destination); if (!file_prepare_directory($dirname, FILE_CREATE_DIRECTORY)) { throw new MigrateException(t('Could not create directory %dirname', array('%dirname' => $dirname))); } // If the start and end file is exactly the same, there is nothing to do. if (drupal_realpath($source) === drupal_realpath($destination)) { return parent::import($row, $old_destination_id_values); } $replace = FILE_EXISTS_REPLACE; if (!empty($this->configuration['rename'])) { $entity_id = $row->getDestinationProperty($this->getKey('id')); if (!empty($entity_id) && ($entity = $this->storage->load($entity_id))) { $replace = FILE_EXISTS_RENAME; } } if ($this->configuration['move']) { $copied = file_unmanaged_move($source, $destination, $replace); } else { // Determine whether we can perform this operation based on overwrite rules. $original_destination = $destination; $destination = file_destination($destination, $replace); if ($destination === FALSE) { throw new MigrateException(t('File %file could not be copied because a file by that name already exists in the destination directory (%destination)', array('%file' => $source, '%destination' => $original_destination))); } $source = $this->urlencode($source); $copied = @copy($source, $destination); } if ($copied) { return parent::import($row, $old_destination_id_values); } else { throw new MigrateException(t('File %source could not be copied to %destination.', array('%source' => $source, '%destination' => $destination))); } }
/** * Tests comment preview. */ function testCommentPreview() { // As admin user, configure comment settings. $this->drupalLogin($this->adminUser); $this->setCommentPreview(DRUPAL_OPTIONAL); $this->setCommentForm(TRUE); $this->setCommentSubject(TRUE); $this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.'); $this->drupalLogout(); // Login as web user. $this->drupalLogin($this->webUser); // Test escaping of the username on the preview form. \Drupal::service('module_installer')->install(['user_hooks_test']); \Drupal::state()->set('user_hooks_test_user_format_name_alter', TRUE); $edit = array(); $edit['subject[0][value]'] = $this->randomMachineName(8); $edit['comment_body[0][value]'] = $this->randomMachineName(16); $this->drupalPostForm('node/' . $this->node->id(), $edit, t('Preview')); $this->assertEscaped('<em>' . $this->webUser->id() . '</em>'); \Drupal::state()->set('user_hooks_test_user_format_name_alter_safe', TRUE); $this->drupalPostForm('node/' . $this->node->id(), $edit, t('Preview')); $this->assertTrue($this->webUser->getDisplayName() instanceof MarkupInterface, 'Username is marked safe'); $this->assertNoEscaped('<em>' . $this->webUser->id() . '</em>'); $this->assertRaw('<em>' . $this->webUser->id() . '</em>'); // Add a user picture. $image = current($this->drupalGetTestFiles('image')); $user_edit['files[user_picture_0]'] = drupal_realpath($image->uri); $this->drupalPostForm('user/' . $this->webUser->id() . '/edit', $user_edit, t('Save')); // As the web user, fill in the comment form and preview the comment. $this->drupalPostForm('node/' . $this->node->id(), $edit, t('Preview')); // Check that the preview is displaying the title and body. $this->assertTitle(t('Preview comment | Drupal'), 'Page title is "Preview comment".'); $this->assertText($edit['subject[0][value]'], 'Subject displayed.'); $this->assertText($edit['comment_body[0][value]'], 'Comment displayed.'); // Check that the title and body fields are displayed with the correct values. $this->assertFieldByName('subject[0][value]', $edit['subject[0][value]'], 'Subject field displayed.'); $this->assertFieldByName('comment_body[0][value]', $edit['comment_body[0][value]'], 'Comment field displayed.'); // Check that the user picture is displayed. $this->assertFieldByXPath("//article[contains(@class, 'preview')]//div[contains(@class, 'user-picture')]//img", NULL, 'User picture displayed.'); }