/**
  * @param CActiveRecord $model
  * @param $sortableAttribute
  * @param $sortOrderData
  *
  * @return string
  */
 private function update($model, $sortableAttribute, $sortOrderData)
 {
     $pk = $model->tableSchema->primaryKey;
     $pk_array = array();
     if (is_array($pk)) {
         // composite key
         $string_ids = array_keys($sortOrderData);
         $array_ids = array();
         foreach ($string_ids as $string_id) {
             $array_ids[] = explode(',', $string_id);
         }
         foreach ($array_ids as $array_id) {
             $pk_array[] = array_combine($pk, $array_id);
         }
     } else {
         // normal key
         $pk_array = array_keys($sortOrderData);
     }
     $models = $model->model()->findAllByPk($pk_array);
     $transaction = Yii::app()->db->beginTransaction();
     try {
         foreach ($models as $model) {
             $_key = is_array($pk) ? implode(',', array_values($model->primaryKey)) : $model->primaryKey;
             $model->{$sortableAttribute} = $sortOrderData[$_key];
             $model->save();
         }
         $transaction->commit();
     } catch (Exception $e) {
         // an exception is raised if a query fails
         $transaction->rollback();
     }
 }
Example #2
1
 public function run($action, $to, $id)
 {
     $to = CActiveRecord::model($this->getController()->CQtreeGreedView['modelClassName'])->findByPk((int) $to);
     $moved = CActiveRecord::model($this->getController()->CQtreeGreedView['modelClassName'])->findByPk((int) $id);
     if (!is_null($to) && !is_null($moved)) {
         try {
             switch ($action) {
                 case 'child':
                     $moved->moveAsLast($to);
                     break;
                 case 'before':
                     if ($to->isRoot()) {
                         $moved->moveAsRoot();
                     } else {
                         $moved->moveBefore($to);
                     }
                     break;
                 case 'after':
                     if ($to->isRoot()) {
                         $moved->moveAsRoot();
                     } else {
                         $moved->moveAfter($to);
                     }
                     break;
             }
         } catch (Exception $e) {
             Yii::app()->user->setFlash('CQTeeGridView', $e->getMessage());
         }
     }
     $this->getController()->redirect(array($this->getController()->CQtreeGreedView['adminAction']));
 }
Example #3
0
 /**
  * @return CActiveRecord
  */
 private function getModelInstance()
 {
     if (!isset($this->commentModelClass)) {
         throw new CException(Yii::t('yiiext', 'commentModelClass should be defined.'));
     }
     return CActiveRecord::model($this->commentModelClass);
 }
 /**
  * Returns the static model of the specified AR class.
  *
  * @param string $className
  * @return YdActiveRecord the static model class
  */
 public static function model($className = null)
 {
     if (!$className) {
         $className = get_called_class();
     }
     return parent::model($className);
 }
Example #5
0
 public function validateModel($attribute, $params)
 {
     if ($this->hasErrors('model')) {
         return;
     }
     $class = @Yii::import($this->model, true);
     if (!is_string($class) || !$this->classExists($class)) {
         $this->addError('model', "Class '{$this->model}' does not exist or has syntax error.");
     } else {
         if (!is_subclass_of($class, 'CActiveRecord')) {
             $this->addError('model', "'{$this->model}' must extend from CActiveRecord.");
         } else {
             $table = CActiveRecord::model($class)->tableSchema;
             if ($table->primaryKey === null) {
                 $this->addError('model', "Table '{$table->name}' does not have a primary key.");
             } else {
                 if (is_array($table->primaryKey)) {
                     $this->addError('model', "Table '{$table->name}' has a composite primary key which is not supported by crud generator.");
                 } else {
                     $this->_modelClass = $class;
                     $this->_table = $table;
                 }
             }
         }
     }
 }
 /**
  * Validates composite unique keys
  */
 public function validateCompositeUniqueKeys()
 {
     $this->_normalizeKeysData();
     $object = $this->getOwner();
     foreach ($this->uniqueKeys as $uk) {
         // check whether validation of the current key should be skipped
         foreach ($uk['skipOnErrorIn'] as $skipAttr) {
             if ($object->getError($skipAttr)) {
                 continue 2;
             }
         }
         $criteria = new CDbCriteria();
         foreach ($uk['attributes'] as $attr) {
             if ($object->{$attr} === null) {
                 $criteria->addCondition("`{$attr}`" . ' is null');
             } else {
                 $criteria->compare("`{$attr}`", $object->{$attr});
             }
         }
         /*
          * if the model is a new record or if it's an old record with modified unique key value
          * then the composite key should be unique ($criteriaLimit = 0)
          *
          * if we are updating an existing record without changes of unique key attributes
          * then we should allow one existing record satisfying the criteria
          */
         $ukIsChanged = !$object->isNewRecord && $uk['oldValue'] != $this->_getUkValue($uk['attributes']);
         $criteriaLimit = $object->isNewRecord || $ukIsChanged ? 0 : 1;
         if (CActiveRecord::model(get_class($object))->count($criteria) > $criteriaLimit) {
             foreach ($uk['errorAttributes'] as $attr) {
                 $object->addError($attr, $uk['errorMessage']);
             }
         }
     }
 }
