<?php

/**
 * @file
 * Testing that users can not input bad URLs or labels.
 */

/**
 * Testing that users can not input bad URLs or labels.
 */
class LinkFieldCrudTest extends LinkBaseTestClass {

  /**
   * Link supposed to be good.
   */
  const LINK_INPUT_TYPE_GOOD = 0;

  /**
   * Link supposed to have a bad title.
   */
  const LINK_INPUT_TYPE_BAD_TITLE = 1;

  /**
   * Link supposed to have a bad URL.
   */
  const LINK_INPUT_TYPE_BAD_URL = 2;

  /**
   * Get Info.
   */
  public static function getInfo() {
    return array(
      'name' => 'Link CRUD - browser test',
      'description' => 'Tests the field CRUD (create, read, update, delete) API 2.',
      'group' => 'Link',
    );
  }

  /**
   * {@inheritdoc}
   */
  public function setUp(array $modules = array()) {
    $modules[] = 'field_ui';
    $modules[] = 'link';
    parent::setUp($modules);
  }

  /**
   * Creates a link field for the "page" type and creates a page with a link.
   */
  public function testLinkCreate() {
    // libxml_use_internal_errors(true);
    $this->web_user = $this->drupalCreateUser(array(
      'administer content types',
      'administer fields',
      'administer nodes',
      'administer filters',
      'access content',
      'create page content',
      'access administration pages',
    ));
    $this->drupalLogin($this->web_user);

    // Create field.
    $name = strtolower($this->randomName());
    $edit = array(
      'fields[_add_new_field][label]' => $name,
      'fields[_add_new_field][field_name]' => $name,
      'fields[_add_new_field][type]' => 'link_field',
      'fields[_add_new_field][widget_type]' => 'link_field',
    );
    $this->drupalPost('admin/structure/types/manage/page/fields', $edit, t('Save'));
    $this->drupalPost(NULL, array(), t('Save field settings'));
    $this->drupalPost(NULL, array(), t('Save settings'));

    // Is field created?
    $this->assertRaw(t('Saved %label configuration', array('%label' => $name)), 'Field added');
    node_types_rebuild();
    menu_rebuild();

    $permission = 'create page content';
    $this->checkPermissions(array($permission), TRUE);

    // Create page form
    // $this->drupalGet('node/add');.
    $this->drupalGet('node/add/page');
    $field_name = 'field_' . $name;
    $this->assertField('edit-field-' . $name . '-und-0-title', 'Title found');
    $this->assertField('edit-field-' . $name . '-und-0-url', 'URL found');

    $input_test_cases = array(
      array(
        'href' => 'http://example.com/' . $this->randomName(),
        'label' => $this->randomName(),
        'msg' => 'Link found',
        'type' => self::LINK_INPUT_TYPE_GOOD,
      ),
      array(
        'href' => 'http://example.com/' . $this->randomName(),
        'label' => $this->randomName() . '<script>alert("hi");</script>',
        'msg' => 'JS in label',
        'type' => self::LINK_INPUT_TYPE_BAD_TITLE,
      ),
      array(
        'href' => 'http://example.com/' . $this->randomName(),
        'label' => $this->randomName() . '<script src="http://devil.site.com"></script>',
        'msg' => 'Remote JS in label',
        'type' => self::LINK_INPUT_TYPE_BAD_TITLE,
      ),
      array(
        'href' => 'http://example.com/' . $this->randomName(),
        'label' => $this->randomName() . '" onmouseover="alert(\'hi\')',
        'msg' => 'JS in label',
        'type' => self::LINK_INPUT_TYPE_BAD_TITLE,
      ),
      array(
        'href' => 'http://example.com/' . $this->randomName(),
        'label' => $this->randomName() . '\' onmouseover="alert(\'hi\')',
        'msg' => 'Escaped JS in label',
        'type' => self::LINK_INPUT_TYPE_BAD_TITLE,
      ),
      array(
        'href' => 'javascript:alert("http://example.com/' . $this->randomName() . '")',
        'label' => $this->randomName(),
        'msg' => 'JS in URL',
        'type' => self::LINK_INPUT_TYPE_BAD_URL,
      ),
      array(
        'href' => 'http://example.com?foo=bar&fruit=mango',
        'label' => $this->randomName(),
        'msg' => 'URL with querystring',
        'type' => self::LINK_INPUT_TYPE_GOOD,
      ),
      array(
        'href' => 'http://ecs-es.kelkoo.es/ctl/go/sitesearchGo?.ts=1338833010331&.sig=qP9GXeEFH6syBzwmzYkxmsvp1EI-',
        'label' => 'http://ecs-es.kelkoo.es/ctl/go/sitesearchGo?.ts=1338833010331&.sig=qP9GXeEFH6syBzwmzYkxmsvp1EI-',
        'msg' => 'URL with . in querystring',
        'type' => self::LINK_INPUT_TYPE_GOOD,
      ),
    );
    $test_case = array(
      'href' => 'www.example.com/' . $this->randomName(),
      'label' => $this->randomName(),
      'msg' => 'Link found',
      'type' => self::LINK_INPUT_TYPE_GOOD,
    );
    $test_case['expected_href'] = 'http://' . $test_case['href'];
    $input_test_cases[] = $test_case;

    foreach ($input_test_cases as $input) {
      $this->drupalLogin($this->web_user);
      $this->drupalGet('node/add/page');

      $edit = array(
        'title' => $input['label'],
        $field_name . '[und][0][title]' => $input['label'],
        $field_name . '[und][0][url]' => $input['href'],
      );
      $this->drupalPost(NULL, $edit, t('Save'));
      if ($input['type'] == self::LINK_INPUT_TYPE_BAD_URL) {
        $this->assertRaw(t('The value %value provided for %field is not a valid URL.', array(
          '%field' => $name,
          '%value' => trim($input['href']),
        )), 'Not a valid URL: ' . $input['href']);
        continue;
      }
      else {
        $this->assertRaw(' ' . t('has been created.',
            array('@type' => 'Basic Page', '%title' => $edit['title'])),
          'Page created: ' . $input['href']);
      }
      $url = $this->getUrl();

      // Change to Anonymous user.
      $this->drupalLogout();

      $this->drupalGet($url);
      // debug($this);
      // If simpletest starts using something to override the error system, this
      // will flag us and let us know it's broken.
      $this->assertFalse(libxml_use_internal_errors(TRUE));
      $expected_href = $input['href'];
      if (isset($input['expected_href'])) {
        $expected_href = $input['expected_href'];
      }
      $elements = $this->xpath('//a[@href="' . $expected_href . '" and text()="' . $input['label'] . '"]');
      libxml_use_internal_errors(FALSE);
      $this->assertIdentical(isset($elements[0]), $input['type'] == self::LINK_INPUT_TYPE_GOOD, $input['msg']);
    }
    // libxml_use_internal_errors(FALSE);
  }

