Exemple #1
0
 public static function parseDate($date)
 {
     if (($t = CDateTimeParser::parse($date, 'dd/MM/yyyy')) || ($t = CDateTimeParser::parse($date, 'yyyy-MM-dd'))) {
         return date("Y-m-d", $t);
     }
     return null;
 }
 protected function validateAttribute($object, $attribute)
 {
     $message = Yii::t('yii', '{attribute} must be greater than "{compareValue}".');
     $compare = $this->compare;
     /*if (empty($object->attributes[$compare]) && empty($object->attributes[$attribute])) return;*/
     if ($object->attributes[$compare] == null && $object->attributes[$attribute] == null) {
         return;
     }
     Yii::log($object->attributes[$compare] . " " . $object->attributes[$attribute]);
     if (!isset($object->attributes[$attribute])) {
         $object->addError($attribute, 'An ' . $object->getAttributeLabel($attribute) . ' is required.');
     }
     if ($compare == null) {
         throw new CException('Compare value is required.');
     }
     if (!isset($object->attributes[$compare])) {
         $object->addError($compare, 'A ' . $object->getAttributeLabel($compare) . ' is required.');
     }
     if (!$object->hasErrors($attribute)) {
         $value = $object->attributes[$attribute];
         $compareValue = $object->attributes[$compare];
         $pattern = $this->pattern;
         if (CDateTimeParser::parse($value, $pattern) < CDateTimeParser::parse($compareValue, $pattern)) {
             $params = array('{attribute}' => $object->getAttributeLabel($attribute), '{compareValue}' => $object->getAttributeLabel($compare));
             $object->addError($attribute, strtr($message, $params));
         }
     }
 }
Exemple #3
0
 function testParseDefaults()
 {
     $this->assertEquals('31-12-2011 23:59:59', date('d-m-Y H:i:s', CDateTimeParser::parse('2011-12-31', 'yyyy-MM-dd', array('hour' => 23, 'minute' => 59, 'second' => 59))));
     // test matching with wildcards, this example is mssql timestamp
     $this->assertEquals('2011-02-10 23:43:04', date('Y-m-d H:i:s', CDateTimeParser::parse('2011-02-10 23:43:04.973', 'yyyy-MM-dd hh:mm:ss.???')));
     $this->assertEquals('2011-01-10 23:43:04', date('Y-m-d H:i:s', CDateTimeParser::parse('2011-01-10 23:43:04.973', 'yyyy?MM?dd?hh?mm?ss????')));
 }
