Exemplo n.º 1
0
 function init()
 {
     HTML_QuickForm2_Factory::registerRule('checkValidFilename', 'Piwik_Installation_FormDatabaseSetup_Rule_checkValidFilename');
     $checkUserPrivilegesClass = 'Piwik_Installation_FormDatabaseSetup_Rule_checkUserPrivileges';
     HTML_QuickForm2_Factory::registerRule('checkUserPrivileges', $checkUserPrivilegesClass);
     $availableAdapters = Piwik_Db_Adapter::getAdapters();
     $adapters = array();
     foreach ($availableAdapters as $adapter => $port) {
         $adapters[$adapter] = $adapter;
     }
     $this->addElement('text', 'host')->setLabel(Piwik_Translate('Installation_DatabaseSetupServer'))->addRule('required', Piwik_Translate('General_Required', Piwik_Translate('Installation_DatabaseSetupServer')));
     $user = $this->addElement('text', 'username')->setLabel(Piwik_Translate('Installation_DatabaseSetupLogin'));
     $user->addRule('required', Piwik_Translate('General_Required', Piwik_Translate('Installation_DatabaseSetupLogin')));
     $requiredPrivileges = Piwik_Installation_FormDatabaseSetup_Rule_checkUserPrivileges::getRequiredPrivilegesPretty();
     $user->addRule('checkUserPrivileges', Piwik_Translate('Installation_InsufficientPrivileges', $requiredPrivileges . '<br/><br/>') . Piwik_Translate('Installation_InsufficientPrivilegesHelp'));
     $this->addElement('password', 'password')->setLabel(Piwik_Translate('Installation_DatabaseSetupPassword'));
     $item = $this->addElement('text', 'dbname')->setLabel(Piwik_Translate('Installation_DatabaseSetupDatabaseName'));
     $item->addRule('required', Piwik_Translate('General_Required', Piwik_Translate('Installation_DatabaseSetupDatabaseName')));
     $item->addRule('checkValidFilename', Piwik_Translate('General_NotValid', Piwik_Translate('Installation_DatabaseSetupDatabaseName')));
     $this->addElement('text', 'tables_prefix')->setLabel(Piwik_Translate('Installation_DatabaseSetupTablePrefix'))->addRule('checkValidFilename', Piwik_Translate('General_NotValid', Piwik_Translate('Installation_DatabaseSetupTablePrefix')));
     $this->addElement('select', 'adapter')->setLabel(Piwik_Translate('Installation_DatabaseSetupAdapter'))->loadOptions($adapters)->addRule('required', Piwik_Translate('General_Required', Piwik_Translate('Installation_DatabaseSetupAdapter')));
     $this->addElement('submit', 'submit', array('value' => Piwik_Translate('General_Next') . ' »', 'class' => 'submit'));
     // default values
     $this->addDataSource(new HTML_QuickForm2_DataSource_Array(array('host' => '127.0.0.1', 'tables_prefix' => 'piwik_')));
 }
 public function testNegatesResult()
 {
     $mockEl = $this->getMock('HTML_QuickForm2_Element', array('getType', 'getRawValue', 'setValue', '__toString'));
     $mockEl->expects($this->atLeastOnce())->method('getRawValue')->will($this->returnValue('foo'));
     $inArrayOne = new HTML_QuickForm2_Rule_NotCallback($mockEl, 'an error', array('callback' => 'in_array', 'arguments' => array(array('foo', 'bar', 'baz'))));
     $inArrayTwo = HTML_QuickForm2_Factory::createRule('notcallback', $mockEl, 'an error', array('callback' => 'in_array', 'arguments' => array(array('one', 'two', 'three'))));
     $this->assertFalse($inArrayOne->validate());
     $this->assertTrue($inArrayTwo->validate());
 }
Exemplo n.º 3
0
 static function register($name, $namespace, $view_dir)
 {
     $class = '\\Larakit\\QuickForm\\Element' . Str::studly($name);
     $cont = '\\HTML_QuickForm2_Container';
     if (trim($class, '\\') instanceof $cont) {
         self::$containers[] = $class;
     }
     $path = 'QuickForm/Element' . Str::studly($name) . '.php';
     \HTML_QuickForm2_Factory::registerElement($name, $class, $path);
     if (is_subclass_of($class, '\\HTML_QuickForm2_Container')) {
         self::container($class);
     }
     self::$elements[$name] = compact('class', 'namespace', 'view_dir');
 }