Example #7
0
 public function run($id = false, $model = false, $forceDelete = false)
 {
     $modelName = $this->model && is_string($this->model) ? $this->model : (request()->getParam('model') ? request()->getParam('model') : $this->controller->model);
     if ($id) {
         //delete one model
         $result = $this->controller->loadModel($modelName, $id)->delete();
         if (!request()->isAjaxRequest && $result) {
             $this->controller->redirect(user()->gridIndex);
         }
         Common::jsonSuccess(true);
     } else {
         $items = Common::getChecked('items');
         if ($items) {
             if (!$forceDelete) {
                 foreach ($items as $id) {
                     $this->controller->loadModel($modelName, $id)->delete();
                 }
             } else {
                 $criteria = new SDbCriteria();
                 $criteria->compare('id', $items);
                 CActiveRecord::model($modelName)->deleteAll($criteria);
             }
             Common::jsonSuccess(true);
         }
     }
     Common::jsonError("Ошибка");
 }
 public function suggestIdentifier($model)
 {
     if (!$model instanceof CActiveRecord) {
         $model = CActiveRecord::model(Yii::import($model));
     }
     if (is_callable(array($model, 'getItemLabel'))) {
         return 'itemLabel';
     }
     $nonNumericFound = false;
     $columns = $model->tableSchema->columns;
     foreach ($columns as $column) {
         if ($column->isPrimaryKey) {
             $fallbackName = $column->name;
         }
         // Use the first non-numeric column as a fallback
         if (!$column->isForeignKey && !$column->isPrimaryKey && $column->type != 'BIGINT' && $column->type != 'INT' && $column->type != 'INTEGER' && $column->type != 'BOOLEAN' && !$nonNumericFound) {
             $fallbackName = $column->name;
             $nonNumericFound = true;
         }
         // Return the first title, name, label column, if found
         if (in_array($column->name, array("title", "name", "label"))) {
             $fallbackName = $column->name;
             break;
         }
     }
     return $fallbackName;
 }
Example #9
0
 /**
  * @param CActiveRecord $modelClass
  * @param CDbColumnSchema $column
  */
 public function generateValueField($modelClass, $column, $view = false)
 {
     if ($column->isForeignKey) {
         $model = CActiveRecord::model($modelClass);
         $table = $model->getTableSchema();
         $fk = $table->foreignKeys[$column->name];
         $fmodel = CActiveRecord::model(ucfirst($fk[0]));
         $modelTable = ucfirst($fmodel->tableName());
         $fcolumns = $fmodel->attributeNames();
         //$rel = $model->getActiveRelation($column->name);
         $relname = strtolower($fk[0]);
         foreach ($model->relations() as $key => $value) {
             if (strcasecmp($value[2], $column->name) == 0) {
                 $relname = $key;
             }
         }
         //return("\$model->{$relname}->{$fcolumns[1]}");
         //return("CHtml::value(\$model,\"{$relname}.{$fcolumns[1]}\")");
         //return("{$relname}.{$fcolumns[1]}");
         if ($view) {
             return "\n\t\t\t\t\tarray(\n\t\t\t\t\t\t\t'name'=>'{$column->name}',\n\t\t\t\t\t\t\t'value'=>CHtml::value(\$model,'{$relname}.{$fcolumns[1]}'),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t";
         } else {
             return "\n\t\t\t\t\tarray(\n\t\t\t\t\t\t\t'name'=>'{$column->name}',\n\t\t\t\t\t\t\t'value'=>'\$data->{$relname}->{$fcolumns[1]}',\n\t\t\t\t\t\t\t'filter'=>CHtml::listData({$modelTable}::model()->findAll(), '{$fcolumns[0]}', '{$fcolumns[1]}'),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t";
         }
         //{$relname}.{$fcolumns[1]}
     } elseif (strtoupper($column->dbType) == 'BOOLEAN' or strtoupper($column->dbType) == 'TINYINT(1)' or strtoupper($column->dbType) == 'BIT') {
         if ($view) {
             return "\n\t\t\t\t\tarray(\n\t\t\t\t\t\t\t'name'=>'{$column->name}',\n\t\t\t\t\t\t\t'value'=>\$model->{$column->name}?Yii::t('app', 'Yes'):Yii::t('app', 'No'),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t";
         } else {
             return "\n\t\t\t\t\tarray(\n\t\t\t\t\t\t\t'name'=>'{$column->name}',\n\t\t\t\t\t\t\t'value'=>'\$data->{$column->name}?Yii::t('app','Yes'):Yii::t('app', 'No')',\n\t\t\t\t\t\t\t\t'filter'=>array('0'=>Yii::t('app','No'),'1'=>Yii::t('app','Yes')),\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t";
         }
     } else {
         return "'" . $column->name . "'";
     }
 }