Exemple #4
0
 function actionAddWorker()
 {
     $model = new Worker();
     $user = new User();
     $u_transaction = $user->dbConnection->beginTransaction();
     $this->performAjaxValidation($user);
     if (isset($_POST['Worker'])) {
         if (isset($_POST['User'])) {
             $user->login = $_POST['User']['login'];
             $user->password = $_POST['User']['password'];
             $user->role = 'worker';
             if ($user->save()) {
                 $model->attributes = $_POST['Worker'];
                 $model->user_id = $user->id;
                 $timestamp = CDateTimeParser::parse($model->birthdate, 'dd-MM-yyyy');
                 $model->birthdate = date('Y-m-d', $timestamp);
                 if ($model->save()) {
                     $u_transaction->commit();
                     $this->redirect(array('view', 'id' => $model->user_id));
                 } else {
                     $u_transaction->rollback();
                     //откатываем данные по юзеру, в случае если данные по работнику не сохранились
                     throw new CHttpException(901, 'Ошибка сохранения данных работника.');
                 }
             } else {
                 throw new CHttpException(902, "Ошибка сохранения данных авторизации");
             }
         } else {
             throw new CHttpException(903, 'Ошибка передачи данных авторизации.');
         }
     } else {
         $this->render('add_worker', array('model' => $model, 'user' => $user));
     }
 }
 /**
  * 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;
     }
     $valid = false;
     // reason of array checking is explained here: https://github.com/yiisoft/yii/issues/1955
     if (!is_array($value)) {
         $formats = is_string($this->format) ? array($this->format) : $this->format;
         foreach ($formats as $format) {
             $timestamp = CDateTimeParser::parse($value, $format, array('month' => 1, 'day' => 1, 'hour' => 0, 'minute' => 0, 'second' => 0));
             if ($timestamp !== false) {
                 $valid = true;
                 if ($this->timestampAttribute !== null) {
                     $object->{$this->timestampAttribute} = $timestamp;
                 }
                 break;
             }
         }
     }
     if (!$valid) {
         $message = $this->message !== null ? $this->message : Yii::t('yii', 'The format of {attribute} is invalid.');
         $this->addError($object, $attribute, $message);
     }
 }
Exemple #6
0
 public function actionCronDaily($type)
 {
     set_time_limit(0);
     $logmodel = HoleCronLog::model()->findByAttributes(array('type' => $type), 'time_finish >= ' . CDateTimeParser::parse(date('Y-m-d'), 'yyyy-MM-dd'));
     if (!$logmodel) {
         $logmodel = new HoleCronLog();
         if ($type == "achtung-notifications") {
             $logmodel->type = $type;
             $logmodel->time_finish = time();
             $logmodel->save();
             //отмечаем ямы как просроченные
             $holes = Holes::model()->findAll(array('condition' => 't.STATE in ("inprogress", "achtung") AND t.DATE_SENT > 0'));
             foreach ($holes as $hole) {
                 $WAIT_DAYS = 38 - ceil((time() - $hole->DATE_SENT) / 86400);
                 if ($WAIT_DAYS < 0 && $hole->STATE == 'inprogress') {
                     $hole->STATE = 'achtung';
                     $hole->update();
                 } elseif ($hole->STATE == 'achtung' && $WAIT_DAYS > 0) {
                     $hole->STATE = 'inprogress';
                     $hole->update();
                 }
             }
             //echo count($holes);
             //Находим пользователей с просроченными запросами
             $users = 1;
             $limit = 200;
             $ofset = 0;
             while ($users) {
                 $users = UserGroupsUser::model()->findAll(array('select' => '*, t.id as notUseAfrefind', 'condition' => 'relProfile.send_achtung_notifications=1 AND t.email != ""', 'with' => array('relProfile', 'requests' => array('with' => array('answer', 'hole' => array('with' => array('type', 'pictures_fresh'))), 'condition' => 'requests.date_sent < ' . (time() - 60 * 60 * 24 * 28) . ' AND requests.type="gibdd" AND (requests.notification_sended=0 OR requests.notification_sended < ' . (time() - 60 * 60 * 24 * 30) . ' ) AND hole.STATE NOT IN ("fixed", "prosecutor") AND answer.request_id IS NULL'), 'relUserGroupsGroup'), 'limit' => $limit, 'offset' => $ofset));
                 foreach ($users as $user) {
                     $holes = array();
                     $i = 0;
                     foreach ($user->requests as $request) {
                         $WAIT_DAYS = 38 - ceil((time() - $request->date_sent) / 86400);
                         if ($WAIT_DAYS < 0) {
                             $holes[$i] = $request->hole;
                             $holes[$i]->PAST_DAYS = abs($WAIT_DAYS);
                             $i++;
                             $request->notification_sended = time();
                             $request->update();
                         }
                     }
                     if ($holes) {
                         $headers = "MIME-Version: 1.0\r\nFrom: \"Rosyama\" <" . Yii::app()->params['adminEmail'] . ">\r\nReply-To: " . Yii::app()->params['adminEmail'] . "\r\nContent-Type: text/html; charset=utf-8";
                         Yii::app()->request->baseUrl = Yii::app()->request->hostInfo;
                         $mailbody = $this->renderPartial('/ugmail/achtung_notification', array('user' => $user, 'holes' => $holes), true);
                         //echo $mailbody; die();
                         //$user->email
                         echo 'Напоминание на ' . count($holes) . 'ям, отправлено пользователю ' . $user->username . '<br />';
                         mail($user->email, "=?utf-8?B?" . base64_encode('Истекло время ожидания ответа от ГИБДД') . "?=", $mailbody, $headers);
                     }
                     unset($holes);
                 }
                 $ofset += $limit;
                 //if ($ofset > 2000) break;
             }
             $this->render('/site/index');
         }
     }
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Person();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Person'])) {
         $model->attributes = $_POST['Person'];
         $model->job = 0;
         $model->birthday = CDateTimeParser::parse($model->birthday, 'dd/MM/yyyy');
         $model->avatar = CUploadedFile::getInstance($model, 'avatar');
         if ($model->avatar != null) {
             $avatar_name = 'image_' . $model->id . '_' . time() . '.' . $model->avatar->getExtensionName();
             $model->avatar->saveAs(Yii::getPathOfAlias('webroot') . Person::M_IMAGES . $avatar_name);
             $image = Yii::app()->image->load(Yii::getPathOfAlias('webroot') . Person::M_IMAGES . $avatar_name);
             if (128 < $image->__get('width')) {
                 $image->resize(128, 128, Image::HEIGHT);
             }
             $image->save(Yii::getPathOfAlias('webroot') . Person::M_THUMBNAIL . $avatar_name);
             // or $image->save('images/small.jpg');
             $model->avatar = $avatar_name;
         } else {
             $model->avatar = Person::M_NOIMAGE;
         }
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
Exemple #8
0
 public function beforeValidate()
 {
     parent::beforeValidate();
     if ($this->birthday && $this->birthday != '0000-00-00') {
         $this->birthday = date('Y-m-d', CDateTimeParser::parse($this->birthday, 'dd.MM.yyyy'));
     }
     return true;
 }
Exemple #9
0
 public function init()
 {
     $yiidatetimesec = Yii::app()->locale->getDateFormat('yiidatetimesec');
     $phpdatetime = Yii::app()->locale->getDateFormat('phpdatetimes');
     $this->from_date = date($phpdatetime, CDateTimeParser::parse('01/01/' . date('Y') . ' 00:00:00', $yiidatetimesec));
     $this->to_date = date($phpdatetime);
     return parent::init();
 }
Exemple #10
0
 public static function formatDateTime($dateTime, $format = 'default')
 {
     $dateFormat = param('dateFormat', 'd.m.Y H:i:s');
     if ($format == 'default') {
         return date($dateFormat, strtotime($dateTime));
     } else {
         return Yii::app()->dateFormatter->format(Yii::app()->locale->getDateFormat('long'), CDateTimeParser::parse($dateTime, 'yyyy-MM-dd hh:mm:ss'));
     }
 }
Exemple #11
0
 public function transaction($in, $out, $model)
 {
     $due_date = DocchequesEav::model()->findByPk(array("doc_id" => $model->doc_id, "line" => $model->line, 'attribute' => 'cheque_date'));
     if ($due_date == NULL) {
         throw new Exception("NO due date was found for transaction", 401);
     }
     $valuedate = date("Y-m-d H:m:s", CDateTimeParser::parse($due_date->value, Yii::app()->locale->getDateFormat('yiishort')));
     $in->valuedate = $valuedate;
     $out->valuedate = $valuedate;
 }
Exemple #12
0
function inbox_date($time_str)
{
    $tstamp = strtotime($time_str);
    if (date('z', time()) <= date('z', $tstamp)) {
        $date_str = Yii::app()->dateFormatter->format('h:mm a', CDateTimeParser::parse($tstamp, 'yyyy-MM-dd'), 'medium', null);
    } else {
        $date_str = Yii::app()->dateFormatter->format('MMM d', CDateTimeParser::parse($tstamp, 'yyyy-MM-dd'), 'medium', null);
    }
    return $date_str;
}
 /**
  * Given a value, attempt to convert the value to a db datetime format based on the format provided.
  * If the value does not convert properly, meaning the value is not really in the format specified, then a
  * InvalidValueToSanitizeException will be thrown.
  * @param mixed $value
  * @return sanitized value
  * @throws InvalidValueToSanitizeException
  */
 public function sanitizeValue($value)
 {
     if ($value == null) {
         return $value;
     }
     $timeStamp = CDateTimeParser::parse($value, $this->mappingRuleData['format']);
     if ($timeStamp === false || !is_int($timeStamp)) {
         throw new InvalidValueToSanitizeException(Zurmo::t('ImportModule', 'Invalid datetime format.'));
     }
     return DateTimeUtil::convertTimestampToDbFormatDateTime($timeStamp);
 }
 public function actionUserinputSave()
 {
     if (isset($_POST['item_id']) && $_POST['item_id'] > 0 && isset($_POST['DtTest'])) {
         $item_id = (int) $_POST['item_id'];
         $model = DtTest::model()->findByPk($item_id);
         $model->c_date = Yii::app()->dateFormatter->formatDateTime(CDateTimeParser::parse($_POST['DtTest']['c_date'], Yii::app()->locale->getDateFormat('small')), 'database', false);
         $model->c_time = $_POST['c_time_hour'] . ':' . $_POST['c_time_min'] . ':00';
         $model->c_datetime = Yii::app()->lc->mergeDatetime(array('date' => $_POST['DtTest']['c_datetime'], 'hour' => $_POST['c_datetime_hour'], 'min' => $_POST['c_datetime_min']), 'database', 'small');
         $model->save();
     }
 }
 protected function validateAttribute($object, $attribute)
 {
     $message = Yii::t('yii', '{attribute} must be greater than "{compareValue}".');
     $compare = $this->compare;
     /*if (empty($object->attributes[$compare]) && empty($object->attributes[$attribute])) return;*/
     if ($object->attributes[$compare] == null && $object->attributes[$attribute] == null) {
         return;
     }
     if (!isset($object->attributes[$attribute])) {
         $object->addError($attribute, 'An ' . $object->getAttributeLabel($attribute) . ' is required.');
     }
     if ($compare == null) {
         throw new CException('Compare value is required.');
     }
     if (!isset($object->attributes[$compare])) {
         $object->addError($compare, 'A ' . $object->getAttributeLabel($compare) . ' is required.');
     }
     if (!$object->hasErrors(null)) {
         $value = $object->attributes[$attribute];
         $compareValue = $object->attributes[$compare];
         $pattern = $this->pattern;
         $startDate = $this->startDate;
         $endDate = $this->endDate;
         $checkTime = true;
         if ($this->checkSameDate) {
             if ($startDate == null) {
                 throw new CException('"startDate" is required.');
             }
             if ($endDate == null) {
                 throw new CException('"endDate" is required.');
             }
             if (!isset($object->attributes[$startDate])) {
                 $object->addError($startDate, 'Time requires a ' . $object->getAttributeLabel($startDate) . '.');
             }
             if (!isset($object->attributes[$endDate])) {
                 $object->addError($endDate, 'Time requires an ' . $object->getAttributeLabel($endDate) . '.');
             }
             if (!$object->hasErrors($attribute)) {
                 $startDateValue = $object->attributes[$startDate];
                 $endDateValue = $object->attributes[$endDate];
                 $datePattern = $this->datePattern;
                 $checkTime = CDateTimeParser::parse($startDateValue, $datePattern) == CDateTimeParser::parse($endDateValue, $datePattern);
                 if ($checkTime) {
                     if (CDateTimeParser::parse($value, $pattern) <= CDateTimeParser::parse($compareValue, $pattern)) {
                         $params = array('{attribute}' => $object->getAttributeLabel($attribute), '{compareValue}' => $object->getAttributeLabel($compare));
                         $object->addError($attribute, strtr($message, $params));
                     }
                 }
             }
         }
     }
 }