  /**
   * Static Link Create.
   *
   * Testing that if you use <strong> in a static title for your link, that the
   * title actually displays <strong>.
   */
  public function testStaticLinkCreate() {
    $this->web_user = $this->drupalCreateUser(array(
      'administer content types',
      'administer fields',
      'access content',
      'create page content',
    ));

    $this->drupalLogin($this->web_user);

    // Create field.
    $name = strtolower($this->randomName());
    $field_name = 'field_' . $name;
    $edit = array(
      'fields[_add_new_field][label]' => $name,
      'fields[_add_new_field][field_name]' => $name,
      'fields[_add_new_field][type]' => 'link_field',
      'fields[_add_new_field][widget_type]' => 'link_field',
    );
    $this->drupalPost('admin/structure/types/manage/page/fields', $edit, t('Save'));
    $this->drupalPost(NULL, array(), t('Save field settings'));
    $this->drupalPost(NULL, array(
      'instance[settings][title]' => 'value',
      'instance[settings][title_value]' => '<strong>' . $name . '</strong>',
    ), t('Save settings'));

    // Is field created?
    $this->assertRaw(t('Saved %label configuration', array('%label' => $name)), 'Field added');

    // Create page form.
    $this->drupalGet('node/add/page');
    $this->assertField($field_name . '[und][0][url]', 'URL found');

    $input = array(
      'href' => 'http://example.com/' . $this->randomName(),
    );

    $edit = array(
      'title' => $name,
      $field_name . '[und][0][url]' => $input['href'],
    );
    $this->drupalPost(NULL, $edit, t('Save'));

    $url = $this->getUrl();

    // Change to anonymous user.
    $this->drupalLogout();
    $this->drupalGet($url);

    $this->assertRaw(l('<strong>' . $name . '</strong>', $input['href'], array('html' => TRUE)));
  }