Exemplo n.º 4
0
    /**
     *
     * @return Am_Form
     *
     */
    public function createNewTicketForm()
    {
        $form = parent::createNewTicketForm();
        $element = HTML_QuickForm2_Factory::createElement('text', 'loginOrEmail');
        $element->setId('loginOrEmail')->setLabel(___('E-Mail Address or Username'))->addRule('callback', ___('Can not find user with such username or email'), array($this, 'checkUser'));
        //prepend element to form
        $formElements = $form->getElements();
        $form->insertBefore($element, $formElements[0]);
        $from = HTML_QuickForm2_Factory::createElement('select', 'from');
        $from->setLabel(___('Create ticket as'));
        $from->loadOptions(array('admin' => ___('Admin'), 'user' => ___('Customer')));
        $form->insertBefore($from, $element);
        $form->addScript('script')->setScript(<<<CUT
\$("input#loginOrEmail").autocomplete({
        minLength: 2,
        source: window.rootUrl + "/admin-users/autocomplete"
});
CUT
);
        $id = $form->getId();
        $snippets = ___('Snippets');
        $form->addScript('snippets')->setScript(<<<CUT
\$('#{$id}').find('textarea[name=content]').after('<br /><br /><a href="javascript:;" id="snippets-link" class="local">{$snippets}</a>')
\$('#snippets-link').bind('click', function(){
    var \$this = \$(this);
    var div = \$('<div></div>');
    div.load(window.rootUrl + '/helpdesk/admin/p/view/displaysnippets', {}, function(){
        div.dialog({
            autoOpen: true,
            modal : true,
            title : "",
            width : 700,
            position : ['center', 'center']
        });
        div.find('.grid-wrap').bind('load', function() {
            \$(this).find('a.am-helpdesk-insert-snippet').unbind().click(function(){
                var \$target = \$this.closest('div.am-form').find('textarea[name=content]');
                \$target.insertAtCaret(\$(this).data('snippet-content'))
                div.dialog('close');
            })
        })
    })
})
CUT
);
        return $form;
    }
Exemplo n.º 5
0
 public function createNewTicketForm()
 {
     $form = parent::createNewTicketForm();
     $member = Am_Di::getInstance()->userTable->load($this->getUserId());
     $text = HTML_QuickForm2_Factory::createElement('html', 'loginOrEmail');
     $text->setLabel(___('User'))->setHtml(sprintf('<div>%s %s (%s)</div>', $member->name_f, $member->name_l, $member->login));
     $text->toggleFrozen(true);
     $form->insertBefore($text, $form->getElementById('loginOrEmail'));
     $form->removeChild($form->getElementById('loginOrEmail'));
     $loginOrEmail = HTML_QuickForm2_Factory::createElement('hidden', 'loginOrEmail');
     $loginOrEmail->setValue($member->login);
     $form->addElement($loginOrEmail);
     $user_id = HTML_QuickForm2_Factory::createElement('hidden', 'user_id');
     $user_id->setValue($member->pk());
     $form->addElement($user_id);
     return $form;
 }
Exemplo n.º 6
0
 /**
  * Validates the element's value
  * 
  * @return   bool    whether uploaded file's MIME type is correct
  * @throws   HTML_QuickForm2_InvalidArgumentException if a bogus $registeredType
  *           was passed to constructor or bogus MIME type(s) provided
  */
 protected function checkValue($value)
 {
     if (!empty($this->registeredType)) {
         $mime = HTML_QuickForm2_Factory::getRuleConfig($this->registeredType);
     } else {
         $mime = null;
     }
     if (null === $mime) {
         $mime = $this->getOptions();
     }
     if (0 == count($mime) || !is_string($mime) && !is_array($mime)) {
         throw new HTML_QuickForm2_InvalidArgumentException('MimeType Rule requires MIME type(s), ' . preg_replace('/\\s+/', ' ', var_export($mime, true)) . ' given');
     }
     if (!isset($value['error']) || UPLOAD_ERR_NO_FILE == $value['error']) {
         return true;
     }
     return is_array($mime) ? in_array($value['type'], $mime) : $value['type'] == $mime;
 }
Exemplo n.º 7
0
 /**
  * Validates the element's value
  * 
  * @return   bool    whether uploaded file's size is within given limit
  * @throws   HTML_QuickForm2_InvalidArgumentException if a bogus $registeredType
  *           was passed to constructor or a bogus size limit was provided 
  */
 protected function checkValue($value)
 {
     if (!empty($this->registeredType)) {
         $limit = HTML_QuickForm2_Factory::getRuleConfig($this->registeredType);
     } else {
         $limit = null;
     }
     if (null === $limit) {
         $limit = $this->getOptions();
     }
     if (0 >= $limit) {
         throw new HTML_QuickForm2_InvalidArgumentException('MaxFileSize Rule requires a positive size limit, ' . preg_replace('/\\s+/', ' ', var_export($limit, true)) . ' given');
     }
     if (!isset($value['error']) || UPLOAD_ERR_NO_FILE == $value['error']) {
         return true;
     }
     return $limit >= @filesize($value['tmp_name']);
 }
 public function testAddElementWithUnderscoreInType()
 {
     HTML_QuickForm2_Factory::registerElement('super_box', 'HTML_QuickForm2_Element_InputCheckbox');
     $this->assertTrue(HTML_QuickForm2_Factory::isElementRegistered('super_box'));
     $c = new HTML_QuickForm2_ContainerImpl('cCOT3');
     $el1 = $c->addSuper_Box('sBox_1');
     $el2 = $c->addsuper_box('sBox_2');
     $el3 = $c->addSuper_box('sBox_3');
     $this->assertSame($el1, $c->getElementById('sBox_1-0'));
     $this->assertSame($el2, $c->getElementById('sBox_2-0'));
     $this->assertSame($el3, $c->getElementById('sBox_3-0'));
     try {
         $c->addSuper_Select('sSel_1');
     } catch (HTML_QuickForm2_InvalidArgumentException $e) {
         $this->assertEquals("Element type 'super_select' is not known", $e->getMessage());
         return;
     }
     $this->fail('Expected HTML_QuickForm2_InvalidArgumentException was not thrown');
 }