Exemple #16
0
 public function myDateValidator($param)
 {
     $dateStart = CDateTimeParser::parse($this->date_start, Booking::getYiiDateFormat());
     // format to unix timestamp
     $dateEnd = CDateTimeParser::parse($this->date_end, Booking::getYiiDateFormat());
     // format to unix timestamp
     if ($param == 'date_start' && $dateStart < CDateTimeParser::parse(date('Y-m-d'), 'yyyy-MM-dd')) {
         $this->addError('date_start', tt('Wrong check-in date', 'booking'));
     }
     if ($param == 'date_end' && $dateEnd <= $dateStart) {
         $this->addError('date_end', tt('Wrong check-out date', 'booking'));
     }
 }
Exemple #17
0
 public static function checkForSync($type, $status = "RUNNING", $before = 600)
 {
     $criteria = new CDbCriteria();
     $criteria->condition = 'type=:type AND status=:status';
     $criteria->params = array(':type' => $type, ':status' => $status);
     $criteria->order = "id DESC";
     $running = DaemonJobs::model()->find($criteria);
     if ($running && time() - CDateTimeParser::parse($running->start_time, 'yyyy-MM-dd HH:mm:ss') < $before) {
         return false;
     } else {
         return true;
     }
 }
 /**
  * Given a value, attempt to convert the value to a db datetime format based on the format provided.
  * If the value does not convert properly, meaning the value is not really in the format specified, then a
  * InvalidValueToSanitizeException will be thrown.
  * @param string $modelClassName
  * @param string $attributeName
  * @param mixed $value
  * @param array $mappingRuleData
  */
 public static function sanitizeValue($modelClassName, $attributeName, $value, $mappingRuleData)
 {
     assert('is_string($modelClassName)');
     assert('is_string($attributeName)');
     assert('isset($mappingRuleData["format"])');
     if ($value == null) {
         return $value;
     }
     $timeStamp = CDateTimeParser::parse($value, $mappingRuleData['format']);
     if ($timeStamp === false || !is_int($timeStamp)) {
         throw new InvalidValueToSanitizeException(Zurmo::t('ImportModule', 'Invalid datetime format.'));
     }
     return DateTimeUtil::convertTimestampToDbFormatDateTime($timeStamp);
 }
 public function getStartDate($family)
 {
     $sub = Subscription::model()->findByAttributes(array('family_id' => $family->id), array('order' => 'end_year DESC, end_month DESC'));
     Yii::trace("SC.getStartDate called for family #" . $family->id . "=" . gettype($family), 'application.controllers.SubscriptionController');
     if ($sub) {
         $dt = new DateTime(sprintf("%d-%02d-%d", $sub->end_year, $sub->end_month, 15));
         $dt->add(new DateInterval('P1M'));
         return $dt;
     } else {
         $dt = new DateTime();
         $dt->setTimestamp(CDateTimeParser::parse($family->reg_date, Yii::app()->locale->getDateFormat('short')));
         return $dt;
     }
 }
