/**
  * Displays the login page
  * @param object $formModel
  * @param bool $isMobile Whether this was called from mobile site controller
  */
 public function login(LoginForm $model, $isMobile = false)
 {
     $model->attributes = $_POST['LoginForm'];
     // get user input data
     Session::cleanUpSessions();
     $ip = $this->owner->getRealIp();
     $userModel = $model->getUser();
     $isRealUser = $userModel instanceof User;
     $effectiveUsername = $isRealUser ? $userModel->username : $model->username;
     $isActiveUser = $isRealUser && $userModel->status == User::STATUS_ACTIVE;
     /* increment count on every session with this user/IP, to prevent brute force attacks 
        using session_id spoofing or whatever */
     Yii::app()->db->createCommand('UPDATE x2_sessions SET status=status-1,lastUpdated=:time WHERE user=:name AND 
         CAST(IP AS CHAR)=:ip AND status BETWEEN -2 AND 0')->bindValues(array(':time' => time(), ':name' => $effectiveUsername, ':ip' => $ip))->execute();
     $activeUser = Yii::app()->db->createCommand()->select('username')->from('x2_users')->where('username=:name AND status=1', array(':name' => $model->username))->limit(1)->queryScalar();
     // get the correctly capitalized username
     if (isset($_SESSION['sessionId'])) {
         $sessionId = $_SESSION['sessionId'];
     } else {
         $sessionId = $_SESSION['sessionId'] = session_id();
     }
     $session = X2Model::model('Session')->findByPk($sessionId);
     /* get the number of failed login attempts from this IP within timeout interval. If the 
        number of login attempts exceeds maximum, display captcha */
     $badAttemptsRefreshTimeout = 900;
     $maxFailedLoginAttemptsPerIP = 100;
     $maxLoginsBeforeCaptcha = 5;
     $this->pruneTimedOutBans($badAttemptsRefreshTimeout);
     $failedLoginRecord = FailedLogins::model()->findActiveByIp($ip);
     $badAttemptsWithThisIp = $failedLoginRecord ? $failedLoginRecord->attempts : 0;
     if ($badAttemptsWithThisIp >= $maxFailedLoginAttemptsPerIP) {
         $this->recordFailedLogin($ip);
         throw new CHttpException(403, Yii::t('app', 'You are not authorized to use this application'));
     }
     // if this client has already tried to log in, increment their attempt count
     if ($session === null) {
         $session = new Session();
         $session->id = $sessionId;
         $session->user = $model->getSessionUserName();
         $session->lastUpdated = time();
         $session->status = 0;
         $session->IP = $ip;
     } else {
         $session->lastUpdated = time();
         $session->user = $model->getSessionUserName();
     }
     if ($isActiveUser === false) {
         $model->verifyCode = '';
         // clear captcha code
         $model->validate();
         // validate captcha if it's being used
         $this->recordFailedLogin($ip);
         $session->save();
         if ($badAttemptsWithThisIp + 1 >= $maxFailedLoginAttemptsPerIP) {
             throw new CHttpException(403, Yii::t('app', 'You are not authorized to use this application'));
         } else {
             if ($badAttemptsWithThisIp >= $maxLoginsBeforeCaptcha - 1) {
                 $model->useCaptcha = true;
                 $model->setScenario('loginWithCaptcha');
                 $session->status = -2;
             }
         }
     } else {
         if ($model->validate() && $model->login()) {
             // user successfully logged in
             if ($model->rememberMe) {
                 foreach (array('username', 'rememberMe') as $attr) {
                     // Expires in 30 days
                     AuxLib::setCookie(CHtml::resolveName($model, $attr), $model->{$attr}, 2592000);
                 }
             } else {
                 foreach (array('username', 'rememberMe') as $attr) {
                     // Remove the cookie if they unchecked the box
                     AuxLib::clearCookie(CHtml::resolveName($model, $attr));
                 }
             }
             // We're not using the isAdmin parameter of the application
             // here because isAdmin in this context hasn't been set yet.
             $isAdmin = Yii::app()->user->checkAccess('AdminIndex');
             if ($isAdmin && !$isMobile) {
                 $this->owner->attachBehavior('updaterBehavior', new UpdaterBehavior());
                 $this->owner->checkUpdates();
                 // check for updates if admin
             } else {
                 Yii::app()->session['versionCheck'] = true;
             }
             // ...or don't
             $session->status = 1;
             $session->save();
             SessionLog::logSession($model->username, $sessionId, 'login');
             $_SESSION['playLoginSound'] = true;
             if (YII_UNIT_TESTING && defined('X2_DEBUG_EMAIL') && X2_DEBUG_EMAIL) {
                 Yii::app()->session['debugEmailWarning'] = 1;
             }
             // if ( isset($_POST['themeName']) ) {
             //     $profile = X2Model::model('Profile')->findByPk(Yii::app()->user->id);
             //     $profile->theme = array_merge(
             //         $profile->theme,
             //         ThemeGenerator::loadDefault( $_POST['themeName'])
             //     );
             //     $profile->save();
             // }
             LoginThemeHelper::login();
             if ($isMobile) {
                 $this->owner->redirect($this->owner->createUrl('/mobile/home'));
             } else {
                 if (Yii::app()->user->returnUrl == '/site/index') {
                     $this->owner->redirect(array('/site/index'));
                 } else {
                     // after login, redirect to wherever
                     $this->owner->redirect(Yii::app()->user->returnUrl);
                 }
             }
         } else {
             // login failed
             $model->verifyCode = '';
             // clear captcha code
             $this->recordFailedLogin($ip);
             $session->save();
             if ($badAttemptsWithThisIp + 1 >= $maxFailedLoginAttemptsPerIP) {
                 throw new CHttpException(403, Yii::t('app', 'You are not authorized to use this application'));
             } else {
                 if ($badAttemptsWithThisIp >= $maxLoginsBeforeCaptcha - 1) {
                     $model->useCaptcha = true;
                     $model->setScenario('loginWithCaptcha');
                     $session->status = -2;
                 }
             }
         }
     }
     $model->rememberMe = false;
 }
Example #2
0
 /**
  * Checks if model attribute has error, returns true or false
  *
  * @param CActiveRecord $model Model attribute belongs to
  * @param string $attribute Name of attribute
  * @return bool True if attribute has error, otherwise false
  */
 public function hasError($model, $attribute)
 {
     CHtml::resolveName($model, $attribute);
     // turn [a][b]attr into attr
     $error = $model->getError($attribute);
     return $error != '';
 }
Example #3
0
 public function getElementName()
 {
     // Имя элемента
     // Menu[name]
     $attr = $this->attributeName;
     if ($attr != null) {
         return CHtml::resolveName($this->model, $attr);
     }
     $elementName = "ve_";
     $elementName .= $this->objectParameter->getIdParameter();
     return $elementName;
 }
Example #4
0
    public function run()
    {
        $cs = Yii::app()->getClientScript();
        $textAreaOptions = $this->gettextareaOptions();
        $textAreaOptions['name'] = CHtml::resolveName($this->model, $this->name);
        $this->id = $textAreaOptions['id'] = CHtml::getIdByName($textAreaOptions['name']);
        echo CHtml::activeTextArea($this->model, $this->name, $textAreaOptions);
        $properties_string = CJavaScript::encode($this->getKeProperties());
        $js = <<<EOF
KindEditor.ready(function(K) {
\tvar editor_{$this->id} = K.create('#{$this->id}', 
{$properties_string}
\t);
});
EOF;
        $cs->registerScript('KE' . $this->name, $js, CClientScript::POS_HEAD);
    }
Example #5
0
 /**
  * Returns all uploaded files for the given model attribute.
  * @param CModel $model the model instance
  * @param string $attribute the attribute name. For tabular file uploading, this can be in the format of "[$i]attributeName", where $i stands for an integer index.
  * @return array array of TUploadedFile objects.
  * Empty array is returned if no available file was found for the given attribute.
  */
 public static function getInstances($model, $attribute)
 {
     self::$_files = array();
     if (!isset($_FILES) || !is_array($_FILES)) {
         return [];
     }
     foreach ($_FILES as $class => $info) {
         self::collectFilesRecursive($class, $info['name'], $info['tmp_name'], $info['type'], $info['size'], $info['error']);
     }
     $name = CHtml::resolveName($model, $attribute);
     $len = strlen($name);
     $results = array();
     //Yii::log(var_export(self::$_files, true), CLogger::LEVEL_INFO);
     foreach (array_keys(self::$_files) as $key) {
         //兼容移动客户端上传的附件uploadedfile_x的格式
         if ((0 === strncmp($key, $name, $len) || 1 === preg_match('/^uploadedfile_\\d+$/i', $key)) && self::$_files[$key]->getError() != UPLOAD_ERR_NO_FILE) {
             $results[] = self::$_files[$key];
         }
     }
     return $results;
 }
Example #6
0
 /**
  * Only one line is changed from CForm to render a valid class when
  * using tabular inputs. The line is marked.
  */
 public function renderElement($element)
 {
     if (is_string($element)) {
         if (($e = $this[$element]) === null && ($e = $this->getButtons()->itemAt($element)) === null) {
             return $element;
         } else {
             $element = $e;
         }
     }
     if ($element->getVisible() || $this->getModel()->isAttributeSafe(substr($element->name, 3))) {
         if ($element instanceof CFormInputElement) {
             //print_r($element->name); die;
             if ($element->type === 'hidden') {
                 return "<div style=\"visibility:hidden\">\n" . $element->render() . "</div>\n";
             } else {
                 //print_r($element); die;
                 $elementName = $element->name;
                 return '<div class="row field_' . strtolower(preg_replace('/(\\[\\w*\\])?\\[(\\w*)\\]/', '_$2', CHtml::resolveName($element->getParent()->getModel(), $elementName))) . "\">\n" . $element->render() . "</div>\n";
                 // This line is the change
             }
         } elseif ($element instanceof CFormButtonElement) {
             return $element->render() . "\n";
         } else {
             return $element->render();
         }
     }
     return '';
 }
Example #7
0
 /**
  * Renders the stars.
  * @param string $id the ID of the container
  * @param string $name the name of the input
  */
 protected function renderStars($id, $name)
 {
     $inputCount = (int) (($this->maxRating - $this->minRating) / $this->ratingStepSize + 1);
     $starSplit = (int) ($inputCount / $this->starCount);
     if ($this->hasModel()) {
         $attr = $this->attribute;
         CHtml::resolveName($this->model, $attr);
         $selection = $this->model->{$attr};
     } else {
         $selection = $this->value;
     }
     $options = $starSplit > 1 ? array('class' => "{split:{$starSplit}}") : array();
     for ($value = $this->minRating, $i = 0; $i < $inputCount; ++$i, $value += $this->ratingStepSize) {
         $options['id'] = $id . '_' . $i;
         $options['value'] = $value;
         if (isset($this->titles[$value])) {
             $options['title'] = $this->titles[$value];
         } else {
             unset($options['title']);
         }
         echo CHtml::radioButton($name, !strcmp($value, $selection), $options) . "\n";
     }
 }
 /**
  * Generates a checkbox group for a model attribute.
  *
  * This method is a wrapper for {@link CActiveForm::checkbox} and {@link customFieldGroup}.
  * Please check {@link CActiveForm::checkbox} for detailed information about $htmlOptions argument.
  * About $options argument parameters see {@link TbActiveForm} documentation.
  *
  * @param CModel $model The data model.
  * @param string $attribute The attribute.
  * @param array $htmlOptions Additional HTML attributes.
  * @param array $options Group attributes.
  * @return string The generated checkbox group.
  * @see CActiveForm::checkbox
  * @see customFieldGroup
  */
 public function checkboxGroup($model, $attribute, $options = array())
 {
     $this->initOptions($options);
     if ($this->type == self::TYPE_INLINE) {
         self::addCssClass($options['labelOptions'], 'inline');
     }
     $field = $this->checkbox($model, $attribute, $options['widgetOptions']['htmlOptions']);
     if ((!array_key_exists('uncheckValue', $options['widgetOptions']) || isset($options['widgetOptions']['uncheckValue'])) && preg_match('/\\<input.*?type="hidden".*?\\>/', $field, $matches)) {
         $hiddenField = $matches[0];
         $field = str_replace($hiddenField, '', $field);
     }
     $realAttribute = $attribute;
     CHtml::resolveName($model, $realAttribute);
     ob_start();
     echo '<div class="checkbox">';
     if (isset($hiddenField)) {
         echo $hiddenField;
     }
     echo CHtml::tag('label', $options['labelOptions'], false, false);
     echo $field;
     if (isset($options['label'])) {
         if ($options['label']) {
             echo $options['label'];
         }
     } else {
         echo ' ' . $model->getAttributeLabel($realAttribute);
     }
     echo CHtml::closeTag('label');
     echo '</div>';
     $fieldData = ob_get_clean();
     $options['label'] = '';
     return $this->customFieldGroupInternal($fieldData, $model, $attribute, $options);
 }
Example #9
0
 /**
  * Creates the HTML code wrapping the error text for given model attribute.
  *
  * @param CModel $model the data model
  * @param string $attribute the attribute name
  * @param array $htmlOptions additional HTML attributes to be rendered in the container div tag.
  * @return string the error display. Empty if no errors are found.
  *
  * @see CModel::getErrors
  * @see errorMessageCss
  */
 protected static function renderError($model, $attribute, $htmlOptions = array())
 {
     /* Using side effects of `resolveName`: 
        `$attribute` will be modified: `[a][b]attr` will be turned into `attr` */
     CHtml::resolveName($model, $attribute);
     $error = $model->getError($attribute);
     return $error != '' ? CHtml::tag('span', $htmlOptions, $error) : '';
 }
Example #10
0
 /**
  * Displays the first validation error for a model attribute.
  * @param CModel $model the data model
  * @param string $attribute the attribute name
  * @param array $htmlOptions additional HTML attributes to be rendered in the container tag.
  * @return string the error display. Empty if no errors are found.
  * @see CModel::getErrors
  * @see errorMessageCss
  * @see $errorContainerTag
  */
 public static function error($model, $attribute, $htmlOptions = array())
 {
     CHtml::resolveName($model, $attribute);
     // turn [a][b]attr into attr
     $error = $model->getError($attribute);
     return $error != '' ? CHtml::tag('span', self::defaultOption('class', self::$errorMessageCss, $htmlOptions), $error) : '';
 }
Example #11
0
 /**
  * Returns the id that should be used for the specified attribute
  * @param string $attribute the attribute
  * @return string the id 
  */
 protected function getAttributeId($attribute)
 {
     return isset($this->htmlOptions['id']) ? $this->htmlOptions['id'] : CHtml::getIdByName(CHtml::resolveName($this->model, $attribute));
 }
Example #12
0
 /**
  * Generates a checkbox row for a model attribute.
  *
  * This method is a wrapper for {@link \CActiveForm::checkBox} and {@link customFieldRow}.
  * Please check {@link \CActiveForm::checkBox} for detailed information about $htmlOptions argument.
  * About $rowOptions argument parameters see {@link ActiveForm} documentation.
  *
  * @param \CModel $model The data model.
  * @param string $attribute The attribute.
  * @param array $htmlOptions Additional HTML attributes.
  * @param array $rowOptions Row attributes.
  * @return string The generated checkbox row.
  * @see \CActiveForm::checkBox
  * @see customFieldRow
  */
 public function checkBoxRow($model, $attribute, $htmlOptions = [], $rowOptions = [])
 {
     $this->initRowOptions($rowOptions);
     Html::addCssClass($rowOptions['labelOptions'], 'checkbox');
     if ($this->type == self::TYPE_INLINE) {
         Html::addCssClass($rowOptions['labelOptions'], 'inline');
     }
     $field = $this->checkBox($model, $attribute, $htmlOptions);
     if ((!array_key_exists('uncheckValue', $htmlOptions) || isset($htmlOptions['uncheckValue'])) && preg_match('/\\<input.*?type="hidden".*?\\>/', $field, $matches)) {
         $hiddenField = $matches[0];
         $field = str_replace($hiddenField, '', $field);
     }
     $realAttribute = $attribute;
     \CHtml::resolveName($model, $realAttribute);
     ob_start();
     if (isset($hiddenField)) {
         echo $hiddenField;
     }
     echo \CHtml::tag('label', $rowOptions['labelOptions'], false, false);
     echo $field;
     if (isset($rowOptions['label'])) {
         if ($rowOptions['label']) {
             echo $rowOptions['label'];
         }
     } else {
         echo $model->getAttributeLabel($realAttribute);
     }
     echo \CHtml::closeTag('label');
     $fieldData = ob_get_clean();
     $rowOptions['label'] = '';
     return $this->customFieldRowInternal($fieldData, $model, $attribute, $rowOptions);
 }
Example #13
0
 /**
  * Generate form input name for an attribute so that the urlencoded post data
  * comes in a form that can be properly interpreted by setAttributes in the
  * container model
  * {@link JSONEmbeddedModelFieldsBehavior}
  * @param string $attribute
  */
 public function resolveName($attribute)
 {
     if (!isset($this->exoFormName)) {
         $this->exoFormName = CHtml::resolveName($this->exoModel, $this->exoAttr);
     }
     return $this->exoFormName . strtr(CHtml::resolveName($this, $attribute), array(get_class($this) => ''));
 }
Example #14
0
 /**
  * Displays the first validation error for a model attribute.
  * This is similar to {@link CHtml::error} except that it registers the model attribute
  * so that if its value is changed by users, an AJAX validation may be triggered.
  * @param CModel $model the data model
  * @param string $attribute the attribute name
  * @param array $htmlOptions additional HTML attributes to be rendered in the container div tag.
  * Besides all those options available in {@link CHtml::error}, the following options are recognized in addition:
  * <ul>
  * <li>validationDelay</li>
  * <li>validateOnChange</li>
  * <li>validateOnType</li>
  * <li>hideErrorMessage</li>
  * <li>inputContainer</li>
  * <li>errorCssClass</li>
  * <li>successCssClass</li>
  * <li>validatingCssClass</li>
  * <li>beforeValidateAttribute</li>
  * <li>afterValidateAttribute</li>
  * </ul>
  * These options override the corresponding options as declared in {@link options} for this
  * particular model attribute. For more details about these options, please refer to {@link clientOptions}.
  * Note that these options are only used when {@link enableAjaxValidation} or {@link enableClientValidation}
  * is set true.
  *
  * When client-side validation is enabled, an option named "clientValidation" is also recognized.
  * This option should take a piece of JavaScript code to perform client-side validation. In the code,
  * the variables are predefined:
  * <ul>
  * <li>value: the current input value associated with this attribute.</li>
  * <li>messages: an array that may be appended with new error messages for the attribute.</li>
  * <li>attribute: a data structure keeping all client-side options for the attribute</li>
  * </ul>
  * @param boolean $enableAjaxValidation whether to enable AJAX validation for the specified attribute.
  * Note that in order to enable AJAX validation, both {@link enableAjaxValidation} and this parameter
  * must be true.
  * @param boolean $enableClientValidation whether to enable client-side validation for the specified attribute.
  * Note that in order to enable client-side validation, both {@link enableClientValidation} and this parameter
  * must be true. This parameter has been available since version 1.1.7.
  * @return string the validation result (error display or success message).
  * @see CHtml::error
  */
 public function error($model, $attribute, $htmlOptions = array(), $enableAjaxValidation = true, $enableClientValidation = true)
 {
     if (!$this->enableAjaxValidation) {
         $enableAjaxValidation = false;
     }
     if (!$this->enableClientValidation) {
         $enableClientValidation = false;
     }
     if (!isset($htmlOptions['class'])) {
         $htmlOptions['class'] = $this->errorMessageCssClass;
     }
     if (!$enableAjaxValidation && !$enableClientValidation) {
         return CHtml::error($model, $attribute, $htmlOptions);
     }
     $id = CHtml::activeId($model, $attribute);
     $inputID = isset($htmlOptions['inputID']) ? $htmlOptions['inputID'] : $id;
     unset($htmlOptions['inputID']);
     if (!isset($htmlOptions['id'])) {
         $htmlOptions['id'] = $inputID . '_em_';
     }
     $option = array('id' => $id, 'inputID' => $inputID, 'errorID' => $htmlOptions['id'], 'model' => get_class($model), 'name' => CHtml::resolveName($model, $attribute), 'enableAjaxValidation' => $enableAjaxValidation);
     $optionNames = array('validationDelay', 'validateOnChange', 'validateOnType', 'hideErrorMessage', 'inputContainer', 'errorCssClass', 'successCssClass', 'validatingCssClass', 'beforeValidateAttribute', 'afterValidateAttribute');
     foreach ($optionNames as $name) {
         if (isset($htmlOptions[$name])) {
             $option[$name] = $htmlOptions[$name];
             unset($htmlOptions[$name]);
         }
     }
     if ($model instanceof CActiveRecord && !$model->isNewRecord) {
         $option['status'] = 1;
     }
     if ($enableClientValidation) {
         $validators = isset($htmlOptions['clientValidation']) ? array($htmlOptions['clientValidation']) : array();
         foreach ($model->getValidators($attribute) as $validator) {
             if ($enableClientValidation && $validator->enableClientValidation) {
                 if (($js = $validator->clientValidateAttribute($model, $attribute)) != '') {
                     $validators[] = $js;
                 }
             }
         }
         if ($validators !== array()) {
             $option['clientValidation'] = "js:function(value, messages, attribute) {\n" . implode("\n", $validators) . "\n}";
         }
     }
     $html = CHtml::error($model, $attribute, $htmlOptions);
     if ($html === '') {
         if (isset($htmlOptions['style'])) {
             $htmlOptions['style'] = rtrim($htmlOptions['style'], ';') . ';display:none';
         } else {
             $htmlOptions['style'] = 'display:none';
         }
         $html = CHtml::tag('div', $htmlOptions, '');
     }
     $this->attributes[$inputID] = $option;
     return $html;
 }
 public function renderBoolean($field, array $htmlOptions = array())
 {
     $fieldName = $field->fieldName;
     $inputName = CHtml::resolveName($this->owner, $fieldName);
     $for = CHtml::getIdByName($inputName);
     return CHtml::label('', $for) . CHtml::activeCheckBox($this->owner, $field->fieldName, array_merge(array('unchecked' => 0, 'title' => $field->attributeLabel), $htmlOptions));
 }
Example #16
0
        <?php echo $form->error($model, 'username'); ?>
    </div>
    <div data-role="fieldcontain">
        <?php
        echo $form->label($model, 'password', array(
            'for' => CHtml::resolveName($model, $a='password')
        ));
        ?>
        <?php echo $form->passwordField($model, 'password'); ?>
        <?php echo $form->error($model, 'password'); ?>
    </div>
<!--
    <div data-role="fieldcontain">
        <?php
        echo $form->label($model, 'rememberMe', array(
            'for' => CHtml::resolveName($model, $a='rememberMe')
        ));
        ?>
        <?php
        echo $form->dropDownList($model, 'rememberMe', array(
            '0' => Yii::t('app', 'Off'),
            '1' => Yii::t('app', 'On')
                ), array(
            'data-role' => 'slider'
                )
        );
        ?>
        <?php echo $form->error($model, 'rememberMe'); ?>
    </div>
-->
        <?php echo CHtml::submitButton(Yii::t('app', 'Login')); ?>
Example #17
0
 /**
  * Renders a vertical custom field group for a model attribute.
  *
  * @param array|string $fieldData Pre-rendered field as string or array of arguments for call_user_func_array() function.
  * @param CModel $model The data model.
  * @param string $attribute The attribute.
  * @param array $options Row options.
  * 
  */
 protected function verticalGroup(&$fieldData, &$model, &$attribute, &$options)
 {
     $groupOptions = isset($options['groupOptions']) ? $options['groupOptions'] : array();
     self::addCssClass($groupOptions, 'form-group');
     $_attribute = $attribute;
     CHtml::resolveName($model, $_attribute);
     if ($model->hasErrors($_attribute) && $this->clientOptions['errorCssClass']) {
         self::addCssClass($groupOptions, $this->clientOptions['errorCssClass']);
     }
     echo CHtml::openTag('div', $groupOptions);
     self::addCssClass($options['labelOptions'], 'control-label');
     if (isset($options['label'])) {
         if (!empty($options['label'])) {
             echo CHtml::label($options['label'], CHtml::activeId($model, $attribute), $options['labelOptions']);
         }
     } else {
         echo $this->labelEx($model, $attribute, $options['labelOptions']);
     }
     if (isset($options['wrapperHtmlOptions']) && !empty($options['wrapperHtmlOptions'])) {
         $wrapperHtmlOptions = $options['wrapperHtmlOptions'];
     } else {
         $wrapperHtmlOptions = $options['wrapperHtmlOptions'] = array();
     }
     echo CHtml::openTag('div', $wrapperHtmlOptions);
     if (!empty($options['prepend']) || !empty($options['append'])) {
         $this->renderAddOnBegin($options['prepend'], $options['append'], $options['prependOptions']);
     }
     if (is_array($fieldData)) {
         echo call_user_func_array($fieldData[0], $fieldData[1]);
     } else {
         echo $fieldData;
     }
     if (!empty($options['prepend']) || !empty($options['append'])) {
         $this->renderAddOnEnd($options['append'], $options['appendOptions']);
     }
     if ($this->showErrors && $options['errorOptions'] !== false) {
         echo $this->error($model, $attribute, $options['errorOptions'], $options['enableAjaxValidation'], $options['enableClientValidation']);
     }
     if (isset($options['hint'])) {
         self::addCssClass($options['hintOptions'], $this->hintCssClass);
         echo CHtml::tag($this->hintTag, $options['hintOptions'], $options['hint']);
     }
     echo '</div></div>';
 }
Example #18
0
 /**
  * Displays the first validation error for a model attribute.
  * @param CModel $model the data model
  * @param string $attribute the attribute name
  * @param array $htmlOptions additional HTML attributes to be rendered in the container div tag.
  * @param string $tag the tag to use for rendering the error.
  * @return string the error display. Empty if no errors are found.
  * @see CModel::getErrors
  * @see errorMessageCss
  */
 public static function getErrorHtml($model, $attribute, $htmlOptions = array())
 {
     CHtml::resolveName($model, $attribute);
     $error = $model->getError($attribute);
     if ($error !== null) {
         return CHtml::tag('span', $htmlOptions, $error);
     } else {
         return '';
     }
 }
Example #19
0
 * "Powered by X2Engine".
 *****************************************************************************************/
$namespacedId = $this->htmlOptions['id'];
Yii::app()->clientScript->registerScript('multiTypeAutocompleteJS' . $this->namespace, "\n\n\$(function () {\n    var container\$ = \$('#" . $namespacedId . "');\n    var excludeList = " . CJSON::encode($this->staticOptions) . ";\n\n    container\$.find ('select').change (function () {\n        var autocomplete\$ = container\$.find ('.record-name-autocomplete');\n        var modelType = container\$.find ('select').val ();\n        if (\$.inArray (modelType, excludeList) >= 0) {\n            container\$.find ('input').css ('visibility', 'hidden')\n            return;\n        }\n        var throbber\$ = x2.forms.inputLoading (container\$.find ('.record-name-autocomplete'));\n        \$.ajax ({\n            type: 'GET',\n            url: '" . Yii::app()->controller->createUrl('ajaxGetModelAutocomplete') . "',\n            data: {\n                modelType: modelType\n            },\n            success: function (data) {\n                if (data === 'failure') {\n                    autocomplete\$.attr ('disabled', 'disabled');\n                    autocomplete\$.siblings ('label').hide ();\n                } else {\n                    autocomplete\$.siblings ('label').show ();\n                    // remove span element used by jQuery widget\n                    container\$.find ('input').\n                        first ().next ('span').remove ();\n\n                    // replace old autocomplete with the new one\n                    container\$.find ('input').first ().replaceWith (data); \n         \n                }\n                // remove the loading gif\n                throbber\$.remove ();\n            }\n        });\n    });\n});\n\n", CClientScript::POS_END);
echo CHtml::openTag('div', X2Html::mergeHtmlOptions(array('class' => "multi-type-autocomplete-container", 'id' => $namespacedId), $this->htmlOptions));
if (isset($this->model)) {
    echo CHtml::activeDropDownList($this->model, $this->selectName, $this->options, array('class' => ''));
} else {
    echo CHtml::dropDownList($this->selectName, $this->selectValue, $this->options, array('class' => 'x2-select type-select'));
}
$htmlOptions = array();
if (isset($this->model)) {
    echo CHtml::activeLabel($this->model, $this->autocompleteName, array('style' => $this->selectValue === 'calendar' ? 'display: none;' : ''));
}
if (isset($this->autocompleteName)) {
    $htmlOptions['name'] = isset($this->model) ? CHtml::resolveName($this->model, $this->autocompleteName) : $this->autocompleteName;
}
if ($this->selectValue === 'calendar') {
    $htmlOptions['disabled'] = 'disabled';
    $htmlOptions['style'] = 'display: none;';
    $this->selectValue = 'Contacts';
}
if (!in_array($this->selectValue, $this->staticOptions)) {
    X2Model::renderModelAutocomplete($this->selectValue, false, $htmlOptions, $this->autocompleteValue);
} else {
    ?>
        <input class="record-name-autocomplete" type="hidden"></input>
        <?php 
}
if (isset($this->model)) {
    echo CHtml::activeHiddenField($this->model, $this->hiddenInputName, array('class' => 'hidden-id'));
Example #20
0
 /**
  * Clears remember me cookies and redirects to login page. 
  */
 public function actionForgetMe()
 {
     $loginForm = new LoginForm();
     foreach (array('username', 'rememberMe') as $attr) {
         // Remove the cookie if they unchecked the box
         AuxLib::clearCookie(CHtml::resolveName($loginForm, $attr));
     }
     $this->redirect(array('login'));
 }
Example #21
0
 public function testResolveName()
 {
     $testModel = new CHtmlTestFormModel();
     $attrName = 'stringAttr';
     $this->assertEquals('CHtmlTestFormModel[stringAttr]', CHtml::resolveName($testModel, $attrName));
     $this->assertEquals('stringAttr', $attrName);
     $attrName = 'arrayAttr[k1]';
     $this->assertEquals('CHtmlTestFormModel[arrayAttr][k1]', CHtml::resolveName($testModel, $attrName));
     $this->assertEquals('arrayAttr[k1]', $attrName);
     $attrName = 'arrayAttr[k3][k5]';
     $this->assertEquals('CHtmlTestFormModel[arrayAttr][k3][k5]', CHtml::resolveName($testModel, $attrName));
     $this->assertEquals('arrayAttr[k3][k5]', $attrName);
     $attrName = '[k3][k4]arrayAttr';
     $this->assertEquals('CHtmlTestFormModel[k3][k4][arrayAttr]', CHtml::resolveName($testModel, $attrName));
     $this->assertEquals('arrayAttr', $attrName);
     $attrName = '[k3]arrayAttr[k4]';
     $this->assertEquals('CHtmlTestFormModel[k3][arrayAttr][k4]', CHtml::resolveName($testModel, $attrName));
     $this->assertEquals('arrayAttr[k4]', $attrName);
     // next two asserts gives 100% code coverage of the CHtml::resolveName() method
     // otherwise penultimate line (last closing curly bracket) of the CHtml::resolveName() will not be unit tested
     $attrName = '[k3';
     $this->assertEquals('CHtmlTestFormModel[[k3]', CHtml::resolveName($testModel, $attrName));
     $this->assertEquals('[k3', $attrName);
 }
Example #22
0
 /**
  * Displays the first validation error for a model attribute.
  * @param CModel $model the data model.
  * @param string $attribute the attribute name.
  * @param array $htmlOptions additional HTML attributes.
  * @return string the rendered error. Empty if no errors are found.
  */
 public static function error($model, $attribute, $htmlOptions = array())
 {
     parent::resolveName($model, $attribute);
     // turn [a][b]attr into attr
     $error = $model->getError($attribute);
     return !empty($error) ? self::help($error, $htmlOptions) : '';
 }
Example #23
0
 /**
  * Displays the first validation error for a model attribute.
  * @param CModel $model the data model
  * @param string $attribute the attribute name
  * @param array $htmlOptions additional HTML attributes to be rendered in the container div tag.
  * @return string the error display. Empty if no errors are found.
  * @see CModel::getErrors
  * @see errorMessageCss
  */
 protected static function renderError($model, $attribute, $htmlOptions = array())
 {
     CHtml::resolveName($model, $attribute);
     // turn [a][b]attr into attr
     $error = $model->getError($attribute);
     if (self::$showError == true) {
         return $error != '' ? CHtml::tag('span', $htmlOptions, $error) : '';
     }
 }
Example #24
0
 protected function radioButton()
 {
     echo '<div class="input"><div class="inputs-list">';
     echo '<label for="' . CHtml::getIdByName(CHtml::resolveName($this->model, $this->attribute)) . '">';
     echo $this->form->radioButton($this->model, $this->attribute, $this->htmlOptions) . ' ';
     echo '<span>' . $this->model->getAttributeLabel($this->attribute) . '</span>';
     echo $this->getError() . $this->getHint();
     echo '</label></div></div>';
 }
 /**
  * Returns all uploaded files for the given model attribute.
  * @param CModel $model the model instance
  * @param string $attribute the attribute name. For tabular file uploading, this can be in the format of "[$i]attributeName", where $i stands for an integer index.
  * @return array array of CUploadedFile objects.
  * Empty array is returned if no available file was found for the given attribute.
  */
 public static function getInstances($model, $attribute)
 {
     return self::getInstancesByName(CHtml::resolveName($model, $attribute));
 }
Example #26
0
        }
        ?>
</div></div><?php 
        echo '<br />';
        echo CHtml::activeLabel($model, 'data');
        echo CHtml::activeTextArea($model, 'data', array('id' => 'custom-field-template'));
        echo '<br />' . Yii::t('admin', 'The template defines how the field will be displayed in X2Engine. The type defines how to interpret the template. If the type is Formula, it will be interpreted as an X2Workflow formula.');
        echo '<br /><br />';
        break;
}
if ($model->type != 'timerSum') {
    $dummyFieldName = 'customized_field';
    foreach ($model->getErrors('defaultValue') as $index => $message) {
        $dummyModel->addError('customized_field', $message);
    }
    echo CHtml::label($model->getAttributeLabel('defaultValue'), CHtml::resolveName($dummyModel, $dummyFieldName));
    $model->fieldName = 'customized_field';
    echo X2Model::renderModelInput($dummyModel, $model, array('id' => 'defaultValue-input-' . $model->type));
    echo CHtml::error($dummyModel, 'customized_field');
}
echo "<script id=\"input-clientscript-" . time() . "\">\n";
Yii::app()->clientScript->echoScripts();
echo "\n</script>";
?>
            </div>
        <br>

        <?php 