Exemplo n.º 9
0
 function init()
 {
     HTML_QuickForm2_Factory::registerRule('checkTimezone', 'Piwik_Installation_FormFirstWebsiteSetup_Rule_isValidTimezone');
     $urlExample = 'http://example.org';
     $javascriptOnClickUrlExample = "javascript:if(this.value=='{$urlExample}'){this.value='http://';} this.style.color='black';";
     $timezones = Piwik_SitesManager_API::getInstance()->getTimezonesList();
     $timezones = array_merge(array('No timezone' => Piwik_Translate('SitesManager_SelectACity')), $timezones);
     $this->addElement('text', 'siteName')->setLabel(Piwik_Translate('Installation_SetupWebSiteName'))->addRule('required', Piwik_Translate('General_Required', Piwik_Translate('Installation_SetupWebSiteName')));
     $url = $this->addElement('text', 'url')->setLabel(Piwik_Translate('Installation_SetupWebSiteURL'));
     $url->setAttribute('style', 'color:rgb(153, 153, 153);');
     $url->setAttribute('onfocus', $javascriptOnClickUrlExample);
     $url->setAttribute('onclick', $javascriptOnClickUrlExample);
     $url->addRule('required', Piwik_Translate('General_Required', Piwik_Translate('Installation_SetupWebSiteURL')));
     $tz = $this->addElement('select', 'timezone')->setLabel(Piwik_Translate('Installation_Timezone'))->loadOptions($timezones);
     $tz->addRule('required', Piwik_Translate('General_Required', Piwik_Translate('Installation_Timezone')));
     $tz->addRule('checkTimezone', Piwik_Translate('General_NotValid', Piwik_Translate('Installation_Timezone')));
     $this->addElement('submit', 'submit', array('value' => Piwik_Translate('General_Next') . ' »', 'class' => 'submit'));
     // default values
     $this->addDataSource(new HTML_QuickForm2_DataSource_Array(array('url' => $urlExample)));
 }
Exemplo n.º 10
0
    /**
     *
     * @return Am_Form
     *
     */
    public function createNewTicketForm()
    {
        $form = parent::createNewTicketForm();
        $element = HTML_QuickForm2_Factory::createElement('text', 'loginOrEmail');
        $element->setId('loginOrEmail')->setLabel(___('E-Mail Address or Username'))->addRule('callback', ___('Can not find user with such username or email'), array($this, 'checkUser'));
        //prepend element to form
        $formElements = $form->getElements();
        $form->insertBefore($element, $formElements[0]);
        $from = HTML_QuickForm2_Factory::createElement('select', 'from');
        $from->setLabel(___('Create ticket as'));
        $from->loadOptions(array('admin' => ___('Admin'), 'user' => ___('Customer')));
        $form->insertBefore($from, $element);
        $script = <<<CUT
        \$("input#loginOrEmail").autocomplete({
                minLength: 2,
                source: window.rootUrl + "/admin-users/autocomplete"
        });
CUT;
        $form->addScript('script')->setScript($script);
        return $form;
    }
Exemplo n.º 11
0
 function init()
 {
     HTML_QuickForm2_Factory::registerRule('checkLogin', 'Piwik_Installation_FormGeneralSetup_Rule_isValidLoginString');
     HTML_QuickForm2_Factory::registerRule('checkEmail', 'Piwik_Installation_FormGeneralSetup_Rule_isValidEmailString');
     $login = $this->addElement('text', 'login')->setLabel(Piwik_Translate('Installation_SuperUserLogin'));
     $login->addRule('required', Piwik_Translate('General_Required', Piwik_Translate('Installation_SuperUserLogin')));
     $login->addRule('checkLogin');
     $password = $this->addElement('password', 'password')->setLabel(Piwik_Translate('Installation_Password'));
     $password->addRule('required', Piwik_Translate('General_Required', Piwik_Translate('Installation_Password')));
     $passwordBis = $this->addElement('password', 'password_bis')->setLabel(Piwik_Translate('Installation_PasswordRepeat'));
     $passwordBis->addRule('required', Piwik_Translate('General_Required', Piwik_Translate('Installation_PasswordRepeat')));
     $passwordBis->addRule('eq', Piwik_Translate('Installation_PasswordDoNotMatch'), $password);
     $email = $this->addElement('text', 'email')->setLabel(Piwik_Translate('Installation_Email'));
     $email->addRule('required', Piwik_Translate('General_Required', Piwik_Translate('Installation_Email')));
     $email->addRule('checkEmail', Piwik_Translate('UsersManager_ExceptionInvalidEmail'));
     $this->addElement('checkbox', 'subscribe_newsletter_security', null, array('content' => '&nbsp;&nbsp;' . Piwik_Translate('Installation_SecurityNewsletter')));
     $this->addElement('checkbox', 'subscribe_newsletter_community', null, array('content' => '&nbsp;&nbsp;' . Piwik_Translate('Installation_CommunityNewsletter')));
     $this->addElement('submit', 'submit', array('value' => Piwik_Translate('General_Next') . ' »', 'class' => 'submit'));
     // default values
     $this->addDataSource(new HTML_QuickForm2_DataSource_Array(array('subscribe_newsletter_community' => 1, 'subscribe_newsletter_security' => 1)));
 }