Exemple #20
0
 public function beforeSave()
 {
     if ($this->isNewRecord) {
         $this->dateDBformat = false;
     }
     if (!$this->dateDBformat) {
         $this->dateDBformat = true;
         $this->dt = date("Y-m-d H:i:s", CDateTimeParser::parse($this->dt, Yii::app()->locale->getDateFormat('yiishort')));
     }
     //return true;
     //echo $this->due_date.";".$this->issue_date.";".$this->modified;
     //Yii::app()->end();
     return parent::beforeSave();
 }
 public function approve()
 {
     try {
         $model = (new $this->class_name())->findByPk($this->id_record);
         if ($this->attribute == 'max_exec_date') {
             $model->max_exec_date = Yii::app()->dateFormatter->format($model->dateTimeIncomeFormat, CDateTimeParser::parse($this->new_value, $model->dateTimeOutcomeFormat));
         } else {
             $model->{$this->attribute} = $this->new_value;
         }
         $model->save(false);
         $this->delete();
     } catch (Exception $ex) {
     }
 }
Exemple #22
0
 public function beforeSave()
 {
     if ($this->isNewRecord) {
         $this->dateDBformat = false;
     }
     if (!$this->dateDBformat) {
         $this->dateDBformat = true;
         $this->date = date("Y-m-d H:i:s", CDateTimeParser::parse($this->date, Yii::app()->locale->getDateFormat('yiishort')));
     }
     if ($this->extCorrelation === null) {
         $this->extCorrelation = '0';
     }
     return parent::beforeSave();
 }