Example #10
0
 /**
  * This is the default 'index' action that is invoked
  * when an action is not explicitly requested by users.
  */
 public function actionIndex()
 {
     $buscar = new BuscarPeliculaForm();
     if (isset($_POST['BuscarPeliculaForm'])) {
         $buscar->attributes = $_POST['BuscarPeliculaForm'];
         if ($buscar->validate()) {
             // Hacer consulta y redireccionar con resultados
             switch ($buscar->param) {
                 case "titulo":
                     $peliculas = CActiveRecord::model("Pelicula")->findAll('titulo LIKE "%' . $buscar->value . '%"');
                     break;
                 case "agno":
                     $peliculas = CActiveRecord::model("Pelicula")->findAll('agno LIKE "%' . $buscar->value . '%"');
                     break;
             }
             $this->render('index', array("msg" => "Busco " . $buscar->value . " por " . $buscar->param, "peliculas" => $peliculas, "buscar" => $buscar));
         } else {
             $peliculas = CActiveRecord::model("Pelicula")->findAll();
             $this->render('index', array("msg" => "Ultimas añadidas", "peliculas" => $peliculas, "buscar" => $buscar));
         }
     } else {
         $peliculas = CActiveRecord::model("Pelicula")->findAll();
         $this->render('index', array("msg" => "Ultimas añadidas", "peliculas" => $peliculas, "buscar" => $buscar));
     }
 }
Example #11
0
 public function testTags()
 {
     $model = $this->newModel();
     $tags = array('#this', '#that');
     // Test adding:
     //		ob_start();
     $realModel = $this->contacts('testAnyone');
     $response = $model->addTags('Contacts', $realModel->id, $tags);
     $tagTable = CActiveRecord::model('Tags')->tableName();
     $tagsOnServer = Yii::app()->db->createCommand()->select('tag')->from($tagTable)->where('itemId=:itemId AND type=:itemType', array(':itemId' => $realModel->id, ':itemType' => get_class($realModel)))->queryColumn();
     //		var_dump($tags);
     //		var_dump($tagsOnServer);
     //		print_r(json_decode($response,1));
     $tagsNotAdded = array_diff($tags, $tagsOnServer);
     $this->assertEmpty($tagsNotAdded, 'Failed asserting that tags were saved on the server.');
     // Test getting:
     $tagsFromServer = $model->getTags('Contacts', $this->contacts('testAnyone')->id);
     //		ob_end_clean();
     //		var_dump($tagsFromServer);
     //		var_dump($tagsOnServer);
     $tagsNotRetrieved = array_diff($tagsOnServer, $tagsFromServer);
     $this->assertEmpty($tagsNotRetrieved, 'Failed asserting that all tags were properly retrieved.');
     // Test deleting:
     $response = $model->removeTag('Contacts', $this->contacts('testAnyone')->id, '#this');
     $tagsOnServer = Yii::app()->db->createCommand()->select('tag')->from($tagTable)->where('itemId=:itemId AND type=:itemType', array(':itemId' => $realModel->id, ':itemType' => get_class($realModel)))->queryColumn();
     $tagsDeleted = array_diff($tags, $tagsOnServer);
     //		var_dump($response);
     //		var_dump($tagsDeleted);
     $this->assertEquals(1, count($tagsDeleted), 'Failed asserting that one and only one tag was deleted.');
     $this->assertEquals('#this', $tagsDeleted[0], 'Failed asserting that the right tag got deleted.');
 }
Example #12
0
 public function actionIndex()
 {
     $criteria = $this->getIndexCriteria();
     $dataProvider = new CActiveDataProvider($this->getModelClass(), array('criteria' => $criteria, 'pagination' => array('pageSize' => $this->getPagesize(), 'pageVar' => 'page')));
     list($downloadSum, $totalPriceSum) = CActiveRecord::model($this->getModelClass())->sum(array('download_number', 'total_price'), $criteria);
     /*模糊搜索start*/
     $filter = $this->getFilterCondition();
     $cp_id = $filter['cp_id'];
     $adv_id = $filter['adv_id'];
     /*获得满足$cp_id的Advertise 10-28*/
     $cpadv = new CDbCriteria();
     $cpadv->order = 'id ASC';
     $cpadv->compare('cp_id', $cp_id);
     $advertises = Advertise::model()->findAll($cpadv);
     /*获得满足$adv_id的Channel 10-28*/
     $criteria = new CDbCriteria();
     $criteria->select = "channel_id";
     $criteria->order = "channel_id asc";
     $criteria->compare('adv_id', $adv_id);
     $criteria->distinct = true;
     $advtertises = AdvertiseChannel::model()->findAll($criteria);
     $i = 0;
     foreach ($advtertises as $a) {
         $arr[$i] = $a->channel->id;
         $i++;
     }
     $criter = new CDbCriteria();
     $criter->addInCondition('id', $arr);
     $criter->order = "name desc";
     $criter->distinct = true;
     $channels = Channel::model()->findAll($criter);
     /*10-28 end*/
     $this->render('/report/index', array('downloadSum' => $downloadSum ? $downloadSum : '0', 'totalPriceSum' => $totalPriceSum ? $totalPriceSum : '0.00', 'dataProvider' => $dataProvider, 'filter' => $filter, 'cp' => CP::model()->findAll(), 'advertises' => $advertises, 'channels' => $channels, 'attributes' => $this->getAdminAttributes()));
 }