Exemplo n.º 12
0
 /**
  * Validates the element's value
  * 
  * @return   bool    whether element's value matches given regular expression
  * @throws   HTML_QuickForm2_InvalidArgumentException if a bogus $registeredType
  *           was passed to constructor
  * @throws   HTML_QuickForm2_Exception if regular expression is missing
  */
 protected function checkValue($value)
 {
     if (!empty($this->registeredType)) {
         $regex = HTML_QuickForm2_Factory::getRuleConfig($this->registeredType);
     } else {
         $regex = null;
     }
     if (null === $regex) {
         $regex = $this->getOptions();
     }
     if (!is_string($regex)) {
         throw new HTML_QuickForm2_Exception('Regex Rule requires a regular expression, ' . preg_replace('/\\s+/', ' ', var_export($regex, true)) . ' given');
     }
     if ($this->owner instanceof HTML_QuickForm2_Element_InputFile) {
         if (!isset($value['error']) || UPLOAD_ERR_NO_FILE == $value['error']) {
             return true;
         }
         $value = $value['name'];
     } elseif (!strlen($value)) {
         return true;
     }
     return preg_match($regex . 'D', $value);
 }
Exemplo n.º 13
0
 public function toArray()
 {
     $id = $this->getId();
     $name = $this->getName();
     $selectFrom = new HTML_QuickForm2_Element_Select("_{$name}", array('id' => "{$id}-from") + $this->attributes);
     $selectTo = new HTML_QuickForm2_Element_Select($name, array('id' => "{$id}-to") + $this->attributes);
     $strValues = array_map('strval', $this->values);
     foreach ($this->optionContainer as $option) {
         // We don't do optgroups here
         if (!is_array($option)) {
             continue;
         }
         $value = $option['attr']['value'];
         unset($option['attr']['value']);
         if (in_array($value, $strValues, true)) {
             $selectTo->addOption($option['text'], $value, empty($option['attr']) ? null : $option['attr']);
         } else {
             $selectFrom->addOption($option['text'], $value, empty($option['attr']) ? null : $option['attr']);
         }
     }
     $buttonFromTo = HTML_QuickForm2_Factory::createElement('button', "{$name}_fromto", array('type' => 'button', 'id' => "{$id}-fromto") + (empty($this->data['from_to']['attributes']) ? array() : self::prepareAttributes($this->data['from_to']['attributes'])), array('content' => empty($this->data['from_to']['content']) ? ' &gt;&gt; ' : $this->data['from_to']['content']));
     $buttonToFrom = HTML_QuickForm2_Factory::createElement('button', "{$name}_tofrom", array('type' => 'button', 'id' => "{$id}-tofrom") + (empty($this->data['to_from']['attributes']) ? array() : self::prepareAttributes($this->data['to_from']['attributes'])), array('content' => empty($this->data['to_from']['content']) ? ' &lt;&lt; ' : $this->data['to_from']['content']));
     return array('select_from' => $selectFrom->__toString(), 'select_to' => $selectTo->__toString(), 'button_from_to' => $buttonFromTo->__toString(), 'button_to_from' => $buttonToFrom->__toString());
 }