Exemple #23
0
 /**
  * Updates a particular model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id the ID of the model to be updated
  */
 public function actionUpdate($id)
 {
     $model = $this->loadModel($id);
     $this->layout = '//layouts/header_user';
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['News'])) {
         $model->attributes = $_POST['News'];
         $model->date = CDateTimeParser::parse($model->date, 'dd.MM.yyyy');
         if ($model->save()) {
             $this->redirect(array('admin'));
         }
     }
     $this->render('update', array('model' => $model));
 }
 /**
  * Given a value, attempt to convert the value to a db date format based on the format provided.  If the value
  * does not convert properly, meaning the value is not really in the format specified, then a
  * InvalidValueToSanitizeException will be thrown.
  * @param mixed $value
  * @return sanitized value
  * @throws InvalidValueToSanitizeException
  */
 public function sanitizeValue($value)
 {
     if ($value == null) {
         return $value;
     }
     $timeZone = date_default_timezone_get();
     date_default_timezone_set('GMT');
     $timeStamp = CDateTimeParser::parse($value, $this->mappingRuleData['format']);
     date_default_timezone_set($timeZone);
     if ($timeStamp === false) {
         throw new InvalidValueToSanitizeException(Zurmo::t('ImportModule', 'Invalid date format.'));
     }
     $dbDateValue = DateTimeUtil::convertTimestampToDbFormatDate($timeStamp);
     return $dbDateValue;
 }