Example #13
0
 protected function validateAttribute($object, $attribute)
 {
     $value = $object->{$attribute};
     if ($this->allowEmpty && $this->isEmpty($value)) {
         return;
     }
     $className = $this->className === null ? get_class($object) : Yii::import($this->className);
     $attributeName = $this->attributeName === null ? $attribute : $this->attributeName;
     $finder = CActiveRecord::model($className);
     $table = $finder->getTableSchema();
     if (!is_array($attributeName)) {
         $attributeName = array($attributeName);
     }
     $condition = array();
     foreach ($attributeName as $aN) {
         if (($column = $table->getColumn($aN)) === null) {
             throw new CException(Yii::t('yii', 'Table "{table}" does not have a column named "{column}".', array('{column}' => $aN, '{table}' => $table->name)));
         }
         $condition[] = $column->rawName . '=:vp';
     }
     $criteria = array('condition' => implode(' OR ', $condition), 'params' => array(':vp' => $value));
     if ($this->criteria !== array()) {
         $criteria = new CDbCriteria($criteria);
         $criteria->mergeWith($this->criteria);
     }
     if (!$finder->exists($criteria)) {
         $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} "{value}" is invalid.');
         $this->addError($object, $attribute, $message, array('{value}' => $value));
     }
 }
 /**
  * Authentication
  * @return bool
  */
 public function authenticate()
 {
     /** @var AccountModule $account */
     $account = Yii::app()->getModule('account');
     /** @var AccountUser $user */
     $user = CActiveRecord::model($account->userClass)->find('(LOWER(username)=? OR LOWER(email)=?)', array(strtolower($this->username), strtolower($this->username)));
     if (!$user) {
         $this->errorCode = self::ERROR_USERNAME_INVALID;
         return false;
     }
     if ($account->activatedField && !$user->{$account->activatedField}) {
         $this->errorCode = self::ERROR_NOT_ACTIVATED;
         return false;
     }
     if ($account->disabledField && $user->{$account->disabledField}) {
         $this->errorCode = self::ERROR_DISABLED;
         return false;
     }
     if (!$this->skipPassword && !CPasswordHelper::verifyPassword($this->password, $user->{$account->passwordField})) {
         $this->errorCode = self::ERROR_PASSWORD_INVALID;
         return false;
     }
     $this->_id = $user->primaryKey;
     $this->username = $account->usernameField && $user->{$account->usernameField} ? $user->{$account->usernameField} : $user->{$account->emailField};
     $this->errorCode = self::ERROR_NONE;
     return true;
 }
Example #15
0
 /**
  * @param CModel $object the object being validated
  * @param string $attribute if there is an validation error then error message
  * will be added to this property
  */
 protected function validateAttribute($object, $attribute)
 {
     $class = get_class($object);
     Yii::import($class);
     $keyColumns = explode(',', $this->keyColumns);
     if (count($keyColumns) == 1) {
         throw new CException('CUniqueValidator should be used instead');
     }
     $columnsLabels = $object->attributeLabels();
     $criteria = new CDbCriteria();
     $keyColumnsLabels = array();
     foreach ($keyColumns as &$column) {
         $column = trim($column);
         $criteria->compare($column, $object->{$column});
         $keyColumnsLabels[] = $columnsLabels[$column];
     }
     unset($column);
     $criteria->limit = 1;
     if (CActiveRecord::model($class)->count($criteria)) {
         $message = Yii::t('yii', $this->errorMessage, array('{columns_labels}' => join(', ', $keyColumnsLabels)));
         if ($this->addErrorToAllColumns) {
             foreach ($keyColumns as $column) {
                 $this->addError($object, $column, $message);
             }
         } else {
             $this->addError($object, $attribute, $message);
         }
     }
 }
Example #16
0
    public function run() 
    {
		$modelClassName = $this->getController()->CQtreeGreedView['modelClassName'];
        $model = new $modelClassName();
        
		$model->scenario = 'create';
        $this->getController()->performAjaxValidation($model);
    	
        if (isset($_POST[$this->getController()->CQtreeGreedView['modelClassName']])) {
            $model->attributes = $_POST[$this->getController()->CQtreeGreedView['modelClassName']];

            try {
                if ($model->tree->hasManyRoots == true) {
                	if ($model->saveNode()) {
                        $this->getController()->redirect(array($this->getController()->CQtreeGreedView['adminAction']));
                    }
                } else {
                    $root = CActiveRecord::model($this->getController()->CQtreeGreedView['modelClassName'])->roots()->find();

                    if ($root && $model->appendTo($root)) {
                        $this->getController()->redirect(array($this->getController()->CQtreeGreedView['adminAction']));
                    }
                }
            } catch (Exception $e) {
                $model->addError("CQTeeGridView", $e->getMessage());
            }
        }

        $this->getController()->render('create', array(
            'model' => $model,
        ));
    }