Exemplo n.º 14
0
class Am_Form_Container_PrefixFieldset extends HTML_QuickForm2_Container_Group
{
    public function getType()
    {
        return 'fieldset';
    }
}
HTML_QuickForm2_Factory::registerElement('period', 'Am_Form_Element_Period');
HTML_QuickForm2_Factory::registerElement('date', 'Am_Form_Element_Date');
HTML_QuickForm2_Factory::registerElement('integer', 'Am_Form_Element_Integer');
HTML_QuickForm2_Factory::registerElement('advcheckbox', 'Am_Form_Element_AdvCheckbox');
HTML_QuickForm2_Factory::registerElement('advradio', 'Am_Form_Element_AdvRadio');
HTML_QuickForm2_Factory::registerElement('email_checkbox', 'Am_Form_Element_EmailCheckbox');
HTML_QuickForm2_Factory::registerElement('email_select', 'Am_Form_Element_EmailSelect');
HTML_QuickForm2_Factory::registerElement('email_link', 'Am_Form_Element_EmailLink');
HTML_QuickForm2_Factory::registerElement('email_with_days', 'Am_Form_Element_EmailWithDays');
HTML_QuickForm2_Factory::registerElement('upload', 'Am_Form_Element_Upload');
HTML_QuickForm2_Factory::registerElement('script', 'Am_Form_Element_Script');
HTML_QuickForm2_Factory::registerElement('html', 'Am_Form_Element_Html');
HTML_QuickForm2_Factory::registerElement('csrf', 'Am_Form_Element_Csrf');
HTML_QuickForm2_Factory::registerElement('options_editor', 'Am_Form_Element_OptionsEditor');
HTML_QuickForm2_Factory::registerElement('htmleditor', 'Am_Form_Element_HtmlEditor');
HTML_QuickForm2_Factory::registerElement('magicselect', 'Am_Form_Element_MagicSelect');
HTML_QuickForm2_Factory::registerElement('sortablemagicselect', 'Am_Form_Element_SortableMagicSelect');
HTML_QuickForm2_Factory::registerElement('checkboxedgroup', 'Am_Form_Element_CheckboxedGroup');
HTML_QuickForm2_Factory::registerElement('advfieldset', 'Am_Form_Container_AdvFieldset');
HTML_QuickForm2_Factory::registerElement('multi_select', 'Am_Form_Element_MultiSelect');
HTML_QuickForm2_Factory::registerElement('category', 'Am_Form_Element_Category');
HTML_QuickForm2_Factory::registerRule('callback2', 'Am_Rule_Callback2');
HTML_QuickForm2_Factory::registerRule('remote', 'HTML_QuickForm2_Rule_Remote');
Exemplo n.º 15
0
 public function testConfigOverridesOptions()
 {
     $mockFile = $this->getMock('HTML_QuickForm2_Element_InputFile', array('getValue'));
     $mockFile->expects($this->once())->method('getValue')->will($this->returnValue(array('name' => 'pr0n.jpg', 'type' => 'image/jpeg', 'tmp_name' => dirname(dirname(__FILE__)) . '/_files/1024-bytes.upload', 'error' => UPLOAD_ERR_OK, 'size' => 1024)));
     HTML_QuickForm2_Factory::registerRule('filesize-override-512', 'HTML_QuickForm2_Rule_MaxFileSize', null, 512);
     $maxSize = $mockFile->addRule('filesize-override-512', 'too big', 10240);
     $this->assertFalse($maxSize->validate());
 }
Exemplo n.º 16
0
 public function testCreateRuleValid()
 {
     $mockNode = $this->getMock('HTML_QuickForm2_Node', array('updateValue', 'getId', 'getName', 'getType', 'getValue', 'setId', 'setName', 'setValue', '__toString'));
     HTML_QuickForm2_Factory::registerRule('fakerule', 'FakeRule', dirname(__FILE__) . '/_files/FakeRule.php');
     $rule = HTML_QuickForm2_Factory::createRule('fakerule', $mockNode, 'An error message', 'Some options');
     $this->assertType('FakeRule', $rule);
     $this->assertSame($mockNode, $rule->owner);
     $this->assertEquals('An error message', $rule->getMessage());
     $this->assertEquals('Some options', $rule->getOptions());
     $this->assertEquals('fakerule', $rule->registeredType);
 }
Exemplo n.º 17
0
 public function testConfigOverridesOptions()
 {
     $mockEl = $this->getMock('HTML_QuickForm2_Element', array('getType', 'getValue', 'setValue', '__toString'));
     $mockEl->expects($this->once())->method('getValue')->will($this->returnValue('foo'));
     HTML_QuickForm2_Factory::registerRule('regex-override', 'HTML_QuickForm2_Rule_Regex', null, '/^[a-zA-Z]+$/');
     $override = HTML_QuickForm2_Factory::createRule('regex-override', $mockEl, 'an error', '/^[0-9]+$/');
     $this->assertTrue($override->validate());
 }
Exemplo n.º 18
0
 /**
  * Creates a validation rule
  *
  * This method is mostly useful when when chaining several rules together
  * via {@link HTML_QuickForm2_Rule::and_()} and {@link HTML_QuickForm2_Rule::or_()}
  * methods:
  * <code>
  * $first->addRule('nonempty', 'Fill in either first or second field')
  *     ->or_($second->createRule('nonempty'));
  * </code>
  *
  * @param string $type    Rule type
  * @param string $message Message to display if validation fails
  * @param mixed  $options Configuration data for the rule
  *
  * @return   HTML_QuickForm2_Rule    The created rule
  * @throws   HTML_QuickForm2_InvalidArgumentException If rule type is unknown
  * @throws   HTML_QuickForm2_NotFoundException        If class for the rule
  *           can't be found and/or loaded from file
  */
 public function createRule($type, $message = '', $options = null)
 {
     return HTML_QuickForm2_Factory::createRule($type, $this, $message, $options);
 }