Exemple #25
0
 public function save()
 {
     //print_r($this->Deposit);
     $num = 0;
     $linenum = 1;
     $tranType = Settings::model()->findByPk('transactionType.chequedeposit')->value;
     if ($this->refnum == '' || $this->date == '' || !is_array($this->Deposit)) {
         return false;
     }
     $valuedate = date("Y-m-d H:m:s", CDateTimeParser::parse($this->date, Yii::app()->locale->getDateFormat('yiishort')));
     foreach ($this->Deposit as $line => $val) {
         list($a, $b) = explode(',', $line);
         $cheq = Doccheques::model()->findByPk(array("doc_id" => $a, "line" => $b));
         $oppt_acc = PaymentType::model()->findByPk($cheq->type)->oppt_account_id;
         //print_r($cheq);
         $accout = new Transactions();
         $accout->num = $num;
         $accout->account_id = $this->account_id;
         $accout->type = $tranType;
         $accout->refnum1 = $this->refnum;
         $accout->valuedate = $valuedate;
         //$accout->details=$this->company;
         $accout->currency_id = $cheq->currency_id;
         $accout->owner_id = Yii::app()->user->id;
         $accout->linenum = $linenum;
         $accout->sum = $cheq->sum * -1;
         $linenum++;
         $num = $accout->save();
         $oppt = new Transactions();
         $oppt->num = $num;
         $oppt->account_id = $oppt_acc;
         $oppt->type = $tranType;
         $oppt->refnum1 = $this->refnum;
         $oppt->valuedate = $valuedate;
         //$oppt->details=$this->company;
         $oppt->currency_id = $cheq->currency_id;
         $oppt->owner_id = Yii::app()->user->id;
         $oppt->linenum = $linenum;
         $oppt->sum = $cheq->sum * 1;
         $linenum++;
         $num = $oppt->save();
         $cheq->bank_refnum = $num;
         $cheq->save();
     }
     //Yii::app()->end();
     return $num;
 }
Exemple #26
0
 private function _normalizeContent($content)
 {
     if (!empty($content['published_date'])) {
         $content['published_date'] = CDateTimeParser::parse(trim($content['published_date']), 'dd-MM-yyyy');
     }
     if (!empty($content['price'])) {
         $price = explode(' ', trim($content['price']));
         if (count($price) > 0) {
             $content['price'] = intval(floatval($price[0]) * 1000);
         }
     }
     if (!empty($content['size'])) {
         $content['size'] = trim($content['size']);
     }
     if (!empty($content['publisher'])) {
         $content['publisher'] = trim($content['publisher']);
     }
     if (!empty($content['book_company'])) {
         $content['book_company'] = trim($content['book_company']);
     }
     if (!empty($content['book_name'])) {
         $name = trim($content['book_name']);
         $matches = preg_match('/\\((.*?)\\)/', $name);
         if (count($matches) > 0) {
             if (strtolower($matches[1]) == 'bìa mềm' || strtolower($matches[1]) == 'bìa cứng') {
                 $content['type'] = $matches[1];
             }
             $content['book_name'] = trim(preg_replace('/\\((.*?)\\)/', '', $name));
         }
     }
     if (!empty($content['num_page'])) {
         $content['num_page'] = intval(trim($content['num_page']));
     }
     if (!empty($content['description'])) {
         $description = trim($content['description']);
         $arrRemoveStr = array('TIKI KHUYÊN ĐỌC', 'ĐÁNH GIÁ TỪ TIKI.VN:', 'Mời các bạn đón đọc!');
         foreach ($arrRemoveStr as $str) {
             $description = str_replace($str, '', $description);
         }
         $content['description'] = $description;
     }
     if (!empty($content['author'])) {
         $content['author'] = trim($content['author']);
     }
     return $content;
 }
 public function afterFind($event)
 {
     foreach ($event->sender->tableSchema->columns as $columnName => $column) {
         if ($column->dbType != 'date' and $column->dbType != 'datetime') {
             continue;
         }
         if (!strlen($event->sender->{$columnName})) {
             $event->sender->{$columnName} = null;
             continue;
         }
         if ($column->dbType == 'date') {
             $event->sender->{$columnName} = Yii::app()->dateFormatter->format('dd-MM-yyyy', CDateTimeParser::parse($event->sender->{$columnName}, $this->dateIncomeFormat));
         } else {
             $event->sender->{$columnName} = Yii::app()->dateFormatter->formatDateTime(CDateTimeParser::parse($event->sender->{$columnName}, $this->dateTimeIncomeFormat), 'medium', 'medium');
         }
     }
     return true;
 }
