CDbCriteria PHP Class Code Examples

This page contains top rated real world PHP examples of class CDbCriteria extracted from open source projects. You can rate examples to help us improve the quality of examples

Example #1
Show file File: PersController.php Project: noiary/Aion-Core-v4.7.5
1
 public function actionIndex()
 {
     if (Yii::app()->user->isGuest) {
         $this->redirect(Yii::app()->homeUrl);
     }
     $this->pageTitle = Yii::t('title', 'Character list');
     $criteria = new CDbCriteria();
     $criteria->select = 'name, account_id, account_name, exp, race, player_class, creation_date';
     $criteria->join = 'INNER JOIN ' . Config::db('db') . '.log_referals ON (log_referals.slave_id = t.account_id AND log_referals.master_id = "' . Yii::app()->user->id . '" AND status = "unpaid")';
     $referals = Players::model()->findAll($criteria);
     $form = new LogReferals();
     if (isset($_POST['LogReferals'])) {
         $form->attributes = $_POST['LogReferals'];
         $check_isset = LogReferals::model()->count('master_id = ' . Yii::app()->user->id . ' AND slave_id = ' . $form->slave_id . ' AND status = "unpaid"');
         if ($check_isset != 1) {
             Yii::app()->user->setFlash('message', '<div class="flash_error">' . Yii::t('pers', 'You have no referrаls.') . '</div>');
             $this->refresh();
         }
         $master = AccountData::model()->find('id = ' . Yii::app()->user->id);
         $check_ip = AccountData::model()->count('id = ' . $form->slave_id . ' AND last_ip = "' . $master->last_ip . '"');
         if ($check_ip != 0) {
             $log = LogReferals::model()->find('master_id = ' . Yii::app()->user->id . ' AND slave_id = ' . $form->slave_id . ' AND status = "unpaid"');
             $log->status = 'blocked';
             $log->update(false);
             Yii::app()->user->setFlash('message', '<div class="flash_error">' . Yii::t('pers', 'You have no referrаls.') . '</div>');
             $this->refresh();
         }
         $criteria = new CDbCriteria();
         $criteria->select = 'exp';
         $criteria->condition = 'account_id = ' . $form->slave_id;
         $criteria->order = 'exp DESC';
         $criteria->limit = 1;
         $check_lvl = Players::model()->find($criteria);
         if (Info::lvl($check_lvl->exp) < Config::get('referal_level')) {
             Yii::app()->user->setFlash('message', '<div class="flash_error">' . Yii::t('pers', 'Less than the minimum level.') . '</div>');
             $this->refresh();
         }
         $criteria = new CDbCriteria();
         $criteria->condition = 'id = ' . Yii::app()->user->id;
         $money = AccountData::model()->find($criteria);
         $money[Yii::app()->params->money] = $money[Yii::app()->params->money] + Config::get('referal_bonus');
         $money->save();
         $criteria = new CDbCriteria();
         $criteria->condition = 'id = ' . $form->slave_id;
         $money = AccountData::model()->find($criteria);
         $money[Yii::app()->params->money] = $money[Yii::app()->params->money] + Config::get('referal_bonus_ref');
         $money->save();
         $log = LogReferals::model()->find('master_id = ' . Yii::app()->user->id . ' AND slave_id = ' . $form->slave_id . ' AND status = "unpaid"');
         $log->status = 'complete';
         $log->update(false);
         Yii::app()->user->setFlash('message', '<div class="flash_success">' . Yii::t('pers', 'Bonus credit applied!') . '</div>');
         $this->refresh();
     }
     $this->render('/pers', array('model' => Players::getPlayers(), 'referals' => $referals));
 }