Exemplo n.º 19
0
 public function testConfigOverridesOptions()
 {
     HTML_QuickForm2_Factory::registerRule('length-1-5', 'HTML_QuickForm2_Rule_Length', null, array('min' => 1, 'max' => 5));
     $mockElFoo = $this->getMock('HTML_QuickForm2_Element', array('getType', 'getValue', 'setValue', '__toString'));
     $mockElFoo->expects($this->atLeastOnce())->method('getValue')->will($this->returnValue('foo'));
     $mockElFoobar = $this->getMock('HTML_QuickForm2_Element', array('getType', 'getValue', 'setValue', '__toString'));
     $mockElFoobar->expects($this->atLeastOnce())->method('getValue')->will($this->returnValue('foobar'));
     $ruleFoo = $mockElFoo->addRule('length-1-5', 'not in range', array('min' => 4));
     $this->assertTrue($ruleFoo->validate());
     $ruleFoobar = $mockElFoobar->addRule('length-1-5', 'not in range', array('max' => 7));
     $this->assertFalse($ruleFoobar->validate());
 }
Exemplo n.º 20
0
 /**
  * Class constructor, form's "id" and "method" attributes can only be set here
  *
  * @param    string  "id" attribute of <form> tag
  * @param    string  HTTP method used to submit the form
  * @param    mixed   Additional attributes (either a string or an array)
  * @param    bool    Whether to track if the form was submitted by adding
  *                   a special hidden field
  */
 public function __construct($id, $method = 'post', $attributes = null, $trackSubmit = true)
 {
     $method = 'GET' == strtoupper($method) ? 'get' : 'post';
     $trackSubmit = empty($id) ? false : $trackSubmit;
     $this->attributes = array_merge(self::prepareAttributes($attributes), array('method' => $method));
     parent::setId(empty($id) ? null : $id);
     if (!isset($this->attributes['action'])) {
         $this->attributes['action'] = $_SERVER['PHP_SELF'];
     }
     if ($trackSubmit && isset($_REQUEST['_qf__' . $id]) || !$trackSubmit && ('get' == $method && !empty($_GET) || 'post' == $method && (!empty($_POST) || !empty($_FILES)))) {
         $this->addDataSource(new HTML_QuickForm2_DataSource_SuperGlobal($method, get_magic_quotes_gpc()));
     }
     if ($trackSubmit) {
         $this->appendChild(HTML_QuickForm2_Factory::createElement('hidden', '_qf__' . $id));
     }
 }
Exemplo n.º 21
0
 /**
  * read_quickform set a HTML_Quickform2_Element-object to $quickform according
  * to the $type
  * 
  * @param array $options array containing parameters for the input-tag
  * @param bool $defaults text-fields with default-values if true
  * @return string the value of the "id"-parameter of the input-tag
  */
 public function read_quickform($options = array(), $defaults = false)
 {
     // prepare return
     $element = null;
     // prepare ids
     $element_ids = '';
     // check type
     if ($this->get_type() == 'text') {
         // check defaults
         if ($defaults === true) {
             // field-group
             $element = HTML_QuickForm2_Factory::createElement('group', $this->get_table() . '-' . $this->get_id(), $options);
             $element->setLabel($this->get_name() . ':');
             // add select
             $select = $element->addElement('select', 'defaults', array());
             $select->setLabel(parent::lang('class.Field#element#label#textarea.defaults'));
             // add textarea
             $textarea = $element->addElement('textarea', 'manual', array());
             $textarea->setLabel(parent::lang('class.Field#element#label#textarea.manual'));
             // add options
             $this->read_defaults($select);
         } else {
             // textarea
             $element = HTML_QuickForm2_Factory::createElement('textarea', $this->get_table() . '-' . $this->get_id(), $options);
             $element->setLabel($this->get_name() . ':');
             // add rules
             if ($this->get_required() == 1) {
                 $element->addRule('required', parent::lang('class.Field#element#rule#required.text'));
             }
             $element->addRule('regex', parent::lang('class.Field#element#rule#regexp.allowedChars') . ' [' . $_SESSION['GC']->get_config('textarea.desc') . ']', $_SESSION['GC']->get_config('textarea.regexp'));
         }
         // add id to return
         $element_ids = $this->get_table() . '-' . $this->get_id();
     } elseif ($this->get_type() == 'date') {
         // date in input-text for use with jquery
         $element = HTML_QuickForm2_Factory::createElement('text', $this->get_table() . '-' . $this->get_id(), $options);
         $element->setLabel($this->get_name() . ':');
         // add rules
         if ($this->get_required() == 1) {
             $element->addRule('required', parent::lang('class.Field#element#rule#required.date'));
         }
         $element->addRule('callback', parent::lang('class.Field#element#rule#check.date'), array($this, 'callback_check_date'));
         // add id to return
         $element_ids = $this->get_table() . '-' . $this->get_id();
     } elseif ($this->get_type() == 'checkbox') {
         // checkbox
         $element = HTML_QuickForm2_Factory::createElement('checkbox', $this->get_table() . '-' . $this->get_id(), $options);
         $element->setLabel($this->get_name() . ':');
         // add rules
         if ($this->get_required() == 1) {
             $element->addRule('required', parent::lang('class.Field#element#rule#required.checkbox'));
         }
         // add id to return
         $element_ids = $this->get_table() . '-' . $this->get_id();
     } elseif ($this->get_type() == 'dbselect') {
         // read config
         $config = $this->get_config();
         // merge options
         $options = array_merge($options, $config['options']);
         // select
         $element = HTML_QuickForm2_Factory::createElement('select', $this->get_table() . '-' . $this->get_id(), $options);
         $element->setLabel($this->get_name() . ':');
         // add rules
         if ($this->get_required() == 1) {
             $element->addRule('required', parent::lang('class.Field#element#rule#required.checkbox'));
             $element->addRule('callback', parent::lang('class.Field#entry#rule#check.select'), array($this, 'callback_check_select'));
         }
         // add id to return
         $element_ids = $this->get_table() . '-' . $this->get_id();
         // get options from field-config
         $field_options = array('--');
         $this->dbselect_options($field_options);
         // load options
         $element->loadOptions($field_options);
     } elseif ($this->get_type() == 'dbhierselect') {
         // select
         $element = HTML_QuickForm2_Factory::createElement('hierselect', $this->get_table() . '-' . $this->get_id(), $options);
         $element->setLabel($this->get_name() . ':');
         // add rules
         if ($this->get_required() == 1) {
             $element->addRule('required', parent::lang('class.Field#element#rule#required.checkbox'));
             $element->addRule('callback', parent::lang('class.Field#entry#rule#check.hierselect'), array($this, 'callback_check_hierselect'));
         }
         // add id to return
         $element_ids = $this->get_table() . '-' . $this->get_id();
         // get options from field-config
         $field_options_first[0] = '--';
         $field_options_second[0][0] = '--';
         $this->dbhierselect_options($field_options_first, $field_options_second);
         // load options
         $element->loadOptions(array($field_options_first, $field_options_second));
     }
     // set
     $this->set_quickform($element);
     // return
     return $element_ids;
 }