Example #17
0
 public function generateActiveRow($modelClass, $column)
 {
     if ($column->type === 'boolean') {
         return "\$form->checkBoxRow(\$model, '{$column->name}', array('class' => 'popover-help', 'data-original-title' => \$model->getAttributeLabel('{$column->name}'), 'data-content' => \$model->getAttributeDescription('{$column->name}')))";
     } else {
         if (stripos($column->dbType, 'text') !== false) {
             return "\$form->textAreaRow(\$model, '{$column->name}', array('class' => 'span5 popover-help', 'rows' => 6, 'cols' => 50, 'data-original-title' => \$model->getAttributeLabel('{$column->name}'), 'data-content' => \$model->getAttributeDescription('{$column->name}')))";
         } else {
             if ($column->isForeignKey) {
                 $relations = CActiveRecord::model($modelClass)->relations();
                 foreach ($relations as $key => $relation) {
                     if ($relation[0] == 'CBelongsToRelation' && $relation[2] == $column->name) {
                         $relationModel = CActiveRecord::model($relation[1]);
                         $suggestedName = $this->suggestName($relationModel->tableSchema->columns)->name;
                         return "\$form->dropDownListRow(\$model, '{$relation[2]}', CHtml::listData({$relation['1']}::model()->findAll(), 'id', '{$suggestedName}'))";
                     }
                 }
             } else {
                 if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) {
                     $inputField = 'passwordFieldRow';
                 } else {
                     $inputField = 'textFieldRow';
                 }
                 if ($column->type !== 'string' || $column->size === null) {
                     return "\$form->{$inputField}(\$model, '{$column->name}', array('class' => 'span3 popover-help', 'size' => 60, 'maxlength' => 60, 'data-original-title' => \$model->getAttributeLabel('{$column->name}'), 'data-content' => \$model->getAttributeDescription('{$column->name}')))";
                 } else {
                     return "\$form->{$inputField}(\$model, '{$column->name}', array('class' => 'span3 popover-help', 'size' => 60, 'maxlength' => {$column->size}, 'data-original-title' => \$model->getAttributeLabel('{$column->name}'), 'data-content' => \$model->getAttributeDescription('{$column->name}')))";
                 }
             }
         }
     }
 }
 /**
  * @param CModel $object
  * @param string $attribute
  */
 protected function validateAttribute($object, $attribute)
 {
     if (!array_key_exists('site_id', $object->attributes) || !array_key_exists('firm_id', $object->attributes)) {
         $this->addError($object, $attribute, get_class($object) . ' is missing site_id or firm_id');
         return;
     }
     if ($this->message === null) {
         $this->message = 'Site and Firm must be unique for each object';
     }
     $siteId = $object->site_id;
     $firmId = $object->firm_id;
     $finder = CActiveRecord::model(get_class($object));
     $criteria = new CDbCriteria();
     $criteria->condition = 'site_id = :siteId AND firm_id = :firmId';
     $criteria->params = array('siteId' => $siteId, 'firmId' => $firmId);
     $found = $finder->findAll($criteria);
     if (count($found) === 0) {
         //No items found, so must be unique
         return;
     }
     if (count($found) > 1) {
         //More than one item found, definitely not unique
         $this->addError($object, $attribute, $this->message);
         return;
     }
     $foundObject = array_shift($found);
     if ($foundObject->id !== $object->id) {
         //Object exists and is not the one currently be validated so not unique
         $this->addError($object, $attribute, $this->message);
         return;
     }
 }
Example #19
0
 /**
  * Displays the assignments for the user with the given id.
  * @param string $id the user id.
  */
 public function actionView($id)
 {
     $formModel = new AddAuthItemForm();
     /* @var $am CAuthManager|AuthBehavior */
     $am = Yii::app()->getAuthManager();
     if (isset($_POST['AddAuthItemForm'])) {
         $formModel->attributes = $_POST['AddAuthItemForm'];
         if ($formModel->validate()) {
             if (!$am->isAssigned($formModel->items, $id)) {
                 $am->assign($formModel->items, $id);
                 if ($am instanceof CPhpAuthManager) {
                     $am->save();
                 }
                 if ($am instanceof ICachedAuthManager) {
                     $am->flushAccess($formModel->items, $id);
                 }
             }
         }
     }
     $model = CActiveRecord::model($this->module->userClass)->findByPk($id);
     $assignments = $am->getAuthAssignments($id);
     $authItems = $am->getItemsPermissions(array_keys($assignments));
     $authItemDp = new AuthItemDataProvider();
     $authItemDp->setAuthItems($authItems);
     $assignmentOptions = $this->getAssignmentOptions($id);
     if (!empty($assignmentOptions)) {
         $assignmentOptions = array_merge(array('' => Yii::t('AuthModule.main', 'Select item') . ' ...'), $assignmentOptions);
     }
     $this->render('view', array('model' => $model, 'authItemDp' => $authItemDp, 'formModel' => $formModel, 'assignmentOptions' => $assignmentOptions));
 }