  /**
   * CRUD Title Only Title No Link.
   *
   * Testing that if you have the title but no url, the title is not sanitized
   * twice.
   */
  public function testCrudTitleOnlyTitleNoLink() {
    $this->web_user = $this->drupalCreateUser(array(
      'administer content types',
      'administer fields',
      'access content',
      'create page content',
    ));
    $this->drupalLogin($this->web_user);

    // Create field.
    $name = strtolower($this->randomName());
    $field_name = 'field_' . $name;
    $edit = array(
      'fields[_add_new_field][label]' => $name,
      'fields[_add_new_field][field_name]' => $name,
      'fields[_add_new_field][type]' => 'link_field',
      'fields[_add_new_field][widget_type]' => 'link_field',
    );
    $this->drupalPost('admin/structure/types/manage/page/fields', $edit, t('Save'));
    $this->drupalPost(NULL, array(), t('Save field settings'));
    $this->drupalPost(NULL, array(
      'instance[settings][url]' => 1,
    ), t('Save settings'));

    // Is field created?
    $this->assertRaw(t('Saved %label configuration', array('%label' => $name)), 'Field added');

    // Create page form.
    $this->drupalGet('node/add/page');
    $this->assertField($field_name . '[und][0][url]', 'URL found');

    $input = array(
      'title' => 'This & That',
      'href' => '',
    );

    $edit = array(
      'title' => $name,
      $field_name . '[und][0][title]' => $input['title'],
      $field_name . '[und][0][url]' => $input['href'],
    );
    $this->drupalPost(NULL, $edit, t('Save'));

    $url = $this->getUrl();

    // Change to anonymous user.
    $this->drupalLogout();
    $this->drupalGet($url);

    $this->assertRaw('This &amp; That');
  }

  /**
   * CRUD Create Field Defaults.
   *
   * If we're creating a new field and just hit 'save' on the default options,
   * we want to make sure they are set to the expected results.
   */
  public function testCrudCreateFieldDefaults() {
    $this->web_user = $this->drupalCreateUser(array(
      'administer content types',
      'administer fields',
      'access content',
      'create page content',
    ));

    $this->drupalLogin($this->web_user);

    // Create field.
    $name = strtolower($this->randomName());
    $edit = array(
      'fields[_add_new_field][label]' => $name,
      'fields[_add_new_field][field_name]' => $name,
      'fields[_add_new_field][type]' => 'link_field',
      'fields[_add_new_field][widget_type]' => 'link_field',
    );
    $this->drupalPost('admin/structure/types/manage/page/fields', $edit, t('Save'));
    $this->drupalPost(NULL, array(), t('Save field settings'));
    $this->drupalPost(NULL, array(), t('Save settings'));

    // Is field created?
    $this->assertRaw(t('Saved %label configuration', array('%label' => $name)), 'Field added');
    node_types_rebuild();
    menu_rebuild();

    _field_info_collate_fields(TRUE);
    $instances = field_info_instances('node', 'page');

    $instance = $instances['field_' . $name];
    $this->assertFalse($instance['required'], 'Make sure field is not required.');
    $this->assertEqual($instance['settings']['title'], 'optional', 'Title should be optional by default.');
    $this->assertTrue($instance['settings']['validate_url'], 'Make sure validation is on.');
    $this->assertTrue($instance['settings']['enable_tokens'], 'Enable Tokens should be on by default.');
    $this->assertEqual($instance['settings']['display']['url_cutoff'], 80, 'Url cutoff should be at 80 characters.');
    $this->assertEqual($instance['settings']['attributes']['target'], 'default', 'Target should be "default"');
    $this->assertFalse($instance['settings']['attributes']['rel'], 'Rel should be blank by default.');
    $this->assertFalse($instance['settings']['attributes']['class'], 'By default, no class should be set.');
    $this->assertFalse($instance['settings']['title_value'], 'By default, no title should be set.');
  }