Example #2
Show file File: UserbarController.php Project: noiary/Aion-Core-v4.7.5
0
 public function actionIndex()
 {
     if (Yii::app()->user->isGuest) {
         $this->redirect(Yii::app()->homeUrl);
     }
     $this->pageTitle = Yii::t('title', 'Userbar creation');
     $image = null;
     $model = new UserbarForm();
     if (isset($_POST['UserbarForm'])) {
         $model->attributes = $_POST['UserbarForm'];
         if ($model->validate()) {
             $criteria = new CDbCriteria();
             $criteria->select = 'id, name, exp, gender, race, player_class';
             $player = Players::model()->with('abyssRank', 'lifeStats')->findByPK($model->player_id);
             $criteria = new CDbCriteria();
             $criteria->select = 'name';
             $legion = Legions::model()->with(array('legionMembers' => array('joinType' => 'INNER JOIN', 'condition' => 'player_id = ' . $model->player_id)))->find();
             if ($legion == NULL) {
                 $legion->name = null;
             }
             Yii::app()->ih->load($_SERVER['DOCUMENT_ROOT'] . Yii::app()->baseUrl . '/images/userbars/ub' . $model->fon . '.png')->text($player->name, Yii::app()->basePath . '/fonts/romic.ttf', 14, $this->rgb($model->shadow), CImageHandler::CORNER_LEFT_TOP, 8, 8)->text($player->name, Yii::app()->basePath . '/fonts/romic.ttf', 14, $this->rgb($model->name), CImageHandler::CORNER_LEFT_TOP, 8, 7)->text($legion->name, Yii::app()->basePath . '/fonts/monaco.ttf', 10, $this->rgb($model->shadow), CImageHandler::CORNER_LEFT_TOP, 8, 36)->text($legion->name, Yii::app()->basePath . '/fonts/monaco.ttf', 10, $this->rgb($model->legion), CImageHandler::CORNER_LEFT_TOP, 8, 35)->text(Info::class_text($player->player_class) . ', ' . $this->genderRace($player->gender, $player->race), Yii::app()->basePath . '/fonts/verdana.ttf', 8, $this->rgb($model->shadow), CImageHandler::CORNER_LEFT_BOTTOM, 8, 9)->text(Info::class_text($player->player_class) . ', ' . $this->genderRace($player->gender, $player->race), Yii::app()->basePath . '/fonts/verdana.ttf', 8, $this->rgb($model->class_race), CImageHandler::CORNER_LEFT_BOTTOM, 8, 10)->text(Info::lvl($player->exp) . ' Level', Yii::app()->basePath . '/fonts/romic.ttf', 14, $this->rgb($model->shadow), CImageHandler::CORNER_RIGHT_TOP, 8, 6)->text(Info::lvl($player->exp) . ' Level', Yii::app()->basePath . '/fonts/romic.ttf', 14, $this->rgb($model->level), CImageHandler::CORNER_RIGHT_TOP, 8, 5)->text($player->abyssRank->all_kill . '/' . $player->abyssRank->weekly_kill . ' Kills', Yii::app()->basePath . '/fonts/monaco.ttf', 10, $this->rgb($model->shadow), CImageHandler::CORNER_RIGHT_TOP, 8, 34)->text($player->abyssRank->all_kill . '/' . $player->abyssRank->weekly_kill . ' Kills', Yii::app()->basePath . '/fonts/monaco.ttf', 10, $this->rgb($model->kills), CImageHandler::CORNER_RIGHT_TOP, 8, 33)->text($player->lifeStats->hp . ' HP, ' . $player->lifeStats->mp . ' MP', Yii::app()->basePath . '/fonts/verdana.ttf', 8, $this->rgb($model->shadow), CImageHandler::CORNER_RIGHT_BOTTOM, 8, 9)->text($player->lifeStats->hp . ' HP, ' . $player->lifeStats->mp . ' MP', Yii::app()->basePath . '/fonts/verdana.ttf', 8, $this->rgb($model->stats), CImageHandler::CORNER_RIGHT_BOTTOM, 8, 10)->save($_SERVER['DOCUMENT_ROOT'] . Yii::app()->baseUrl . '/userbars/' . $model->player_id . '.png');
             $image = Yii::app()->homeUrl . 'userbars/' . $model->player_id . '.png';
         }
     }
     $this->render('/userbar', array('model' => $model, 'players' => Players::getPlayers(), 'image' => $image));
 }
Example #3
Show file File: CSaveRelationsBehavior.php Project: dsyman2/X2CRM
0
 public function afterDelete($event)
 {
     if ($this->deleteRelatedRecords) {
         $model = $this->owner;
         try {
             foreach ($model->relations() as $relation => $params) {
                 $activeRelation = $model->getActiveRelation($relation);
                 if (is_object($activeRelation) && ($activeRelation instanceof CManyManyRelation || $activeRelation instanceof CHasManyRelation || $activeRelation instanceof CHasOneRelation)) {
                     Yii::trace("deleting {$relation} related records.", 'application.components.CSaveRelatedBehavior');
                     $relationClassName = $activeRelation->className;
                     $relationForeignKey = $activeRelation->foreignKey;
                     if ($activeRelation instanceof CManyManyRelation) {
                         // ManyMany relation : delete related records from the many to many relation table
                         $schema = $model->getCommandBuilder()->getSchema();
                         preg_match('/^\\s*(.*?)\\((.*)\\)\\s*$/', $relationForeignKey, $matches);
                         $joinTable = $schema->getTable($matches[1]);
                         $fks = preg_split('/[\\s,]+/', $matches[2], -1, PREG_SPLIT_NO_EMPTY);
                         $baseParams = array();
                         $baseCriteriaCondition = array();
                         reset($fks);
                         foreach ($fks as $i => $fk) {
                             if (isset($joinTable->foreignKeys[$fk])) {
                                 list($tableName, $pk) = $joinTable->foreignKeys[$fk];
                                 if ($schema->compareTableNames($model->tableSchema->rawName, $tableName)) {
                                     $baseCriteriaCondition[$fk] = $baseParams[':' . $fk] = $model->{$pk};
                                 }
                             }
                         }
                         // Delete records
                         $criteria = new CDbCriteria();
                         $criteria->addColumnCondition($baseCriteriaCondition);
                         $model->getCommandBuilder()->createDeleteCommand($joinTable->name, $criteria)->execute();
                     } else {
                         // HasMany & HasOne relation : delete related records
                         $relatedRecord = new $relationClassName();
                         $criteria = new CDbCriteria();
                         $criteria->addColumnCondition(array($relationForeignKey => $model->primaryKey));
                         $relatedRecord->deleteAll($criteria);
                     }
                 }
             }
             unset($relation);
             if ($this->transactional && $this->transaction) {
                 $this->transaction->commit();
             }
         } catch (Exception $e) {
             Yii::trace("An error occured during the delete operation for related records : " . $e->getMessage(), 'application.components.CSaveRelatedBehavior');
             $this->hasError = true;
             if (isset($relation)) {
                 $model->addError($relation, "An error occured during the delete operation of {$relation}");
             }
             if ($this->transactional && $this->transaction) {
                 $this->transaction->rollBack();
             }
         }
     }
 }
