PHP Method Yii::log Code Examples

This page contains top rated real world PHP examples of method Yii::log extracted from open source projects. You can rate examples to help us improve the quality of examples
Example #1
Show file File: StudentRegisterForm.php Project: aakbar24/CollegeCorner_Ver_2.0
0
 public function save()
 {
     //start a transaction
     $transaction = Yii::app()->db->beginTransaction();
     try {
         if ($this->user->isNewRecord) {
             $this->user->is_verified = 0;
             $verification = new UserVerification();
         }
         //try to save the data to db
         $ret = parent::save();
         if ($ret) {
             $ret = $this->student->save(true, null, $this->user);
             if (isset($verification)) {
                 Yii::log("Verification is set");
                 $verification->user_id = $this->user->user_id;
                 $this->hash = $verification->generateHash();
                 if (!$verification->save()) {
                     throw new Exception();
                 }
                 if (!Emailer::emailStudentActivation($this->user, $this->hash)) {
                     throw new Exception();
                 }
             }
         }
         $transaction->commit();
         //Yii::app()->user->setFlash('success',sprintf(Constants::SUCCESS_SURVEY_SUBMITTED,$model->getSurvey()->title));
         return $ret;
     } catch (Exception $e) {
         //if something happens, simply set the error message and redirect as normal
         $transaction->rollback();
         //Yii::app()->user->setFlash('error','Unable to create your account.');
         return false;
     }
 }
Example #2
Show file File: CrugeAuthDefault.php Project: AndressJose/bolsa-proyecto-integrado
0
 public function authenticate()
 {
     Yii::log(__METHOD__, "info");
     $this->errorCode = self::ERROR_USERNAME_INVALID;
     $model = Yii::app()->user->um->loadUser($this->username);
     Yii::log(__METHOD__ . " usuario retornado es:\n" . CJSON::encode($model), "info");
     $this->_userinstance = null;
     if ($model != null) {
         if ($model->password == $this->_getPwd()) {
             $this->_userinstance = $model;
             $this->errorCode = self::ERROR_NONE;
         } else {
             if (CrugeUtil::config()->debug == true) {
                 // ayuda a instalar, quiza el usuario olvide quitar la encriptacion de claves
                 // y reciba error de ERROR_PASSWORD_INVALID, es porque esta actuando el MD5
                 // y el usuario recien creado trae una clave no encritpada
                 if (CrugeUtil::config()->useEncryptedPassword == true) {
                     echo Yii::app()->user->ui->setupAlert("Quiza su clave no coincide porque ha configurado 'useEncryptedPassword = true' estando en la fase de instalacion, pruebe deshabilitandolo");
                 }
             }
             $this->errorCode = self::ERROR_PASSWORD_INVALID;
         }
     } else {
         // username o email error
         $this->errorCode = self::ERROR_USERNAME_INVALID;
     }
     Yii::log(__CLASS__ . "\nauthenticate returns:\n" . $this->errorCode . "\n boolean result is:" . ($this->errorCode == self::ERROR_NONE), "info");
     return $this->errorCode == self::ERROR_NONE;
 }
Example #3
Show file File: EExcelView.php Project: MGGROUP/SAMDEPURACION
0
 public function init()
 {
     if (isset($_GET[$this->grid_mode_var])) {
         $this->grid_mode = $_GET[$this->grid_mode_var];
     }
     if (isset($_GET['exportType'])) {
         $this->exportType = $_GET['exportType'];
     }
     $lib = Yii::getPathOfAlias($this->libPath) . '.php';
     if ($this->grid_mode == 'export' and !file_exists($lib)) {
         $this->grid_mode = 'grid';
         Yii::log("PHP Excel lib not found({$lib}). Export disabled !", CLogger::LEVEL_WARNING, 'EExcelview');
     }
     if ($this->grid_mode == 'export') {
         $this->title = $this->title ? $this->title : Yii::app()->getController()->getPageTitle();
         $this->initColumns();
         //parent::init();
         //Autoload fix
         spl_autoload_unregister(array('YiiBase', 'autoload'));
         Yii::import($this->libPath, true);
         $this->objPHPExcel = new PHPExcel();
         spl_autoload_register(array('YiiBase', 'autoload'));
         // Creating a workbook
         $this->objPHPExcel->getProperties()->setCreator($this->creator);
         $this->objPHPExcel->getProperties()->setTitle($this->title);
         $this->objPHPExcel->getProperties()->setSubject($this->subject);
         $this->objPHPExcel->getProperties()->setDescription($this->description);
         $this->objPHPExcel->getProperties()->setCategory($this->category);
     } else {
         parent::init();
     }
 }
Example #4
Show file File: BaseController.php Project: nizsheanez/documentation
0
 public function checkAccess($item_name)
 {
     //Если суперпользователь, то разрешено все
     if (isset(Yii::app()->user->role) && Yii::app()->user->role == AuthItem::ROLE_ROOT) {
         return true;
     }
     $auth_item = AuthItem::model()->findByPk($item_name);
     if (!$auth_item) {
         Yii::log('Задача $item_name не найдена!');
         return false;
     }
     if ($auth_item->allow_for_all) {
         return true;
     }
     if ($auth_item->task) {
         if ($auth_item->task->allow_for_all) {
             return true;
         } elseif (Yii::app()->user->checkAccess($auth_item->task->name)) {
             return true;
         }
     } else {
         if (Yii::app()->user->checkAccess($auth_item->name)) {
             return true;
         }
     }
     return false;
 }
