/** * Tries deleting a file that is in use. */ function testInUse() { $file = $this->createFile(); $file_usage = $this->container->get('file.usage'); $file_usage->add($file, 'testing', 'test', 1); $file_usage->add($file, 'testing', 'test', 1); $file_usage->delete($file, 'testing', 'test', 1); $usage = $file_usage->listUsage($file); $this->assertEqual($usage['testing']['test'], array(1 => 1), 'Test file is still in use.'); $this->assertTrue(file_exists($file->getFileUri()), 'File still exists on the disk.'); $this->assertTrue(File::load($file->id()), 'File still exists in the database.'); // Clear out the call to hook_file_load(). file_test_reset(); $file_usage->delete($file, 'testing', 'test', 1); $usage = $file_usage->listUsage($file); $this->assertFileHooksCalled(array('load', 'update')); $this->assertTrue(empty($usage), 'File usage data was removed.'); $this->assertTrue(file_exists($file->getFileUri()), 'File still exists on the disk.'); $file = File::load($file->id()); $this->assertTrue($file, 'File still exists in the database.'); $this->assertTrue($file->isTemporary(), 'File is temporary.'); file_test_reset(); // Call file_cron() to clean up the file. Make sure the changed timestamp // of the file is older than the system.file.temporary_maximum_age // configuration value. db_update('file_managed')->fields(array('changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1)))->condition('fid', $file->id())->execute(); \Drupal::service('cron')->run(); // file_cron() loads $this->assertFileHooksCalled(array('delete')); $this->assertFalse(file_exists($file->getFileUri()), 'File has been deleted after its last usage was removed.'); $this->assertFalse(File::load($file->id()), 'File was removed from the database.'); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, $grouping = NULL) { // Load logo image. $rendered_image = NULL; if (!empty($grouping->logo_fid)) { $file = File::load($grouping->logo_fid); if ($file) { $logo_url = ImageStyle::load('ea_groupings_200x200')->buildUrl($file->getFileUri()); $image_array = array('#theme' => 'image', '#uri' => $logo_url, '#alt' => $this->t('Logo for @grouping', array('@grouping' => $grouping->title)), '#title' => $this->t('@grouping', array('@grouping' => $grouping->title))); $rendered_image = \Drupal::service('renderer')->render($image_array); } } // Construct form. $form = array(); $form['gid'] = array('#type' => 'value', '#value' => $grouping->gid); $form['add'] = array('#type' => 'fieldset', '#description' => $this->t('Update grouping'), '#title' => $this->t('Edit grouping')); $form['add']['title'] = array('#type' => 'textfield', '#title' => $this->t('Title'), '#description' => $this->t('Title of grouping'), '#size' => 20, '#maxlength' => 20, '#required' => FALSE, '#default_value' => $grouping->title); $form['add']['description'] = array('#type' => 'textarea', '#title' => $this->t('Description'), '#description' => $this->t('A short description of the grouping'), '#required' => FALSE, '#default_value' => $grouping->description); $form['add']['logo'] = array('#type' => 'markup', '#markup' => $rendered_image); $form['add']['logo_fid'] = array('#title' => $this->t('Update logo'), '#type' => 'managed_file', '#description' => $this->t('Upload a logo for the grouping'), '#default_value' => NULL, '#upload_location' => 'public://logos/'); $form['add']['time_zone'] = array('#title' => $this->t('Timezone'), '#type' => 'select', '#description' => $this->t('Select a time zone for the grouping'), '#options' => _ea_groupings_get_time_zones(), '#default_value' => $grouping->time_zone); $form['add']['parent_gid'] = array('#type' => 'select', '#description' => $this->t('Select a parent grouping'), '#options' => _ea_groupings_get_groupings_list(FALSE, $grouping->gid), '#disabled' => _ea_groupings_is_parent($grouping->gid), '#default_value' => $grouping->parent_gid); $form['add']['submit'] = array('#type' => 'submit', '#name' => 'add_group', '#value' => $this->t('Update grouping'), '#weight' => 100); $form['add']['old_title'] = array('#type' => 'value', '#value' => $grouping->title); $form['add']['old_logo_fid'] = array('#type' => 'value', '#value' => $grouping->logo_fid); $form['add']['old_parent_gid'] = array('#type' => 'value', '#value' => $grouping->parent_gid); return $form; }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { // Pass the file to the parser. $fid = $form_state->getValue('mtg_import_json_file'); $fid = reset($fid); if ($fid == 0) { return FALSE; } $file = File::load($fid); if (!$file) { drupal_set_message('Unable to load file.'); \Drupal::logger('mtg_import')->error(t('Unable to load the file.')); return FALSE; } $uri = $file->uri->value; $file_contents_raw = file_get_contents($uri); $file_contents = json_decode($file_contents_raw); if (!empty($file_contents->cards)) { $operations = [['mtg_import_parse_set_data', [$file_contents]]]; $chunks = array_chunk($file_contents->cards, 20); foreach ($chunks as $chunk) { $operations[] = ['mtg_import_parse_card_data', [$chunk]]; } $batch = ['title' => t('Importing'), 'operations' => $operations, 'finished' => 'mtg_import_completed', 'progress_message' => t('Completed part @current of @total.')]; batch_set($batch); } else { drupal_set_message(t('There are no cards in the file, so no import will take place.'), 'warning'); } }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $values = $form_state->getValues(); $file = File::load($values['file'][0]); // Load File entity. $read_file = new \SplFileObject($file->url()); // Create file handler. $lines = 1; $in_queue = 0; $queue = \Drupal::queue('eventninja'); // Load queue while (!$read_file->eof()) { $data = $read_file->fgetcsv(';'); if ($lines > 1) { // skip headers $user = user_load_by_mail($data[1]); if ($user === false) { // Verify if user with specified email does not exist. $queue->createItem($data); $in_queue++; } else { $this->logger('eventninja')->log(RfcLogLevel::NOTICE, 'User {mail} hasn\'t been created.', ['mail' => $data[1]]); } } $lines++; } if ($lines > 1) { drupal_set_message($this->t('@num records was scheduled for import', array('@num' => $in_queue)), 'success'); } else { drupal_set_message($this->t('File contains only headers'), 'error'); } }
/** * Tests the Drupal 6 files to Drupal 8 migration. */ public function testFiles() { /** @var \Drupal\file\FileInterface $file */ $file = File::load(1); $this->assertIdentical('Image1.png', $file->getFilename()); $this->assertIdentical('39325', $file->getSize()); $this->assertIdentical('public://image-1.png', $file->getFileUri()); $this->assertIdentical('image/png', $file->getMimeType()); $this->assertIdentical("1", $file->getOwnerId()); // It is pointless to run the second half from MigrateDrupal6Test. if (empty($this->standalone)) { return; } // Test that we can re-import and also test with file_directory_path set. db_truncate(entity_load('migration', 'd6_file')->getIdMap()->mapTableName())->execute(); // Update the file_directory_path. Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize('files/test')))->condition('name', 'file_directory_path')->execute(); Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize($this->getTempFilesDirectory())))->condition('name', 'file_directory_temp')->execute(); $migration = entity_load_unchanged('migration', 'd6_file'); $this->executeMigration($migration); $file = File::load(2); $this->assertIdentical('public://core/modules/simpletest/files/image-2.jpg', $file->getFileUri()); // Ensure that a temporary file has been migrated. $file = File::load(6); $this->assertIdentical('temporary://' . static::getUniqueFilename(), $file->getFileUri()); }
public function content($nid) { $node = \Drupal::entityManager()->getStorage('node')->load($nid); $fields = $node->getFieldDefinitions(); $fcArray = []; foreach ($fields as $field){ $type = $field->getType(); if ($type == 'field_collection') { $field_collection = $field->get('field_name'); foreach ($node->$field_collection as $key => $item){ $item = $item->value; // $fcArray[$key]; $fc = FieldCollectionItem::load($item); foreach ($fc as $fckey => $field){ $fcArray[$key][$fckey] = $field->value; if (is_object($field[0]) && $field[0]->height){ $image = File::load($field[0]->target_id); $fcArray[$key][$fckey] = str_replace('public://', '/drupal/sites/default/files/', $image->uri->value); $fcArray[$key]['field_mosaic_image_alt'] = $field[0]->alt; } if (is_object($field[0]) && $field[0]->uri){ $fcArray[$key][$fckey] = str_replace('internal:', '', $field[0]->uri); } } } } } return new JsonResponse($fcArray); }
/** * 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()); }
/** * Tests RSS enclosure formatter display for RSS feeds. */ function testFileFieldRSSContent() { $node_storage = $this->container->get('entity.manager')->getStorage('node'); $field_name = strtolower($this->randomMachineName()); $type_name = 'article'; $this->createFileField($field_name, 'node', $type_name); // RSS display must be added manually. $this->drupalGet("admin/structure/types/manage/{$type_name}/display"); $edit = array("display_modes_custom[rss]" => '1'); $this->drupalPostForm(NULL, $edit, t('Save')); // Change the format to 'RSS enclosure'. $this->drupalGet("admin/structure/types/manage/{$type_name}/display/rss"); $edit = array("fields[{$field_name}][type]" => 'file_rss_enclosure'); $this->drupalPostForm(NULL, $edit, t('Save')); // Create a new node with a file field set. Promote to frontpage // needs to be set so this node will appear in the RSS feed. $node = $this->drupalCreateNode(array('type' => $type_name, 'promote' => 1)); $test_file = $this->getTestFile('text'); // Create a new node with the uploaded file. $nid = $this->uploadNodeFile($test_file, $field_name, $node->id()); // Get the uploaded file from the node. $node_storage->resetCache(array($nid)); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); // Check that the RSS enclosure appears in the RSS feed. $this->drupalGet('rss.xml'); $uploaded_filename = str_replace('public://', '', $node_file->getFileUri()); $test_element = sprintf('<enclosure url="%s" length="%s" type="%s" />', file_create_url("public://{$uploaded_filename}", array('absolute' => TRUE)), $node_file->getSize(), $node_file->getMimeType()); $this->assertRaw($test_element, 'File field RSS enclosure is displayed when viewing the RSS feed.'); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { drupal_set_message('Settings saved'); // Fetch the file id previously saved. $config = $this->config('cfia_base.settings'); $old_fid = $config->get('cfia_frontpage.frontpage_image', ''); // Load the file set in the form. $value = $form_state->getValue('frontpage_image'); $form_fid = count($value) > 0 ? $value[0] : 0; $file = $form_fid ? File::load($form_fid) : FALSE; // If a file is set. if ($file) { $fid = $file->id(); // Check if the file has changed. if ($fid != $old_fid) { // Remove old file. if ($old_fid) { removeFile($old_fid); } // Add file to file_usage table. \Drupal::service('file.usage')->add($file, 'cfia_base', 'user', '1'); } } else { // If old file exists but no file set in form, remove old file. if ($old_fid) { removeFile($old_fid); } } $this->configFactory()->getEditable('cfia_base.settings')->set('cfia_frontpage.frontpage_title', $form_state->getValue('frontpage_title'))->set('cfia_frontpage.frontpage_lead', $form_state->getValue('frontpage_lead'))->set('cfia_frontpage.frontpage_sub', $form_state->getValue('frontpage_sub'))->set('cfia_frontpage.frontpage_button', $form_state->getValue('frontpage_button'))->set('cfia_frontpage.frontpage_link', $form_state->getValue('frontpage_link'))->set('cfia_footer.footer_text', $form_state->getValue('footer_text')['value'])->set('cfia_footer.footer_twitter', $form_state->getValue('footer_twitter'))->set('cfia_footer.footer_instagram', $form_state->getValue('footer_instagram'))->set('cfia_footer.footer_linkedin', $form_state->getValue('footer_linkedin'))->set('cfia_frontpage.frontpage_image', $file ? $file->id() : NULL)->save(); }
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'); }
/** * Tests file access for file uploaded to a private node. */ function testPrivateFile() { $type_name = 'article'; $field_name = strtolower($this->randomMachineName()); $this->createFileField($field_name, 'node', $type_name, array('uri_scheme' => 'private')); // Create a field with no view access. See // field_test_entity_field_access(). $no_access_field_name = 'field_no_view_access'; $this->createFileField($no_access_field_name, 'node', $type_name, array('uri_scheme' => 'private')); $test_file = $this->getTestFile('text'); $nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => TRUE)); $node = node_load($nid, TRUE); $node_file = file_load($node->{$field_name}->target_id); // Ensure the file can be downloaded. $this->drupalGet(file_create_url($node_file->getFileUri())); $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.'); $this->drupalLogOut(); $this->drupalGet(file_create_url($node_file->getFileUri())); $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.'); // Test with the field that should deny access through field access. $this->drupalLogin($this->admin_user); $nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, array('private' => TRUE)); \Drupal::entityManager()->getStorage('node')->resetCache(array($nid)); $node = Node::load($nid); $node_file = File::load($node->{$no_access_field_name}->target_id); // Ensure the file cannot be downloaded. $user = $this->drupalCreateUser(array('access content')); $this->drupalLogin($user); $this->drupalGet(file_create_url($node_file->getFileUri())); $this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission.'); }
/** * Test a gallery embedded in a view row that is dependent on the Juicebox * cache. */ public function testSubRequestDependent() { $node = $this->node; $xml_path = 'juicebox/xml/field/node/' . $node->id() . '/' . $this->instFieldName . '/_custom'; $xml_url = \Drupal::url('juicebox.xml_field', array('entityType' => 'node', 'entityId' => $node->id(), 'fieldName' => $this->instFieldName, 'displayName' => '_custom')); // Get the urls to the test image and thumb derivative used by default. $uri = \Drupal\file\Entity\File::load($node->{$this->instFieldName}[0]->target_id)->getFileUri(); $test_image_url = entity_load('image_style', 'juicebox_medium')->buildUrl($uri); $test_thumb_url = entity_load('image_style', 'juicebox_square_thumb')->buildUrl($uri); // Check for correct embed markup. This will also prime the cache. $content = $this->drupalGet('juicebox_test_row_formatter'); $this->assertRaw(trim(json_encode(array('configUrl' => $xml_url)), '{}"'), 'Gallery setting found in Drupal.settings.'); $this->assertRaw('id="node--' . $node->id() . '--' . str_replace('_', '-', $this->instFieldName) . '---custom"', 'Embed code wrapper found.'); $this->assertRaw(Html::escape($test_image_url), 'Test image found in embed code'); // Extract the xml-source values from the XML. $matches = array(); // In the pattern below we have to use four (yeah, FOUR) backslashes to // match a SINGLE literal backslash. Our source will contain an encoded // (JSON) "&" character as "\u0026", but we don't want the regex to confuse // that with an actaul "&" char in the pattern itself. preg_match('|xml-source-path=([a-z1-9_-]+)\\\\u0026xml-source-id=([a-z1-9-]+)|', $content, $matches); $this->assertNotNull($matches[1], 'xml-source-path value found in Drupal.settings.'); $this->assertNotNull($matches[2], 'xml-source-id value found in Drupal.settings.'); // Check for correct XML. This example is dependent on a sub-request XML // lookup, so everything below would fail without that feature. $this->drupalGet($xml_path, array('query' => array('xml-source-path' => $matches[1], 'xml-source-id' => $matches[2]))); $this->assertRaw('<?xml version="1.0" encoding="UTF-8"?>', 'Valid XML detected.'); $this->assertRaw('imageURL="' . Html::escape($test_image_url), 'Test image found in XML.' . $test_image_url); $this->assertRaw('thumbURL="' . Html::escape($test_thumb_url), 'Test thumbnail found in XML.' . $test_thumb_url); $this->assertRaw('backgroundcolor="green"', 'Custom background setting from pseudo field instance config found in XML.'); }
/** * Tests the Drupal6 user to Drupal 8 migration. */ public function testUser() { $users = Database::getConnection('default', 'migrate')->select('users', 'u')->fields('u')->condition('uid', 0, '>')->execute()->fetchAll(); foreach ($users as $source) { // Get roles directly from the source. $rids = Database::getConnection('default', 'migrate')->select('users_roles', 'ur')->fields('ur', array('rid'))->condition('ur.uid', $source->uid)->execute()->fetchCol(); $roles = array(RoleInterface::AUTHENTICATED_ID); $id_map = $this->getMigration('d6_user_role')->getIdMap(); foreach ($rids as $rid) { $role = $id_map->lookupDestinationId(array($rid)); $roles[] = reset($role); } /** @var \Drupal\user\UserInterface $user */ $user = User::load($source->uid); $this->assertIdentical($source->uid, $user->id()); $this->assertIdentical($source->name, $user->label()); $this->assertIdentical($source->mail, $user->getEmail()); $this->assertIdentical($source->created, $user->getCreatedTime()); $this->assertIdentical($source->access, $user->getLastAccessedTime()); $this->assertIdentical($source->login, $user->getLastLoginTime()); $is_blocked = $source->status == 0; $this->assertIdentical($is_blocked, $user->isBlocked()); // $user->getPreferredLangcode() might fallback to default language if the // user preferred language is not configured on the site. We just want to // test if the value was imported correctly. $this->assertIdentical($source->language, $user->preferred_langcode->value); $expected_timezone_name = $source->timezone_name ?: $this->config('system.date')->get('timezone.default'); $this->assertIdentical($expected_timezone_name, $user->getTimeZone()); $this->assertIdentical($source->init, $user->getInitialEmail()); $this->assertIdentical($roles, $user->getRoles()); // We have one empty picture in the data so don't try load that. if (!empty($source->picture)) { // Test the user picture. $file = File::load($user->user_picture->target_id); $this->assertIdentical(basename($source->picture), $file->getFilename()); } else { // Ensure the user does not have a picture. $this->assertFalse($user->user_picture->target_id, sprintf('User %s does not have a picture', $user->id())); } // Use the API to check if the password has been salted and re-hashed to // conform to Drupal >= 7 for non-admin users. if ($user->id() != 1) { $this->assertTrue(\Drupal::service('password')->check($source->pass_plain, $user->getPassword())); } } // Rollback the migration and make sure everything is deleted but uid 1. (new MigrateExecutable($this->migration, $this))->rollback(); $users = Database::getConnection('default', 'migrate')->select('users', 'u')->fields('u', ['uid'])->condition('uid', 0, '>')->execute()->fetchCol(); foreach ($users as $uid) { $account = User::load($uid); if ($uid == 1) { $this->assertNotNull($account, 'User 1 was preserved after rollback'); } else { $this->assertNull($account); } } }
/** * @inheritDoc */ public function getPreparedGeocodeValues(array $values = array()) { foreach ($values as $index => $value) { if ($value['target_id']) { $values[$index]['value'] = \Drupal::service('file_system')->realpath(\Drupal\file\Entity\File::load($value['target_id'])->getFileUri()); } } return $values; }
/** * 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'); simpletest_generate_file('escaped-&-text', 64, 10, 'text'); $test_file = File::create(['uri' => 'public://escaped-&-text.txt', 'name' => 'escaped-&-text', 'filesize' => filesize('public://escaped-&-text.txt')]); // 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::service('renderer')->renderRoot($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); // Ensure the filename in the link's title attribute is escaped. $this->assertRaw('title="escaped-&-text.txt"'); // 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 file access for file uploaded to a private node. */ function testPrivateFile() { $node_storage = $this->container->get('entity.manager')->getStorage('node'); $type_name = 'article'; $field_name = strtolower($this->randomMachineName()); $this->createFileField($field_name, 'node', $type_name, array('uri_scheme' => 'private')); $test_file = $this->getTestFile('text'); $nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => TRUE)); \Drupal::entityManager()->getStorage('node')->resetCache(array($nid)); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); // Ensure the file can be viewed. $this->drupalGet('node/' . $node->id()); $this->assertRaw($node_file->getFilename(), 'File reference is displayed after attaching it'); // Ensure the file can be downloaded. $this->drupalGet(file_create_url($node_file->getFileUri())); $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.'); $this->drupalLogOut(); $this->drupalGet(file_create_url($node_file->getFileUri())); $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.'); // Create a field with no view access. See // field_test_entity_field_access(). $no_access_field_name = 'field_no_view_access'; $this->createFileField($no_access_field_name, 'node', $type_name, array('uri_scheme' => 'private')); // Test with the field that should deny access through field access. $this->drupalLogin($this->adminUser); $nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, array('private' => TRUE)); \Drupal::entityManager()->getStorage('node')->resetCache(array($nid)); $node = $node_storage->load($nid); $node_file = File::load($node->{$no_access_field_name}->target_id); // Ensure the file cannot be downloaded. $this->drupalGet(file_create_url($node_file->getFileUri())); $this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission.'); // Attempt to reuse the file when editing a node. $edit = array(); $edit['title[0][value]'] = $this->randomMachineName(); $this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish')); $new_node = $this->drupalGetNodeByTitle($edit['title[0][value]']); $edit[$field_name . '[0][fids]'] = $node_file->id(); $this->drupalPostForm('node/' . $new_node->id() . '/edit', $edit, t('Save and keep published')); // Make sure the form submit failed - we stayed on the edit form. $this->assertUrl('node/' . $new_node->id() . '/edit'); // Check that we got the expected constraint form error. $constraint = new ReferenceAccessConstraint(); $this->assertRaw(SafeMarkup::format($constraint->message, array('%type' => 'file', '%id' => $node_file->id()))); // Attempt to reuse the existing file when creating a new node, and confirm // that access is still denied. $edit = array(); $edit['title[0][value]'] = $this->randomMachineName(); $edit[$field_name . '[0][fids]'] = $node_file->id(); $this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish')); $new_node = $this->drupalGetNodeByTitle($edit['title[0][value]']); $this->assertTrue(empty($new_node), 'Node was not created.'); $this->assertUrl('node/add/' . $type_name); $this->assertRaw(SafeMarkup::format($constraint->message, array('%type' => 'file', '%id' => $node_file->id()))); }
public function submitForm(array &$form, FormStateInterface $form_state) { /** @var FillPdfFormInterface $fillpdf_form */ $fillpdf_form = $this->getEntity(); /** @var FileInterface $file */ $file = File::load($fillpdf_form->get('file')->first()->target_id); $fillpdf_form->delete(); drupal_set_message($this->t('FillPDF form deleted.')); $form_state->setRedirect('fillpdf.forms_admin'); }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { $element = []; $settings = $this->getSettings(); foreach ($items as $delta => $item) { $file = File::load($item->target_id); $metadata = isset($item->data) ? unserialize($item->data) : array(); $scheme = file_uri_scheme($file->getFileUri()); $provider = $this->providerManager->loadProviderFromStream($scheme, $file, $metadata); $element[$delta] = $provider->renderEmbedCode($settings); } return $element; }
/** * Load a single file and ensure that the correct values are returned. */ function testSingleValues() { // Create a new file entity from scratch so we know the values. $file = $this->createFile('druplicon.txt', NULL, 'public'); $by_fid_file = File::load($file->id()); $this->assertFileHookCalled('load'); $this->assertTrue(is_object($by_fid_file), '\\Drupal\\file\\Entity\\File::load() returned an object.'); $this->assertEqual($by_fid_file->id(), $file->id(), 'Loading by fid got the same fid.', 'File'); $this->assertEqual($by_fid_file->getFileUri(), $file->getFileUri(), 'Loading by fid got the correct filepath.', 'File'); $this->assertEqual($by_fid_file->getFilename(), $file->getFilename(), 'Loading by fid got the correct filename.', 'File'); $this->assertEqual($by_fid_file->getMimeType(), $file->getMimeType(), 'Loading by fid got the correct MIME type.', 'File'); $this->assertEqual($by_fid_file->isPermanent(), $file->isPermanent(), 'Loading by fid got the correct status.', 'File'); $this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.'); }
/** * {@inheritdoc} */ public function collectFieldValues($component, $field_definition) { $bundle = $component->bundle(); $field_name = $field_definition->getName(); $field_language = $field_definition->language()->getId(); $field_value = $component->get($field_name)->getValue(); $field_type = $field_definition->getType(); if ($field_type == 'image' && !empty($field_value) || $field_type == 'file' && !empty($field_value)) { $file = File::load($field_value[0]['target_id']); $url = file_create_url($file->get('uri')->value); $field_value[0]['url'] = $url; } $field_attribute = 'component/' . $component->id() . '/' . $field_name . '/' . $field_language . '/full'; return [str_replace($bundle . '_', '', $field_name) => array('content' => !empty($field_value) ? $field_value[0] : NULL, 'quickedit' => $field_attribute, 'type' => $field_type)]; }
protected function setUp() { parent::setUp(); $this->fieldName = 'field_image'; // Create the image field. $this->createImageField($this->fieldName, 'article'); // Set the RDF mapping for the new field. rdf_get_mapping('node', 'article')->setFieldMapping($this->fieldName, array('properties' => array('og:image'), 'mapping_type' => 'rel'))->setBundleMapping(array('types' => array()))->save(); // Get the test image that simpletest provides. $image = current($this->drupalGetTestFiles('image')); // Save a node with the image. $nid = $this->uploadNodeImage($image, $this->fieldName, 'article', $this->randomMachineName()); $this->node = Node::load($nid); $this->file = File::load($this->node->{$this->fieldName}->target_id); }
/** * Tests a single file entity. * * @param int $id * The file ID. * @param string $name * The expected file name. * @param string $uri * The expected URI. * @param string $mime * The expected MIME type. * @param int $size * The expected file size. * @param int $created * The expected creation time. * @param int $changed * The expected modification time. * @param int $uid * The expected owner ID. */ protected function assertEntity($id, $name, $uri, $mime, $size, $created, $changed, $uid) { /** @var \Drupal\file\FileInterface $file */ $file = File::load($id); $this->assertTrue($file instanceof FileInterface); $this->assertIdentical($name, $file->getFilename()); $this->assertIdentical($uri, $file->getFileUri()); $this->assertTrue(file_exists($uri)); $this->assertIdentical($mime, $file->getMimeType()); $this->assertIdentical($size, $file->getSize()); // isPermanent(), isTemporary(), etc. are determined by the status column. $this->assertTrue($file->isPermanent()); $this->assertIdentical($created, $file->getCreatedTime()); $this->assertIdentical($changed, $file->getChangedTime()); $this->assertIdentical($uid, $file->getOwnerId()); }
function testFileSave() { // Create a new file entity. $file = File::create(array('uid' => 1, 'filename' => 'druplicon.txt', 'uri' => 'public://druplicon.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT)); file_put_contents($file->getFileUri(), 'hello world'); // Save it, inserting a new record. $file->save(); // Check that the correct hooks were called. $this->assertFileHooksCalled(array('insert')); $this->assertTrue($file->id() > 0, 'A new file ID is set when saving a new file to the database.', 'File'); $loaded_file = File::load($file->id()); $this->assertNotNull($loaded_file, 'Record exists in the database.'); $this->assertEqual($loaded_file->isPermanent(), $file->isPermanent(), 'Status was saved correctly.'); $this->assertEqual($file->getSize(), filesize($file->getFileUri()), 'File size was set correctly.', 'File'); $this->assertTrue($file->getChangedTime() > 1, 'File size was set correctly.', 'File'); $this->assertEqual($loaded_file->langcode->value, 'en', 'Langcode was defaulted correctly.'); // Resave the file, updating the existing record. file_test_reset(); $file->status->value = 7; $file->save(); // Check that the correct hooks were called. $this->assertFileHooksCalled(array('load', 'update')); $this->assertEqual($file->id(), $file->id(), 'The file ID of an existing file is not changed when updating the database.', 'File'); $this->assertTrue($file->getChangedTime() >= $file->getChangedTime(), "Timestamp didn't go backwards.", 'File'); $loaded_file = File::load($file->id()); $this->assertNotNull($loaded_file, 'Record still exists in the database.', 'File'); $this->assertEqual($loaded_file->isPermanent(), $file->isPermanent(), 'Status was saved correctly.'); $this->assertEqual($loaded_file->langcode->value, 'en', 'Langcode was saved correctly.'); // Try to insert a second file with the same name apart from case insensitivity // to ensure the 'uri' index allows for filenames with different cases. $uppercase_values = array('uid' => 1, 'filename' => 'DRUPLICON.txt', 'uri' => 'public://DRUPLICON.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT); $uppercase_file = File::create($uppercase_values); file_put_contents($uppercase_file->getFileUri(), 'hello world'); $violations = $uppercase_file->validate(); $this->assertEqual(count($violations), 0, 'No violations when adding an URI with an existing filename in upper case.'); $uppercase_file->save(); // Ensure the database URI uniqueness constraint is triggered. $uppercase_file_duplicate = File::create($uppercase_values); file_put_contents($uppercase_file_duplicate->getFileUri(), 'hello world'); $violations = $uppercase_file_duplicate->validate(); $this->assertEqual(count($violations), 1); $this->assertEqual($violations[0]->getMessage(), t('The file %value already exists. Enter a unique file URI.', ['%value' => $uppercase_file_duplicate->getFileUri()])); // Ensure that file URI entity queries are case sensitive. $fids = \Drupal::entityQuery('file')->condition('uri', $uppercase_file->getFileUri())->execute(); $this->assertEqual(1, count($fids)); $this->assertEqual(array($uppercase_file->id() => $uppercase_file->id()), $fids); }
public function submitForm(array &$form, FormStateInterface $form_state) { /* Fetch the array of the file stored temporarily in database */ $afile = $form_state->getValue('afile'); /* Load the object of the file by it's fid */ dpm($afile[0]); $file = File::load($afile[0]); /* Set the status flag permanent of the file object */ $file->setPermanent(); /* Save the file in database */ $file->save(); $current_uri = \Drupal::request()->getRequestUri(); $path_args = array_slice(explode('/', $current_uri), -2, 2); $entry = array('co_degre' => $path_args[0], 'co_modu' => explode('?', $path_args[1])[0], 'fid' => $afile[0], 'zone' => 3); // dpm($entry); $module = BbCrudController::create('gbb_file', $entry); }
/** * {@inheritdoc} */ public function preprocessVariables(Variables $variables, $hook, array $info) { $options = []; $file = $variables['file'] instanceof File ? $variables['file'] : File::load($variables['file']->fid); $url = file_create_url($file->getFileUri()); $file_size = $file->getSize(); $mime_type = $file->getMimeType(); // Set options as per anchor format described at // http://microformats.org/wiki/file-format-examples $options['attributes']['type'] = "{$mime_type}; length={$file_size}"; // Use the description as the link text if available. if (empty($variables['description'])) { $link_text = $file->getFilename(); } else { $link_text = $variables['description']; $options['attributes']['title'] = $file->getFilename(); } // Retrieve the generic mime type from core (mislabeled as "icon_class"). $generic_mime_type = file_icon_class($mime_type); // Map the generic mime types to an icon and state. $mime_map = ['application-x-executable' => ['label' => t('binary file'), 'icon' => 'console'], 'audio' => ['label' => t('audio file'), 'icon' => 'headphones'], 'image' => ['label' => t('image'), 'icon' => 'picture'], 'package-x-generic' => ['label' => t('archive'), 'icon' => 'compressed'], 'text' => ['label' => t('document'), 'icon' => 'file'], 'video' => ['label' => t('video'), 'icon' => 'film']]; // Retrieve the mime map array. $mime = isset($mime_map[$generic_mime_type]) ? $mime_map[$generic_mime_type] : ['label' => t('file'), 'icon' => 'file', 'state' => 'primary']; // Classes to add to the file field for icons. // $variables->addClass([ // 'file', // // Add a specific class for each and every mime type. // 'file--mime-' . strtr($mime_type, ['/' => '-', '.' => '-']), // // Add a more general class for groups of well known mime types. // 'file--' . $generic_mime_type, // ]); // Set the icon for the mime type. $icon = Materialize::material_icons_font($mime['icon']); $variables->icon = Element::create($icon)->addClass('text-primary')->getArray(); $options['attributes']['title'] = t('Open @mime in new window', ['@mime' => $mime['label']]); if ($this->theme->getSetting('tooltip_enabled')) { $options['attributes']['data-toggle'] = 'tooltip'; $options['attributes']['data-placement'] = 'bottom'; } $variables['link'] = Link::fromTextAndUrl($link_text, Url::fromUri($url, $options)); // Add the file size as a variable. $variables->file_size = format_size($file_size); // Preprocess attributes. $this->preprocessAttributes($variables, $hook, $info); }
/** * Tests the Drupal 6 files to Drupal 8 migration. */ public function testFiles() { $this->assertEntity(1, 'Image1.png', '39325', 'public://image-1.png', 'image/png', '1'); $this->assertEntity(2, 'Image2.jpg', '1831', 'public://image-2.jpg', 'image/jpeg', '1'); $this->assertEntity(3, 'Image-test.gif', '183', 'public://image-test.gif', 'image/jpeg', '1'); $this->assertEntity(5, 'html-1.txt', '24', 'public://html-1.txt', 'text/plain', '1'); // Test that we can re-import and also test with file_directory_path set. \Drupal::database()->truncate($this->getMigration('d6_file')->getIdMap()->mapTableName())->execute(); // Update the file_directory_path. Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize('files/test')))->condition('name', 'file_directory_path')->execute(); Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize(file_directory_temp())))->condition('name', 'file_directory_temp')->execute(); $this->executeMigration('d6_file'); $file = File::load(2); $this->assertIdentical('public://core/modules/simpletest/files/image-2.jpg', $file->getFileUri()); // File 7, created in static::migrateDumpAlter(), shares a path with // file 5, which means it should be skipped entirely. $this->assertNull(File::load(7)); }
protected function setUp() { parent::setUp(); $node_storage = $this->container->get('entity.manager')->getStorage('node'); $this->fieldName = strtolower($this->randomMachineName()); $type_name = 'article'; $this->createFileField($this->fieldName, 'node', $type_name); // Set the teaser display to show this field. entity_get_display('node', 'article', 'teaser')->setComponent($this->fieldName, array('type' => 'file_default'))->save(); // Set the RDF mapping for the new field. $mapping = rdf_get_mapping('node', 'article'); $mapping->setFieldMapping($this->fieldName, array('properties' => array('rdfs:seeAlso'), 'mapping_type' => 'rel'))->save(); $test_file = $this->getTestFile('text'); // Create a new node with the uploaded file. $nid = $this->uploadNodeFile($test_file, $this->fieldName, $type_name); $node_storage->resetCache(array($nid)); $this->node = $node_storage->load($nid); $this->file = File::load($this->node->{$this->fieldName}->target_id); }
/** * Tests the normal formatter display on node display. */ function testUploadPath() { /** @var \Drupal\node\NodeStorageInterface $node_storage */ $node_storage = $this->container->get('entity.manager')->getStorage('node'); $field_name = strtolower($this->randomMachineName()); $type_name = 'article'; $this->createFileField($field_name, 'node', $type_name); /** @var \Drupal\file\FileInterface $test_file */ $test_file = $this->getTestFile('text'); // Create a new node. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); // Check that the file was uploaded to the correct location. $node_storage->resetCache(array($nid)); $node = $node_storage->load($nid); /** @var \Drupal\file\FileInterface $node_file */ $node_file = $node->{$field_name}->entity; $date_formatter = $this->container->get('date.formatter'); $expected_filename = 'public://' . $date_formatter->format(REQUEST_TIME, 'custom', 'Y') . '-' . $date_formatter->format(REQUEST_TIME, 'custom', 'm') . '/' . $test_file->getFilename(); $this->assertPathMatch($expected_filename, $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path.', array('%file' => $node_file->getFileUri()))); // Change the path to contain multiple subdirectories. $this->updateFileField($field_name, $type_name, array('file_directory' => 'foo/bar/baz')); // Upload a new file into the subdirectories. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); // Check that the file was uploaded into the subdirectory. $node_storage->resetCache(array($nid)); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); $this->assertPathMatch('public://foo/bar/baz/' . $test_file->getFilename(), $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path.', array('%file' => $node_file->getFileUri()))); // Check the path when used with tokens. // Change the path to contain multiple token directories. $this->updateFileField($field_name, $type_name, array('file_directory' => '[current-user:uid]/[current-user:name]')); // Upload a new file into the token subdirectories. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); // Check that the file was uploaded into the subdirectory. $node_storage->resetCache(array($nid)); $node = $node_storage->load($nid); $node_file = File::load($node->{$field_name}->target_id); // Do token replacement using the same user which uploaded the file, not // the user running the test case. $data = array('user' => $this->adminUser); $subdirectory = \Drupal::token()->replace('[user:uid]/[user:name]', $data); $this->assertPathMatch('public://' . $subdirectory . '/' . $test_file->getFilename(), $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path with token replacements.', array('%file' => $node_file->getFileUri()))); }
/** * @inheritdoc */ public function populateWithFieldData(FillPdfFormInterface $pdf_form, array $field_mapping, array $context) { /** @var FileInterface $original_file */ $original_file = File::load($pdf_form->file->target_id); $pdf_data = file_get_contents($original_file->getFileUri()); $fields = $field_mapping['fields']; $require = drupal_get_path('module', 'fillpdf') . '/lib/JavaBridge/java/Java.inc'; require_once DRUPAL_ROOT . '/' . $require; try { $fillpdf = new \java('com.ocdevel.FillpdfService', base64_encode($pdf_data), 'bytes'); foreach ($fields as $key => $field) { if (substr($field, 0, 7) == '{image}') { // Remove {image} marker. $image_filepath = substr($field, 7); $image_realpath = $this->fileSystem->realpath($image_filepath); $fillpdf->image($key, $image_realpath, 'file'); } else { $fillpdf->text($key, $field); } } } catch (\JavaException $e) { drupal_set_message(java_truncate((string) $e), 'error'); return NULL; } try { if ($context['flatten']) { $populated_pdf = java_values(base64_decode($fillpdf->toByteArray())); } else { $populated_pdf = java_values(base64_decode($fillpdf->toByteArrayUnflattened())); } } catch (\JavaException $e) { drupal_set_message(java_truncate((string) $e), 'error'); return NULL; } return $populated_pdf; }
/** * Tests the Drupal6 user to Drupal 8 migration. */ public function testUser() { $users = Database::getConnection('default', 'migrate')->select('users', 'u')->fields('u')->execute()->fetchAll(); foreach ($users as $source) { // Get roles directly from the source. $rids = Database::getConnection('default', 'migrate')->select('users_roles', 'ur')->fields('ur', array('rid'))->condition('ur.uid', $source->uid)->execute()->fetchCol(); $roles = array(RoleInterface::AUTHENTICATED_ID); $migration_role = entity_load('migration', 'd6_user_role'); foreach ($rids as $rid) { $role = $migration_role->getIdMap()->lookupDestinationId(array($rid)); $roles[] = reset($role); } /** @var \Drupal\user\UserInterface $user */ $user = User::load($source->uid); $this->assertIdentical($source->uid, $user->id()); $this->assertIdentical($source->name, $user->label()); $this->assertIdentical($source->mail, $user->getEmail()); $this->assertIdentical($source->created, $user->getCreatedTime()); $this->assertIdentical($source->access, $user->getLastAccessedTime()); $this->assertIdentical($source->login, $user->getLastLoginTime()); $is_blocked = $source->status == 0; $this->assertIdentical($is_blocked, $user->isBlocked()); // $user->getPreferredLangcode() might fallback to default language if the // user preferred language is not configured on the site. We just want to // test if the value was imported correctly. $this->assertIdentical($source->language, $user->preferred_langcode->value); $expected_timezone_name = $source->timezone_name ?: $this->config('system.date')->get('timezone.default'); $this->assertIdentical($expected_timezone_name, $user->getTimeZone()); $this->assertIdentical($source->init, $user->getInitialEmail()); $this->assertIdentical($roles, $user->getRoles()); // We have one empty picture in the data so don't try load that. if (!empty($source->picture)) { // Test the user picture. $file = File::load($user->user_picture->target_id); $this->assertIdentical(basename($source->picture), $file->getFilename()); } // Use the API to check if the password has been salted and re-hashed to // conform the Drupal >= 7. $this->assertTrue(\Drupal::service('password')->check($source->pass_plain, $user->getPassword())); } }