Example #4
Show file File: PostController.php Project: jicheng17/yiifamilyblog
0
 /**
  * Lists all models.
  */
 public function actionIndex()
 {
     if (Yii::app()->user->isGuest) {
         $criteria = new CDbCriteria(array('condition' => 'status=' . Post::STATUS_PUBLISHED, 'order' => 'id DESC', 'with' => 'commentCount'));
     } else {
         $criteria = new CDbCriteria(array('order' => 'id DESC', 'with' => 'commentCount'));
     }
     if (isset($_GET['tag'])) {
         $criteria->addSearchCondition('tags', $_GET['tag']);
     }
     $dataProvider = new CActiveDataProvider('Post', array('pagination' => array('pageSize' => Yii::app()->params['postsPerPage']), 'criteria' => $criteria));
     $this->render('index', array('dataProvider' => $dataProvider));
 }
Example #5
Show file File: CDbCommandBuilder.php Project: frogoscar/mobcent-discuz
0
 /**
  * Creates a query criteria.
  * @param mixed $condition query condition or criteria.
  * If a string, it is treated as query condition (the WHERE clause);
  * If an array, it is treated as the initial values for constructing a {@link CDbCriteria} object;
  * Otherwise, it should be an instance of {@link CDbCriteria}.
  * @param array $params parameters to be bound to an SQL statement.
  * This is only used when the first parameter is a string (query condition).
  * In other cases, please use {@link CDbCriteria::params} to set parameters.
  * @return CDbCriteria the created query criteria
  * @throws CException if the condition is not string, array and CDbCriteria
  */
 public function createCriteria($condition = '', $params = array())
 {
     if (is_array($condition)) {
         $criteria = new CDbCriteria($condition);
     } elseif ($condition instanceof CDbCriteria) {
         $criteria = clone $condition;
     } else {
         $criteria = new CDbCriteria();
         $criteria->condition = $condition;
         $criteria->params = $params;
     }
     return $criteria;
 }
Example #6
Show file File: SubcomponentController.php Project: jimminababan/kontrol-anggaran
0
 private function validateRemovedData($filePath, $fields = array(), $worksheet, $highestRow, $startingRow = 2)
 {
     /* ===== (IMPORT DATA CHECKER) check if RKAKL data subcomponent already removed, but app master data already realize === */
     //clear SubcomponentError table if exists
     $exist = SubcomponentError::model()->exists();
     if ($exist) {
         Yii::app()->db->createCommand()->truncateTable(SubcomponentError::model()->tableName());
     }
     $subcomponentCodeFromExcel = [];
     for ($row = $startingRow; $row <= $highestRow; ++$row) {
         $attributes = array();
         for ($col = 0; $col < count($fields); ++$col) {
             $val = $worksheet->getCellByColumnAndRow($fields[$col]['col'], $row)->getValue();
             $attributes[$fields[$col]['name']] = $val;
         }
         //(IMPORT DATA CHECKER) get all excel subcomponent
         $code = $attributes['satker_code'] . "." . $attributes['activity_code'] . "." . $attributes['output_code'] . "." . $attributes['suboutput_code'] . "." . $attributes['component_code'] . "." . $attributes['code'];
         array_push($subcomponentCodeFromExcel, $code);
     }
     // (IMPORT DATA CHECKER) compare excel.subcomponent with current data subcomponent removed
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('code', $subcomponentCodeFromExcel);
     $removedSubcomponents = Subcomponent::model()->findAll($criteria);
     // (IMPORT DATA CHECKER) compare $removedSubcomponents with realization.package_code
     $removedSubcomponentsArray = [];
     foreach ($removedSubcomponents as $r) {
         array_push($removedSubcomponentsArray, $r->code);
     }
     if (count($removedSubcomponentsArray) > 0) {
         $criteria = new CDbCriteria();
         $criteria->addInCondition('package_code', $removedSubcomponentsArray);
         $realizationsError = Realization::model()->findAll($criteria);
         //insert to SubcomponentError table
         $whereInSubcomponent = [];
         foreach ($realizationsError as $r) {
             array_push($whereInSubcomponent, $r->package_code);
         }
         $criteria = new CDbCriteria();
         $criteria->addInCondition('code', $whereInSubcomponent);
         $subcomponentsError = Subcomponent::model()->findAll($criteria);
         foreach ($subcomponentsError as $s) {
             $model = new SubcomponentError();
             $model->attributes = ['code' => $s->code, 'satker_code' => $s->satker_code, 'activity_code' => $s->activity_code, 'output_code' => $s->output_code, 'suboutput_code' => $s->suboutput_code, 'component_code' => $s->component_code, 'name' => $s->name];
             $model->save();
         }
         if (count($subcomponentsError) > 0) {
             unlink($filePath);
             Yii::app()->user->setFlash('error', "Terdapat data terhapus di RKAKL, dimana data tsb sudah terealisasi.");
             $this->redirect(array('import'));
         }
     }
     /* ===== EOF (IMPORT DATA CHECKER) check if RKAKL data subcomponent already removed, but app master data already realize === */
 }