Example #5
Show file File: AdminattributerelevanceController.php Project: schrapps/risksur
0
 public function actionCreate()
 {
     $modelArray[] = new EvaAttributesMatrix();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['EvaAttributesMatrix'])) {
         //$model = new EvaAttributesMatrix();
         $success = true;
         $transaction = Yii::app()->db->beginTransaction();
         try {
             foreach ($_POST['EvaAttributesMatrix'] as $index => $row) {
                 $modelArray[$index] = new EvaAttributesMatrix();
                 $modelArray[$index]->unsetAttributes();
                 $modelArray[$index]->attributes = $row;
                 if (!$modelArray[$index]->validate()) {
                     $success = false;
                     break;
                 }
                 $modelArray[$index]->save(false);
             }
             if ($success) {
                 $transaction->commit();
                 Yii::app()->user->setFlash('success', 'Attribute relevance saved successfully');
                 $this->redirect('index');
                 return;
             }
         } catch (Exception $e) {
             $transaction->rollBack();
             Yii::log($e->getMessage(), 'error', 'ctrl.Attributerelevance');
             Yii::app()->user->setFlash('error', 'An error occurred, ' . 'please try again or contact you administrator if the problem persists');
         }
     }
     $this->menu = [['label' => 'List Attribute Relevance', 'url' => $this->createUrl('index')]];
     $this->render('create', ['model' => $modelArray]);
 }
Example #6
Show file File: RWebUser.php Project: stan5621/eduwind
0
 public function init()
 {
     //parent::init();
     $this->attachBehaviors($this->behaviors);
     //$this->_initialized=true;
     Yii::app()->getSession()->open();
     if ($this->getIsGuest() && $this->allowAutoLogin) {
         //从cookie得到用户的id
         $userId = $this->getUserIdFromCookie();
         //查看是否有session登记到userId名下,没有的话,恢复用户的身份,否则什么都不做
         if (!Yii::app()->getSession()->getUserOldSession($userId)) {
             $this->restoreFromCookie();
         }
         if (!$this->getIsGuest()) {
             //如果用cookie-based login 恢复了登录的状态
             //记录登录情况
             $category = EwDbLogRoute::LOGIN_AUTO;
             $level = CLogger::LEVEL_INFO;
             $msg = serialize(array('message' => EwDbLogRoute::LOGIN_AUTO_MSG, 'userId' => $this->getId()));
             Yii::log($msg, $level, $category);
             //向session表中记录用户的id
             Yii::app()->getSession()->writeUserId($this->getId());
         }
     } elseif ($this->autoRenewCookie && $this->allowAutoLogin) {
         $this->renewCookie();
     }
     if ($this->autoUpdateFlash) {
         $this->updateFlash();
     }
     $this->updateAuthStatus();
 }
Example #7
Show file File: LanguageSelector.php Project: mjrouser/cityapi
0
 public static function setLanguage($cookieDays = 180)
 {
     if (Yii::app()->request->getPost('languageSelector') !== null && in_array($_POST['languageSelector'], self::getLanguagesList(), true)) {
         Yii::app()->setLanguage($_POST['languageSelector']);
         $cookie = new CHttpCookie('language', $_POST['languageSelector']);
         $cookie->expire = time() + 60 * 60 * 24 * $cookieDays;
         Yii::app()->request->cookies['language'] = $cookie;
     } else {
         if (isset(Yii::app()->request->cookies['language']) && in_array(Yii::app()->request->cookies['language']->value, self::getLanguagesList(), true)) {
             Yii::app()->setLanguage(Yii::app()->request->cookies['language']->value);
         } else {
             if (isset(Yii::app()->request->cookies['language'])) {
                 // Invalid language
                 unset(Yii::app()->request->cookies['language']);
             } else {
                 Yii::import('ext.EGeoIP');
                 try {
                     $geoIp = new EGeoIP();
                     $geoIp->locate();
                     $countryCode = strtolower($geoIp->getCountryCode());
                     if (!in_array($countryCode, self::getLanguagesList(), true)) {
                         return;
                     }
                     Yii::app()->setLanguage($countryCode);
                     $cookie = new CHttpCookie('language', $countryCode);
                     $cookie->expire = time() + 60 * 60 * 24 * $cookieDays;
                     Yii::app()->request->cookies['language'] = $cookie;
                 } catch (Exception $exception) {
                     Yii::log($exception->__toString(), 'error', 'app.widgets.languageSelector');
                 }
             }
         }
     }
 }
Example #8
Show file File: BDLbs.php Project: CenturyWarDesign/umbrella
0
 public static function createOrUpdate($id, $title, $address, $latitude, $longitude, $type = 'create')
 {
     $querystring_arrays = array();
     $uri = '';
     if ($type == 'create') {
         //这里是创建
         $uri = '/geodata/v3/poi/create';
         $querystring_arrays = array('id' => $id, 'title' => $title, 'latitude' => $latitude, 'longitude' => $longitude, 'coord_type' => 1, 'geotable_id' => GEOTABLE_ID, 'ak' => MAP_AK);
     } else {
         //这里是更新
         $uri = '/geodata/v3/poi/update';
         $querystring_arrays = array('id' => $id, 'title' => $title, 'latitude' => $latitude, 'longitude' => $longitude, 'coord_type' => 1, 'geotable_id' => GEOTABLE_ID, 'ak' => MAP_AK);
     }
     $sn = BDLbs::caculateAKSN($uri, $querystring_arrays, "POST");
     $querystring_arrays['sn'] = $sn;
     Yii::trace(CVarDumper::dumpAsString($querystring_arrays), 'create or update baidu poi post');
     $ret = Yii::app()->curl->post(Yii::app()->params['baiduapi'] . $uri, $querystring_arrays);
     $ret = json_decode($ret, true);
     Yii::trace(CVarDumper::dumpAsString($ret), 'create or update baidu poi');
     if ($ret['status'] == 0) {
         return $ret['id'];
     } else {
         Yii::log(CVarDumper::dumpAsString($ret), 'error', 'create or update baidu poi ERROR');
         return -1;
     }
 }
