/** * Сохраняет сообщения лога в базу данных. */ public function export() { $tableName = $this->db->quoteTableName($this->logTable); $sql = "INSERT INTO {$tableName} ([[level]], [[category]], [[log_time]], [[prefix]], [[message]])\n VALUES (:level, :category, :log_time, :prefix, :message)"; $command = $this->db->createCommand($sql); $i = 1; $saveText = ''; foreach ($this->messages as $message) { if ($i == 1) { list($text, $level, $category, $timestamp) = $message; } else { $text = $message[0]; } if (!is_string($text)) { // exceptions may not be serializable if in the call stack somewhere is a Closure if ($text instanceof \Exception) { $saveText .= (string) $text . "\n\n"; } else { $saveText .= VarDumper::export($text) . "\n\n"; } } else { $saveText .= $text; } $i++; } $command->bindValues([':level' => $level, ':category' => $category, ':log_time' => $timestamp, ':prefix' => $this->getMessagePrefix($message), ':message' => $saveText])->execute(); }
public function actionTovote (){ $id = (int)$_POST['id']; $voter = (int)$_POST['vote']; $ret = array(); // check $ip = MHelper::Ip()->getIp(); $vote = PollVote::model()->find(array('condition'=>'choice_id=:id and ip_address=:ip','params'=>array(':id'=>$id,':ip'=>$ip))); if(!$vote){ $vote = new PollVote; $vote->vote = $voter; $vote->choice_id = $id; $vote->ip_address = $ip; if(!Yii::app()->user->isGuest){ $vote->user_id = Yii::app()->user->id; } if(!$vote->save()){ VarDumper::dump($vote->errors); die(); // Ctrl + X Delete line } $weight = ''; $sql = "SELECT COUNT(*) FROM poll_vote WHERE choice_id={$id} and vote={$voter}"; $numClients = Yii::app()->db->createCommand($sql)->queryScalar(); $review = PollChoice::model()->findByPk($id); if($voter == 1){ $review->yes = $numClients; $diff = $review->yes - $review->no; $sum = $review->yes + $review->no; if($diff>0){ $weight = round(($diff)*100/$sum); } $review->weight = $weight; $review->votes = $diff; $review->save(false,array('yes','weight','votes')); } else { $review->no = $numClients; $diff = $review->yes - $review->no; $sum = $review->yes + $review->no; if($diff>0){ $weight = round(($diff)*100/$sum); } $review->weight = $weight; $review->votes = $diff; $review->save(false,array('no','weight','votes')); } $ret['flag'] = true; $ret['count'] = $numClients; $ret['yes'] = $review->yes; $ret['no'] = $review->no; $ret['type'] = $review->type; $ret['id'] = $review->id; $ret['weight'] = $weight; $ret['weight_text'] = (!empty($weight))?'считают '.$weight.'%':''; echo CJSON::encode($ret); } }
/** * Displays a single Rule model. * @param integer $id * @return mixed */ public function actionView($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { if (count($model->errors) > 0) { Yii::$app->session->setFlash('danger', Yii::t('igolf', 'Error(s): {0}', [VarDumper::dumpAsString($model->errors, 4, true)])); } return $this->render('view', ['model' => $model]); } }
/** * Dumps a variable in terms of a string. * This method achieves the similar functionality as var_dump and print_r * but is more robust when handling complex objects such as Yii controllers. * @param mixed $var variable to be dumped * @param integer $depth maximum depth that the dumper should go into the variable. Defaults to 10. * @param boolean $highlight whether the result should be syntax-highlighted * @return string the string representation of the variable */ public static function dumpAsString($var, $depth = 10, $highlight = false) { self::$_output = ''; self::$_objects = array(); self::$_depth = $depth; self::dumpInternal($var, 0); if ($highlight) { $result = highlight_string("<?php\n" . self::$_output, true); self::$_output = preg_replace('/<\\?php<br \\/>/', '', $result, 1); } return self::$_output; }
/** * * @param array $attributes * @throws Exception * @return \conquer\oauth2\models\RefreshToken */ public static function createRefreshToken(array $attributes) { static::deleteAll(['<', 'expires', time()]); $attributes['refresh_token'] = \Yii::$app->security->generateRandomString(40); $refreshToken = new static($attributes); if ($refreshToken->save()) { return $refreshToken; } else { \Yii::error(__CLASS__ . ' validation error:' . VarDumper::dumpAsString($refreshToken->errors)); } throw new Exception('Unable to create refresh token', Exception::SERVER_ERROR); }
/** * @inheritdoc */ public function formatMessage($message) { list($text, $level, $category, $timestamp) = $message; $level = Logger::getLevelName($level); if (!is_string($text)) { // exceptions may not be serializable if in the call stack somewhere is a Closure if ($text instanceof \Exception) { $text = (string) $text; } else { $text = VarDumper::export($text); } } $prefix = $this->getMessagePrefix($message); return "{$prefix}[{$level}][{$category}] {$text}"; }
public function actionCreateTestUser($email) { /* add demo users */ $demoUser = new FrontendUser(); $demoUser->username = "******"; $demoUser->email = $email; $password = $email . '123'; $demoUser->password = $password; $demoUser->save(); echo 'Ошибки:'; VarDumper::dump($demoUser->errors); if (sizeof($demoUser->errors) == 0) { echo '<h1>Новый пользователь успешно создан</h1>'; echo '<h2>Логин:' . $email . '</h2>'; echo '<h2>Пароль:' . $password . '</h2>'; } }
/** * Stores log messages to DB. */ public function export() { $tableName = $this->db->quoteTableName($this->logTable); $sql = "INSERT INTO {$tableName} ([[level]], [[category]], [[log_time]], [[prefix]], [[message]], [[user_id]], [[book_id]])\n VALUES (:level, :category, :log_time, :prefix, :message, :user_id, :book_id)"; $command = $this->db->createCommand($sql); foreach ($this->messages as $message) { list($text, $level, $category, $timestamp) = $message; if (!is_string($text)) { $text = VarDumper::export($text); } if ($category === 'book') { $m = explode('_', $text); $book_id = $m[0]; $text = end($m); } $command->bindValues([':level' => $level, ':category' => $category, ':log_time' => $timestamp, ':prefix' => $this->getMessagePrefix($message), ':message' => $text, ':user_id' => \Yii::$app->user->id ? \Yii::$app->user->id : null, ':book_id' => isset($book_id) ? $book_id : ''])->execute(); } }
/** * Handles uncaught PHP exceptions. * * This method is implemented as a PHP exception handler. * * @param \Exception $exception the exception that is not caught */ public function handleException($exception) { // disable error capturing to avoid recursive errors while handling exceptions $this->unregister(); // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent // HTTP exceptions will override this value in renderException() if (PHP_SAPI !== 'cli') { http_response_code(500); } try { $this->renderException($exception); } catch (\Exception $e) { // an other exception could be thrown while displaying the exception $msg = "An Error occurred while handling another error:\n"; $msg .= (string) $e; $msg .= "\nPrevious exception:\n"; $msg .= (string) $exception; echo 'An internal server error occurred.'; $msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER); error_log($msg); exit(1); } }
public function book() { //if we don't have a flight OR we moved to another flight if ($this->getCurrent() == null || $this->getCurrent()->flightVoyage->id != $this->flightVoyage->getId()) { //if we don't have a flight AND we moved to another flight if ($this->getCurrent() != null and $this->getCurrent()->flightVoyage->id != $this->flightVoyage->getId()) { $this->flightBooker = FlightBooker::model()->findByAttributes(array('flightVoyageId' => $this->flightVoyage->getId())); if (!$this->flightBooker) { $this->flightBooker = new FlightBooker(); $this->flightBooker->flightVoyageId = $this->flightVoyage->getId(); $this->flightBooker->flightVoyage = $this->flightVoyage; $this->flightBooker->status = 'enterCredentials'; $this->flightBooker->setFlightBookerComponent($this); if (!$this->flightBooker->save()) { VarDumper::dump($this->flightBooker->getErrors()); } } $this->flightBooker->setFlightBookerComponent($this); } if ($this->flightBooker == null) { Yii::trace('New flightBooker to db', 'FlightBookerComponent.book'); $this->flightBooker = new FlightBooker(); $this->flightBooker->flightVoyageId = $this->flightVoyage->getId(); $this->flightBooker->flightVoyage = $this->flightVoyage; $this->flightBooker->status = 'enterCredentials'; $this->flightBooker->setFlightBookerComponent($this); if (!$this->flightBooker->save()) { VarDumper::dump($this->flightBooker->getErrors()); } } } Yii::trace(CVarDumper::dumpAsString($this->flightBooker->getErrors()), 'FlightBookerComponent.book'); if (!$this->flightBooker->id) { $this->flightBooker->id = $this->flightBooker->primaryKey; } Yii::app()->user->setState('flightVoyageId', $this->flightBooker->flightVoyage->id); }
/** * The only difference here is to check if the form is used for tabular input. * If it is load attributes from the appropriate index from the submitted data */ public function loadData() { echo "load data"; //VarDumper::dump($this); //print_r($this); if (isset($this->_model)) { echo "model_exists"; if ($this->_model !== null) { $class = get_class($this->_model); echo "in feel"; if (strcasecmp($this->getRoot()->method, 'get') && isset($_POST[$class])) { echo 'in post'; if ($this->isTabular()) { echo 'tabular'; $this->_model->setAttributes($_POST[$class][$this->_key]); } else { echo 'notabular'; $this->_model->setAttributes($_POST[$class]); } } elseif (isset($_GET[$class])) { echo 'in get'; if ($this->isTabular()) { $this->_model->setAttributes($_GET[$class][$this->_key]); } else { $this->_model->setAttributes($_GET[$class]); } } } } foreach ($this->getElements() as $element) { if ($element instanceof self) { //echo 'Self instance'.get_class(self::); VarDumper::dump($element->getElements()); $element->loadData(); } } }
/** * Displays the login page */ public function actionLogin() { if (Yii::app()->user->isGuest) { $modelLogin = new UserLogin(); $modelRegister = new RegistrationForm(); $modelRecovery = new UserRecoveryForm(); // collect user input data if (isset($_POST['ajax']) && $_POST['ajax'] === 'form-login') { $errors = CActiveForm::validate($modelLogin); echo $errors; /* if(Yii::app()->request->urlReferrer && Yii::app()->request->urlReferrer == 'http://'.Yii::app()->request->serverName.'/mkreview'){ // Сохраняем в сессию единицу, чтобы сохранить данные в localStorage при создании отзыва Yii::app()->session['redirectReview'] = 1; }*/ Yii::app()->end(); } if (isset($_POST['ajax']) && $_POST['ajax'] === 'form-register') { if (isset($_POST['RegistrationForm']['username'])) { $modelRegister->fullname = $_POST['RegistrationForm']['username']; } $errors = CActiveForm::validate($modelRegister); if ($errors != '[]') { echo $errors; Yii::app()->end(); } } if (isset($_POST['UsersLogin'])) { $modelLogin->attributes = $_POST['UsersLogin']; // validate user input and redirect to previous page if valid if ($modelLogin->validate()) { $this->lastViset(); /* if(Yii::app()->request->urlReferrer && Yii::app()->request->urlReferrer == 'http://'.Yii::app()->request->serverName.'/mkreview'){ // Сохраняем в сессию единицу, чтобы сохранить данные в localStorage при создании отзыва Yii::app()->session['redirectReview'] = 1; }*/ if (Yii::app()->user->returnUrl == '/index.php' || Yii::app()->user->returnUrl == '/') { $this->redirect(Yii::app()->getModule('users')->returnUrl); } else { $this->redirect(Yii::app()->user->returnUrl); } } else { VarDumper::dump($modelLogin->errors); die; // Ctrl + X Delete line } } if (isset($_POST['RegistrationForm'])) { $modelRegister->attributes = $_POST['RegistrationForm']; $modelRegister->fullname = $modelRegister->username; $modelRegister->verifyPassword = $modelRegister->password; if ($modelRegister->validate()) { $soucePassword = $modelRegister->password; $modelRegister->activkey = UsersModule::encrypting(microtime() . $modelRegister->password); $modelRegister->password = UsersModule::encrypting($modelRegister->password); $modelRegister->verifyPassword = UsersModule::encrypting($modelRegister->verifyPassword); $modelRegister->superuser = 0; $modelRegister->status = Yii::app()->getModule('users')->activeAfterRegister ? User::STATUS_ACTIVE : User::STATUS_NOACTIVE; if ($modelRegister->save()) { if (Yii::app()->getModule('users')->sendActivationMail) { $activation_url = $this->createAbsoluteUrl('/users/activation/activation', array("activkey" => $modelRegister->activkey, "email" => $modelRegister->email)); UsersModule::sendMail($modelRegister->email, UsersModule::t("You registered from {site_name}", array('{site_name}' => Yii::app()->name)), UsersModule::t("Please activate you account go to {activation_url}", array('{activation_url}' => $activation_url))); } // wellcome email // $subject = Yii::t('email','Welcome'); // $message = Yii::t('email', 'Welcome to <a href="{url}">{catalog}</a>.', array('{url}'=>$this->createAbsoluteUrl('/'), '{catalog}'=>Yii::app()->name)); // SendMail::send($modelRegister->email,$subject,$message,true); if ((Yii::app()->getModule('users')->loginNotActiv || Yii::app()->getModule('users')->activeAfterRegister && Yii::app()->getModule('users')->sendActivationMail == false) && Yii::app()->getModule('users')->autoLogin) { $identity = new UserIdentity($modelRegister->username, $soucePassword); $identity->authenticate(); Yii::app()->user->login($identity, 0); $this->lastViset(); if (Yii::app()->request->isAjaxRequest) { echo '[]'; Yii::app()->end(); } else { /*if(Yii::app()->request->urlReferrer && Yii::app()->request->urlReferrer == 'http://'.Yii::app()->request->serverName.'/mkreview'){ // Сохраняем в сессию единицу, чтобы сохранить данные в localStorage при создании отзыва Yii::app()->session['redirectReview'] = 1; }*/ if (Yii::app()->request->urlReferrer && Yii::app()->request->urlReferrer != 'http://' . Yii::app()->request->serverName . '/login') { $url = Yii::app()->request->urlReferrer; $this->redirect($url); } else { $this->redirect('/'); } } } else { if (!Yii::app()->getModule('users')->activeAfterRegister && !Yii::app()->getModule('users')->sendActivationMail) { Yii::app()->user->setFlash('registration', UsersModule::t("Thank you for your registration. Contact Admin to activate your account.")); } elseif (Yii::app()->getModule('users')->activeAfterRegister && Yii::app()->getModule('users')->sendActivationMail == false) { Yii::app()->user->setFlash('registration', UsersModule::t("Thank you for your registration. Please {{login}}.", array('{{login}}' => CHtml::link(UserModule::t('Login'), Yii::app()->getModule('users')->loginUrl)))); } elseif (Yii::app()->getModule('users')->loginNotActiv) { Yii::app()->user->setFlash('registration', UsersModule::t("Thank you for your registration. Please check your email or login.")); } else { Yii::app()->user->setFlash('registration', UsersModule::t("Thank you for your registration. Please check your email.")); } if (Yii::app()->request->isAjaxRequest) { echo '[]'; Yii::app()->end(); } else { /*if(Yii::app()->request->urlReferrer && Yii::app()->request->urlReferrer == 'http://'.Yii::app()->request->serverName.'/mkreview'){ // Сохраняем в сессию единицу, чтобы сохранить данные в localStorage при создании отзыва Yii::app()->session['redirectReview'] = 1; }*/ if (Yii::app()->request->urlReferrer && Yii::app()->request->urlReferrer != 'http://' . Yii::app()->request->serverName . '/login') { $url = Yii::app()->request->urlReferrer; $this->redirect($url); } else { $this->redirect('/'); } } } } } else { var_dump($modelRegister->errors); die; } } // display the login form $this->render('application.modules.users.views.user.login', array('modelLogin' => $modelLogin, 'modelRecovery' => $modelRecovery, 'modelRegister' => $modelRegister)); } else { if (Yii::app()->request->urlReferrer && Yii::app()->request->urlReferrer != 'http://' . Yii::app()->request->serverName . '/login') { $url = Yii::app()->request->urlReferrer; $this->redirect($url); } else { $this->redirect('/'); } } }
/** * Manages all models. */ public function actionAdmin() { /*$roomSizes = array( 'Одноместный %s', 'Двухместный %s', 'Двухместный Твин %s', 'Двухместный %s с одноместным размещением', 'Трехместный %s', 'Четырехместный %s', ); $roomTypes = array( 'большой номер', 'номер студия', 'семейный номер', 'семейный номер студия', 'номер Сьюит', 'улучшеный номер', 'Эконом', 'Бизнес', 'номер De luxe', 'номер для молодожёнов', 'номер с балконом', ); foreach($roomTypes as $roomType){ foreach($roomSizes as $roomSize){ $name = sprintf($roomSize,$roomType); $roomName = new RoomNamesRus(); $roomName->roomNameRus = $name; $roomName->save(); } }*/ /*$criteria = new CDbCriteria(); $criteria->group = 'sizeName,typeName,roomNameCanonical'; $roomSizes = array('DBL'=>2,'SGL'=>1,'TWIN'=>3,'TWIN for Single use'=>4,'TRPL'=>5,'QUAD'=>6,'DBL for Single use'=>7,'DBL OR TWIN'=>8); echo 'найдено комбинаций: '.HotelRoomDb::model()->count($criteria); $rooms = HotelRoomDb::model()->findAll($criteria); /** @var $rooms HotelRoomDb[] */ /*foreach($rooms as $room){ if($room->roomNameCanonical){ $nemoRoom = new RoomNamesNemo(); $nemoRoom->roomTypeId = $room->typeId; $nemoRoom->roomSizeId = $roomSizes[$room->sizeName]; $nemoRoom->roomNameCanonical = $room->roomNameCanonical; $nemoRoom->save(); } }*/ /* * связи для таблиц */ //двухместные апартаменты /*$criteria = new CDbCriteria(); $criteria->addSearchCondition('roomNameCanonical', '%apartment%', false); $criteria->addSearchCondition('roomSizeId',6); //$criteria->group = 'sizeName,typeName,roomNameCanonical'; //$roomSizes = array('DBL'=>2,'SGL'=>1,'TWIN'=>3,'TWIN for Single use'=>4,'TRPL'=>5,'QUAD'=>6,'DBL for Single use'=>7,'DBL OR TWIN'=>8); echo 'найдено комбинаций: '.RoomNamesNemo::model()->count($criteria).'<br />'; $rooms = RoomNamesNemo::model()->findAll($criteria); $rusRoomName = RoomNamesRus::model()->findByAttributes(array('roomNameRus'=>'Четырехместные апартаменты')); VarDumper::dump($rusRoomName);*/ /** @var $rooms RoomNamesNemo[] */ /*foreach($rooms as $room){ echo "{$rusRoomName->roomNameRus} {$rusRoomName->id}<br />"; if($room->roomNameCanonical){ echo $room->roomSizeId.' '.$room->roomNameCanonical.' <br />'; $room->roomNameRusId = $rusRoomName->id; $room->save(); //$nemoRoom = new RoomNamesNemo(); //$nemoRoom->roomTypeId = $room->typeId; //$nemoRoom->roomSizeId = $roomSizes[$room->sizeName]; //$nemoRoom->roomNameCanonical = $room->roomNameCanonical; //$nemoRoom->save(); } }*/ //семейные /*$criteria = new CDbCriteria(); $criteria->addSearchCondition('roomNameCanonical', '%family%', false); $criteria->addSearchCondition('roomSizeId',3); //$criteria->group = 'sizeName,typeName,roomNameCanonical'; //$roomSizes = array('DBL'=>2,'SGL'=>1,'TWIN'=>3,'TWIN for Single use'=>4,'TRPL'=>5,'QUAD'=>6,'DBL for Single use'=>7,'DBL OR TWIN'=>8); echo 'найдено комбинаций: '.RoomNamesNemo::model()->count($criteria).'<br />'; $rooms = RoomNamesNemo::model()->findAll($criteria); $rusRoomName = RoomNamesRus::model()->findByAttributes(array('roomNameRus'=>'Двухместный Твин семейный номер')); VarDumper::dump($rusRoomName);*/ /** @var $rooms RoomNamesNemo[] */ /*foreach($rooms as $room){ echo "{$rusRoomName->roomNameRus} {$rusRoomName->id}<br />"; if($room->roomNameCanonical){ echo $room->roomSizeId.' '.$room->roomNameCanonical.' <br />'; $room->roomNameRusId = $rusRoomName->id; $room->save(); } }*/ //studio /*$criteria = new CDbCriteria(); $criteria->addSearchCondition('roomNameCanonical', '%suite%', false); $criteria->addSearchCondition('roomSizeId',6); //$criteria->group = 'sizeName,typeName,roomNameCanonical'; //$roomSizes = array('DBL'=>2,'SGL'=>1,'TWIN'=>3,'TWIN for Single use'=>4,'TRPL'=>5,'QUAD'=>6,'DBL for Single use'=>7,'DBL OR TWIN'=>8); echo 'найдено комбинаций: '.RoomNamesNemo::model()->count($criteria).'<br />'; $rooms = RoomNamesNemo::model()->findAll($criteria); $rusRoomName = RoomNamesRus::model()->findByAttributes(array('roomNameRus'=>'Четырехместный большой номер')); VarDumper::dump($rusRoomName); /** @var $rooms RoomNamesNemo[] */ /*foreach($rooms as $room){ echo "{$rusRoomName->roomNameRus} {$rusRoomName->id}<br />"; if($room->roomNameCanonical){ echo $room->roomSizeId.' '.$room->roomNameCanonical.' <br />'; //$room->roomNameRusId = $rusRoomName->id; //$room->save(); } } //studio /*$criteria = new CDbCriteria(); $criteria->addSearchCondition('roomNameCanonical', '%tive suite%', false); $criteria->addSearchCondition('roomSizeId',3); //$criteria->group = 'sizeName,typeName,roomNameCanonical'; //$roomSizes = array('DBL'=>2,'SGL'=>1,'TWIN'=>3,'TWIN for Single use'=>4,'TRPL'=>5,'QUAD'=>6,'DBL for Single use'=>7,'DBL OR TWIN'=>8); echo 'найдено комбинаций: '.RoomNamesNemo::model()->count($criteria).'<br />'; $rooms = RoomNamesNemo::model()->findAll($criteria); $rusRoomName = RoomNamesRus::model()->findByAttributes(array('roomNameRus'=>'Двухместный Твин улучшеный номер')); VarDumper::dump($rusRoomName);*/ /** @var $rooms RoomNamesNemo[] */ /*foreach($rooms as $room){ echo "{$rusRoomName->roomNameRus} {$rusRoomName->id}<br />"; if($room->roomNameCanonical){ echo $room->roomSizeId.' '.$room->roomNameCanonical.' <br />'; //$room->roomNameRusId = $rusRoomName->id; //$room->save(); } }*/ //распечатать все /*$rusRoomNames = RoomNamesRus::model()->findAll(); foreach($rusRoomNames as $room){ echo "{$room->id} {$room->roomNameRus} <br />"; }*/ Yii::import('site.common.modules.hotel.models.*'); $hbc = new HotelBookClient(); $rts = $hbc->getRoomTypes(); $roomTypes = array(); foreach ($rts as $rt) { $roomTypes[$rt['id']] = $rt['name']; } VarDumper::dump($roomTypes); }
private function autocompleteHotelsAirports() { $search = array('query' => 'LED', 'airport_req' => 1, 'hotel_req' => 2); VarDumper::dump($search); $fullUrl = $this->buildAutocompleteApiUrl($search); $result = file_get_contents($fullUrl); return $result; }
public function starRating($id, $ratingAjax) { $id = (int)$id; $org = Orgs::model()->findByPk($id); if($org){ $rating = OrgsRating::model()->findByAttributes(array( 'org'=>$id )); // если не было категории - делаем if(!$rating) { $rating = new OrgsRating; $rating->org = $id; $rating->vote_count = 1; $rating->vote_sum = $ratingAjax; $rating->vote_average = round($rating->vote_sum / $rating->vote_count,2); $rating->save(false); $org->rating_id = $rating->id; $org->save(false,array('rating_id')); } else { $rating->vote_count = $rating->vote_count + 1; $rating->vote_sum = $rating->vote_sum + $ratingAjax; $rating->vote_average = round($rating->vote_sum / $rating->vote_count,2); if(!$rating->save()){ VarDumper::dump($rating->errors); die(); // Ctrl + X Delete line } } } return true; }
/** * Update category */ public function actionUpdate($id) { $err = true; $this->breadcrumbs = array('Теги' => array('index'), 'Редактировать'); $id = (int) $id; $model = $this->loadModel($id); if ($model->status_id == Category::STATUS_DELETED) { $this->render('categorydeleted'); Yii::app()->end(); } $this->pageTitle = $model->title . ' - ' . Yii::app()->name; if (isset($_POST['Category'])) { $model->attributes = $_POST['Category']; if ($model->validate()) { if ($model->getParent() === null) { $parent_id_old = null; } else { $parent_id_old = $model->getParent()->id; } $target = null; if ($parent_id_old == $model->parent_id) { // if sending parent_id == current parrent_id do nothing; if ($model->saveNode()) { $err = false; } } else { // move node // $model->deleteNode(); // $model->refresh(); if ($model->parent_id) { $pos = isset($_POST['position']) ? (int) $_POST['position'] : null; $target = $this->loadModel($model->parent_id); $childs = $target->children()->findAll(); if (!empty($pos) && isset($childs[$pos - 1]) && $childs[$pos - 1] instanceof Category && $childs[$pos - 1]['id'] != $model->id) { $model->moveAfter($childs[$pos - 1]); if ($model->saveNode()) { $err = false; } } else { if ($target->id != $model->id) { $model->moveAsLast($target); if ($model->saveNode()) { $err = false; } } } } else { $model->moveAsRoot(); if ($model->saveNode()) { $err = false; } } } if (Yii::app()->request->isAjaxRequest) { if ($err === false) { echo json_encode(array('success' => true)); } else { echo json_encode(array('success' => false)); } Yii::app()->end(); } else { if ($err === false) { Yii::app()->user->setFlash('success', "Тег {$model->title} успешно обновлен"); $this->redirect(Yii::app()->createAbsoluteUrl('/admin/tags')); } else { Yii::app()->user->setFlash('error', "Ошибка обновления тега"); } $this->redirect(array('index')); } } else { if (Yii::app()->request->isAjaxRequest) { echo CJSON::encode(array('success' => false, 'message' => $model->errors)); Yii::app()->end(); } else { VarDumper::dump($model->errors); die; // Ctrl + X Delete line } } } $criteria = new CDbCriteria(); $criteria->condition = 'model_name=:model_name and model_id=' . $model->id; $criteria->params = array(':model_name' => 'Category'); $this->render('_form', array('model' => $model)); }
public function execute() { $valid = false; //collecting booking info for whole ticket $booking = new BookingForm(); if (isset($_POST['BookingForm'])) { $valid = true; $booking->attributes = $_POST['BookingForm']; $valid = $valid && $booking->validate(); } //collecting adults passport data $adults = Yii::app()->flightBooker->getCurrent()->FlightVoyage->adultPassengerInfo; $adultPassports = array(); if ($adults) { $countAdults = $adults->count; for ($i = 0; $i < $countAdults; $i++) { $adultPassports[] = new FlightAdultPassportForm(); } $isOk = $this->collect('FlightAdultPassportForm', $adultPassports); $valid = $valid && $isOk; } //collecting child passport data $children = Yii::app()->flightBooker->getCurrent()->FlightVoyage->childPassengerInfo; $childrenPassports = array(); if ($children) { $countChildren = $children->count; for ($i = 0; $i < $countChildren; $i++) { $childrenPassports[] = new FlightChildPassportForm(); } $isOk = $this->collect('FlightChildPassportForm', $childrenPassports); $valid = $valid && $isOk; } //collecting infant passport data $infant = Yii::app()->flightBooker->getCurrent()->FlightVoyage->infantPassengerInfo; $infantPassports = array(); if ($infant) { $infantChildren = $infant->count; for ($i = 0; $i < $infantChildren; $i++) { $infantPassports[] = new FlightInfantPassportForm(); } $isOk = $this->collect('FlightInfantPassportForm', $infantPassports); $valid = $valid && $isOk; } if ($valid) { //saving data to objects //TODO: link to OrderBooking object $flightBookerComponent = Yii::app()->flightBooker; $flightBookerComponent->book(); $flightBookerId = $flightBookerComponent->getCurrent()->primaryKey; $bookingAr = new OrderBooking(); $bookingAr->populate($booking); if (!Yii::app()->user->isGuest) { $bookingAr->userId = Yii::app()->user->id; } $bookingPassports = array(); $allPassports = array_merge($adultPassports, $childrenPassports, $infantPassports); foreach ($allPassports as $passport) { $bookingPassport = new FlightBookingPassport(); $bookingPassport->populate($passport, $flightBookerId); if (!$bookingPassport->save()) { VarDumper::dump($bookingPassport->getErrors()); } else { $bookingPassports[] = $bookingPassport; } } if ($bookingAr->save()) { Yii::app()->flightBooker->getCurrent()->orderBookingId = $bookingAr->id; Yii::app()->flightBooker->status('booking'); } else { VarDumper::dump($bookingAr->getErrors()); $this->getController()->render('flightBooker.views.enterCredentials', array('passport' => $passport, 'booking' => $booking)); } } else { $this->getController()->render('flightBooker.views.enterCredentials', array('adultPassports' => $adultPassports, 'childrenPassports' => $childrenPassports, 'infantPassports' => $infantPassports, 'booking' => $booking)); } }
$baseUrl = WebAsset::register($this)->baseUrl; //$this->title = $name; //TODO traducir textos a español pagina error ?> <div class="container"> <div class="row"> <div class="col-lg-12 col-md-12"> <div class="error-content"> <div class="error-content"> <?php if (Yii::$app->getSession()->hasFlash('error')) { echo '<div class="alert alert-danger">' . Yii::$app->getSession()->getFlash('error') . '</div>'; } ?> <?php $identity = Yii::$app->getUser()->getIdentity(); // $identity = Yii::$app->getUser()->identity; echo '<pre>'; print_r($identity); if (isset($identity->perfil)) { VarDumper::dump($identity->perfil, 10, true); } ?> </div> </div> </div> </div> </div>
/** * Generates a string depending on enableI18N property * * @param string $string the text be generated * @param array $placeholders the placeholders to use by `Yii::t()` * @return string */ public function generateString($string = '', $placeholders = []) { $string = addslashes($string); if ($this->enableI18N) { // If there are placeholders, use them if (!empty($placeholders)) { $ph = ', ' . VarDumper::export($placeholders); } else { $ph = ''; } $str = "Lang::get('{$this->messageCategory}.{$string}')"; } else { // No I18N, replace placeholders by real words, if any if (!empty($placeholders)) { $phKeys = array_map(function ($word) { return '{' . $word . '}'; }, array_keys($placeholders)); $phValues = array_values($placeholders); $str = "'" . str_replace($phKeys, $phValues, $string) . "'"; } else { // No placeholders, just the given string $str = "'" . $string . "'"; } } return $str; }
public function actionUpdate($id) { $user = $this->_loadUser($id); // if($user->id == Yii::app()->user->id) // $this->redirect('/settings'); // форма изменения пароля $changePassword = new UserChangePassword(); if (isset($_POST['User'])) { $this->performAjaxValidation($user, 'form-fullname'); $this->performAjaxValidation($user, 'form-about'); $this->performAjaxValidation($user, 'form-social'); if (isset($_POST['ajax']) && $_POST['ajax'] === 'form-account-username') { $errors = CActiveForm::validate($user); if ($errors !== '[]') { // echo CJSON::encode($errors); //echo CJSON::encode(false); echo 'false'; Yii::app()->end(); } } if (isset($_POST['ajax']) && $_POST['ajax'] === 'form-account-email') { $errors = CActiveForm::validate($user); if ($errors !== '[]') { //echo CJSON::encode($errors); //echo CJSON::encode(false); echo 'false'; Yii::app()->end(); } } $data = Yii::app()->request->getPost('User'); if ($data) { $user->attributes = $data; } if (!$user->save()) { VarDumper::dump($user->errors); } } if (isset($_POST['UserChangePassword'])) { $this->performAjaxValidation($changePassword, 'form-changepassword'); $data = Yii::app()->request->getPost('UserChangePassword'); $changePassword->attributes = $data; if ($changePassword->validate()) { $new_password = User::model()->notsafe()->findbyPk($user->id); $new_password->password = UsersModule::encrypting($changePassword->password); $new_password->activkey = UsersModule::encrypting(microtime() . $changePassword->password); if ($new_password->save(false)) { echo 'done'; } else { // VarDumper::dump($new_password->errors); } } } if (Yii::app()->request->isAjaxRequest) { Yii::app()->end(); } else { $this->render('view', array('user' => $user, 'changePassword' => $changePassword)); } }
public function actionStarRating($id) { $ratingAjax=isset($_POST['rate']) ? $_POST['rate'] : 0; $id = (int)$id; $org = Orgs::model()->findByPk($id); if($org){ $rating = OrgsRating::model()->findByAttributes(array( 'org'=>$id )); // если не было категории - делаем if(!$rating) { $rating = new OrgsRating; $rating->org = $id; $rating->vote_count = 1; $rating->vote_sum = $ratingAjax; $rating->vote_average = round($rating->vote_sum / $rating->vote_count,2); $rating->save(false); $org->rating_id = $rating->id; $org->save(false,array('rating_id')); } else { $rating->vote_count = $rating->vote_count + 1; $rating->vote_sum = $rating->vote_sum + $ratingAjax; $rating->vote_average = round($rating->vote_sum / $rating->vote_count,2); if(!$rating->save()){ VarDumper::dump($rating->errors); die(); // Ctrl + X Delete line } } echo CJSON::encode(array('status'=>'OK')); Yii::app()->end(); } }
public function saveReference($order) { $orderHasFlightVoyage = new OrderHasFlightVoyage(); $orderHasFlightVoyage->orderId = $order->id; $orderHasFlightVoyage->orderFlightVoyage = $this->internalId; if (!$orderHasFlightVoyage->save()) { throw new CException(VarDumper::dumpAsString($this->attributes) . VarDumper::dumpAsString($orderHasFlightVoyage->errors)); } }
public function run() { VarDumper::dump(Yii::app()->order->getPayment()); }
/** * Formats a log message for display as a string. * @param string $message The log message to be formatted. * @return string The formatted message. */ public function formatMessage($message) : string { list($text, $level, $category) = $message; return strtr('[{level}@{category}] {text}', ['{category}' => $category, '{level}' => Logger::getLevelName($level), '{text}' => is_string($text) ? $text : VarDumper::export($text)]); }
function vd($var, $depth = 10, $highlight = true) { VarDumper::dump($var, $depth, $highlight); die; }
public function __doRequest($request, $location, $action, $version, $oneWay = 0) { //echo $action; if (strpos($action, 'Search11') !== FALSE) { //echo $action.'||||'; $request = '<?xml version="1.0" encoding="UTF-8"?> <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> <env:Body> <Search xmlns="http://tempuri.org/"> <Request> <Requisites> <Login>webdev012</Login> <Password>HHFJGYU3*^H</Password> </Requisites> <RequestType>U</RequestType> <UserID>15</UserID> <Search> <ODPairs Type="OW" Direct="false" AroundDates="0"> <ODPair> <DepDate>2012-06-13T00:00:00</DepDate> <DepAirp>MOW</DepAirp> <ArrAirp>IJK</ArrAirp> </ODPair> </ODPairs> <Travellers> <Traveller Type="ADT" Count="1"/> </Travellers> <Restrictions> <ClassPref>All</ClassPref> <OnlyAvail>true</OnlyAvail> <AirVPrefs/> <IncludePrivateFare>false</IncludePrivateFare> <CurrencyCode>RUB</CurrencyCode> </Restrictions> </Search> </Request> </Search> </env:Body> </env:Envelope>'; //echo VarDumper::xmlDump($request); $sXML = $this->makeSoapRequest($request, $location, $action, $version); //$sXML = parent::__doRequest($request, $location, $action, $version); //echo VarDumper::xmlDump($sXML); //die(); } elseif (strpos($action, 'bookFlight1') !== FALSE) { $this->gdsRequest->requestXml = UtilsHelper::formatXML($request); $this->gdsRequest->save(); echo '???'; VarDumper::dump($request); return ""; } else { //die(); $this->gdsRequest->requestXml = UtilsHelper::formatXML($request); $this->gdsRequest->save(); //VarDumper::dump($request); //die(); $startTime = microtime(true); $sXML = $this->makeSoapRequest($request, $location, $action, $version); $endTime = microtime(true); $this->gdsRequest->executionTime = $endTime - $startTime; $this->gdsRequest->responseXml = UtilsHelper::formatXML($sXML); $this->gdsRequest->save(); if (!$sXML) { $this->gdsRequest->errorDescription = Yii::t('application', 'Error on soap request. Curl description: {curl_desc}. Last headers: {last_headers}.', array('{curl_desc}' => GDSNemoSoapClient::$lastCurlError, '{last_headers}' => GDSNemoSoapClient::$lastHeaders)); $this->gdsRequest->save(); throw new CException(Yii::t('application', 'Error on soap request. Curl description: {curl_desc}. Last headers: {last_headers}.', array('{curl_desc}' => GDSNemoSoapClient::$lastCurlError, '{last_headers}' => GDSNemoSoapClient::$lastHeaders))); } //$sXML = parent::__doRequest($request, $location, $action, $version); //echo VarDumper::xmlDump($sXML); //die(); } return $sXML; }
public function actionDefault() { if ($error = Yii::app()->errorHandler->error) { VarDumper::dump($error); } }
/** * Displays the contact page */ public function actionContact() { $this->pageTitle = Yii::app()->name . ' - ' . Yii::t('site', 'Contact'); $model = new ContactForm(); if (isset($_POST['ajax']) && $_POST['ajax'] === 'contact-form') { $model->attributes = Yii::app()->request->getPost('ContactForm'); $errors = CActiveForm::validate($model); if ($errors !== '[]') { echo $errors; } else { if ($model->validate()) { $subject = 'Анетика. Сообщение с формы обратной связи.'; $content = null; $content .= 'Имя: ' . $model->name . "\r\n"; $content .= 'E-mail: ' . $model->email . "\r\n" . 'Сообщение: ' . "\r\n" . $model->body; $mailto = '*****@*****.**'; // $mailto = '*****@*****.**'; $send = SendMail::send($mailto, $subject, $content, false); if (!isset($send->ErrorInfo) && !empty($send->ErrorInfo)) { VarDumper::dump($send->ErrorInfo); die; // Ctrl + X Delete line } if ($send) { $message = Yii::t('site', 'Your message has been successfully sent'); if (Yii::app()->request->isAjaxRequest) { echo CJSON::encode(array('flag' => true, 'message' => $message)); } else { Yii::app()->user->setFlash('success', $message); $this->refresh(); } } else { $message = Yii::t('site', 'Error sending message.'); // $message .= $send->ErrorInfo; if (Yii::app()->request->isAjaxRequest) { echo CJSON::encode(array('flag' => false, 'message' => $message)); } else { Yii::app()->user->setFlash('error', $message); $this->refresh(); } } } } Yii::app()->end(); } $this->render('contact', array('model' => $model)); }
/** * Function for sorting by uasort * @param HotelStack $a * @param HotelStack $b */ private static function compareStacksByHotelsParams($a, $b) { if (is_object($a->getHotel()) and $a->getHotel() instanceof Hotel) { $valA = $a->getHotel()->getValueOfParam(self::$sortParam); } else { throw new CException('Incorrect first hotel incoming to compareness: ' . VarDumper::dumpAsString($a)); } if (is_object($b->getHotel()) and $b->getHotel() instanceof Hotel) { $valB = $b->getHotel()->getValueOfParam(self::$sortParam); } else { throw new CException('Incorrect second hotel incoming to compareness: ' . VarDumper::dumpAsString($b)); } if ($valA < $valB) { return -1; } elseif ($valA > $valB) { return 1; } return 0; }
<div> <?php echo $error['message']; ?> </div> <?php if (YII_DEBUG) { ?> <div style="margin-top: 10px;"> <b>Файл:</b> <?php echo $error['file']; ?> <br> <b>Строка:</b> <?php echo $error['line']; ?> <pre style="margin-top: 10px;"><?php echo $error['trace']; ?> </pre> </div> <?php VarDumper::dump($error); } ?> <div> <br> <a href="javascript:history.back(-1)">← Назад</a> </div> </div>