Example #20
0
 /**
  * Default action.
  *
  * Will be called either by `yiic testmail index` or just by `yiic testmail`.
  */
 public function actionIndex()
 {
     $config = (require ROOT_DIR . '/common/config/main.php');
     $table_names_man = array('UserDetail', 'Wallet', 'RecoveryRequest', 'Address', 'Fiat', 'Transaction', 'User');
     $model_files = array_merge(glob(ROOT_DIR . '/common/models/*.php'), glob(ROOT_DIR . '/frontend/models/*.php'));
     foreach ($model_files as $model_filename) {
         $model_name = basename(str_replace(".php", "", $model_filename));
         if (stristr($model_name, 'Form')) {
             continue;
         }
         try {
             $model = CActiveRecord::model($model_name);
             if ($model) {
                 $tblname = $model->tableSchema->rawName;
                 Yii::app()->db->createCommand("DROP TABLE {$tblname}")->execute();
             }
         } catch (Exception $e) {
             echo "\n{$e}\n";
         }
     }
     try {
         Yii::app()->db->createCommand("DROP TABLE tbl_migration")->execute();
     } catch (Exception $e) {
     }
 }
Example #21
0
 /**
  * Validates the attribute of the object.
  * If there is any error, the error message is added to the object.
  * @param CModel $object the object being validated
  * @param string $attribute the attribute being validated
  */
 protected function validateAttribute($object, $attribute)
 {
     $value = $object->{$attribute};
     if ($this->allowEmpty && $this->isEmpty($value)) {
         return;
     }
     $className = $this->className === null ? get_class($object) : Yii::import($this->className);
     $attributeName = $this->attributeName === null ? $attribute : $this->attributeName;
     $finder = CActiveRecord::model($className);
     $table = $finder->getTableSchema();
     if (($column = $table->getColumn($attributeName)) === null) {
         throw new CException(Yii::t('yii', 'Table "{table}" does not have a column named "{column}".', array('{column}' => $attributeName, '{table}' => $table->name)));
     }
     $columnName = $column->rawName;
     $criteria = new CDbCriteria();
     if ($this->criteria !== array()) {
         $criteria->mergeWith($this->criteria);
     }
     $tableAlias = empty($criteria->alias) ? $finder->getTableAlias(true) : $criteria->alias;
     $valueParamName = CDbCriteria::PARAM_PREFIX . CDbCriteria::$paramCount++;
     $criteria->addCondition($this->caseSensitive ? "{$tableAlias}.{$columnName}={$valueParamName}" : "LOWER({$tableAlias}.{$columnName})=LOWER({$valueParamName})");
     $criteria->params[$valueParamName] = $value;
     if (!$finder->exists($criteria)) {
         $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} "{value}" is invalid.');
         $this->addError($object, $attribute, $message, array('{value}' => CHtml::encode($value)));
     }
 }