  /**
   * CRUD Create Field With Class.
   *
   * If we're creating a new field and just hit 'save' on the default options,
   * we want to make sure they are set to the expected results.
   */
  public function testCrudCreateFieldWithClass() {
    $this->web_user = $this->drupalCreateUser(array(
      'administer content types',
      'administer fields',
      'access content',
      'create page content',
    ));
    $this->drupalLogin($this->web_user);

    // Create field.
    $name = strtolower($this->randomName());
    $edit = array(
      'fields[_add_new_field][label]' => $name,
      'fields[_add_new_field][field_name]' => $name,
      'fields[_add_new_field][type]' => 'link_field',
      'fields[_add_new_field][widget_type]' => 'link_field',
    );
    $this->drupalPost('admin/structure/types/manage/page/fields', $edit, t('Save'));

    $this->drupalPost(NULL, array(), t('Save field settings'));
    $link_class_name = 'basic-link-' . strtolower($this->randomName());
    $edit = array(
      'instance[settings][attributes][class]' => $link_class_name,
    );
    $this->drupalPost(NULL, $edit, t('Save settings'));

    // Is field created?
    $this->assertRaw(t('Saved %label configuration', array('%label' => $name)), 'Field added');
    node_types_rebuild();
    menu_rebuild();

    _field_info_collate_fields(TRUE);
    $instances = field_info_instances('node', 'page');

    $instance = $instances['field_' . $name];
    $this->assertFalse($instance['required'], 'Make sure field is not required.');
    $this->assertEqual($instance['settings']['title'], 'optional', 'Title should be optional by default.');
    $this->assertTrue($instance['settings']['validate_url'], 'Make sure validation is on.');
    $this->assertTrue($instance['settings']['enable_tokens'], 'Enable Tokens should be on by default.');
    $this->assertEqual($instance['settings']['display']['url_cutoff'], 80, 'Url cutoff should be at 80 characters.');
    $this->assertEqual($instance['settings']['attributes']['target'], 'default', 'Target should be "default"');
    $this->assertFalse($instance['settings']['attributes']['rel'], 'Rel should be blank by default.');
    $this->assertEqual($instance['settings']['attributes']['class'], $link_class_name, 'One class should be set.');
    $this->assertFalse($instance['settings']['title_value'], 'By default, no title should be set.');

    // Now, let's create a node with this field and make sure the link shows up:
    // create page form.
    $field_name = 'field_' . $name;
    $this->drupalGet('node/add/page');
    $this->assertField($field_name . '[und][0][url]', 'URL found');

    $input = array(
      'title' => 'This & That',
      'href' => 'http://www.example.com/',
    );

    $edit = array(
      'title' => $field_name,
      $field_name . '[und][0][title]' => $input['title'],
      $field_name . '[und][0][url]' => $input['href'],
    );
    $this->drupalPost(NULL, $edit, t('Save'));

    $url = $this->getUrl();

    // Change to anonymous user.
    $this->drupalLogout();
    $this->drupalGet($url);

    $this->assertRaw('This &amp; That');
    $this->assertPattern('|class\s?=\s?"' . $link_class_name . '"|', "Class $link_class_name exists on page.");
  }