Exemplo n.º 22
0
 public function testRenderStaticLabels()
 {
     $element = HTML_QuickForm2_Factory::createElement('text', 'static')->setLabel(array('a label', 'another label', 'foo' => 'named label'));
     $renderer = HTML_QuickForm2_Renderer::factory('array')->setOption('static_labels', false);
     $array = $element->render($renderer)->toArray();
     $this->assertInternalType('array', $array['label']);
     $array = $element->render($renderer->setOption('static_labels', true)->reset())->toArray();
     $this->assertEquals('a label', $array['label']);
     $this->assertEquals('another label', $array['label_2']);
     $this->assertEquals('named label', $array['label_foo']);
 }
Exemplo n.º 23
0
 public function testConfigOverridesOptions()
 {
     $mockEl = $this->getMock('HTML_QuickForm2_Element', array('getType', 'getValue', 'setValue', '__toString'));
     $mockEl->expects($this->atLeastOnce())->method('getValue')->will($this->returnValue('foo'));
     HTML_QuickForm2_Factory::registerRule('compare-override', 'HTML_QuickForm2_Rule_Compare', null, array('operator' => '===', 'operand' => 'foo'));
     $rule1 = HTML_QuickForm2_Factory::createRule('compare-override', $mockEl, '...', array('operator' => '===', 'operand' => 'bar'));
     $rule2 = HTML_QuickForm2_Factory::createRule('compare-override', $mockEl, '...', array('operator' => '!==', 'operand' => 'foo'));
     $this->assertTrue($rule1->validate());
     $this->assertTrue($rule2->validate());
 }
 public function testRenderGroupedElementsWithSeparators()
 {
     $group = HTML_QuickForm2_Factory::createElement('group', 'foo', array('id' => 'testSeparators'));
     $element1 = $group->addElement('text', 'bar');
     $element2 = $group->addElement('text', 'baz');
     $element3 = $group->addElement('text', 'quux');
     $renderer = HTML_Quickform2_Renderer::factory('callback')->setCallbackForId('testSeparators', array(get_class($this), '_renderTestSeparators'))->setElementCallbackForGroupId('testSeparators', 'HTML_QuickForm2_Element_InputText', array(get_class($this), '_renderTestSeparators2'));
     $this->assertEquals('<foo>' . $element1 . '</foo><foo>' . $element2 . '</foo><foo>' . $element3 . '</foo>', $group->render($renderer->reset())->__toString());
     $group->setSeparator('&nbsp;');
     $this->assertEquals('<foo>' . $element1 . '</foo>&nbsp;<foo>' . $element2 . '</foo>&nbsp;<foo>' . $element3 . '</foo>', $group->render($renderer->reset())->__toString());
     $group->setSeparator(array('<br />', '&nbsp;'));
     $this->assertEquals('<foo>' . $element1 . '</foo><br /><foo>' . $element2 . '</foo>&nbsp;<foo>' . $element3 . '</foo>', $group->render($renderer->reset())->__toString());
 }
