public function content()
 {
     $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
     $userId = $user->get('uid')->value;
     $data = array(array('job_title' => '', 'job_path' => '', 'company_name' => '', 'application_date' => ''));
     $appliedJobs = db_select('user_job_application', 'uja')->condition('uja.user_id', $userId, '=')->fields('uja', array('job_id', 'date'))->orderBy('uja.date', 'DESC')->execute()->fetchAll();
     if ($appliedJobs) {
         $x = 0;
         foreach ($appliedJobs as $appliedJob) {
             $jobNode = \Drupal\node\Entity\Node::load($appliedJob->job_id);
             $jobTitle = $jobNode->getTitle();
             $jobPathAlias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $appliedJob->job_id);
             $companyNodeEntity = $jobNode->get('field_company');
             $companyNode = \Drupal\node\Entity\Node::load($companyNodeEntity->entity->id());
             $companyName = $companyNode->getTitle();
             $data[$x]['job_title'] = $jobTitle;
             $data[$x]['job_path'] = $jobPathAlias;
             $data[$x]['company_name'] = $companyName;
             $data[$x]['application_date'] = $appliedJob->date;
             $x++;
         }
     }
     $markUp = $this->createMarkUp($data);
     return array('#type' => 'markup', '#markup' => $markUp);
 }
Ejemplo n.º 2
0
 /**
  * Test CCK migration from Drupal 6 to 8.
  */
 public function testCckFields()
 {
     $node = Node::load(1);
     $this->assertIdentical('This is a shared text field', $node->field_test->value);
     $this->assertIdentical('filtered_html', $node->field_test->format);
     $this->assertIdentical('10', $node->field_test_two->value);
     $this->assertIdentical('20', $node->field_test_two[1]->value);
     $this->assertIdentical('42.42', $node->field_test_three->value, 'Single field second value is correct.');
     $this->assertIdentical('3412', $node->field_test_integer_selectlist[0]->value);
     $this->assertIdentical('1', $node->field_test_identical1->value, 'Integer value is correct');
     $this->assertIdentical('1', $node->field_test_identical2->value, 'Integer value is correct');
     $this->assertIdentical('This is a field with exclude unset.', $node->field_test_exclude_unset->value, 'Field with exclude unset is correct.');
     // Test that link fields are migrated.
     $this->assertIdentical('https://www.drupal.org/project/drupal', $node->field_test_link->uri);
     $this->assertIdentical('Drupal project page', $node->field_test_link->title);
     $this->assertIdentical(['target' => '_blank'], $node->field_test_link->options['attributes']);
     // Test the file field meta.
     $this->assertIdentical('desc', $node->field_test_filefield->description);
     $this->assertIdentical('5', $node->field_test_filefield->target_id);
     $planet_node = Node::load(3);
     $value_1 = $planet_node->field_multivalue->value;
     $value_2 = $planet_node->field_multivalue[1]->value;
     // SQLite does not support scales for float data types so we need to convert
     // the value manually.
     if ($this->container->get('database')->driver() == 'sqlite') {
         $value_1 = sprintf('%01.2f', $value_1);
         $value_2 = sprintf('%01.2f', $value_2);
     }
     $this->assertIdentical('33.00', $value_1);
     $this->assertIdentical('44.00', $value_2);
 }
 /**
  * Test for autocomplete processing.
  *
  * Tests that processing does not crash when the entity types of the
  * referenced entity and of the entity the field is attached to are different.
  */
 public function testEntityReferenceRevisionsAutocompleteProcessing()
 {
     $admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer nodes', 'administer blocks', 'create article content', 'administer content types', 'administer node fields', 'administer node display', 'administer node form display', 'edit any article content'));
     $this->drupalLogin($admin_user);
     // Create a custom block content bundle.
     $this->createBlockContentType(array('type' => 'customblockcontent', 'name' => 'Custom Block Content'));
     // Create entity reference revisions field attached to article.
     static::fieldUIAddNewField('admin/structure/types/manage/article', 'entity_reference_revisions', 'Entity reference revisions', 'entity_reference_revisions', array('settings[target_type]' => 'block_content', 'cardinality' => '-1'), array('settings[handler_settings][target_bundles][customblockcontent]' => TRUE));
     // Create custom block.
     $block_label = $this->randomMachineName();
     $block_content = $this->randomString();
     $edit = array('info[0][value]' => $block_label, 'body[0][value]' => $block_content, 'revision' => TRUE);
     $this->drupalPostForm('block/add', $edit, t('Save'));
     $block = $this->drupalGetBlockByInfo($block_label);
     // Create an article.
     $title = $this->randomMachineName();
     $edit = array('title[0][value]' => $title, 'body[0][value]' => 'Revision 1', 'field_entity_reference_revisions[0][target_id]' => $block_label . ' (' . $block->id() . ')', 'revision' => TRUE);
     $this->drupalPostForm('node/add/article', $edit, t('Save and publish'));
     $this->assertText($title);
     $this->assertText(Html::escape($block_content));
     // Check if the block content is not deleted since there is no composite
     // relationship.
     $node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
     $node = Node::load($node->id());
     $node->delete();
     $this->assertNotNull(BlockContent::load($block->id()));
 }