  /**
   * CRUD Create Field With Two Classes.
   *
   * If we're creating a new field and just hit 'save' on the default options,
   * we want to make sure they are set to the expected results.
   */
  public function testCrudCreateFieldWithTwoClasses() {
    $this->web_user = $this->drupalCreateUser(array(
      'administer content types',
      'administer fields',
      'access content',
      'create page content',
    ));
    $this->drupalLogin($this->web_user);

    // Create field.
    $name = strtolower($this->randomName());
    $edit = array(
      'fields[_add_new_field][label]' => $name,
      'fields[_add_new_field][field_name]' => $name,
      'fields[_add_new_field][type]' => 'link_field',
      'fields[_add_new_field][widget_type]' => 'link_field',
    );
    $this->drupalPost('admin/structure/types/manage/page/fields', $edit, t('Save'));

    $this->drupalPost(NULL, array(), t('Save field settings'));
    $link_class_name = 'basic-link ' . strtoupper($this->randomName());
    $edit = array(
      'instance[settings][attributes][class]' => $link_class_name,
    );
    $this->drupalPost(NULL, $edit, t('Save settings'));

    // Is field created?
    $this->assertRaw(t('Saved %label configuration', array('%label' => $name)), 'Field added');
    node_types_rebuild();
    menu_rebuild();

    _field_info_collate_fields(TRUE);
    $instances = field_info_instances('node', 'page');

    $instance = $instances['field_' . $name];
    $this->assertFalse($instance['required'], 'Make sure field is not required.');
    $this->assertEqual($instance['settings']['title'], 'optional', 'Title should be optional by default.');
    $this->assertTrue($instance['settings']['validate_url'], 'Make sure validation is on.');
    $this->assertTrue($instance['settings']['enable_tokens'], 'Enable Tokens should be on by default.');
    $this->assertEqual($instance['settings']['display']['url_cutoff'], 80, 'Url cutoff should be at 80 characters.');
    $this->assertEqual($instance['settings']['attributes']['target'], 'default', 'Target should be "default"');
    $this->assertFalse($instance['settings']['attributes']['rel'], 'Rel should be blank by default.');
    $this->assertEqual($instance['settings']['attributes']['class'], $link_class_name, 'Two classes should be set.');
    $this->assertFalse($instance['settings']['title_value'], 'By default, no title should be set.');

    // Now, let's create a node with this field and make sure the link shows up:
    // create page form.
    $field_name = 'field_' . $name;
    $this->drupalGet('node/add/page');
    $this->assertField($field_name . '[und][0][url]', 'URL found');

    $input = array(
      'title' => 'This & That',
      'href' => 'http://www.example.com/',
    );

    $edit = array(
      'title' => $field_name,
      $field_name . '[und][0][title]' => $input['title'],
      $field_name . '[und][0][url]' => $input['href'],
    );
    $this->drupalPost(NULL, $edit, t('Save'));

    $url = $this->getUrl();

    // Change to anonymous user.
    $this->drupalLogout();
    $this->drupalGet($url);

    $this->assertRaw('This &amp; That');
    $this->assertPattern('|class\s?=\s?"' . $link_class_name . '"|', "Classes $link_class_name exist on page.");
  }

  /**
   * Tests that link titles properly preserve the query params.
   */
  public function testLinkTitlePreservesQueryParams() {
    // Create field.
    $field_name = $this->createLinkField();

    // Create page form.
    $this->drupalGet('node/add/page');
    $this->assertField($field_name . '[und][0][title]', 'Title found');
    $this->assertField($field_name . '[und][0][url]', 'URL found');

    $link_title_tests = array(
      array(
        'href' => 'http://example.com/' . $this->randomName(),
      ),
      array(
        'href' => 'http://example.com/' . $this->randomName() . '?property=value',
      ),
      array(
        'href' => 'http://example.com/' . $this->randomName() . '?property=value&mango=thebest',
      ),
      array(
        'href' => 'http://example.com/' . $this->randomName() . '#position',
      ),
      array(
        'href' => 'http://example.com/' . $this->randomName() . '#lower?property=value2',
      ),
      array(
        'href' => 'http://example.com/' . $this->randomName() . '?property=value2#lower',
      ),
    );

    foreach ($link_title_tests as &$input) {
      $this->drupalGet('node/add/page');
      $this->assertResponse(200);

      // Intentionally set empty title, to force using the url as the title.
      $edit = array(
        'title' => 'Some node title',
        $field_name . '[und][0][title]' => '',
        $field_name . '[und][0][url]' => $input['href'],
      );
      $this->drupalPost(NULL, $edit, t('Save'));
      // Confirm the node saved correctly.
      $this->assertResponse(200);
      $this->assertText($edit['title']);
      $input['url'] = $this->getUrl();
    }

    // Change to anonymous user.
    $this->drupalLogout();

    // Loop over the nodes, confirm each URL is rendered correctly.
    foreach ($link_title_tests as $input) {
      $this->drupalGet($input['url']);
      // This is precarious. It isn't possible to compare the link as-is because
      // it is already filtered via check_plain().
      $this->assertRaw(l($input['href'], $input['href'], array('html' => TRUE)), "Test that the link title has been set to " . $input['href']);
    }
  }

}