Example #7
Show file File: MetricaController.php Project: AndressJose/sistema-examenes
0
 public function actionRefreshExamsEvolution()
 {
     $anios = array_values(json_decode(stripslashes($_POST['anios'])));
     $cuats = array_values(json_decode(stripslashes($_POST['cuatrimestres'])));
     $cuats_unique = array_unique($cuats);
     $this->createDaysArray();
     $utils = new Utils();
     $planes = Plan::model()->findAll(array('order' => 'anioPlan'));
     $resultados = array();
     foreach ($planes as $key) {
         //Por cada id de plan se obtienen todas las materias del mismo
         $criteriaPlanes = new CDbCriteria();
         $criteriaPlanes->select = 't.materia_id';
         $criteriaPlanes->condition = "plan_id == " . $key->id;
         $criteriaPlanes->addInCondition('t.anio', $anios);
         if (count($cuats_unique) == 1) {
             $criteriaPlanes->addCondition("t.cuatrimestre==" . $cuats_unique[0]);
         }
         $materiasPlan = MateriaPlan::model()->findAll($criteriaPlanes);
         $materias = array();
         $matPlan = array();
         foreach ($materiasPlan as $value) {
             array_push($matPlan, $value->Materia_id);
         }
         foreach ($matPlan as $value) {
             if (!in_array($value, $materias, true)) {
                 array_push($materias, $value);
             }
         }
         //Obtengo los examenes de las materias dadas
         $criteriaMaterias = new CDbCriteria();
         $criteriaMaterias->select = 't.*';
         $criteriaMaterias->join = "INNER JOIN Tipo_Examen as tipoexamen ON(tipoexamen.id=t.tipoexamen_id)";
         $criteriaMaterias->addInCondition('t.materia_id', $materias);
         $criteriaMaterias->order = 't.fechaExamen ASC';
         $examenes = Examen::model()->findAll($criteriaMaterias);
         //Arreglo donde se guardaran los datos
         $datos = array();
         $datosNormalDate = $this->fechas;
         //Informacion que se devuelve  a la vista:
         // fecha del examen, dias de preparacion y peso de cada dia
         foreach ($examenes as $arr) {
             $fecha = $arr->fechaExamen;
             $dias = $arr->diasPreparacion;
             $complejidad = $arr->tipoexamen->complejidad;
             $utils->CalculateWeight($datos, $datosNormalDate, $fecha, $dias, $complejidad);
         }
         $resultados[$key->id] = $datosNormalDate;
     }
     header("Content-type: application/json");
     //Envio la informacion en formato jSON
     echo CJSON::encode(array('result' => $resultados));
 }
Example #8
Show file File: CliproController.php Project: hipogea/zega
0
 public function actionUpdate($id)
 {
     $model = $this->loadModel($id);
     // Uncomment the following line if AJAX validation is needed
     $this->performAjaxValidation($model);
     if (isset($_POST['Clipro'])) {
         $model->attributes = $_POST['Clipro'];
         if ($model->save()) {
             /*if (!empty($_GET['asDialog']))
             		{
             			//Close the dialog, reset the iframe and update the grid
             			echo CHtml::script("window.parent.$('#cru-dialog').dialog('close');window.parent.$('#cru-frame').attr('src','');window.parent.$.fn.yiiGridView.update('{$_GET['gridId']}');");
             				Yii::app()->end();
             		}*/
             //ASUSTANDO AL USUARP APRA QUE LLEN LAS DIRECIONES
             Yii::app()->user->setFlash('success', 'Se ha actualizado los datos del  proveedor  ' . $model->despro);
             Direcciones::model()->find("c_hcod=:codigo", array(":codigo" => $model->codpro));
             if (is_null(Direcciones::model()->find("c_hcod=:codigo", array(":codigo" => $model->codpro)))) {
                 $this->redirect(array('update', 'id' => $model->codpro));
             } else {
                 $this->redirect(array('view', 'id' => $model->codpro));
             }
         }
         if (!empty($_GET['asDialog'])) {
             $this->layout = '//layouts/iframe';
         }
         //----- end new code --------------------
         //	$this->render('update',array('model'=>$model,'proveedor'=>$proveedor,'proveedor2'=>$proveedor2));
     }
     //$filtro1=$model->attributes['razondestinatario'];
     $modelodirecciones = new Direcciones();
     $modelocontactos = new Contactos();
     $modeloobjetos = new ObjetosCliente();
     $criteriazo = new CDbCriteria();
     $criteriazo->condition = "c_hcod ='" . $model->codpro . "'";
     //$criteria->compare('razondestinatario', 'SOLTE',true);
     //$criteria->compare('descripcion', 'ADE',true);
     //echo $model->attributes['descripcion'];
     $proveedor = new CActiveDataProvider($modelodirecciones, array('criteria' => $criteriazo));
     //$this->render('busca',array('model'=>$model,'proveedor'=>$proveedor));
     //$modelodirecciones=Direcciones::find('c_hcod=:c_hcod', array(':c_hcod'=>$model->codpro));
     //$modelocontactos =Contactos::model()->find('c_hcod=:c_hcod', array(':c_hcod'=>$model->codpro));
     $proveedor2 = new CActiveDataProvider($modelocontactos, array('criteria' => $criteriazo));
     $criteriazo1 = new CDbCriteria();
     $criteriazo1->condition = "codpro ='" . $model->codpro . "'";
     $proveedor3 = new CActiveDataProvider($modeloobjetos, array('criteria' => $criteriazo1));
     //----- begin new code --------------------
     if (!empty($_GET['asDialog'])) {
         $this->layout = '//layouts/iframe';
     }
     //----- end new code --------------------
     $this->render('update', array('model' => $model, 'proveedor' => $proveedor, 'proveedor2' => $proveedor2, 'proveedor3' => $proveedor3));
 }
