Esempio n. 1
0
 /**
  *  This ensures a specific file is actually an image.
  */
 function testFileValidateIsImage()
 {
     $this->assertTrue(file_exists($this->image->getFileUri()), 'The image being tested exists.', 'File');
     $errors = file_validate_is_image($this->image);
     $this->assertEqual(count($errors), 0, 'No error reported for our image file.', 'File');
     $this->assertTrue(file_exists($this->nonImage->getFileUri()), 'The non-image being tested exists.', 'File');
     $errors = file_validate_is_image($this->nonImage);
     $this->assertEqual(count($errors), 1, 'An error reported for our non-image file.', 'File');
 }
Esempio n. 2
0
 /**
  * Tests using entity fields of the image field type.
  */
 public function testImageItem()
 {
     // Create a test entity with the image field set.
     $entity = EntityTest::create();
     $entity->image_test->target_id = $this->image->id();
     $entity->image_test->alt = $alt = $this->randomMachineName();
     $entity->image_test->title = $title = $this->randomMachineName();
     $entity->name->value = $this->randomMachineName();
     $entity->save();
     $entity = entity_load('entity_test', $entity->id());
     $this->assertTrue($entity->image_test instanceof FieldItemListInterface, 'Field implements interface.');
     $this->assertTrue($entity->image_test[0] instanceof FieldItemInterface, 'Field item implements interface.');
     $this->assertEqual($entity->image_test->target_id, $this->image->id());
     $this->assertEqual($entity->image_test->alt, $alt);
     $this->assertEqual($entity->image_test->title, $title);
     $image = $this->imageFactory->get('public://example.jpg');
     $this->assertEqual($entity->image_test->width, $image->getWidth());
     $this->assertEqual($entity->image_test->height, $image->getHeight());
     $this->assertEqual($entity->image_test->entity->id(), $this->image->id());
     $this->assertEqual($entity->image_test->entity->uuid(), $this->image->uuid());
     // Make sure the computed entity reflects updates to the referenced file.
     file_unmanaged_copy(\Drupal::root() . '/core/misc/druplicon.png', 'public://example-2.jpg');
     $image2 = File::create(['uri' => 'public://example-2.jpg']);
     $image2->save();
     $entity->image_test->target_id = $image2->id();
     $entity->image_test->alt = $new_alt = $this->randomMachineName();
     // The width and height is only updated when width is not set.
     $entity->image_test->width = NULL;
     $entity->save();
     $this->assertEqual($entity->image_test->entity->id(), $image2->id());
     $this->assertEqual($entity->image_test->entity->getFileUri(), $image2->getFileUri());
     $image = $this->imageFactory->get('public://example-2.jpg');
     $this->assertEqual($entity->image_test->width, $image->getWidth());
     $this->assertEqual($entity->image_test->height, $image->getHeight());
     $this->assertEqual($entity->image_test->alt, $new_alt);
     // Check that the image item can be set to the referenced file directly.
     $entity->image_test = $this->image;
     $this->assertEqual($entity->image_test->target_id, $this->image->id());
     // Delete the image and try to save the entity again.
     $this->image->delete();
     $entity = EntityTest::create(array('mame' => $this->randomMachineName()));
     $entity->save();
     // Test image item properties.
     $expected = array('target_id', 'entity', 'alt', 'title', 'width', 'height');
     $properties = $entity->getFieldDefinition('image_test')->getFieldStorageDefinition()->getPropertyDefinitions();
     $this->assertEqual(array_keys($properties), $expected);
     // Test the generateSampleValue() method.
     $entity = EntityTest::create();
     $entity->image_test->generateSampleItems();
     $this->entityValidateAndSave($entity);
     $this->assertEqual($entity->image_test->entity->get('filemime')->value, 'image/jpeg');
 }