Ejemplo n.º 4
0
 protected function setUp()
 {
     parent::setUp();
     // Create and log in user.
     $web_user = $this->drupalCreateUser(array('view page revisions', 'revert page revisions', 'delete page revisions', 'edit any page content', 'delete any page content'));
     $this->drupalLogin($web_user);
     // Create initial node.
     $node = $this->drupalCreateNode();
     $settings = get_object_vars($node);
     $settings['revision'] = 1;
     $settings['isDefaultRevision'] = TRUE;
     $nodes = array();
     $logs = array();
     // Get original node.
     $nodes[] = clone $node;
     // Create three revisions.
     $revision_count = 3;
     for ($i = 0; $i < $revision_count; $i++) {
         $logs[] = $node->revision_log = $this->randomMachineName(32);
         // Create revision with a random title and body and update variables.
         $node->title = $this->randomMachineName();
         $node->body = array('value' => $this->randomMachineName(32), 'format' => filter_default_format());
         $node->setNewRevision();
         $node->save();
         $node = Node::load($node->id());
         // Make sure we get revision information.
         $nodes[] = clone $node;
     }
     $this->nodes = $nodes;
     $this->revisionLogs = $logs;
 }
Ejemplo n.º 5
0
  /**
   * Lists all instances of fields on any views.
   *
   * @return array
   *   The Views fields report page.
   */
  public function nodeMarkup($node, $key = 'default') {
    $node = Node::load($node);

    $builded_entity = entity_view($node, $key);
    $markup = drupal_render($builded_entity);

    $links = array();
    $links['default'] = array(
      'title' => 'Default',
      'url' => Url::fromRoute('ds_devel.markup', array('node' => $node->id())),
    );
    $view_modes = \Drupal::entityManager()->getViewModes('node');
    foreach ($view_modes as $id => $info) {
      if (!empty($info['status'])) {
        $links[] = array(
          'title' => $info['label'],
          'url' => Url::fromRoute('ds_devel.markup_view_mode', array('node' => $node->id(), 'key' => $id)),
        );
      }
    }

    $build['links'] = array(
      '#theme' => 'links',
      '#links' => $links,
      '#prefix' => '<div>',
      '#suffix' => '</div><hr />',
    );
    $build['markup'] = [
      '#markup' => '<code><pre>' . Html::escape($markup) . '</pre></code>',
      '#allowed_tags' => ['code', 'pre'],
    ];

    return $build;
  }
Ejemplo n.º 6
0
 /**
  * {@inheritdoc}
  */
 public function nodeDelete($node)
 {
     $node = $node instanceof NodeInterface ? $node : Node::load($node->nid);
     if ($node instanceof NodeInterface) {
         $node->delete();
     }
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     //TODO v2 Send Email via Cron not on Submit
     $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
     $username = $user->get('name')->value;
     $userId = $user->get('uid')->value;
     $mailManager = \Drupal::service('plugin.manager.mail');
     $jobNode = \Drupal::routeMatch()->getParameter('node');
     $jobNodeTitle = $jobNode->getTitle();
     $companyNodeEntity = $jobNode->get('field_company');
     $companyNode = \Drupal\node\Entity\Node::load($companyNodeEntity->entity->id());
     $companyEmail = $companyNode->field_email->value;
     $resumeFileId = $form_state->getValue('resume');
     $resumeFile = db_select('file_managed', 'f')->condition('f.fid', $resumeFileId, '=')->fields('f', array('uri'))->execute()->fetchField();
     $atttachment = array('filepath' => $resumeFile);
     $module = 'job_mailer';
     $key = 'apply_job';
     $params['job_title'] = $jobNodeTitle;
     $params['message'] = "<html>\n           <p>Please see attached resume for user: {$username}\n           </html>";
     $params['attachment'] = $atttachment;
     $langcode = \Drupal::currentUser()->getPreferredLangcode();
     $send = true;
     $reply = \Drupal::config('system.site')->get('mail');
     $result = $mailManager->mail($module, $key, $companyEmail, $langcode, $params, $reply, $send);
     db_insert('user_job_application')->fields(array('job_id' => $jobNode->id(), 'user_id' => $userId, 'date' => date('Y-m-d H:i:s')))->execute();
     drupal_set_message('Your application has been sent.');
 }
Ejemplo n.º 8
0
 public function createICal($nid)
 {
     $node = \Drupal\node\Entity\Node::load($nid);
     $eventdate = $node->get('field_event_date')->getValue();
     $title = $node->get('title')->getValue();
     $title = $title[0]['value'];
     $startdate = $eventdate[0]['value'];
     $enddate = $eventdate[1]['value'];
     if (empty($enddate)) {
         $enddate = $startdate;
     }
     $startdate = self::convertDateToICal($startdate);
     $enddate = self::convertDateToICal($enddate);
     $filecontents = self::buildICSFile($startdate, $enddate, $title, $nid);
     // open raw memory as file so no temp files needed, you might run out of memory though
     $file = fopen('php://memory', 'w');
     fwrite($file, $filecontents);
     // reset the file pointer to the start of the file
     rewind($file);
     // tell the browser it's going to be a calendar file
     header('Content-Type: text/calendar; charset=utf-8');
     // tell the browser we want to save it instead of displaying it
     header('Content-Disposition: attachment; filename="calendar.ics";');
     header('Cache-Control: store, no-cache, must-revalidate, post-check=0, pre-check=0');
     // make php send the generated file to the browser
     fpassthru($file);
     exit;
     /*
     	return array(
     		'#type' => 'markup',
     		'#markup' => $this->t('Hello, ical World!<pre>' . $filecontents . "</pre>"),
     	);
     */
 }