Example #9
Show file File: PlanController.php Project: tiger2soft/travelman
0
 public function actionDropList()
 {
     $dataFormat = new DataFormat();
     $currentCity = UserRefreshForm::model()->getCurrentCity();
     $criteria1 = new CDbCriteria();
     $criteria2 = new CDbCriteria();
     $criteria3 = new CDbCriteria();
     $dropListModel = DropList::model();
     $dropListData1 = null;
     $dropListData2 = null;
     $dropListData3 = null;
     $format2 = array();
     $format3 = array();
     $format1 = array();
     if (isset($_POST['DropList']['secenicName']) && !empty($_POST['DropList']['secenicName'])) {
         $secenicName = $_POST['DropList']['secenicName'];
         $criteria1->addSearchCondition(' secenicName', $secenicName);
         $criteria1->addCondition("cityName='{$currentCity}'");
         $dropListData1 = $dropListModel->findAll($criteria1);
         $format1 = $dataFormat->format($dropListData1, null);
         if (count($format1) <= 0) {
             //匹配整个数据库
             $criteria2->addSearchCondition(' secenicName', $secenicName);
             $dropListData2 = $dropListModel->findAll($criteria2);
             //分词
             $scws = new SCWS();
             $scws->sendMobile($secenicName);
             $param1 = $scws->result[0];
             if ($param1 != null) {
                 $criteria3->addCondition("cityName='{$param1}'");
             }
             if (count($scws->result) > 1) {
                 $param2 = $scws->result[1];
                 $criteria3->addSearchCondition(' secenicName', $param2);
             }
             // $total = $dropListModel->count($criteria);
             // $pager = new CPagination($total);
             // $pager->pageSize = 100;
             // $pager->applyLimit($criteria);
             $dropListData3 = $dropListModel->findAll($criteria3);
             $format2 = $dataFormat->format($dropListData2, null);
             $format3 = $dataFormat->format($dropListData3, null);
         }
         $format = array_merge($format1, $format2, $format3);
         //去除重复的ID
         if (count($format) > 0) {
             $this->sendMobile(0, $format);
         } else {
             $this->sendMobile(3, '数据为空');
         }
     } else {
         $this->sendMobile(1, '数据错误');
     }
     $this->render('dropList', array('dropList' => $dropListModel));
 }
