<?php

/**
 * @file
 * Testing CRUD API in the browser.
 */

/**
 * Testing that users can not input bad URLs or labels
 */
class LinkUITest extends DrupalWebTestcase {

  /**
   * 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;

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

  /**
   * Implementation of setUp().
   */
  function setUp() {
    parent::setUp('content', 'link');
  }

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

    // create field
    $name = strtolower($this->randomName());
    $edit = array(
      '_add_new_field[label]' => $name,
      '_add_new_field[field_name]' => $name,
      '_add_new_field[type]' => 'link',
      '_add_new_field[widget_type]' => 'link',
    );
    $this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
    $this->drupalPost(NULL, array('validate_url' => TRUE), t('Save field settings'));

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

    // create page form
    $this->drupalGet('node/add/page');
    $field_name = 'field_' . $name;
    $this->assertField($field_name . '[0][title]', 'Title found');
    $this->assertField($field_name . '[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 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' => 'js label',
        'type' => self::LINK_INPUT_TYPE_BAD_TITLE
      ),
      array(
        'href' => 'http://example.com/' . $this->randomName(),
        'label' => $this->randomName() . '" onmouseover="alert(\'hi\')',
        'msg' => 'js label',
        'type' => self::LINK_INPUT_TYPE_BAD_TITLE
      ),
       array(
        'href' => 'http://example.com/' . $this->randomName(),
        'label' => $this->randomName() . '\' onmouseover="alert(\'hi\')',
        'msg' => 'js label',
        'type' => self::LINK_INPUT_TYPE_BAD_TITLE
      ),
     array(
        'href' => 'javascript:alert("http://example.com/' . $this->randomName() . '")',
        'label' => $this->randomName(),
        'msg' => 'js url',
        'type' => self::LINK_INPUT_TYPE_BAD_URL
      ),
    );
    foreach ($input_test_cases as $input) {
      $this->drupalLogin($account);
      $this->drupalGet('node/add/page');

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

      // change to anonym 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));
      $path = '//a[@href="'. $input['href'] .'" and text()="'. $input['label'] .'"]';
      //$this->pass(htmlentities($path));
      $elements = $this->xpath($path);
      libxml_use_internal_errors(FALSE);
      $this->assertIdentical(isset($elements[0]), $input['type'] == self::LINK_INPUT_TYPE_GOOD, $input['msg']);
    }
    //libxml_use_internal_errors(FALSE);
  }
  
  /**
   * Creates a link field for the "page" type and creates a page with a link.
   * Just like the above test, only here we're turning off the validation on the field.
   */
  function testLinkCreate_NoValidation() {
    //libxml_use_internal_errors(true);
    $account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
    $this->drupalLogin($account);

    // create field
    $name = strtolower($this->randomName());
    $edit = array(
      '_add_new_field[label]' => $name,
      '_add_new_field[field_name]' => $name,
      '_add_new_field[type]' => 'link',
      '_add_new_field[widget_type]' => 'link',
    );
    $this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
    $this->drupalPost(NULL, array('validate_url' => FALSE), t('Save field settings'));

    // Is field created?
    $this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
    _content_type_info(TRUE);
    $fields = content_fields();
    $this->assertTRUE(0 === $fields['field_'. $name]['validate_url'], 'Make sure validation is off.');
    
    // create page form
    $this->drupalGet('node/add/page');
    $field_name = 'field_' . $name;
    $this->assertField($field_name . '[0][title]', 'Title found');
    $this->assertField($field_name . '[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 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' => 'js label',
        'type' => self::LINK_INPUT_TYPE_BAD_TITLE
      ),
      array(
        'href' => 'http://example.com/' . $this->randomName(),
        'label' => $this->randomName() . '" onmouseover="alert(\'hi\')',
        'msg' => 'js label',
        'type' => self::LINK_INPUT_TYPE_BAD_TITLE
      ),
       array(
        'href' => 'http://example.com/' . $this->randomName(),
        'label' => $this->randomName() . '\' onmouseover="alert(\'hi\')',
        'msg' => 'js label',
        'type' => self::LINK_INPUT_TYPE_BAD_TITLE
      ),
     array(
        'href' => 'javascript:alert("http://example.com/' . $this->randomName() . '")',
        'label' => $this->randomName(),
        'msg' => 'js url',
        'type' => self::LINK_INPUT_TYPE_BAD_URL
      ),
    );
    foreach ($input_test_cases as $input) {
      $this->drupalLogin($account);
      $this->drupalGet('node/add/page');

      $edit = array(
        'title' => $input['label'],
        $field_name . '[0][title]' => $input['label'],
        $field_name . '[0][url]' => $input['href'],
      );
      $this->drupalPost(NULL, $edit, t('Save'));
      if ($input['type'] == self::LINK_INPUT_TYPE_BAD_URL) {
        //$this->assertRaw(t('Not a valid URL.'), 'Not a valid URL: ' . $input['href']);
        $this->assertNoRaw($input['href']);
        $this->assertRaw(t('@type %title has been created.', array('@type' => 'Page', '%title' => $edit['title'])), 'Page created: ' . $input['href']);
        continue;
      }
      else {
        $this->assertRaw(t('@type %title has been created.', array('@type' => 'Page', '%title' => $edit['title'])), 'Page created: ' . $input['href']);
      }
      $url = $this->getUrl();

      // change to anonym 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));
      $path = '//a[@href="'. $input['href'] .'" and text()="'. $input['label'] .'"]';
      //$this->pass(htmlentities($path));
      $elements = $this->xpath($path);
      libxml_use_internal_errors(FALSE);
      $this->assertIdentical(isset($elements[0]), $input['type'] == self::LINK_INPUT_TYPE_GOOD, $input['msg']);
    }
    //libxml_use_internal_errors(FALSE);
  }
  
  /**
   * Testing that if you use <strong> in a static title for your link, that the
   * title actually displays <strong>.
   */
  function testStaticLinkCreate() {
    $account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
    $this->drupalLogin($account);

    // create field
    $name = strtolower($this->randomName());
    $field_name = 'field_'. $name;
    $edit = array(
      '_add_new_field[label]' => $name,
      '_add_new_field[field_name]' => $name,
      '_add_new_field[type]' => 'link',
      '_add_new_field[widget_type]' => 'link',
    );
    $this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
    $this->drupalPost(NULL, array(
      'title' => 'value',
      'title_value' => '<strong>'. $name .'</strong>'), t('Save field settings'));

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

    // create page form
    $this->drupalGet('node/add/page');
    $this->assertField($field_name . '[0][url]', 'URL found');
    
    $input = array(
      'href' => 'http://example.com/' . $this->randomName()
    );
    
    $edit = array(
      'title' => $name,
      $field_name . '[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)));
  }
  
  /**
   * 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.
   */
  function testCRUDCreateFieldDefaults() {
    $account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
    $this->drupalLogin($account);

    // create field
    $name = strtolower($this->randomName());
    $edit = array(
      '_add_new_field[label]' => $name,
      '_add_new_field[field_name]' => $name,
      '_add_new_field[type]' => 'link',
      '_add_new_field[widget_type]' => 'link',
    );
    $this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
    $this->drupalPost(NULL, array(), t('Save field settings'));

    // Is field created?
    $this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
    _content_type_info(TRUE);
    $fields = content_fields();
    $field = $fields['field_'. $name];
    $this->assertTrue(1 === $field['validate_url'], 'Make sure validation is on.');
    $this->assertFalse($field['required'], 'Make sure field is not required.');
    $this->assertEqual($field['title'], 'optional', 'Title should be optional by default.');
    $this->assertFalse($field['enable_tokens'], 'Enable Tokens should be off by default.');
    $this->assertEqual($field['display']['url_cutoff'], 80, 'Url cutoff should be at 80 characters.');
    $this->assertEqual($field['attributes']['target'], 'default', 'Target should be "default"');
    $this->assertFalse($field['attributes']['rel'], 'Rel should be blank by default.');
    $this->assertFalse($field['attributes']['class'], 'By default, no class should be set.');
    $this->assertFalse($field['attributes']['title'], 'By default, no title should be set.');
    
    //$this->fail('<pre>'. print_r($fields['field_'. $name], TRUE) .'</pre>');
  }
}