Ejemplo n.º 9
0
 function testMenuTokens()
 {
     // Add a menu.
     $menu = entity_create('menu', array('id' => 'main-menu', 'label' => 'Main menu', 'description' => 'The <em>Main</em> menu is used on many sites to show the major sections of the site, often in a top navigation bar.'));
     $menu->save();
     // Add a root link.
     /** @var \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent $root_link */
     $root_link = entity_create('menu_link_content', array('link' => ['uri' => 'internal:/admin'], 'title' => 'Administration', 'menu_name' => 'main-menu'));
     $root_link->save();
     // Add another link with the root link as the parent.
     /** @var \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent $parent_link */
     $parent_link = entity_create('menu_link_content', array('link' => ['uri' => 'internal:/admin/config'], 'title' => 'Configuration', 'menu_name' => 'main-menu', 'parent' => $root_link->getPluginId()));
     $parent_link->save();
     // Test menu link tokens.
     $tokens = array('id' => $parent_link->getPluginId(), 'title' => 'Configuration', 'menu' => 'Main menu', 'menu:name' => 'Main menu', 'menu:machine-name' => $menu->id(), 'menu:description' => 'The <em>Main</em> menu is used on many sites to show the major sections of the site, often in a top navigation bar.', 'menu:menu-link-count' => '2', 'menu:edit-url' => \Drupal::url('entity.menu.edit_form', ['menu' => 'main-menu'], array('absolute' => TRUE)), 'url' => \Drupal::url('system.admin_config', [], array('absolute' => TRUE)), 'url:absolute' => \Drupal::url('system.admin_config', [], array('absolute' => TRUE)), 'url:relative' => \Drupal::url('system.admin_config', [], array('absolute' => FALSE)), 'url:path' => 'admin/config', 'url:alias' => 'admin/config', 'edit-url' => \Drupal::url('entity.menu_link_content.canonical', ['menu_link_content' => $parent_link->id()], array('absolute' => TRUE)), 'parent' => 'Administration', 'parent:id' => $root_link->getPluginId(), 'parent:title' => 'Administration', 'parent:menu' => 'Main menu', 'parent:parent' => NULL, 'parents' => 'Administration', 'parents:count' => 1, 'parents:keys' => $root_link->getPluginId(), 'root' => 'Administration', 'root:id' => $root_link->getPluginId(), 'root:parent' => NULL, 'root:root' => NULL);
     $this->assertTokens('menu-link', array('menu-link' => $parent_link), $tokens);
     // Add a node.
     $node = $this->drupalCreateNode();
     // Allow main menu for this node type.
     //$this->config('menu.entity.node.' . $node->getType())->set('available_menus', array('main-menu'))->save();
     // Add a node menu link.
     /** @var \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent $node_link */
     $node_link = entity_create('menu_link_content', array('link' => ['uri' => 'entity:node/' . $node->id()], 'title' => 'Node link', 'parent' => $parent_link->getPluginId(), 'menu_name' => 'main-menu'));
     $node_link->save();
     // Test [node:menu] tokens.
     $tokens = array('menu-link' => 'Node link', 'menu-link:id' => $node_link->getPluginId(), 'menu-link:title' => 'Node link', 'menu-link:menu' => 'Main menu', 'menu-link:url' => $node->url('canonical', ['absolute' => TRUE]), 'menu-link:url:path' => 'node/' . $node->id(), 'menu-link:edit-url' => $node_link->url('edit-form', ['absolute' => TRUE]), 'menu-link:parent' => 'Configuration', 'menu-link:parent:id' => $parent_link->getPluginId(), 'menu-link:parents' => 'Administration, Configuration', 'menu-link:parents:count' => 2, 'menu-link:parents:keys' => $root_link->getPluginId() . ', ' . $parent_link->getPluginId(), 'menu-link:root' => 'Administration', 'menu-link:root:id' => $root_link->getPluginId());
     $this->assertTokens('node', array('node' => $node), $tokens);
     // Reload the node which will not have $node->menu defined and re-test.
     $loaded_node = Node::load($node->id());
     $this->assertTokens('node', array('node' => $loaded_node), $tokens);
     // Regression test for http://drupal.org/node/1317926 to ensure the
     // original node object is not changed when calling menu_node_prepare().
     $this->assertTrue(!isset($loaded_node->menu), t('The $node->menu property was not modified during token replacement.'), 'Regression');
 }
Ejemplo n.º 10
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.');
 }