Example #9
Show file File: TaskQueue.php Project: uiDeveloper116/webstore
0
 public static function CreateEvent($strModule, $strController, $strAction, $data_id = null, $product_id = null)
 {
     if ($strController == "amazon") {
         $MerchantID = _xls_get_conf('AMAZON_MERCHANT_ID');
         $MarketplaceID = _xls_get_conf('AMAZON_MARKETPLACE_ID');
         $MWS_ACCESS_KEY_ID = _xls_get_conf('AMAZON_MWS_ACCESS_KEY_ID');
         $MWS_SECRET_ACCESS_KEY = _xls_get_conf('AMAZON_MWS_SECRET_ACCESS_KEY');
         if (empty($MerchantID) || empty($MarketplaceID) || empty($MWS_ACCESS_KEY_ID) || empty($MWS_SECRET_ACCESS_KEY)) {
             return false;
         }
     }
     //Check to make sure it's not duplicate
     $objTask = TaskQueue::model()->findByAttributes(array('module' => $strModule, 'controller' => $strController, 'action' => $strAction, 'data_id' => $data_id, 'product_id' => $product_id));
     if ($objTask instanceof TaskQueue) {
         return;
     }
     $objTask = new TaskQueue();
     $objTask->module = $strModule;
     $objTask->controller = $strController;
     $objTask->action = $strAction;
     $objTask->data_id = $data_id;
     $objTask->product_id = $product_id;
     if (!$objTask->save()) {
         Yii::log("Error creating Task {$strModule}, {$strController}, {$strAction} " . print_r($objTask->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
     }
 }
Example #10
Show file File: EdeboController.php Project: upmunspel/abiturient
0
 /**
  * This is the default 'index' action that is invoked
  * when an action is not explicitly requested by users.
  */
 public function actionIndex()
 {
     $model = new EdeboStatusChange();
     $res = "";
     $request_list = array();
     $idRequestSpeciality = "";
     if (isset($_POST['EdeboStatusChange'])) {
         $model->attributes = $_POST['EdeboStatusChange'];
         if ($model->validate()) {
             try {
                 $res = WebServices::getRequestsByStatus($model->StatusID, $model->QualificationID, date("Y-m-d", strtotime($model->Data)));
             } catch (Exception $exc) {
                 Yii::log($exc->getTraceAsString());
             }
         }
     }
     if (isset($_REQUEST["idRequestSpeciality"])) {
         $idRequestSpeciality = $_REQUEST["idRequestSpeciality"];
         $models = Personspeciality::model()->findAll("SepcialityID = :id", array("id" => $_REQUEST["idRequestSpeciality"]));
         foreach ($models as $item) {
             //$item = new Personspeciality();
             if (!empty($item->edboID)) {
                 $request_list[] = $item->edboID;
             }
         }
         //$request_list = CJSON::encode($request_list);
     }
     //$res =  CJSON::encode(array(1,2,3,4,5,6,7,8,9,10));
     $this->render('index', array('model' => $model, 'res' => $res, "request_list" => $request_list, "idRequestSpeciality" => $idRequestSpeciality));
 }
Example #11
Show file File: DirpyDownloadMP3.php Project: nbchicong/phatam.com
0
 /**
  * @param $youtubeUrl
  * @param $bitrate
  * @return bool|mixed|MyCurlFile
  */
 public function downloadMp3ByDirpy($youtubeUrl, $bitrate)
 {
     $this->log("------ Download MP3 by Dirpy.Com");
     $metadata = $this->getDirpyMp3Metadata($youtubeUrl, $bitrate);
     if ($metadata == null) {
         $this->log("ERROR: Not get meta data for link: " . $youtubeUrl);
         Yii::log("ERROR: Not get meta data for link: " . $youtubeUrl, CLogger::LEVEL_ERROR, "ProcessMp3");
         return false;
     }
     $url = $this->renderMP3DownloadLinkForDirpy($youtubeUrl, $metadata);
     $url = $this->baseDirpyURL . "/download" . $url . "&downloadToken=" . $this->getDownloadToken();
     //    $this->log("---- URL DOWNLOAD ${url}");
     $fileName = CVietnameseTools::makeCodeName($metadata['filename']) . '.mp3';
     $this->log("------ Downloading MP3");
     $response = $this->myCurl->download($url, $fileName);
     if ($response != false) {
         $folderSave = '/tmp/';
         $file = $folderSave . $fileName;
         $mp3File = new MP3File($file);
         $mp3Second = $mp3File->getDurationEstimate();
         $metadataTimeSecond = $this->getSecondOfTime($metadata['end_time']);
         $this->log("------ Checking duration mp3 file downloaded " . $mp3Second . " and compare with meta time " . $metadataTimeSecond);
         if ($mp3Second >= $metadataTimeSecond) {
             return $response;
         }
         return false;
     }
     return $response;
 }
Example #12
Show file File: UsrController.php Project: ayhamomran/user2
0
 /**
  * Sends out an email containing instructions and link to the email verification
  * or password recovery page, containing an activation key.
  * @param CFormModel $model it must have a getIdentity() method
  * @param strign $mode 'recovery', 'verify' or 'oneTimePassword'
  * @return boolean if sending the email succeeded
  */
 public function sendEmail(CFormModel $model, $mode)
 {
     $mail = $this->module->mailer;
     $mail->AddAddress($model->getIdentity()->getEmail(), $model->getIdentity()->getName());
     $params = array('siteUrl' => $this->createAbsoluteUrl('/'));
     switch ($mode) {
         default:
             return false;
         case 'recovery':
         case 'verify':
             $mail->Subject = $mode == 'recovery' ? Yii::t('UsrModule.usr', 'Password recovery') : Yii::t('UsrModule.usr', 'Email address verification');
             $params['actionUrl'] = $this->createAbsoluteUrl('default/' . $mode, array('activationKey' => $model->getIdentity()->getActivationKey(), 'username' => $model->getIdentity()->getName()));
             break;
         case 'oneTimePassword':
             $mail->Subject = Yii::t('UsrModule.usr', 'One Time Password');
             $params['code'] = $model->getNewCode();
             break;
     }
     $body = $this->renderPartial($mail->getPathViews() . '.' . $mode, $params, true);
     $full = $this->renderPartial($mail->getPathLayouts() . '.email', array('content' => $body), true);
     $mail->MsgHTML($full);
     if ($mail->Send()) {
         return true;
     } else {
         Yii::log($mail->ErrorInfo, 'error');
         return false;
     }
 }
Example #13
Show file File: SimpleUploadWidget.php Project: CHILMEX/amocasion
0
 public function afterSave($event)
 {
     if (!empty($_FILES)) {
         $model = $this->getOwner();
         $file = new File();
         $file->filename = UploadUtils::createUniquefilename($_FILES[self::NAME]['name'], UploadUtils::getPath(self::$fileDir));
         if (move_uploaded_file($_FILES[self::NAME]['tmp_name'], UploadUtils::getPath(self::$fileDir) . DIRECTORY_SEPARATOR . $file->filename)) {
             $file->entity = get_class($model);
             $file->EXid = $model->getPrimaryKey();
             $file->uid = Yii::app()->user->id;
             $file->tag = $this->tag;
             $file->weight = 0;
             $file->timestamp = time();
             $file->filemime = CFileHelper::getMimeTypeByExtension($_FILES[self::NAME]['name']);
             $file->filesize = $_FILES[self::NAME]['size'];
             $file->status = File::STATUS_SAVED;
             // Ensure all other files of the entity are deleted
             //UploadUtils::deleteAllFiles(get_class($this->getOwner()), self::$fileDir);
             if ($file->save()) {
                 Yii::trace("File saved " . $file . "!!!!");
             } else {
                 Yii::log("Could not save File " . print_r($file->getErrors(), true), CLogger::LEVEL_ERROR);
             }
         } else {
             Yii::log("Couldnt move the file", CLogger::LEVEL_ERROR);
         }
     } else {
         Yii::log("Files empty!!!", CLogger::LEVEL_ERROR);
     }
 }
Example #14
Show file File: worldpaysim.php Project: uiDeveloper116/webstore
0
 /**
  * Processes returned $_GET or $_POST variables from the third party website
  *
  * @return array|bool
  */
 public function gateway_response_process()
 {
     Yii::log(sprintf("%s Transaction %s", __CLASS__, print_r($_GET, true)), $this->logLevel, 'application.' . __CLASS__ . "." . __FUNCTION__);
     $instId = Yii::app()->getRequest()->getQuery('instId');
     $transId = Yii::app()->getRequest()->getQuery('transId');
     $cartId = Yii::app()->getRequest()->getQuery('cartId');
     $authAmount = Yii::app()->getRequest()->getQuery('authAmount');
     $messageText = Yii::app()->getRequest()->getQuery('rawAuthMessage');
     $transTime = Yii::app()->getRequest()->getQuery('transTime');
     //Unix epoch time
     if (empty($transId)) {
         // failed order
         Yii::log("Failed: " . print_r($_GET, true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
         return false;
     }
     if (empty($instId)) {
         return false;
     }
     if ($instId != $this->config['login']) {
         // it's not the same!
         return false;
     }
     if (empty($cartId)) {
         return false;
     }
     if ($transId > 0) {
         $retArray = array('order_id' => $cartId, 'amount' => $authAmount, 'success' => true, 'data' => $transId, 'payment_date' => date("Y-m-d H:i:s", strtotime($transTime)));
     } else {
         Yii::log("Declined Reason: " . strtoupper($messageText), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
         $retArray = array('order_id' => $cartId, 'amount' => 0, 'success' => false, 'data' => '');
     }
     return $retArray;
 }
Example #15
Show file File: RobokassaPaymentSystem.php Project: alextravin/yupe
0
 /**
  * @param Payment $payment
  * @param CHttpRequest $request
  * @return bool
  */
 public function processCheckout(Payment $payment, CHttpRequest $request)
 {
     $amount = $request->getParam('OutSum');
     $orderId = (int) $request->getParam('InvId');
     $crc = strtoupper($request->getParam('SignatureValue'));
     $order = Order::model()->findByPk($orderId);
     if (null === $order) {
         Yii::log(Yii::t('RobokassaModule.robokassa', 'Order with id = {id} not found!', ['{id}' => $orderId]), CLogger::LEVEL_ERROR, self::LOG_CATEGORY);
         return false;
     }
     if ($order->isPaid()) {
         Yii::log(Yii::t('RobokassaModule.robokassa', 'Order with id = {id} already payed!', ['{id}' => $orderId]), CLogger::LEVEL_ERROR, self::LOG_CATEGORY);
         return false;
     }
     $settings = $payment->getPaymentSystemSettings();
     $myCrc = strtoupper(md5("{$amount}:{$orderId}:" . $settings['password2']));
     if ($myCrc !== $crc) {
         Yii::log(Yii::t('RobokassaModule.robokassa', 'Error pay order with id = {id}! Bad crc!', ['{id}' => $orderId]), CLogger::LEVEL_ERROR, self::LOG_CATEGORY);
         return false;
     }
     if ($amount != Yii::app()->money->convert($order->total_price, $payment->currency_id)) {
         Yii::log(Yii::t('RobokassaModule.robokassa', 'Error pay order with id = {id}! Incorrect price!', ['{id}' => $orderId]), CLogger::LEVEL_ERROR, self::LOG_CATEGORY);
         return false;
     }
     if ($order->pay($payment)) {
         Yii::log(Yii::t('RobokassaModule.robokassa', 'Success pay order with id = {id}!', ['{id}' => $orderId]), CLogger::LEVEL_INFO, self::LOG_CATEGORY);
         return true;
     } else {
         Yii::log(Yii::t('RobokassaModule.robokassa', 'Error pay order with id = {id}! Error change status!', ['{id}' => $orderId]), CLogger::LEVEL_ERROR, self::LOG_CATEGORY);
         return false;
     }
 }
Example #16
Show file File: ErrorController.php Project: hucongyang/test
0
 /**
  * This is the action to handle external exceptions.
  */
 public function actionError()
 {
     if ($error = Yii::app()->errorHandler->error) {
         if ($error['code'] != 404 || !isset($aErrorMsg[$error['errorCode']])) {
             Yii::log(' error : ' . $error['file'] . ":" . $error['line'] . ":" . $error['message'], 'error', 'system');
         }
         $ret = new ReturnInfo(FAIL_RET, Yii::t('exceptions', $error['message']), intval($error['errorCode']));
         if (Yii::app()->request->getIsAjaxRequest()) {
             echo json_encode($ret);
         } else {
             if (empty($error['errorCode'])) {
                 if (isset($this->aErrorMsg[$error['code']])) {
                     if (empty($this->aErrorMsg[$error['code']]['message'])) {
                         $this->aErrorMsg[$error['code']]['message'] = $error['message'];
                     }
                     $this->render('error', $this->aErrorMsg[$error['code']]);
                 } else {
                     $this->render('error', $this->aErrorMsg['1000']);
                 }
             } else {
                 $this->render('error', $this->aErrorMsg[$error['errorCode']]);
             }
         }
     }
 }
Example #17
Show file File: YumProfile.php Project: bhaveshsoni/yii-user-management
0
 public function afterSave()
 {
     if ($this->isNewRecord) {
         Yii::log(Yum::t('A profile been created: {profile}', array('{profile}' => json_encode($this->attributes))));
     }
     return parent::afterSave();
 }
Example #18
Show file File: ContentContainerStreamAction.php Project: skapl/design
0
 public function init()
 {
     parent::init();
     // Get Content Container by Param
     if ($this->contentContainer->wall_id != "") {
         $this->criteria->condition .= " AND wall_entry.wall_id = " . $this->contentContainer->wall_id;
         //$this->criteria->condition .= " AND wall_entry.created_by=".$this->contentContainer->id;
     } else {
         file_put_contents("php://stderr", print_r("in else", TRUE));
         Yii::log("No wall id for content container " . get_class($this->contentContainer) . " - " . $this->contentContainer->getPrimaryKey() . " set - stopped stream action!", CLogger::LEVEL_ERROR);
         $this->criteria->condition .= " AND 1=2";
     }
     /**
      * Limit to public posts when no member
      */
     //if (!$this->contentContainer->canAccessPrivateContent($this->user)) {
     //    $this->criteria->condition .= " AND content.visibility=" . Content::VISIBILITY_PUBLIC;
     //}
     /**
      * Handle sticked posts only in content containers
      */
     if ($this->limit != 1) {
         if ($this->from == '') {
             $this->criteria->order = "content.sticked DESC, " . $this->criteria->order;
         } else {
             $this->criteria->condition .= " AND (content.sticked != 1 OR content.sticked is NULL)";
         }
     }
 }
Example #19
Show file File: MPartDownloadController.php Project: youngsun45/miniyun
0
 /**
  * 处理下载文件逻辑 
  */
 private function downloadFile()
 {
     $file_name = $_POST["Filename"];
     $key = $_POST["key"];
     $path = '';
     // 参数检查
     if (strlen(trim($file_name)) <= 0 || strlen(trim($key)) <= 0) {
         Yii::log(Yii::t('api', "Request is Error, file_name:'{$file_name}'"), CLogger::LEVEL_ERROR, "miniyun.api");
         throw new MException(Yii::t('api', MConst::FILE_NOT_EXIST), MConst::DOWNLOAD_FILE_FAILS);
     }
     // 全路径
     $path = str_replace("\${filename}", $file_name, $key);
     if (is_null($path) || strlen(trim($path)) <= 0) {
         Yii::log(Yii::t('api', "Request is Error, file_name:'{$file_name}'"), CLogger::LEVEL_ERROR, "miniyun.api");
         throw new MException(Yii::t('api', MConst::FILE_NOT_EXIST), MConst::DOWNLOAD_FILE_FAILS);
     }
     $file_path = DOCUMENT_ROOT_BLOCK . $path;
     //文件不存在
     if (file_exists($file_path) == false) {
         Yii::log(Yii::t('api', "File do not exist, path:'{$file_path}'"), CLogger::LEVEL_ERROR, "miniyun.api");
         throw new MException(Yii::t('api', MConst::FILE_NOT_EXIST), MConst::DOWNLOAD_FILE_FAILS);
     }
     $content_type = 'application/force-download';
     MUtils::download($file_path, $content_type, $file_name);
 }
Example #20
Show file File: DaMigrateCommand.php Project: Cranky4/npfs
0
 public function afterAction($action, $params, $exitCode = 0)
 {
     $content = ob_get_clean();
     echo $content;
     Yii::log($content, CLogger::LEVEL_INFO, 'command.migrate');
     return parent::afterAction($action, $params, $exitCode);
 }
Example #21
Show file File: AlternateAuthTm.php Project: Telemedellin/tm
0
 public function authenticate()
 {
     Yii::log(__METHOD__, "info");
     $this->errorCode = self::ERROR_USERNAME_INVALID;
     $model = Yii::app()->user->um->loadUser($this->username);
     Yii::log(__METHOD__ . ' ' . CrugeTranslator::t('logger', 'Returned User') . ":\n" . CJSON::encode($model), "info");
     $this->_userinstance = null;
     if ($model != null) {
         if (CrugeUtil::checkhash($this->password, $model->password)) {
             $this->_userinstance = $model;
             $this->errorCode = self::ERROR_NONE;
         } else {
             if (CrugeUtil::config()->debug == true) {
                 // ayuda a instalar, quiza el usuario olvide quitar la encriptacion de claves
                 // y reciba error de ERROR_PASSWORD_INVALID, es porque esta actuando el Hash
                 // y el usuario recien creado trae una clave no encritpada
                 if (CrugeUtil::config()->useEncryptedPassword == true) {
                     echo Yii::app()->user->ui->setupAlert(CrugeTranslator::t('logon', 'Maybe your password doesn\'t match because you have set up \'useEncryptedPassword = true\' when you were installing Cruge, try \'false\' instead'));
                 }
             }
             $this->errorCode = self::ERROR_PASSWORD_INVALID;
         }
     } else {
         // username o email error
         $this->errorCode = self::ERROR_USERNAME_INVALID;
     }
     Yii::log(__CLASS__ . "\nauthenticate returns:\n" . $this->errorCode . "\n boolean result is:" . ($this->errorCode == self::ERROR_NONE), "info");
     return $this->errorCode == self::ERROR_NONE;
 }
Example #22
Show file File: MPartUploadController.php Project: youngsun45/miniyun
0
 /**
  * 控制器执行主逻辑函数
  *
  * @return mixed $value 返回最终需要执行完的结果
  */
 public function invoke()
 {
     Yii::trace(Yii::t('api', 'Begin to process {class}::{function}', array('{class}' => get_class($this), '{function}' => __FUNCTION__)), "miniyun.api");
     // 调用父类初始化函数,注册自定义的异常和错误处理逻辑
     parent::init();
     // keys,是作为参数的键值,进行请求合法验证
     $keys = array('Filename', 'key');
     # 重新序列化参数
     $post = array();
     foreach ($_POST as $key => $value) {
         if ($key == "Filename") {
             $name = explode("_part_", $value);
             $post[$key] = $name[0];
         } else {
             $post[$key] = $value;
         }
     }
     if (MSecurity::verification($keys, $post) == false) {
         Yii::log(Yii::t('api', "Request is Error, verification error"), CLogger::LEVEL_ERROR, "miniyun.api");
         throw new MException(Yii::t('api', MConst::INVLID_REQUEST . "3"), MConst::UPLOAD_FILE_FAILS);
     }
     // 处理创建文件
     if (!MUtils::create(DOCUMENT_CACHE, $_POST, $_FILES)) {
         throw new MException(Yii::t('api', MConst::INVLID_REQUEST . "4"), MConst::UPLOAD_FILE_FAILS);
     }
 }
Example #23
Show file File: ActivityWidget.php Project: alefernie/intranet
0
 /**
  * Runs the Widget
  */
 public function run()
 {
     // Possible Security Flaw: Check type!
     $type = $this->activity->type;
     $underlyingObject = $this->activity->getUnderlyingObject();
     // Try to figure out wallEntryId of this activity
     $wallEntryId = 0;
     if ($underlyingObject != null) {
         if ($underlyingObject instanceof HActiveRecordContent || $underlyingObject instanceof HActiveRecordContentAddon) {
             $wallEntryId = $underlyingObject->content->getFirstWallEntryId();
         }
     }
     // When element is assigned to a workspace, assign variable
     $workspace = null;
     if ($this->activity->content->space_id != "") {
         $workspace = Space::model()->findByPk($this->activity->content->space_id);
     }
     // User that fired the activity
     $user = $this->activity->content->user;
     if ($user == null) {
         Yii::log("Skipping activity without valid user", "warning");
         return;
     }
     // Dertermine View
     $view = "";
     if ($this->activity->module == "") {
         $view = 'application.modules_core.activity.views.activities.' . $this->activity->type;
     } else {
         $view = $this->activity->module . '.views.activities.' . $this->activity->type;
     }
     // Activity Layout can access it
     $this->wallEntryId = $wallEntryId;
     $this->render($view, array('activity' => $this->activity, 'wallEntryId' => $wallEntryId, 'user' => $user, 'target' => $underlyingObject, 'workspace' => $workspace));
 }
Example #24
Show file File: TTMailer.php Project: schrapps/risksur
0
 /**
  * ttSendMail
  *
  * @param mixed   $subject
  * @param mixed   $altBody
  * @param mixed   $message
  * @param mixed   $toAddress
  * @param mixed   $toName
  * @access public
  * @return void
  */
 public function ttSendMail($subject, $altBody, $message, $toAddress, $toName)
 {
     $mailResource = Yii::app()->mailresource;
     $mailResource->resources['Host'] = Yii::app()->params->mail['host'];
     $mailResource->resources['SMTPAuth'] = Yii::app()->params->mail['smtpauth'];
     $mailResource->resources['Username'] = Yii::app()->params->mail['username'];
     $mailResource->resources['Password'] = Yii::app()->params->mail['password'];
     $mailResource->resources['Port'] = Yii::app()->params->mail['port'];
     $mailResource->resources['From'] = Yii::app()->params->mail['from'];
     $mailResource->resources['FromName'] = Yii::app()->params->mail['fromname'];
     $mailResource->resources['CharSet'] = Yii::app()->params->mail['charset'];
     $mailResource->resources['SMTPSecure'] = Yii::app()->params->mail['smtpsecure'];
     $phpMailer = new JPhpMailer();
     foreach ($mailResource->resources as $mailVar => $value) {
         $phpMailer->{$mailVar} = $value;
     }
     $phpMailer->Subject = $subject;
     $phpMailer->AltBody = $altBody;
     $phpMailer->MsgHTML($message);
     $phpMailer->AddAddress($toAddress, $toName);
     $phpMailer->SetFrom($phpMailer->From, $phpMailer->FromName);
     $phpMailer->IsSMTP();
     if (!$phpMailer->Send()) {
         Yii::log("Mail cannot be sent, check whether a mail agent is installed", "error", self::LOG_CAT);
         return false;
     }
     return true;
 }
Example #25
Show file File: TaggingCacheBehavior.php Project: kuzmina-mariya/gallery
0
 /**
  * Инвалидирует данные, помеченные тегом(ами)
  *
  * @param string $tags - теги кеша
  * 
  * @return void
  */
 public function clear($tags)
 {
     foreach ((array) $tags as $tag) {
         $this->owner->set(self::PREFIX . $tag, microtime(true));
     }
     Yii::log(Yii::t('YupeModule.yupe', 'Invalidated tags: {tags}', array('{tags}' => implode(', ', (array) $tags))));
 }
Example #26
Show file File: JsTrans.php Project: pawel-baster/JsTrans
0
 public function init()
 {
     $assetManager = Yii::app()->assetManager;
     // set default language
     if (!$this->defaultLanguage) {
         $this->defaultLanguage = Yii::app()->language;
     }
     // normalize missingTranslation url
     if ($this->onMissingTranslation) {
         $this->onMissingTranslation = CHtml::normalizeUrl($this->onMissingTranslation);
     }
     // create arrays from params
     if (!is_array($this->categories)) {
         $this->categories = array($this->categories);
     }
     if (!is_array($this->languages)) {
         $this->languages = array($this->languages);
     }
     // set paths
     $this->_assetsPath = dirname(__FILE__) . '/assets';
     $this->_publishPath = $assetManager->getPublishedPath($this->_assetsPath);
     $this->_publishUrl = $assetManager->getPublishedUrl($this->_assetsPath);
     // create hash
     $hash = substr(md5(implode($this->categories) . ':' . implode($this->languages)), 0, 10);
     $dictionaryFile = "JsTrans.dictionary.{$hash}.js";
     // publish assets and generate dictionary file if neccessary
     if (!file_exists($this->_publishPath) || YII_DEBUG) {
         // publish and get new url and path
         $assetsManager = Yii::app()->getAssetManager();
         $forceCopy = empty($assetsManager) || !$assetsManager->linkAssets ? true : false;
         $this->_publishUrl = $assetManager->publish($this->_assetsPath, false, -1, $forceCopy);
         $this->_publishPath = $assetManager->getPublishedPath($this->_assetsPath);
         // declare config (passed to JS)
         $config = array('language' => $this->defaultLanguage, 'onMissingTranslation' => $this->onMissingTranslation);
         // getting protected loadMessages method using Reflection to call it from outside
         $messages = Yii::app()->messages;
         $loadMessages = new ReflectionMethod(get_class($messages), 'loadMessages');
         $loadMessages->setAccessible(true);
         // loop message files and store translations in array
         $dictionary = array();
         foreach ($this->languages as $lang) {
             if (!isset($dictionary[$lang])) {
                 $dictionary[$lang] = array();
             }
             foreach ($this->categories as $cat) {
                 $dictionary[$lang][$cat] = $loadMessages->invoke($messages, $cat, $lang);
             }
         }
         // JSONify config/dictionary
         $data = 'Yii.translate.config=' . CJSON::encode($config) . ';' . 'Yii.translate.dictionary=' . CJSON::encode($dictionary);
         // save to dictionary file
         if (!file_put_contents($this->_publishPath . '/' . $dictionaryFile, $data)) {
             Yii::log('Error: Could not write dictionary file', 'trace', 'jstrans');
             return null;
         }
     }
     $jsTransFile = YII_DEBUG ? 'JsTrans.min.js' : 'JsTrans.js';
     Yii::app()->getClientScript()->addPackage('JsTrans', ['baseUrl' => $this->_publishUrl, 'js' => [$jsTransFile, $dictionaryFile]]);
     Yii::app()->getClientScript()->registerPackage('JsTrans');
 }
Example #27
Show file File: SysparamController.php Project: pelo8888/php-angular-yii
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)
 {
     $transaction = Yii::app()->db->beginTransaction();
     try {
         $model = $this->loadModel($id);
         if ($model->editable == false) {
             $this->render('/site/invalidOperation', array('header' => 'Operacion no valida', 'message' => 'El parametro que desea modifica esta marcado como no editable', 'returnUrl' => Yii::app()->createUrl('sysparam/admin')));
             $transaction->rollback();
             return;
         }
         if (isset($_POST['Sysparam'])) {
             $model->attributes = $_POST['Sysparam'];
             if ($model->save()) {
                 $this->audit->logAudit(Yii::app()->user->id, new DateTime(), AppConstants::AUDIT_OBJECT_SYSPARAM, AppConstants::AUDIT_OPERATION_EDIT, "sysparam = " . $model->name . ", nuevo_valor = " . $model->value);
                 $this->render('/site/successfullOperation', array('header' => 'Par&aacute;metro modificado con &eacute;xito', 'message' => 'Haga click en volver para regresar a la gestión de parámetros', 'returnUrl' => Yii::app()->createUrl('sysparam/admin')));
                 $transaction->commit();
                 return;
             } else {
                 $transaction->rollback();
             }
         }
         $this->render('update', array('model' => $model));
     } catch (Exception $exc) {
         Yii::log($exc->getMessage(), DBLog::LOG_LEVEL_ERROR);
         $transaction->rollback();
     }
 }
Example #28
Show file File: FeatureToggle.php Project: BehalfFE/featureToggle
0
 public function init()
 {
     parent::init();
     if (!$this->isComponentActive()) {
         return;
     }
     try {
         $this->userInfo = call_user_func($this->userInfoCallable);
         $this->setUser($this->userInfo);
         $memcacheServerName = $this->cacheServer['host'];
         $memcacheServerPort = $this->cacheServer['port'];
         if ($memcacheServerName && $memcacheServerPort) {
             $memcached = new \Memcached();
             $memcached->addServer($memcacheServerName, $memcacheServerPort);
             $cacheDriver = new \Doctrine\Common\Cache\MemcachedCache();
             $cacheDriver->setMemcached($memcached);
             $cacheStorage = new \Kevinrob\GuzzleCache\Storage\DoctrineCacheStorage($cacheDriver);
         } else {
             $cacheStorage = new \Kevinrob\GuzzleCache\Storage\DoctrineCacheStorage(new \Doctrine\Common\Cache\FilesystemCache('/tmp/'));
         }
         $this->client = new \LaunchDarkly\LDClient($this->apiKey, array("cache" => $cacheStorage));
         $this->featureToggleUser = (new \LaunchDarkly\LDUserBuilder($this->user->key))->secondary($this->user->secondary)->ip($this->user->ip)->country($this->user->country)->email($this->user->email)->name($this->user->name)->avatar($this->user->avatar)->firstName($this->user->firstName)->lastName($this->user->lastName)->anonymous($this->user->anonymous)->custom(array('type' => $this->user->type, 'parentCompanyId' => $this->user->parentId, 'referredAccountId' => $this->user->referredAccountId, 'channel' => $this->user->channel, 'payoutMethod' => isset($this->user->payoutMethod) ? $this->user->payoutMethod : null))->build();
     } catch (\Exception $ex) {
         $this->componentActive = false;
         \Yii::log("Cannot initiate Feature Toggles: {$ex->getMessage()}", \CLogger::LEVEL_WARNING, 'system.featureToggle');
     }
 }
Example #29
Show file File: QuotationCommand.php Project: zwq/unpei
0
 public function run()
 {
     echo date('Y-m-d H:i:s') . " [Quotation] start \n";
     Yii::app()->getComponent('log');
     Yii::log(date('Y-m-d H:i:s') . " [Quotation] start", 'info', 'command');
     $time = $_SERVER['REQUEST_TIME'];
     $failuretime = 3600 * 24 * 2;
     //2天
     $t = $time - $failuretime;
     //无询价单的报价单失效
     $quosql = 'update `pap_quotation` set Status="5" where IfSend="2" and CreateTime<' . $t . ' and Status="1" and InquiryID=0';
     $quocount = Yii::app()->papdb->CreateCommand($quosql)->execute();
     Yii::log(date('Y-m-d H:i:s') . " The quotation " . $quocount . " total failure(not inq)" . " [Quotation] end \n", 'info', 'command');
     //根据询价单发送的报价单(已报价未确认或拒绝)
     $inq = 'update `pap_inquiry` set Status="5" where Status=1 and InquiryID in( select InquiryID from `pap_quotation` ' . 'where IfSend="2" and CreateTime<' . $t . ' and Status="1" and InquiryID!=0)';
     $inqcount_quo = Yii::app()->papdb->CreateCommand($inq)->execute();
     Yii::log(date('Y-m-d H:i:s') . " The inquiry " . $inqcount_quo . " total failure(have quo)" . " [Quotation] end \n", 'info', 'command');
     $quosql_inq = 'update `pap_quotation` set Status="5" where CreateTime<' . $t . ' and Status="1" and InquiryID!=0';
     $quocount_inq = Yii::app()->papdb->CreateCommand($quosql_inq)->execute();
     Yii::log(date('Y-m-d H:i:s') . " The quotation " . $quocount_inq . " total failure(have inq)" . " [Quotation] end \n", 'info', 'command');
     //询价单失效(未报价)
     $inqsql = 'update `pap_inquiry` set Status="5" where  CreateTime<' . $t . ' and Status=0';
     $inqcount = Yii::app()->papdb->CreateCommand($inqsql)->execute();
     Yii::log(date('Y-m-d H:i:s') . " The inquiry " . $inqcount . " total failure(not quo)" . " [Quotation] end \n", 'info', 'command');
     echo date('Y-m-d H:i:s') . " [Quotation] end \n";
 }
Example #30
Show file File: EvalForm.php Project: schrapps/risksur
0
 /**
  * @param string $evalId
  * @param bool $newRecord
  * @return bool
  */
 public function save($evalId, $newRecord = true)
 {
     // fetch the form data
     $evaElements = [];
     $model = new EvaluationDetails();
     $transaction = Yii::app()->db->beginTransaction();
     try {
         if (!$newRecord) {
             $model->deleteAll('evalId=:evaId', [':evaId' => $evalId]);
         }
         foreach ($this->_properties as $attrNameAndId => $attrVal) {
             $model->unsetAttributes();
             $attrParams = explode("_", $attrNameAndId);
             $evaElements['evalId'] = $evalId;
             $evaElements['evalElementsId'] = $attrParams[1];
             $evaElements['value'] = is_array($attrVal) ? json_encode($attrVal) : $attrVal;
             $model->attributes = $evaElements;
             //print_r($model->attributes); die;
             $model->setIsNewRecord(true);
             $model->save();
         }
         //die;
         $transaction->commit();
     } catch (Exception $e) {
         Yii::log($e->getMessage(), 'error', 'models.EvalForm');
         $transaction->rollBack();
         EvaluationHeader::model()->deleteByPk($evalId);
         return false;
     }
     //var_dump($evaElements, $model); die;
     return true;
 }