Exemple #28
0
        public function search()
	{
            $tmpFechaNac=$this->xfechaNac;
            $this->fechaNac='';
            $provider=parent::search();
            
                $this->fechaNac=$tmpFechaNac;   
	
                $criteria=new CDbCriteria;
                
                if (!empty($this->fechaNac))
                {
                    $criteria->compare('fechaNac', date('Y-m-d', CDateTimeParser::parse($this->fechaNac, yii::app()->locale->dateFormat)));
                }
                $provider->getCriteria()->mergeWith($criteria);
                
            return $provider;
        }
Exemple #29
0
 /**
  * Validates the attribute of the model.
  * If there is any error, the error message is added to the model.
  * @param RedBeanModel $model the model being validated
  * @param string $attribute the attribute being validated
  */
 protected function validateAttribute($object, $attribute)
 {
     $value = $object->{$attribute};
     if ($this->allowEmpty && $this->isEmpty($value)) {
         return;
     }
     switch ($this->type) {
         case 'blob':
         case 'longblob':
             return;
         case 'integer':
             $valid = preg_match('/^[-+]?[0-9]+$/', trim($value));
             // Not Coding Standard
             break;
         case 'float':
             $valid = preg_match('/^[-+]?([0-9]*\\.)?[0-9]+([eE][-+]?[0-9]+)?$/', trim($value));
             // Not Coding Standard
             break;
         case 'date':
             $valid = DateTimeUtil::isValidDbFormattedDate($value);
             break;
         case 'time':
             $valid = CDateTimeParser::parse($value, $this->timeFormat) !== false;
             break;
         case 'datetime':
             $valid = DateTimeUtil::isValidDbFormattedDateTime($value);
             break;
         case 'array':
             $valid = is_array($value);
             break;
         case 'string':
         default:
             return;
     }
     if (!$valid) {
         if ($this->message !== null) {
             $message = $this->message;
         } else {
             $message = Zurmo::t('Core', '{attribute} must be {type}.');
         }
         $this->addError($object, $attribute, $message, array('{type}' => $this->type));
     }
 }
 public function actionUpdate($id)
 {
     $model = $this->loadModel($id);
     if (isset($_POST['Parametro'])) {
         $model->setAttributes($_POST['Parametro']);
         if ($model->valorfecha != '') {
             $model->valorfecha = date('Y-m-d', CDateTimeParser::parse($model->valorfecha, Yii::app()->locale->dateFormat));
         }
         try {
             if ($model->save()) {
                 $this->setFlash('notice', array('title' => 'Mensaje', 'content' => 'Se grabó correctamente.'));
                 $this->redirect(array('manage'));
             }
             // $model->refresh(); // Vuelvo a tomar los valores de la base de datos si falla la validac
         } catch (Exception $e) {
             $model->addError('', $e->getMessage());
         }
     }
     $this->render('update', array('model' => $model));
 }