Ejemplo n.º 11
0
 /**
  * Test node migration from Drupal 6 to 8.
  */
 public function testNode()
 {
     $node = Node::load(1);
     $this->assertIdentical('1', $node->id(), 'Node 1 loaded.');
     $this->assertIdentical('und', $node->langcode->value);
     $this->assertIdentical('test', $node->body->value);
     $this->assertIdentical('test', $node->body->summary);
     $this->assertIdentical('filtered_html', $node->body->format);
     $this->assertIdentical('story', $node->getType(), 'Node has the correct bundle.');
     $this->assertIdentical('Test title', $node->getTitle(), 'Node has the correct title.');
     $this->assertIdentical('1388271197', $node->getCreatedTime(), 'Node has the correct created time.');
     $this->assertIdentical(FALSE, $node->isSticky());
     $this->assertIdentical('1', $node->getOwnerId());
     $this->assertIdentical('1420861423', $node->getRevisionCreationTime());
     /** @var \Drupal\node\NodeInterface $node_revision */
     $node_revision = \Drupal::entityManager()->getStorage('node')->loadRevision(1);
     $this->assertIdentical('Test title', $node_revision->getTitle());
     $this->assertIdentical('1', $node_revision->getRevisionAuthor()->id(), 'Node revision has the correct user');
     // This is empty on the first revision.
     $this->assertIdentical(NULL, $node_revision->revision_log->value);
     // Test that we can re-import using the EntityContentBase destination.
     $connection = Database::getConnection('default', 'migrate');
     $connection->update('node_revisions')->fields(array('title' => 'New node title', 'format' => 2))->condition('vid', 1)->execute();
     $connection->delete('content_field_test_two')->condition('delta', 1)->execute();
     $migration = Migration::load('d6_node__story');
     $this->executeMigration($migration);
     $node = Node::load(1);
     $this->assertIdentical('New node title', $node->getTitle());
     // Test a multi-column fields are correctly upgraded.
     $this->assertIdentical('test', $node->body->value);
     $this->assertIdentical('full_html', $node->body->format);
 }
Ejemplo n.º 12
0
 /**
  * Checks HTML double escaping of revision logs.
  */
 public function testNodeRevisionDoubleEscapeFix()
 {
     $this->drupalLogin($this->editor);
     $nodes = [];
     // Create the node.
     $node = $this->drupalCreateNode();
     $username = ['#theme' => 'username', '#account' => $this->editor];
     $editor = \Drupal::service('renderer')->renderPlain($username);
     // Get original node.
     $nodes[] = clone $node;
     // Create revision with a random title and body and update variables.
     $node->title = $this->randomMachineName();
     $node->body = ['value' => $this->randomMachineName(32), 'format' => filter_default_format()];
     $node->setNewRevision();
     $revision_log = 'Revision <em>message</em> with markup.';
     $node->revision_log->value = $revision_log;
     $node->save();
     // Make sure we get revision information.
     $node = Node::load($node->id());
     $nodes[] = clone $node;
     $this->drupalGet('node/' . $node->id() . '/revisions');
     // Assert the old revision message.
     $date = format_date($nodes[0]->revision_timestamp->value, 'short');
     $url = new Url('entity.node.revision', ['node' => $nodes[0]->id(), 'node_revision' => $nodes[0]->getRevisionId()]);
     $this->assertRaw(\Drupal::l($date, $url) . ' by ' . $editor);
     // Assert the current revision message.
     $date = format_date($nodes[1]->revision_timestamp->value, 'short');
     $this->assertRaw($nodes[1]->link($date) . ' by ' . $editor . '<p class="revision-log">' . $revision_log . '</p>');
 }
Ejemplo n.º 13
0
 /**
  * Create an overview of webform content.
  */
 public function contentOverview()
 {
     // @todo This needs to be removed and the view webform_webforms used instead.
     $query = db_select('webform', 'w');
     $query->join('node', 'n', 'w.nid = n.nid');
     $query->fields('n');
     $nodes = $query->execute()->fetchAllAssoc('nid');
     module_load_include('inc', 'webform', 'includes/webform.admin');
     $header = array(t('Title'), array('data' => t('View'), 'colspan' => '4'), array('data' => t('Operations'), 'colspan' => '3'));
     $rows = array();
     if (!empty($nodes)) {
         foreach ($nodes as $node) {
             $node = Node::load($node->nid);
             $rows[] = array(\Drupal::l($node->getTitle(), Url::fromRoute('entity.node.canonical', ['node' => $node->id()])), t('Submissions'), t('Analysis'), t('Table'), t('Download'), $node->access('update') ? \Drupal::l(t('Edit'), Url::fromRoute('entity.node.edit_form', ['node' => $node->id()])) : '', t('Components'), t('Clear'));
         }
     }
     if (empty($nodes)) {
         $webform_types = webform_node_types();
         if (empty($webform_types)) {
             $message = t('Webform is currently not enabled on any content types.') . ' ' . t('Visit the <a href="!url">Webform settings</a> page and enable Webform on at least one content type.', array('!url' => Url::fromRoute('webform.settings')->toString()));
         } else {
             $webform_type_list = webform_admin_type_list();
             $message = t('There are currently no webforms on your site. Create a !types piece of content.', array('!types' => $webform_type_list));
         }
         $rows[] = array(array('data' => $message, 'colspan' => 7));
     }
     $table = array('#type' => 'table', '#header' => $header, '#rows' => $rows);
     return $table;
 }