if ($model->type != 'timerSum') {
    ?>
            <div class="row">
Example #27
0
 /**
  * Displays the first validation error for a model attribute.
  * @param CModel $model the data model
  * @param string $attribute the attribute name
  * @param array $htmlOptions additional HTML attributes to be rendered in the container div tag.
  * This parameter has been available since version 1.0.7.
  * @return string the error display. Empty if no errors are found.
  * @see CModel::getErrors
  * @see errorMessageCss
  */
 public static function errorSpan($model, $attribute, $htmlOptions = array())
 {
     CHtml::resolveName($model, $attribute);
     $error = $model->getError($attribute);
     if ($error !== null) {
         if (!isset($htmlOptions['class'])) {
             $htmlOptions['class'] = 'help-inline';
         }
         return CHtml::tag('span', $htmlOptions, $error);
         // Bootstrap errors must be spans
     } else {
         return '';
     }
 }
Example #28
0
 /**
  * Generates a valid HTML ID based for a model attribute.
  * Note, the attribute name may be modified after calling this method if the name
  * contains square brackets (mainly used in tabular input) before the real attribute name.
  * @param CModel $model the data model
  * @param string $attribute the attribute
  * @return string the ID generated based on name.
  */
 public static function resolveId($model, $attribute)
 {
     return CHtml::getIdByName(CHtml::resolveName($model, $attribute));
 }
Example #29
0
 /**
  *### .getContainerCssClass()
  *
  * Returns the container CSS class for the input.
  *
  * @return string the CSS class
  */
 protected function getContainerCssClass()
 {
     $attribute = $this->attribute;
     return $this->model->hasErrors(CHtml::resolveName($this->model, $attribute)) ? CHtml::$errorCss : '';
 }
Example #30
0
 /**
  * Renders a radio button.
  * @return string the rendered content
  */
 protected function radioButton()
 {
     $attribute = $this->attribute;
     echo '<label class="radio" for="' . CHtml::getIdByName(CHtml::resolveName($this->model, $attribute)) . '">';
     echo $this->form->radioButton($this->model, $this->attribute, $this->htmlOptions) . PHP_EOL;
     echo $this->model->getAttributeLabel($attribute);
     echo $this->getError() . $this->getHint();
     echo '</label>';
 }