Example #22
0
 public function execute(&$params)
 {
     $campaign = CActiveRecord::model('Campaign')->findByPk($this->config['options']['campaign']);
     if ($campaign === null || $campaign->launchDate != 0 && $campaign->launchDate < time() || empty($campaign->subject)) {
         return false;
     }
     if (!isset($campaign->list) || $campaign->list->type == 'dynamic' && X2Model::model($campaign->list->modelName)->count($campaign->list->queryCriteria()) < 1) {
         return false;
     }
     // check if there's a template, and load that into the content field
     if ($campaign->template != 0) {
         $template = X2Model::model('Docs')->findByPk($campaign->template);
         if (isset($template)) {
             $campaign->content = $template->text;
         }
     }
     //Duplicate the list for campaign tracking, leave original untouched
     //only if the list is not already a campaign list
     if ($campaign->list->type != 'campaign') {
         $newList = $campaign->list->staticDuplicate();
         if (!isset($newList)) {
             return false;
         }
         $newList->type = 'campaign';
         if (!$newList->save()) {
             return false;
         }
         $campaign->list = $newList;
         $campaign->listId = $newList->id;
     }
     $campaign->launchDate = time();
     return $campaign->save();
 }
 /**
  * Displays the authorization assignments for an user.
  */
 public function actionUser()
 {
     // Create the user model and attach the required behavior
     $userClass = $this->module->userClass;
     $model = CActiveRecord::model($userClass)->findByPk($_GET['id']);
     $model->attachBehavior('rights', new RightsUserBehavior());
     $assignedItems = $this->_authorizer->getAuthItems(null, $model->getId(), null, true);
     $assignments = array_keys($assignedItems);
     // Make sure we have items to be selected
     $selectOptions = Rights::getAuthItemSelectOptions(null, $assignments);
     if ($selectOptions !== array()) {
         // Create a from to add a child for the authorization item
         $form = new CForm(array('elements' => array('itemname' => array('label' => false, 'type' => 'dropdownlist', 'items' => $selectOptions)), 'buttons' => array('submit' => array('type' => 'submit', 'label' => Rights::t('core', 'Assign')))), new AssignmentForm());
         // Form is submitted and data is valid, redirect the user
         if ($form->submitted() === true && $form->validate() === true) {
             // Update and redirect
             $this->_authorizer->authManager->assign($form->model->itemname, $model->getId());
             $item = $this->_authorizer->authManager->getAuthItem($form->model->itemname);
             $item = $this->_authorizer->attachAuthItemBehavior($item);
             Yii::app()->user->setFlash($this->module->flashSuccessKey, Rights::t('core', 'Permission :name assigned.', array(':name' => $item->getNameText())));
             $this->redirect(array('assignment/user', 'id' => $model->getId()));
         }
     } else {
         $form = null;
     }
     // Create a data provider for listing the assignments
     $dataProvider = new AuthItemDataProvider('assignments', array('userId' => $model->getId()));
     // Render the view
     $this->render('user', array('model' => $model, 'dataProvider' => $dataProvider, 'form' => $form));
 }
 /**
  * @param CActiveRecord   $modelClass
  * @param CDbColumnSchema $column
  */
 public function generateAttribute($modelClass, $column, $view = false)
 {
     $code = "";
     if ($column->isForeignKey) {
         $code .= "        array(\n";
         $code .= "            'name' => '{$column->name}',\n";
         foreach ($this->codeModel->relations as $key => $relation) {
             if (($relation[0] == "CHasOneRelation" || $relation[0] == "CBelongsToRelation") && $relation[2] == $column->name) {
                 $relatedModel = CActiveRecord::model($relation[1]);
                 $suggestedfield = $this->codeModel->provider()->suggestIdentifier($relatedModel);
                 $controller = $this->codeModel->resolveController($relation);
                 $value = "(\$model->{$key} !== null)?";
                 $value .= "CHtml::link(\n                            '<i class=\"icon icon-circle-arrow-left\"></i> '.\$model->{$key}->{$suggestedfield},\n                            array('{$controller}/view','{$relatedModel->tableSchema->primaryKey}' => \$model->{$key}->{$relatedModel->tableSchema->primaryKey},'returnUrl' => \\Yii::app()->request->requestUri),\n                            array('class' => '')).";
                 $value .= "' '.";
                 $value .= "CHtml::link(\n                            '<i class=\"icon icon-pencil\"></i> ',\n                            array('{$controller}/update','{$relatedModel->tableSchema->primaryKey}' => \$model->{$key}->{$relatedModel->tableSchema->primaryKey},'returnUrl' => \\Yii::app()->request->requestUri),\n                            array('class' => ''))";
                 $value .= ":'n/a'";
                 $code .= "            'value' => {$value},\n";
                 $code .= "            'type' => 'html',\n";
             }
         }
         $code .= "        ),\n";
     } elseif (stristr($column->name, 'url')) {
         $code .= "array(";
         $code .= "            'name' => '{$column->name}',\n";
         $code .= "            'type' => 'url',\n";
         $code .= "),\n";
     } elseif ($column->name == 'createtime' or $column->name == 'updatetime' or $column->name == 'timestamp') {
         $code .= "array(\n                    'name' => '{$column->name}',\n                    'value' =>\$locale->getDateFormatter()->formatDateTime(\$model->{$column->name}, 'medium', 'medium')),\n";
     } else {
         $code .= "        '" . $column->name . "',\n";
     }
     return $code;
 }
 /**
  * Returns the static model of ParticipantAttributeNames table
  *
  * @static
  * @access public
  * @param string $class
  * @return ParticipantAttributeNames
  */
 public static function model($class = __CLASS__)
 {
     $model = parent::model($class);
     $keys = $model->tableSchema->primaryKey;
     if (is_array($keys) && count($keys) == 2) {
         // Fix the primary key, needed for PgSQL http://bugs.limesurvey.org/view.php?id=6707
         // First load the helper
         Yii::app()->loadHelper('update/updatedb');
         $dbType = setsDBDriverName();
         setVarchar($dbType);
         $table = 'participant_attribute_names';
         if ($dbType == 'mysql') {
             // Only for mysql first remove auto increment
             alterColumn($model->tableName(), $model->primaryKey(), $model->tableSchema->getColumn($model->primaryKey())->dbType, false);
         }
         dropPrimaryKey($table);
         addPrimaryKey($table, (array) $model->primaryKey());
         if ($dbType == 'mysql') {
             // Add back auto increment
             alterColumn($model->tableName(), $model->primaryKey(), Yii::app()->getConfig('autoincrement'));
         }
         // Refresh all schema data now just to make sure
         Yii::app()->db->schema->refresh();
         $model->refreshMetaData();
     }
     return $model;
 }
 /**
  *
  */
 public function validateCurrentPassword()
 {
     $user = CActiveRecord::model($this->userModelName)->findByPk(Yii::app()->user->id);
     if (!$user || !$user->validatePassword($this->current_password)) {
         $this->addError('current_password', 'Incorrect password.');
     }
 }
 /**
  * Displays the authorization assignments for an user.
  */
 public function actionUser()
 {
     // Create the user model and attach the required behavior
     $userClass = $this->module->userClass;
     $model = CActiveRecord::model($userClass)->findByPk($_GET['id']);
     $this->_authorizer->attachUserBehavior($model);
     $assignedItems = $this->_authorizer->getAuthItems(null, $model->getId());
     $assignments = array_keys($assignedItems);
     // Make sure we have items to be selected
     $assignSelectOptions = Rights::getAuthItemSelectOptions(null, $assignments);
     if ($assignSelectOptions !== array()) {
         $formModel = new AssignmentForm();
         // Form is submitted and data is valid, redirect the user
         if (isset($_POST['AssignmentForm']) === true) {
             $formModel->attributes = $_POST['AssignmentForm'];
             if ($formModel->validate() === true) {
                 // Update and redirect
                 $this->_authorizer->authManager->assign($formModel->itemname, $model->getId());
                 $item = $this->_authorizer->authManager->getAuthItem($formModel->itemname);
                 $item = $this->_authorizer->attachAuthItemBehavior($item);
                 Yii::app()->user->setFlash($this->module->flashSuccessKey, Rights::t('core', 'Permission :name assigned.', array(':name' => $item->getNameText())));
                 $this->redirect(array('assignment/user', 'id' => $model->getId()));
             }
         }
     } else {
         $formModel = null;
     }
     // Create a data provider for listing the assignments
     $dataProvider = new RAuthItemDataProvider('assignments', array('userId' => $model->getId()));
     // Render the view
     $this->render('user', array('model' => $model, 'dataProvider' => $dataProvider, 'formModel' => $formModel, 'assignSelectOptions' => $assignSelectOptions));
 }