Ejemplo n.º 14
0
 /**
  * Tests the node summary length functionality.
  */
 public function testSummaryLength()
 {
     /** @var \Drupal\Core\Render\RendererInterface $renderer */
     $renderer = $this->container->get('renderer');
     // Create a node to view.
     $settings = array('body' => array(array('value' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam vitae arcu at leo cursus laoreet. Curabitur dui tortor, adipiscing malesuada tempor in, bibendum ac diam. Cras non tellus a libero pellentesque condimentum. What is a Drupalism? Suspendisse ac lacus libero. Ut non est vel nisl faucibus interdum nec sed leo. Pellentesque sem risus, vulputate eu semper eget, auctor in libero. Ut fermentum est vitae metus convallis scelerisque. Phasellus pellentesque rhoncus tellus, eu dignissim purus posuere id. Quisque eu fringilla ligula. Morbi ullamcorper, lorem et mattis egestas, tortor neque pretium velit, eget eleifend odio turpis eu purus. Donec vitae metus quis leo pretium tincidunt a pulvinar sem. Morbi adipiscing laoreet mauris vel placerat. Nullam elementum, nisl sit amet scelerisque malesuada, dolor nunc hendrerit quam, eu ultrices erat est in orci. Curabitur feugiat egestas nisl sed accumsan.')), 'promote' => 1);
     $node = $this->drupalCreateNode($settings);
     $this->assertTrue(Node::load($node->id()), 'Node created.');
     // Render the node as a teaser.
     $content = $this->drupalBuildEntityView($node, 'teaser');
     $this->assertTrue(strlen($content['body'][0]['#markup']) < 600, 'Teaser is less than 600 characters long.');
     $this->setRawContent($renderer->renderRoot($content));
     // The string 'What is a Drupalism?' is between the 200th and 600th
     // characters of the node body, so it should be included if the summary is
     // 600 characters long.
     $expected = 'What is a Drupalism?';
     $this->assertRaw($expected);
     // Change the teaser length for "Basic page" content type.
     $display = entity_get_display('node', $node->getType(), 'teaser');
     $display_options = $display->getComponent('body');
     $display_options['settings']['trim_length'] = 200;
     $display->setComponent('body', $display_options)->save();
     // Render the node as a teaser again and check that the summary is now only
     // 200 characters in length and so does not include 'What is a Drupalism?'.
     $content = $this->drupalBuildEntityView($node, 'teaser');
     $this->assertTrue(strlen($content['body'][0]['#markup']) < 200, 'Teaser is less than 200 characters long.');
     $this->setRawContent($renderer->renderRoot($content));
     $this->assertText($node->label());
     $this->assertNoRaw($expected);
 }
 /**
  * Tests that the autocomplete input element appears and the creation of a new
  * entity.
  */
 public function testAutoCreate()
 {
     $this->drupalGet('node/add/' . $this->referencingType);
     $this->assertFieldByXPath('//input[@id="edit-test-field-0-target-id" and contains(@class, "form-autocomplete")]', NULL, 'The autocomplete input element appears.');
     $new_title = $this->randomMachineName();
     // Assert referenced node does not exist.
     $base_query = \Drupal::entityQuery('node');
     $base_query->condition('type', $this->referencedType)->condition('title', $new_title);
     $query = clone $base_query;
     $result = $query->execute();
     $this->assertFalse($result, 'Referenced node does not exist yet.');
     $edit = array('title[0][value]' => $this->randomMachineName(), 'test_field[0][target_id]' => $new_title);
     $this->drupalPostForm("node/add/{$this->referencingType}", $edit, 'Save');
     // Assert referenced node was created.
     $query = clone $base_query;
     $result = $query->execute();
     $this->assertTrue($result, 'Referenced node was created.');
     $referenced_nid = key($result);
     $referenced_node = Node::load($referenced_nid);
     // Assert the referenced node is associated with referencing node.
     $result = \Drupal::entityQuery('node')->condition('type', $this->referencingType)->execute();
     $referencing_nid = key($result);
     $referencing_node = Node::load($referencing_nid);
     $this->assertEqual($referenced_nid, $referencing_node->test_field->target_id, 'Newly created node is referenced from the referencing node.');
     // Now try to view the node and check that the referenced node is shown.
     $this->drupalGet('node/' . $referencing_node->id());
     $this->assertText($referencing_node->label(), 'Referencing node label found.');
     $this->assertText($referenced_node->label(), 'Referenced node label found.');
 }
  /**
   * Test Pathauto cleanup in File (Field) Paths.
   */
  public function testPathauto() {
    // Create a File field.
    $field_name = Unicode::strtolower($this->randomMachineName());

    $third_party_settings['filefield_paths']['file_path']['value'] = 'node/[node:title]';
    $third_party_settings['filefield_paths']['file_path']['options']['pathauto'] = TRUE;
    $third_party_settings['filefield_paths']['file_name']['value'] = '[node:title].[file:ffp-extension-original]';
    $third_party_settings['filefield_paths']['file_name']['options']['pathauto'] = TRUE;

    $this->createFileField($field_name, 'node', $this->contentType, [], [], $third_party_settings);

    // Create a node with a test file.
    /** @var \Drupal\file\Entity\File $test_file */
    $test_file = $this->getTestFile('text');
    $edit['title[0][value]'] = $this->randomString() . ' ' . $this->randomString();

    $edit['files[' . $field_name . '_0]'] = \Drupal::service('file_system')
      ->realpath($test_file->getFileUri());
    $this->drupalPostForm("node/add/{$this->contentType}", $edit, $this->t('Save and publish'));

    // Ensure that file path/name have been processed correctly by Pathauto.
    /** @var \Drupal\node\Entity\Node $node */
    $node = Node::load(1);

    $parts = explode('/', $node->getTitle());
    foreach ($parts as &$part) {
      $part = \Drupal::service('pathauto.alias_cleaner')->cleanString($part);
    }
    $title = implode('/', $parts);

    $this->assertEqual($node->{$field_name}[0]->entity->getFileUri(), "public://node/{$title}/{$title}.txt", $this->t('File path/name has been processed correctly by Pathauto'));
  }
Ejemplo n.º 17
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     ConfigurableLanguage::createFromLangcode('it')->save();
     /** @var \Drupal\content_translation\ContentTranslationManagerInterface $manager */
     $manager = \Drupal::service('content_translation.manager');
     $manager->setEnabled('node', 'article', TRUE);
     // Create and log in user.
     $web_user = $this->drupalCreateUser(array('view page revisions', 'revert page revisions', 'delete page revisions', 'edit any page content', 'delete any page content', 'translate any entity'));
     $this->drupalLogin($web_user);
     // Create initial node.
     $node = $this->drupalCreateNode();
     $settings = get_object_vars($node);
     $settings['revision'] = 1;
     $settings['isDefaultRevision'] = TRUE;
     $nodes = array();
     $logs = array();
     // Get original node.
     $nodes[] = clone $node;
     // Create three revisions.
     $revision_count = 3;
     for ($i = 0; $i < $revision_count; $i++) {
         $logs[] = $node->revision_log = $this->randomMachineName(32);
         // Create revision with a random title and body and update variables.
         $node->title = $this->randomMachineName();
         $node->body = array('value' => $this->randomMachineName(32), 'format' => filter_default_format());
         $node->setNewRevision();
         $node->save();
         $node = Node::load($node->id());
         // Make sure we get revision information.
         $nodes[] = clone $node;
     }
     $this->nodes = $nodes;
     $this->revisionLogs = $logs;
 }
 /**
  * Tests exportContentWithReferences().
  */
 public function testExportWithReferences()
 {
     \Drupal::service('module_installer')->install(['node', 'default_content']);
     \Drupal::service('router.builder')->rebuild();
     $this->defaultContentManager = \Drupal::service('default_content.manager');
     $user = User::create(['name' => 'my username']);
     $user->save();
     // Reload the user to get the proper casted values from the DB.
     $user = User::load($user->id());
     $node_type = NodeType::create(['type' => 'test']);
     $node_type->save();
     $node = Node::create(['type' => $node_type->id(), 'title' => 'test node', 'uid' => $user->id()]);
     $node->save();
     // Reload the node to get the proper casted values from the DB.
     $node = Node::load($node->id());
     /** @var \Symfony\Component\Serializer\Serializer $serializer */
     $serializer = \Drupal::service('serializer');
     \Drupal::service('rest.link_manager')->setLinkDomain(DefaultContentManager::LINK_DOMAIN);
     $expected_node = $serializer->serialize($node, 'hal_json', ['json_encode_options' => JSON_PRETTY_PRINT]);
     $expected_user = $serializer->serialize($user, 'hal_json', ['json_encode_options' => JSON_PRETTY_PRINT]);
     $exported_by_entity_type = $this->defaultContentManager->exportContentWithReferences('node', $node->id());
     // Ensure that the node type is not tryed to be exported.
     $this->assertEqual(array_keys($exported_by_entity_type), ['node', 'user']);
     // Ensure the right UUIDs are exported.
     $this->assertEqual([$node->uuid()], array_keys($exported_by_entity_type['node']));
     $this->assertEqual([$user->uuid()], array_keys($exported_by_entity_type['user']));
     // Compare the actual serialized data.
     $this->assertEqual(reset($exported_by_entity_type['node']), $expected_node);
     $this->assertEqual(reset($exported_by_entity_type['user']), $expected_user);
 }
  /**
   * Test Transliteration cleanup in File (Field) Paths.
   */
  public function testTransliteration() {
    // Create a File field.
    $field_name = Unicode::strtolower($this->randomMachineName());

    $third_party_settings['filefield_paths']['file_path']['value'] = 'node/[node:title]';
    $third_party_settings['filefield_paths']['file_path']['options']['transliterate'] = TRUE;
    $third_party_settings['filefield_paths']['file_name']['value'] = '[node:title].[file:ffp-extension-original]';
    $third_party_settings['filefield_paths']['file_name']['options']['transliterate'] = TRUE;

    $this->createFileField($field_name, 'node', $this->contentType, [], [], $third_party_settings);

    // Create a node with a test file.
    /** @var \Drupal\file\Entity\File $test_file */
    $test_file = $this->getTestFile('text');
    $edit['title[0][value]'] = 'тест';

    $edit['files[' . $field_name . '_0]'] = \Drupal::service('file_system')
      ->realpath($test_file->getFileUri());
    $this->drupalPostForm("node/add/{$this->contentType}", $edit, $this->t('Save and publish'));

    // Get created Node ID.
    $matches = [];
    preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
    $nid = $matches[1];

    // Ensure that file path/name have been processed correctly by
    // Transliteration.
    $node = Node::load($nid);
    $this->assertEqual($node->{$field_name}[0]->entity->getFileUri(), "public://node/test/test.txt", $this->t('File path/name has been processed correctly by Transliteration'));
  }
 public function indexDoc()
 {
     $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;
     $batch_size = isset($_GET['batch_size']) ? intval($_GET['batch_size']) : 3;
     $resp = NULL;
     $num_written = 0;
     $query_limit = $batch_size;
     $results = [];
     $range["start"] = $offset;
     $range["end"] = $query_limit;
     $results = searchblox_get_nodes_from_db($range);
     $total_posts = count($results);
     if ($results) {
         try {
             foreach ($results as $result) {
                 //print_r($result); die;
                 $node = Node::load($result->nid);
                 $error_count = searchblox_do_index($node, $result->nid);
                 // Indexes the node returns error if any
                 // Connection refused by server
                 if ($error_count == -111) {
                     throw new \Exception("SearchBlox was unable to connect to the server provided during configuration.");
                 }
                 global $statuscode;
                 // Invalid Document Location
                 if ($statuscode == 502) {
                     throw new \Exception("SearchBlox could not find the requested documents on this location.");
                 }
                 if ($error_count == 0) {
                     $num_written++;
                 } else {
                     throw new \Exception("Some Documents could not be indexed. Please Try again !");
                     return;
                 }
                 $total_posts++;
             }
         } catch (\Exception $e) {
             $error = array('error' => $e->getMessage());
         }
     } else {
         $num_written = 0;
     }
     if (!isset($error) && $error_count == 0) {
         //If indexing successful , then set variable
         if (!\Drupal::state()->get('searchblox_indexed')) {
             \Drupal::state()->set('searchblox_indexed', 1);
             // TO KNOW THAT INDEXING AHS BEEN DONE
         }
     }
     header('Content-Type: application/json');
     if (!isset($error)) {
         $response = array('num_written' => $num_written, 'total' => $total_posts);
         print json_encode($response);
     } else {
         print json_encode($error);
     }
     die;
     // end ajax response , no output now except one hooked with register_shutdown
 }
 /**
  * Test node migration from Drupal 7 to 8.
  */
 public function testMigration()
 {
     $node = Node::load(2);
     $this->assertTrue($node instanceof NodeInterface);
     $this->assertEqual(9, $node->field_tags[0]->target_id);
     $this->assertEqual(14, $node->field_tags[1]->target_id);
     $this->assertEqual(17, $node->field_tags[2]->target_id);
 }
Ejemplo n.º 22
0
 public static function getPretEntity(Node $benzinarie, Term $tip_carburant)
 {
     $preturi_ids = \Drupal::entityQuery('node')->condition('type', 'pret')->condition('field_benzinarie.target_id', $benzinarie->id())->condition('field_tip_carburant.target_id', $tip_carburant->id())->condition('status', 1)->sort('created', 'DESC')->execute();
     if (count($preturi_ids)) {
         $pret_id = array_shift($preturi_ids);
         return Node::load($pret_id);
     }
 }
Ejemplo n.º 23
0
 /**
  * Tests the title on a newly created node.
  *
  * @param array $data
  * @return \Drupal\node\Entity\Node
  */
 protected function assertNodeTitleMatch($data)
 {
     /** @var \Drupal\node\Entity\Node $node */
     // Load the newly created node.
     $node = Node::load(1);
     // Test that the title is the same as what we posted.
     $this->assertEqual($node->title->value, $data['title'][0]['value']);
     return $node;
 }
Ejemplo n.º 24
0
 /**
  * {@inheritdoc}
  */
 public function addItem($nid, $qty = 1, $data = NULL, $msg = TRUE)
 {
     $node = Node::load($nid);
     if (is_null($data) || !isset($data['module'])) {
         $data['module'] = 'uc_product';
     }
     // Invoke hook_uc_add_to_cart() to give other modules a chance to affect the process.
     $result = \Drupal::moduleHandler()->invokeAll('uc_add_to_cart', array($nid, $qty, $data));
     if (is_array($result) && !empty($result)) {
         foreach ($result as $row) {
             if ($row['success'] === FALSE) {
                 // Module implementing the hook does NOT want this item added!
                 if (isset($row['message']) && !empty($row['message'])) {
                     $message = $row['message'];
                 } else {
                     $message = t('Sorry, that item is not available for purchase at this time.');
                 }
                 if (isset($row['silent']) && $row['silent'] === TRUE) {
                     return $this->getAddItemRedirect();
                 } else {
                     drupal_set_message($message, 'error');
                 }
                 // Stay on this page.
                 $query = \Drupal::request()->query;
                 return Url::fromRoute('<current>', [], ['query' => UrlHelper::filterQueryParameters($query->all())]);
             }
         }
     }
     // Now we can go ahead and add the item because either:
     //   1) No modules implemented hook_uc_add_to_cart(), or
     //   2) All modules implementing that hook want this item added.
     $result = \Drupal::entityQuery('uc_cart_item')->condition('cart_id', $this->id)->condition('nid', $nid)->condition('data', serialize($data))->execute();
     if (empty($result)) {
         // If the item isn't in the cart yet, add it.
         $item_entity = CartItem::create(array('cart_id' => $this->id, 'nid' => $nid, 'qty' => $qty, 'data' => $data));
         $item_entity->save();
         if ($msg) {
             drupal_set_message(t('<strong>@product-title</strong> added to <a href=":url">your shopping cart</a>.', ['@product-title' => $node->label(), ':url' => Url::fromRoute('uc_cart.cart')->toString()]));
         }
     } else {
         // If it is in the cart, update the item instead.
         if ($msg) {
             drupal_set_message(t('Your item(s) have been updated.'));
         }
         $item_entity = CartItem::load(current(array_keys($result)));
         $qty += $item_entity->qty->value;
         \Drupal::moduleHandler()->invoke($data['module'], 'uc_update_cart_item', array($nid, $data, min($qty, 999999), $this->id));
     }
     // Invalidate the cache.
     Cache::invalidateTags(['uc_cart:' . $this->id]);
     // Invalidate the cart order.
     // @todo Remove this and cache the order object with a tag instead?
     $session = \Drupal::service('session');
     $session->set('uc_cart_order_rebuild', TRUE);
     return $this->getAddItemRedirect();
 }
 /**
  * Test CCK migration from Drupal 6 to 8.
  */
 public function testCckFields()
 {
     $node = Node::load(1);
     $this->assertEqual($node->field_test->value, 'This is a shared text field', "Shared field storage field is correct.");
     $this->assertEqual($node->field_test->format, 1, "Shared field storage field with multiple columns is correct.");
     $this->assertEqual($node->field_test_two->value, 10, 'Multi field storage field is correct');
     $this->assertEqual($node->field_test_two[1]->value, 20, 'Multi field second value is correct.');
     $this->assertEqual($node->field_test_three->value, '42.42', 'Single field second value is correct.');
     $this->assertEqual($node->field_test_integer_selectlist[0]->value, '3412', 'Integer select list value is correct');
 }
 /**
  * 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'));
     $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::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->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.
     $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(String::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(String::format($constraint->message, array('%type' => 'file', '%id' => $node_file->id())));
 }
 /**
  * Lang.
  * Set a consistent language of those node where language is set to UND
  *
  * @return string
  *   Return a silly string.
  */
 public function lang($lang)
 {
     $query = \Drupal::entityQuery('node')->condition('langcode', 'und');
     $nids = $query->execute();
     foreach ($nids as $nid) {
         $node = Node::load($nid);
         $node->langcode->setValue($lang);
         $node->save();
     }
     return ['#type' => 'markup', '#markup' => $this->t('Implement method: lang')];
 }
Ejemplo n.º 28
0
 /**
  * Provides the replacement html to be rendered in place of the embed code.
  *
  * Does not handle nested embeds.
  *
  * @param array $matches
  *   Array of matches by preg_replace_callback
  *
  * @return string
  *   The rendered HTML replacing the embed code
  */
 public function renderChart($matches)
 {
     /* @var $node \Drupal\Node\NodeInterface */
     $node = Node::load($matches[1]);
     if ($node == FALSE || !$node->isPublished() || !$node->access('view')) {
         return "[[chart-nid:{$matches[1]},chart-view-mode:{$matches[2]}]]";
     } else {
         $view = node_view($node, $matches[2]);
         $render = drupal_render($view);
         return $render;
     }
 }
Ejemplo n.º 29
0
 /**
  * #lazy_builder callback; builds a node's links.
  *
  * @param string $node_entity_id
  *   The node entity ID.
  * @param string $view_mode
  *   The view mode in which the node entity is being viewed.
  * @param string $langcode
  *   The language in which the node entity is being viewed.
  * @param bool $is_in_preview
  *   Whether the node is currently being previewed.
  *
  * @return array
  *   A renderable array representing the node links.
  */
 public static function renderLinks($node_entity_id, $view_mode, $langcode, $is_in_preview)
 {
     $links = array('#theme' => 'links__node', '#pre_render' => array('drupal_pre_render_links'), '#attributes' => array('class' => array('links', 'inline')));
     if (!$is_in_preview) {
         $entity = Node::load($node_entity_id)->getTranslation($langcode);
         $links['node'] = static::buildLinks($entity, $view_mode);
         // Allow other modules to alter the node links.
         $hook_context = array('view_mode' => $view_mode, 'langcode' => $langcode);
         \Drupal::moduleHandler()->alter('node_links', $links, $entity, $hook_context);
     }
     return $links;
 }
Ejemplo n.º 30
0
 /**
  * Builds the response object to be returned. This will be a node.
  * @param $request
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function buildResponseObject($request)
 {
     $alias = $request->query->get('path');
     $path = $this->aliasManager->getPathByAlias($alias);
     // If $path does not contain /node/ it's a result of no alias existing
     // for any nodes in Drupal.
     if (!strstr("/node/", $path)) {
         throw new HttpException(404);
     }
     $parts = explode("/", $path);
     $this->entity = Node::load($parts[2]);
     return true;
 }