Esempio n. 3
0
 /**
  * Tests the embed_button and file usage integration.
  */
 public function testEmbedButtonIconUsage()
 {
     $this->enableModules(['system', 'user', 'file']);
     $this->installSchema('file', ['file_usage']);
     $this->installConfig(['system']);
     $this->installEntitySchema('user');
     $this->installEntitySchema('file');
     $this->installEntitySchema('embed_button');
     $file1 = file_save_data(file_get_contents('core/misc/druplicon.png'));
     $file1->setTemporary();
     $file1->save();
     $file2 = file_save_data(file_get_contents('core/misc/druplicon.png'));
     $file2->setTemporary();
     $file2->save();
     $button = array('id' => 'test_button', 'label' => 'Testing embed button instance', 'type_id' => 'embed_test_default', 'icon_uuid' => $file1->uuid());
     $entity = EmbedButton::create($button);
     $entity->save();
     $this->assertTrue(File::load($file1->id())->isPermanent());
     // Delete the icon from the button.
     $entity->icon_uuid = NULL;
     $entity->save();
     $this->assertTrue(File::load($file1->id())->isTemporary());
     $entity->icon_uuid = $file1->uuid();
     $entity->save();
     $this->assertTrue(File::load($file1->id())->isPermanent());
     $entity->icon_uuid = $file2->uuid();
     $entity->save();
     $this->assertTrue(File::load($file1->id())->isTemporary());
     $this->assertTrue(File::load($file2->id())->isPermanent());
     $entity->delete();
     $this->assertTrue(File::load($file2->id())->isTemporary());
 }
 /**
  * Tests file entity denormalization.
  */
 public function testFileDenormalize()
 {
     $file_params = array('filename' => 'test_1.txt', 'uri' => 'public://test_1.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT);
     // Create a new file entity.
     $file = File::create($file_params);
     file_put_contents($file->getFileUri(), 'hello world');
     $file->save();
     $serializer = \Drupal::service('serializer');
     $normalized_data = $serializer->normalize($file, 'hal_json');
     $denormalized = $serializer->denormalize($normalized_data, 'Drupal\\file\\Entity\\File', 'hal_json');
     $this->assertTrue($denormalized instanceof File, 'A File instance was created.');
     $this->assertIdentical('temporary://' . $file->getFilename(), $denormalized->getFileUri(), 'The expected file URI was found.');
     $this->assertTrue(file_exists($denormalized->getFileUri()), 'The temporary file was found.');
     $this->assertIdentical($file->uuid(), $denormalized->uuid(), 'The expected UUID was found');
     $this->assertIdentical($file->getMimeType(), $denormalized->getMimeType(), 'The expected MIME type was found.');
     $this->assertIdentical($file->getFilename(), $denormalized->getFilename(), 'The expected filename was found.');
     $this->assertTrue($denormalized->isPermanent(), 'The file has a permanent status.');
     // Try to denormalize with the file uri only.
     $file_name = 'test_2.txt';
     $file_path = 'public://' . $file_name;
     file_put_contents($file_path, 'hello world');
     $file_uri = file_create_url($file_path);
     $data = array('uri' => array(array('value' => $file_uri)));
     $denormalized = $serializer->denormalize($data, 'Drupal\\file\\Entity\\File', 'hal_json');
     $this->assertIdentical('temporary://' . $file_name, $denormalized->getFileUri(), 'The expected file URI was found.');
     $this->assertTrue(file_exists($denormalized->getFileUri()), 'The temporary file was found.');
     $this->assertIdentical('text/plain', $denormalized->getMimeType(), 'The expected MIME type was found.');
     $this->assertIdentical($file_name, $denormalized->getFilename(), 'The expected filename was found.');
     $this->assertFalse($denormalized->isPermanent(), 'The file has a permanent status.');
 }
Esempio n. 5
0
 /**
  * {@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();
 }
Esempio n. 6
0
 /**
  * {@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');
     }
 }
Esempio n. 7
0
 /**
  * Tests if public file is always accessible.
  */
 function testFileAccess()
 {
     // Create a new file entity.
     $file = File::create(array('uid' => 1, 'filename' => 'drupal.txt', 'uri' => 'public://drupal.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT));
     file_put_contents($file->getFileUri(), 'hello world');
     // Save it, inserting a new record.
     $file->save();
     // Create authenticated user to check file access.
     $account = $this->createUser(array('access site reports'));
     $this->assertTrue($file->access('view', $account), 'Public file is viewable to authenticated user');
     $this->assertTrue($file->access('download', $account), 'Public file is downloadable to authenticated user');
     // Create anonymous user to check file access.
     $account = $this->createUser()->getAnonymousUser();
     $this->assertTrue($file->access('view', $account), 'Public file is viewable to anonymous user');
     $this->assertTrue($file->access('download', $account), 'Public file is downloadable to anonymous user');
     // Create a new file entity.
     $file = File::create(array('uid' => 1, 'filename' => 'drupal.txt', 'uri' => 'private://drupal.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT));
     file_put_contents($file->getFileUri(), 'hello world');
     // Save it, inserting a new record.
     $file->save();
     // Create authenticated user to check file access.
     $account = $this->createUser(array('access site reports'));
     $this->assertFalse($file->access('view', $account), 'Private file is not viewable to authenticated user');
     $this->assertFalse($file->access('download', $account), 'Private file is not downloadable to authenticated user');
     // Create anonymous user to check file access.
     $account = $this->createUser()->getAnonymousUser();
     $this->assertFalse($file->access('view', $account), 'Private file is not viewable to anonymous user');
     $this->assertFalse($file->access('download', $account), 'Private file is not downloadable to anonymous user');
 }
Esempio n. 8
0
 /**
  * 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.');
 }
Esempio n. 9
0
 /**
  * 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.');
 }
Esempio n. 10
0
  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);
  }
 /**
  * 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.');
 }
 /**
  * {@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;
 }
 /**
  * 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.');
 }
Esempio n. 14
0
 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 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());
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('file');
     $this->installEntitySchema('node');
     $this->installSchema('file', ['file_usage']);
     $this->installSchema('node', ['node_access']);
     $id_mappings = array('d6_file' => array());
     // Create new file entities.
     for ($i = 1; $i <= 3; $i++) {
         $file = File::create(array('fid' => $i, 'uid' => 1, 'filename' => 'druplicon.txt', 'uri' => "public://druplicon-{$i}.txt", 'filemime' => 'text/plain', 'created' => 1, 'changed' => 1, 'status' => FILE_STATUS_PERMANENT));
         $file->enforceIsNew();
         file_put_contents($file->getFileUri(), 'hello world');
         // Save it, inserting a new record.
         $file->save();
         $id_mappings['d6_file'][] = array(array($i), array($i));
     }
     $this->prepareMigrations($id_mappings);
     $this->migrateContent();
     // Since we are only testing a subset of the file migration, do not check
     // that the full file migration has been run.
     $migration = $this->getMigration('d6_upload');
     $migration->set('requirements', []);
     $this->executeMigration($migration);
 }
Esempio n. 17
0
 /**
  * {@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');
     }
 }
Esempio n. 18
0
 /**
  * Creates a file with a given size.
  *
  * @param string $uri
  *   URI of the file to create.
  * @param int $size
  *   Size of the file.
  * @param int $uid
  *   File owner ID.
  * @param int $status
  *   Whether the file should be permanent or temporary.
  *
  * @return \Drupal\Core\Entity\EntityInterface
  *   The file entity.
  */
 protected function createFileWithSize($uri, $size, $uid, $status = FILE_STATUS_PERMANENT)
 {
     file_put_contents($uri, $this->randomMachineName($size));
     $file = File::create(['uri' => $uri, 'uid' => $uid, 'status' => $status]);
     $file->save();
     return $file;
 }
 /**
  * Tests using entity fields of the image field type.
  */
 public function testImageItem()
 {
     // Create a test entity with the image field set.
     $entity = entity_create('entity_test');
     $entity->image_test->target_id = $this->image->id();
     $entity->image_test->alt = $alt = $this->randomMachineName();
     $entity->image_test->title = $title = $this->randomMachineName();
     $entity->name->value = $this->randomMachineName();
     $entity->save();
     $entity = entity_load('entity_test', $entity->id());
     $this->assertTrue($entity->image_test instanceof FieldItemListInterface, 'Field implements interface.');
     $this->assertTrue($entity->image_test[0] instanceof FieldItemInterface, 'Field item implements interface.');
     $this->assertEqual($entity->image_test->target_id, $this->image->id());
     $this->assertEqual($entity->image_test->alt, $alt);
     $this->assertEqual($entity->image_test->title, $title);
     $image = $this->imageFactory->get('public://example.jpg');
     $this->assertEqual($entity->image_test->width, $image->getWidth());
     $this->assertEqual($entity->image_test->height, $image->getHeight());
     $this->assertEqual($entity->image_test->entity->id(), $this->image->id());
     $this->assertEqual($entity->image_test->entity->uuid(), $this->image->uuid());
     // Make sure the computed entity reflects updates to the referenced file.
     file_unmanaged_copy(DRUPAL_ROOT . '/core/misc/feed.png', 'public://example-2.jpg');
     $image2 = entity_create('file', array('uri' => 'public://example-2.jpg'));
     $image2->save();
     $entity->image_test->target_id = $image2->id();
     $entity->image_test->alt = $new_alt = $this->randomMachineName();
     // The width and height is only updated when width is not set.
     $entity->image_test->width = NULL;
     $entity->save();
     $this->assertEqual($entity->image_test->entity->id(), $image2->id());
     $this->assertEqual($entity->image_test->entity->getFileUri(), $image2->getFileUri());
     $image = $this->imageFactory->get('public://example-2.jpg');
     $this->assertEqual($entity->image_test->width, $image->getWidth());
     $this->assertEqual($entity->image_test->height, $image->getHeight());
     $this->assertEqual($entity->image_test->alt, $new_alt);
     // Check that the image item can be set to the referenced file directly.
     $entity->image_test = $this->image;
     $this->assertEqual($entity->image_test->target_id, $this->image->id());
     // Delete the image and try to save the entity again.
     $this->image->delete();
     $entity = entity_create('entity_test', array('mame' => $this->randomMachineName()));
     $entity->save();
     // Test the generateSampleValue() method.
     $entity = entity_create('entity_test');
     $entity->image_test->generateSampleItems();
     $this->entityValidateAndSave($entity);
 }
 /**
  * Tests the editor file reference filter.
  */
 function testEditorFileReferenceFilter()
 {
     $filter = $this->filters['editor_file_reference'];
     $test = function ($input) use($filter) {
         return $filter->process($input, 'und');
     };
     file_put_contents('public://llama.jpg', $this->randomMachineName());
     $image = File::create(['uri' => 'public://llama.jpg']);
     $image->save();
     $id = $image->id();
     $uuid = $image->uuid();
     $cache_tag = ['file:' . $id];
     file_put_contents('public://alpaca.jpg', $this->randomMachineName());
     $image_2 = File::create(['uri' => 'public://alpaca.jpg']);
     $image_2->save();
     $id_2 = $image_2->id();
     $uuid_2 = $image_2->uuid();
     $cache_tag_2 = ['file:' . $id_2];
     $this->pass('No data-entity-type and no data-entity-uuid attribute.');
     $input = '<img src="llama.jpg" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->pass('A non-file data-entity-type attribute value.');
     $input = '<img src="llama.jpg" data-entity-type="invalid-entity-type-value" data-entity-uuid="' . $uuid . '" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->pass('One data-entity-uuid attribute.');
     $input = '<img src="llama.jpg" data-entity-type="file" data-entity-uuid="' . $uuid . '" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->assertEqual($cache_tag, $output->getCacheTags());
     $this->pass('One data-entity-uuid attribute with odd capitalization.');
     $input = '<img src="llama.jpg" data-entity-type="file" DATA-entity-UUID =   "' . $uuid . '" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->assertEqual($cache_tag, $output->getCacheTags());
     $this->pass('One data-entity-uuid attribute on a non-image tag.');
     $input = '<video src="llama.jpg" data-entity-type="file" data-entity-uuid="' . $uuid . '" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->assertEqual($cache_tag, $output->getCacheTags());
     $this->pass('One data-entity-uuid attribute with an invalid value.');
     $input = '<img src="llama.jpg" data-entity-type="file" data-entity-uuid="invalid-' . $uuid . '" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->assertEqual(array(), $output->getCacheTags());
     $this->pass('Two different data-entity-uuid attributes.');
     $input = '<img src="llama.jpg" data-entity-type="file" data-entity-uuid="' . $uuid . '" />';
     $input .= '<img src="alpaca.jpg" data-entity-type="file" data-entity-uuid="' . $uuid_2 . '" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->assertEqual(Cache::mergeTags($cache_tag, $cache_tag_2), $output->getCacheTags());
     $this->pass('Two identical  data-entity-uuid attributes.');
     $input = '<img src="llama.jpg" data-entity-type="file" data-entity-uuid="' . $uuid . '" />';
     $input .= '<img src="llama.jpg" data-entity-type="file" data-entity-uuid="' . $uuid . '" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->assertEqual($cache_tag, $output->getCacheTags());
 }
Esempio n. 21
0
 /**
  * Tests using entity fields of the file field type.
  */
 public function testFileItem()
 {
     // Create a test entity with the
     $entity = entity_create('entity_test');
     $entity->file_test->target_id = $this->file->id();
     $entity->file_test->display = 1;
     $entity->file_test->description = $description = $this->randomName();
     $entity->name->value = $this->randomName();
     $entity->save();
     $entity = entity_load('entity_test', $entity->id());
     $this->assertTrue($entity->file_test instanceof FieldItemListInterface, 'Field implements interface.');
     $this->assertTrue($entity->file_test[0] instanceof FieldItemInterface, 'Field item implements interface.');
     $this->assertEqual($entity->file_test->target_id, $this->file->id());
     $this->assertEqual($entity->file_test->display, 1);
     $this->assertEqual($entity->file_test->description, $description);
     $this->assertEqual($entity->file_test->entity->getFileUri(), $this->file->getFileUri());
     $this->assertEqual($entity->file_test->entity->url(), $url = file_create_url($this->file->getFileUri()));
     $this->assertEqual($entity->file_test->entity->id(), $this->file->id());
     $this->assertEqual($entity->file_test->entity->uuid(), $this->file->uuid());
     // Make sure the computed files reflects updates to the file.
     file_put_contents('public://example-2.txt', $this->randomName());
     $file2 = entity_create('file', array('uri' => 'public://example-2.txt'));
     $file2->save();
     $entity->file_test->target_id = $file2->id();
     $this->assertEqual($entity->file_test->entity->id(), $file2->id());
     $this->assertEqual($entity->file_test->entity->getFileUri(), $file2->getFileUri());
     // Test the deletion of an entity having an entity reference field targeting
     // a non-existing entity.
     $file2->delete();
     $entity->delete();
 }
Esempio n. 22
0
 /**
  * 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);
         }
     }
 }
Esempio n. 23
0
 /**
  * @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;
 }
Esempio n. 24
0
 /**
  * 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())));
 }
Esempio n. 25
0
 /**
  * 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-&amp;-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.');
 }
Esempio n. 26
0
 /**
  * Tests usage of the image field formatters.
  */
 function testImageFormatterTheme()
 {
     /** @var \Drupal\Core\Render\RendererInterface $renderer */
     $renderer = $this->container->get('renderer');
     // Create an image.
     $files = $this->drupalGetTestFiles('image');
     $file = reset($files);
     $original_uri = file_unmanaged_copy($file->uri, 'public://', FILE_EXISTS_RENAME);
     // Create a style.
     $style = entity_create('image_style', array('name' => 'test', 'label' => 'Test'));
     $style->save();
     $url = $style->buildUrl($original_uri);
     // Create a test entity with the image field set.
     $entity = entity_create('entity_test');
     $entity->image_test->target_id = $this->image->id();
     $entity->image_test->alt = NULL;
     $entity->image_test->uri = $original_uri;
     $image = $this->imageFactory->get('public://example.jpg');
     $entity->save();
     // Create the base element that we'll use in the tests below.
     $path = $this->randomMachineName();
     $base_element = array('#theme' => 'image_formatter', '#image_style' => 'test', '#item' => $entity->image_test, '#url' => Url::fromUri('base:' . $path));
     // Test using theme_image_formatter() with a NULL value for the alt option.
     $element = $base_element;
     $this->setRawContent($renderer->renderRoot($element));
     $elements = $this->xpath('//a[@href=:path]/img[@class="image-style-test" and @src=:url and @width=:width and @height=:height]', array(':path' => base_path() . $path, ':url' => $url, ':width' => $image->getWidth(), ':height' => $image->getHeight()));
     $this->assertEqual(count($elements), 1, 'theme_image_formatter() correctly renders with a NULL value for the alt option.');
     // Test using theme_image_formatter() without an image title, alt text, or
     // link options.
     $element = $base_element;
     $element['#item']->alt = '';
     $this->setRawContent($renderer->renderRoot($element));
     $elements = $this->xpath('//a[@href=:path]/img[@class="image-style-test" and @src=:url and @width=:width and @height=:height and @alt=""]', array(':path' => base_path() . $path, ':url' => $url, ':width' => $image->getWidth(), ':height' => $image->getHeight()));
     $this->assertEqual(count($elements), 1, 'theme_image_formatter() correctly renders without title, alt, or path options.');
     // Link the image to a fragment on the page, and not a full URL.
     $fragment = $this->randomMachineName();
     $element = $base_element;
     $element['#url'] = Url::fromRoute('<none>', [], ['fragment' => $fragment]);
     $this->setRawContent($renderer->renderRoot($element));
     $elements = $this->xpath('//a[@href=:fragment]/img[@class="image-style-test" and @src=:url and @width=:width and @height=:height and @alt=""]', array(':fragment' => '#' . $fragment, ':url' => $url, ':width' => $image->getWidth(), ':height' => $image->getHeight()));
     $this->assertEqual(count($elements), 1, 'theme_image_formatter() correctly renders a link fragment.');
 }
Esempio n. 27
0
 /**
  * Retrieves a sample file of the specified type.
  *
  * @return \Drupal\file\FileInterface
  */
 protected function getTestFile($type_name, $size = NULL)
 {
     // Get a file to upload.
     $file = current($this->drupalGetTestFiles($type_name, $size));
     // Add a filesize property to files as would be read by
     // \Drupal\file\Entity\File::load().
     $file->filesize = filesize($file->uri);
     $file = File::create((array) $file);
     $file->save();
     return $file;
 }
Esempio n. 28
0
 /**
  * Tests the normalize function.
  */
 public function testNormalize()
 {
     $file_params = array('filename' => 'test_1.txt', 'uri' => 'public://test_1.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT);
     // Create a new file entity.
     $file = File::create($file_params);
     file_put_contents($file->getFileUri(), 'hello world');
     $file->save();
     $expected_array = array('uri' => array(array('value' => file_create_url($file->getFileUri()))));
     $normalized = $this->serializer->normalize($file, $this->format);
     $this->assertEqual($normalized['uri'], $expected_array['uri'], 'URI is normalized.');
 }
Esempio n. 29
0
 /**
  * Tests using entity fields of the file field type.
  */
 public function testFileItem()
 {
     // Check that the selection handler was automatically assigned to
     // 'default:file'.
     $field_definition = FieldConfig::load('entity_test.entity_test.file_test');
     $handler_id = $field_definition->getSetting('handler');
     $this->assertEqual($handler_id, 'default:file');
     // Create a test entity with the
     $entity = EntityTest::create();
     $entity->file_test->target_id = $this->file->id();
     $entity->file_test->display = 1;
     $entity->file_test->description = $description = $this->randomMachineName();
     $entity->name->value = $this->randomMachineName();
     $entity->save();
     $entity = EntityTest::load($entity->id());
     $this->assertTrue($entity->file_test instanceof FieldItemListInterface, 'Field implements interface.');
     $this->assertTrue($entity->file_test[0] instanceof FieldItemInterface, 'Field item implements interface.');
     $this->assertEqual($entity->file_test->target_id, $this->file->id());
     $this->assertEqual($entity->file_test->display, 1);
     $this->assertEqual($entity->file_test->description, $description);
     $this->assertEqual($entity->file_test->entity->getFileUri(), $this->file->getFileUri());
     $this->assertEqual($entity->file_test->entity->url(), $url = file_create_url($this->file->getFileUri()));
     $this->assertEqual($entity->file_test->entity->id(), $this->file->id());
     $this->assertEqual($entity->file_test->entity->uuid(), $this->file->uuid());
     // Make sure the computed files reflects updates to the file.
     file_put_contents('public://example-2.txt', $this->randomMachineName());
     $file2 = File::create(['uri' => 'public://example-2.txt']);
     $file2->save();
     $entity->file_test->target_id = $file2->id();
     $this->assertEqual($entity->file_test->entity->id(), $file2->id());
     $this->assertEqual($entity->file_test->entity->getFileUri(), $file2->getFileUri());
     // Test the deletion of an entity having an entity reference field targeting
     // a non-existing entity.
     $file2->delete();
     $entity->delete();
     // Test the generateSampleValue() method.
     $entity = EntityTest::create();
     $entity->file_test->generateSampleItems();
     $this->entityValidateAndSave($entity);
     // Verify that the sample file was stored in the correct directory.
     $uri = $entity->file_test->entity->getFileUri();
     $this->assertEqual($this->directory, dirname(file_uri_target($uri)));
     // Make sure the computed files reflects updates to the file.
     file_put_contents('public://example-3.txt', $this->randomMachineName());
     // Test unsaved file entity.
     $file3 = File::create(['uri' => 'public://example-3.txt']);
     $display = entity_get_display('entity_test', 'entity_test', 'default');
     $display->setComponent('file_test', ['label' => 'above', 'type' => 'file_default', 'weight' => 1])->save();
     $entity = EntityTest::create();
     $entity->file_test = array('entity' => $file3);
     $uri = $file3->getFileUri();
     $output = entity_view($entity, 'default');
     \Drupal::service('renderer')->renderRoot($output);
     $this->assertTrue(!empty($entity->file_test->entity));
     $this->assertEqual($entity->file_test->entity->getFileUri(), $uri);
 }
Esempio n. 30
0
 /**
  * {@inheritdoc}
  */
 function setUp()
 {
     parent::setUp();
     $this->addLanguage('de');
     $filtered_html_format = FilterFormat::create(array('format' => 'filtered_html', 'name' => 'Filtered HTML'));
     $filtered_html_format->save();
     $this->drupalCreateContentType(array('type' => 'test_bundle'));
     $this->loginAsAdmin(array('create translation jobs', 'submit translation jobs', 'create test_bundle content', $filtered_html_format->getPermissionName()));
     file_unmanaged_copy(DRUPAL_ROOT . '/core/misc/druplicon.png', 'public://example.jpg');
     $this->image = File::create(array('uri' => 'public://example.jpg'));
     $this->image->save();
 }