Example #28
0
 public static function model($class = null)
 {
     if (!isset($class)) {
         $class = get_called_class();
     }
     return parent::model($class);
 }
Example #29
0
 /**
  * {@inheritdoc}
  *
  * @param array $fixtures fixtures to be loaded. The array keys are fixture
  * names, and the array values are either AR class names or table names. If
  * table names, they must begin with a colon character (e.g. 'Post' means
  * an AR class, while ':Post' means a table name).
  *
  * @return void
  * @since 0.1.0
  */
 public function load($fixtures)
 {
     //$schema = $this->getDbConnection()->getSchema();
     //$schema->checkIntegrity(false);
     $this->_rows = array();
     $this->_records = array();
     foreach ($fixtures as $fixtureName => $tableName) {
         if ($tableName[0] === ':') {
             $tableName = substr($tableName, 1);
             unset($modelClass);
         } else {
             $modelClass = \Yii::import($tableName, true);
             $tableName = CActiveRecord::model($modelClass)->tableName();
         }
         if (($prefix = $this->getDbConnection()->tablePrefix) !== null) {
             $tableName = preg_replace('/{{(.*?)}}/', $prefix . '\\1', $tableName);
         }
         $this->resetTable($tableName);
         $rows = $this->loadFixture($tableName);
         if (is_array($rows) && is_string($fixtureName)) {
             $this->_rows[$fixtureName] = $rows;
             if (isset($modelClass)) {
                 foreach (array_keys($rows) as $alias) {
                     $this->_records[$fixtureName][$alias] = $modelClass;
                 }
             }
         }
     }
     //$schema->checkIntegrity(true);
 }
Example #30
0
 public function run($pid, $action, $to, $id)
 {
     $to = CActiveRecord::model($this->getController()->CQtreeGreedView['modelClassName'])->findByPk((int) $to);
     $moved = CActiveRecord::model($this->getController()->CQtreeGreedView['modelClassName'])->findByPk((int) $id);
     $url = $this->getController()->createUrl('default/' . $this->getController()->CQtreeGreedView['adminAction'], array('id' => $pid, 'msg' => '[!] Элемент успешно пренесен', 'msgtype' => 'success'));
     if (!is_null($to) && !is_null($moved)) {
         try {
             switch ($action) {
                 case 'child':
                     $moved->moveAsLast($to);
                     break;
                 case 'before':
                     if ($to->isRoot()) {
                         //$moved->moveAsRoot();
                         $url = $this->getController()->createUrl('default/' . $this->getController()->CQtreeGreedView['adminAction'], array('id' => $pid, 'msg' => '[!] Ошибка: перенос запрещен!', 'msgtype' => 'error'));
                     } else {
                         $moved->moveBefore($to);
                     }
                     break;
                 case 'after':
                     if ($to->isRoot()) {
                         //$moved->moveAsRoot();
                         $url = $this->getController()->createUrl('default/' . $this->getController()->CQtreeGreedView['adminAction'], array('id' => $pid, 'msg' => '[!] Ошибка: перенос запрещен!', 'msgtype' => 'error'));
                     } else {
                         $moved->moveAfter($to);
                     }
                     break;
             }
         } catch (Exception $e) {
             Yii::app()->user->setFlash('CQTeeGridView', $e->getMessage());
         }
     }
     $this->getController()->redirect($url);
 }