Exemplo n.º 25
0
 /**
  * Validates the element's value
  * 
  * @return   bool    the value returned by a callback function
  * @throws   HTML_QuickForm2_InvalidArgumentException if a bogus $registeredType
  *           was passed to constructor or a bogus callback was provided
  * @throws   HTML_QuickForm2_Exception if the callback is missing
  */
 protected function checkValue($value)
 {
     if (!empty($this->registeredType)) {
         $config = HTML_QuickForm2_Factory::getRuleConfig($this->registeredType);
     } else {
         $config = null;
     }
     $callback = $this->findCallback($config);
     $arguments = $this->findArguments($config);
     if (!is_callable($callback, false, $callbackName)) {
         throw new HTML_QuickForm2_InvalidArgumentException('Callback Rule requires a valid callback, \'' . $callbackName . '\' was given');
     }
     return call_user_func_array($callback, array_merge(array($value), $arguments));
 }
 public function testConfigOverridesOptions()
 {
     $mockFile = $this->getMock('HTML_QuickForm2_Element_InputFile', array('getValue'));
     $mockFile->expects($this->once())->method('getValue')->will($this->returnValue(array('name' => 'pr0n.jpg', 'type' => 'image/jpeg', 'tmp_name' => '/tmp/foobar', 'error' => UPLOAD_ERR_OK, 'size' => 123456)));
     HTML_QuickForm2_Factory::registerRule('type-override-text', 'HTML_QuickForm2_Rule_MimeType', null, 'text/plain');
     $mimeType = $mockFile->addRule('type-override-text', 'need image', array('image/gif', 'image/jpeg'));
     $this->assertFalse($mimeType->validate());
 }
Exemplo n.º 27
0
 /**
  * Appends an element to the container (possibly creating it first)
  *
  * If the first parameter is an instance of HTML_QuickForm2_Node then all
  * other parameters are ignored and the method just calls {@link appendChild()}.
  * In the other case the element is first created via
  * {@link HTML_QuickForm2_Factory::createElement()} and then added via the
  * same method. This is a convenience method to reduce typing and ease
  * porting from HTML_QuickForm.
  *
  * @param    string|HTML_QuickForm2_Node  Either type name (treated
  *               case-insensitively) or an element instance
  * @param    mixed   Element name
  * @param    mixed   Element attributes
  * @param    array   Element-specific data
  * @return   HTML_QuickForm2_Node     Added element
  * @throws   HTML_QuickForm2_InvalidArgumentException
  * @throws   HTML_QuickForm2_NotFoundException
  */
 public function addElement($elementOrType, $name = null, $attributes = null, array $data = array())
 {
     if ($elementOrType instanceof HTML_QuickForm2_Node) {
         return $this->appendChild($elementOrType);
     } else {
         return $this->appendChild(HTML_QuickForm2_Factory::createElement($elementOrType, $name, $attributes, $data));
     }
 }
Exemplo n.º 28
0
 public function testDefaultConfigMerging()
 {
     $this->assertEquals('foo', HTML_QuickForm2_Rule::mergeConfig('foo', null));
     $this->assertEquals('bar', HTML_QuickForm2_Rule::mergeConfig('foo', 'bar'));
     HTML_QuickForm2_Factory::registerRule('no-config', 'HTML_QuickForm2_Rule_ImplConst');
     HTML_QuickForm2_Factory::registerRule('with-config', 'HTML_QuickForm2_Rule_ImplConst', null, 'bar');
     $el = new HTML_QuickForm2_Element_InputText();
     $this->assertEquals('foo', $el->createRule('no-config', '', 'foo')->getConfig());
     $this->assertEquals('bar', $el->createRule('with-config', '', 'foo')->getConfig());
 }
Exemplo n.º 29
0
 public function testConfigOverridesOptions()
 {
     $mockEl = $this->getMock('HTML_QuickForm2_Element', array('getType', 'getValue', 'setValue', '__toString'));
     $mockEl->expects($this->atLeastOnce())->method('getValue')->will($this->returnValue('foo'));
     HTML_QuickForm2_Factory::registerRule('inarray-override', 'HTML_QuickForm2_Rule_Callback', null, array('callback' => 'in_array', 'arguments' => array(array('foo', 'bar', 'baz'))));
     $rule1 = HTML_QuickForm2_Factory::createRule('inarray-override', $mockEl, 'an error', array('callback' => array($this, 'checkNotFoo')));
     $rule2 = HTML_QuickForm2_Factory::createRule('inarray-override', $mockEl, 'an error', array('arguments' => array(array('one', 'two', 'three'))));
     $this->assertTrue($rule1->validate());
     $this->assertTrue($rule2->validate());
 }
 public function testCreateRuleValid()
 {
     $mockNode = $this->getMock('HTML_QuickForm2_Node', $this->nodeAbstractMethods);
     HTML_QuickForm2_Factory::registerRule('fakerule', 'FakeRule', dirname(__FILE__) . '/_files/FakeRule.php');
     /* @var $rule FakeRule */
     $rule = HTML_QuickForm2_Factory::createRule('fakerule', $mockNode, 'An error message', 'Some options');
     $this->assertInstanceOf('FakeRule', $rule);
     $this->assertSame($mockNode, $rule->owner);
     $this->assertEquals('An error message', $rule->getMessage());
     $this->assertEquals('Some options', $rule->getConfig());
 }