Example #10
Show file File: SBReportBanValidator.php Project: Saltly/SourceBans
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)
 {
     if ($this->isEmpty($object->steam, true) && $this->isEmpty($object->ip, true)) {
         return $this->addError($object, $attribute, Yii::t('yii', '{attribute} cannot be blank.'));
     }
     $value = $object->{$attribute};
     if ($this->allowEmpty && $this->isEmpty($value)) {
         return;
     }
     if ($attribute == 'steam') {
         $criteria = new CDbCriteria(array('condition' => 'type = :type', 'params' => array(':type' => SBBan::TYPE_STEAM)));
     } else {
         if ($attribute == 'ip') {
             $criteria = new CDbCriteria(array('condition' => 'type = :type', 'params' => array(':type' => SBBan::TYPE_IP)));
         } else {
             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;
     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 (!$object instanceof CActiveRecord || $object->isNewRecord || $object->tableName() !== $finder->tableName()) {
         $exists = $finder->exists($criteria);
     } else {
         $criteria->limit = 2;
         $objects = $finder->findAll($criteria);
         $n = count($objects);
         if ($n === 1) {
             if ($column->isPrimaryKey) {
                 // primary key is modified and not unique
                 $exists = $object->getOldPrimaryKey() != $object->getPrimaryKey();
             } else {
                 // non-primary key, need to exclude the current record based on PK
                 $exists = array_shift($objects)->getPrimaryKey() != $object->getOldPrimaryKey();
             }
         } else {
             $exists = $n > 1;
         }
     }
     if ($exists) {
         $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} "{value}" has already been taken.');
         $this->addError($object, $attribute, $message, array('{value}' => CHtml::encode($value)));
     }
 }
Example #11
Show file File: ComponentController.php Project: jimminababan/kontrol-anggaran
0
 private function validateRemovedData($filePath, $fields = array(), $worksheet, $highestRow, $startingRow = 2)
 {
     /* ===== (IMPORT DATA CHECKER) check if RKAKL data component already removed, but app master data already realize === */
     //clear ComponentError table if exists
     $exist = ComponentError::model()->exists();
     if ($exist) {
         Yii::app()->db->createCommand()->truncateTable(ComponentError::model()->tableName());
     }
     $componentCodeFromExcel = [];
     for ($row = $startingRow; $row <= $highestRow; ++$row) {
         $attributes = array();
         for ($col = 0; $col < count($fields); ++$col) {
             $val = $worksheet->getCellByColumnAndRow($fields[$col]['col'], $row)->getValue();
             $attributes[$fields[$col]['name']] = $val;
         }
         //(IMPORT DATA CHECKER) get all excel component
         $code = $attributes['satker_code'] . "." . $attributes['activity_code'] . "." . $attributes['output_code'] . "." . $attributes['suboutput_code'] . "." . $attributes['code'];
         array_push($componentCodeFromExcel, $code);
     }
     // (IMPORT DATA CHECKER) compare excel.component with current data component removed
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('code', $componentCodeFromExcel);
     $removedComponents = Component::model()->findAll($criteria);
     //        //(IMPORT DATA CHECKER) compare $removedComponents with realization.package_code
     //        $removedComponentsArray = [];
     //        foreach ($removedComponents as $r) {
     //            array_push($removedComponentsArray, $r->code);
     //        }
     if (count($removedComponents) > 0) {
         $criteria = new CDbCriteria();
         //            $criteria->addInCondition('package_code', $removedComponentsArray);
         foreach ($removedComponents as $r) {
             $criteria->addSearchCondition('package_code', $r->code, true, 'OR');
         }
         $realizationsError = Realization::model()->findAll($criteria);
         //insert to ComponentError table
         $whereInComponent = [];
         foreach ($realizationsError as $r) {
             $codeArray = explode(".", $r->package_code);
             $code = $codeArray[0] . "." . $codeArray[1] . "." . $codeArray[2] . "." . $codeArray[3] . "." . $codeArray[4];
             //get only package code till latest 4 dot (.)
             array_push($whereInComponent, $code);
         }
         $criteria = new CDbCriteria();
         $criteria->addInCondition('code', $whereInComponent);
         $componentsError = Component::model()->findAll($criteria);
         foreach ($componentsError as $s) {
             $model = new ComponentError();
             $model->attributes = ['code' => $s->code, 'satker_code' => $s->satker_code, 'activity_code' => $s->activity_code, 'output_code' => $s->output_code, 'suboutput_code' => $s->suboutput_code, 'name' => $s->name];
             $model->save();
         }
         if (count($componentsError) > 0) {
             unlink($filePath);
             Yii::app()->user->setFlash('error', "Terdapat data terhapus di RKAKL, dimana data tsb sudah terealisasi.");
             $this->redirect(array('import'));
         }
     }
     /* ===== EOF (IMPORT DATA CHECKER) check if RKAKL data component already removed, but app master data already realize === */
 }
Example #12
Show file File: ListingController.php Project: yasirgit/hotmall
0
 /**
  * Returns the data model based on the primary key given in the GET variable.
  * If the data model is not found, an HTTP exception will be raised.
  * @param integer the ID of the model to be loaded
  */
 public function loadModel($id)
 {
     $model = Listing::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     // load categories
     $criteria = new CDbCriteria();
     $criteria->condition = 'listing_id=:listing_id';
     $criteria->select = 'category_id';
     $criteria->params = array(':listing_id' => $id);
     $listingCategories = ListingCategory::model()->findAll($criteria);
     $categories = array();
     foreach ($listingCategories as $category) {
         $categories[] = $category->category_id;
     }
     $model->p_categories = $categories;
     // load locations
     $criteria = new CDbCriteria();
     $criteria->condition = 'listing_id=:listing_id';
     $criteria->select = 'location_id';
     $criteria->params = array(':listing_id' => $id);
     $listingLocations = ListingLocation::model()->findAll($criteria);
     $locations = array();
     foreach ($listingLocations as $location) {
         $locations[] = $location->location_id;
     }
     $model->p_locations = $locations;
     return $model;
 }
Example #13
Show file File: SiteController.php Project: imanifaiz/angular-music-db
0
 public function actionActivate($key, $email)
 {
     $criteria = new CDbCriteria();
     $criteria->condition = 'activation_key=:activation_key AND email=:email';
     $criteria->params = array(':activation_key' => $key, ':email' => $email);
     $user = User::model()->find($criteria);
     if ($user) {
         $user->activation_key = NULL;
         $user->status = User::STATUS_ACTIVE;
         $user->save(false);
         //user has already  been validated when saved for the forst time.
         $successmsg = Yii::t('registration', ',welcome! Your account has been activated.Now you can log in.');
         Yii::app()->user->setFlash('success', $user->username . $successmsg);
         $this->redirect(bu() . '/site/login');
     } else {
         $errormsg = Yii::t('registration', ' Error.Your account could not be activated,please repeat the registration process.');
         $criteria = new CDbCriteria();
         $criteria->condition = ' email=:email';
         $criteria->params = array(':email' => $email);
         $user = User::model()->find($criteria);
         $user->delete();
         Yii::app()->user->setFlash('danger', $errormsg);
         $this->redirect(bu() . '/site/register');
     }
 }
Example #14
Show file File: DefaultController.php Project: tecshuttle/51qsk
0
 public function actionMyPlace()
 {
     $placeCriteria = new CDbCriteria();
     $placeBookingCriteria = new CDbCriteria();
     $placeReviewCriteria = new CDbCriteria();
     //我的场地
     $placeCriteria->order = 'id DESC';
     $placeCriteria->addCondition("host_id = '{$this->_cookiesGet('userId')}'");
     $place = Place::model()->find($placeCriteria);
     //客户评分
     $placeReviewCriteria->order = 'id DESC';
     $placeReviewCriteria->addCondition("place_id = '{$place['id']}'");
     $placeReview = PlaceReview::model()->findAll($placeReviewCriteria);
     //场地信息
     //$placeBookingCriteria->select = "'t.*'";
     //$placeBookingCriteria->join = 'LEFT JOIN seed_place_booking as sl ON t.id=sl.teacher_id';
     //$placeBookingCriteria->addCondition('sl.place_id=:place_id');
     //$placeBookingCriteria->params[':place_id']=$place->id;
     //场地信息分页
     //$count = Teacher::model()->count($placeBookingCriteria);
     //$pager = new CPagination($count);
     //$pager->pageSize = 5;
     //$pager->applyLimit($placeBookingCriteria);
     $teachers = $this->getTeachers($place->id);
     $this->render('myPlace', array('place' => $place, 'teachers' => $teachers, 'placeReview' => $placeReview, 'status' => $this->isStatus()));
 }
Example #15
Show file File: TimelineController.php Project: chezzy/yii-mblog
0
 /**
  * Searches for stuff
  */
 public function actionSearch()
 {
     $query = isset($_GET['q']) ? $_GET['q'] : null;
     // Scope
     $users = null;
     $shares = null;
     if ($query != null) {
         // Make the criteria object
         $userCriteria = new CDbCriteria();
         $searchCriteria = new CDbCriteria();
         // If there is a @ symbol, do a user search
         preg_match_all('/@([A-Za-z0-9\\/\\.]*)/', $query, $matches);
         $mentions = implode(',', $matches[1]);
         if (!empty($matches[1])) {
             $userCriteria->addInCondition('username', $matches[1]);
             $users = User::model()->findAll($userCriteria);
             // Remove the @users from the remaining query
             foreach ($matches[1] as $u) {
                 $query = str_replace('@' . $u, '', $query);
             }
         }
         // Do a like Query
         $searchCriteria->addSearchCondition('text', $query);
         $searchCriteria->limit = 30;
         $shares = Share::model()->findAll($searchCriteria);
     }
     // Render the search
     $this->render('search', array('users' => $users, 'shares' => $shares));
 }
Example #16
Show file File: PromitdealerController.php Project: zwq/unpei
0
 public function actionGetdealers()
 {
     $criteria = new CDbCriteria();
     $criteria->select = 'userID,organName,Phone';
     if (!empty($_GET['Pinyin'])) {
         $criteria->addSearchCondition('Pinyin', $_GET['Pinyin']);
     }
     $criteria2 = new CDbCriteria();
     $criteria2->select = 'DealerID';
     $criteria2->addCondition('OrganID=' . Commonmodel::getOrganID());
     $criteria2->distinct = true;
     $result = MakePromitBrand::model()->findAll($criteria2);
     $userIDs = array();
     if ($result) {
         foreach ($result as $vel) {
             $userIDs[] = $vel->DealerID;
         }
     }
     $criteria->addNotInCondition('userID', $userIDs);
     if (!empty($_GET['Pinyin'])) {
     }
     $res = Dealer::model()->findAll($criteria);
     $count = count($res);
     $page = new CPagination($count);
     $page->pageSize = $_GET['rows'];
     $page->applyLimit($criteria);
     $res = Dealer::model()->findAll($criteria);
     $data = array();
     if ($res) {
         foreach ($res as $v) {
             $data[] = $v->attributes;
         }
     }
     echo json_encode(array('total' => $count, 'rows' => $data));
 }
Example #17
Show file File: StudentsController.php Project: SoftScape/open-school-CE
0
 public function actionSearch()
 {
     $model = new Students();
     $criteria = new CDbCriteria();
     $criteria->condition = 'first_name LIKE :match or middle_name LIKE :match or last_name LIKE :match';
     $criteria->params = array(':match' => $_POST['char'] . '%');
     $criteria->order = 'first_name ASC';
     $total = Students::model()->count($criteria);
     $pages = new CPagination($total);
     $pages->setPageSize(Yii::app()->params['listPerPage']);
     $pages->applyLimit($criteria);
     // the trick is here!
     $posts = Students::model()->findAll($criteria);
     $emp = new Employees();
     $criteria_1 = new CDbCriteria();
     $criteria_1->condition = 'first_name LIKE :match or middle_name LIKE :match or last_name LIKE :match';
     $criteria_1->params = array(':match' => $_POST['char'] . '%');
     $criteria_1->order = 'first_name ASC';
     $tot = Employees::model()->count($criteria_1);
     $pages_1 = new CPagination($total);
     $pages_1->setPageSize(Yii::app()->params['listPerPage']);
     $pages_1->applyLimit($criteria_1);
     // the trick is here!
     $posts_1 = Employees::model()->findAll($criteria_1);
     $this->render('search', array('model' => $model, 'list' => $posts, 'posts' => $posts_1, 'pages' => $pages, 'item_count' => $total, 'page_size' => 10));
     //$stud = Students::model()->findAll('first_name LIKE '.$_POST['char']);
     //echo count($stud);
     //exit;
     //print_r($_POST);
 }
Example #18
Show file File: DocFolders.php Project: dsyman2/X2CRM
0
 private function getChildren($option = null)
 {
     $children = array('folders' => array(), 'docs' => array());
     $folderCriteria = new CDbCriteria();
     if ($option === 'root') {
         $folderCriteria->condition = 'parentFolder IS NULL AND id > 0';
     } else {
         $folderCriteria->compare('parentFolder', $this->id);
     }
     $folderCriteria->mergeWith($this->getAccessCriteria());
     $folderCriteria->order = 'name ASC';
     $children['folders'] = DocFolders::model()->findAll($folderCriteria);
     $docsCriteria = new CDbCriteria();
     $doc = Docs::model();
     if ($option === 'root') {
         $docsCriteria->condition = 'folderId IS NULL AND type NOT IN ("email","quote")';
     } elseif ($option === self::TEMPLATES_FOLDER_ID) {
         $docsCriteria->condition = 'folderId IS NULL AND type IN ("email","quote")';
     } else {
         $docsCriteria->compare('folderId', $this->id);
     }
     $docsCriteria->mergeWith($doc->getAccessCriteria());
     $docsCriteria->order = 'name ASC';
     $children['docs'] = Docs::model()->findAll($docsCriteria);
     return $children;
 }
Example #19
Show file File: MenuM.php Project: Telemedellin/tm
0
 protected function getHijos($url_id)
 {
     $dependencia = new CDbCacheDependency("SELECT GREATEST(MAX(micrositio.creado), MAX(micrositio.modificado)) FROM micrositio WHERE micrositio.estado <> 0");
     $c = new CDbCriteria();
     $c->addCondition('t.estado <> 0');
     $c->addCondition('micrositios.estado > 1');
     if ($url_id == 1) {
         $c->order = 'micrositios.creado DESC';
     } else {
         $c->order = 't.nombre ASC';
     }
     $seccion = Seccion::model()->cache(21600, $dependencia)->with('micrositios')->findByAttributes(array('url_id' => $url_id), $c);
     if ($seccion) {
         return $seccion->micrositios;
     } else {
         $c = new CDbCriteria();
         $c->addCondition('t.estado > 1');
         $c->addCondition('paginas.estado <> 0');
         $c->order = 't.nombre DESC';
         //$micrositio = Micrositio::model()->cache(21600, $dependencia)->with('paginas')->findByAttributes( array('url_id' => $url_id), $c );
         if ($micrositio->seccion_id == 1) {
             return $micrositio->paginas;
         }
     }
     return false;
 }
Example #20
Show file File: AdminevaquestiongroupsController.php Project: schrapps/risksur
0
 /**
  * @param $questions
  * @return array
  */
 private function getAssociationData($questions)
 {
     $questionArray = json_decode($questions, true);
     $econMethods = array_keys($questionArray);
     $methodQuestions = [];
     foreach ($questionArray as $questionGroup) {
         //print_r($questionArray); die;
         $methodQuestions = array_merge($methodQuestions, $questionGroup);
     }
     //print_r($methodQuestions); die;
     $questionCriteria = new CDbCriteria();
     $questionCriteria->addInCondition('evalQuestionId', $methodQuestions);
     $rsQuestions = EvaluationQuestion::model()->findAll($questionCriteria);
     $econMethodCriteria = new CDbCriteria();
     $econMethodCriteria->addInCondition('id', $econMethods);
     $rsEconMethod = EconEvaMethods::model()->findAll($econMethodCriteria);
     $associationData = [];
     foreach ($rsEconMethod as $methodKey => $method) {
         //print_r($questionArray);
         //print_r($method);
         $associationData[$methodKey]['methodName'] = $method->buttonName;
         $associationData[$methodKey]['methodId'] = $method->id;
         $associationData[$methodKey]['questions'] = '<ul>';
         foreach ($rsQuestions as $question) {
             if (isset(array_flip($questionArray[$method->id])[$question->evalQuestionId])) {
                 $associationData[$methodKey]['questions'] .= CHtml::tag('li', [], $question->questionNumber . ' ' . $question->question);
             }
         }
         $associationData[$methodKey]['questions'] .= '</ul>';
     }
     return $associationData;
 }
Example #21
Show file File: InformationController.php Project: Saqo19/heraxos
0
 /**
  * Manages all models.
  */
 public function actionAll()
 {
     $criteria = new CDbCriteria();
     $criteria->compare('top', '1', true);
     $model = Information::model()->findAll($criteria);
     $id = array();
     $i = 0;
     foreach ($model as $value) {
         $id[$i] = $value->id;
         $i++;
     }
     $limit = 5;
     if (count($id) > $limit) {
         shuffle($id);
         $id = array_slice($id, 0, $limit);
     }
     $criteria1 = new CDbCriteria();
     $criteria1->addInCondition('id', $id);
     $model1 = Information::model()->findAll($criteria1, array('top', '1', true));
     $model = new Information('search');
     $model->unsetAttributes();
     // clear any default values
     if (isset($_GET['Information'])) {
         $model->attributes = $_GET['Information'];
     }
     $this->render('admin', array('model' => $model, 'model1' => $model1));
 }
Example #22
Show file File: MultilingualBehavior.php Project: DarkAiR/test
0
 /**
  * Modify passed criteria by replacing conditions on base attributes with conditions on translations.
  * Allow to make search on model translated values.
  * @param CDbCriteria $event
  */
 public function modifySearchCriteria(CDbCriteria $criteria)
 {
     $owner = $this->getOwner();
     $criteria_array = $criteria->toArray();
     foreach ($this->localizedAttributes as $attribute) {
         if (!empty($owner->{$attribute})) {
             $criteria_array['condition'] = str_replace($attribute . ' ', $this->localizedPrefix . $attribute . ' ', $criteria_array['condition']);
         }
     }
     $criteria_array['together'] = true;
     $criteria = new CDbCriteria($criteria_array);
     return $criteria;
 }