PHP Method Yii::warning Code Examples

This page contains top rated real world PHP examples of method Yii::warning extracted from open source projects. You can rate examples to help us improve the quality of examples
Example #1
Show file File: Router.php Project: filsh/yii2-wamp
0
 public function connect(\Closure $callback, array $options = [])
 {
     $options = array_merge(['logging' => $this->logging, 'loggingOutput' => $this->loggingOutput, 'connectionTimeout' => null, 'connectionOptions' => []], $options);
     if (!$options['logging']) {
         Logger::set(new NullLogger());
     }
     if (!$options['loggingOutput']) {
         ob_start();
     }
     $connection = $this->createConnection($options['connectionOptions']);
     $connection->once('open', function (ClientSession $session) use($connection, $callback) {
         call_user_func_array($callback, [$connection, $session]);
     });
     if ($options['connectionTimeout'] !== null) {
         $loop = $connection->getClient()->getLoop();
         $timer = $loop->addTimer($options['connectionTimeout'], function () use($loop) {
             $loop->stop();
         });
         $connection->once('close', function () use($timer) {
             $timer->cancel();
             \Yii::warning('WAMP connection closed by timeout.');
         });
     }
     $connection->open();
     if ($options['logging']) {
         \Yii::info(ob_get_contents());
     }
     if (!$options['loggingOutput']) {
         ob_clean();
     }
 }
Example #2
Show file File: FormWidget.php Project: skeeks-cms/cms-module-form2
0
 protected function _run()
 {
     try {
         $form = null;
         if ($this->form_id) {
             $this->modelForm = Form2Form::find()->where(['id' => $this->form_id])->one();
             if (!$this->modelForm) {
                 throw new ErrorException("Форма не найдена: id=" . $this->form_id);
             }
         } else {
             if ($this->form_code) {
                 $this->modelForm = Form2Form::find()->where(['code' => $this->form_code])->one();
                 if ($form) {
                     $this->form_id = $form->id;
                 }
             }
             if (!$this->modelForm) {
                 throw new ErrorException("Форма не найдена: code=" . $this->form_code);
             }
         }
     } catch (\Exception $e) {
         \Yii::warning($e->getMessage(), static::className());
     }
     if (!$this->modelForm) {
         return "";
     }
     return parent::_run();
 }
Example #3
Show file File: MaterializedAttributes.php Project: DevGroup-ru/dotplant-monster
0
 /**
  * @param ActionData $actionData
  *
  * @return void
  */
 public function run(&$actionData)
 {
     $monsterContentConfigs = [];
     foreach ($this->entities as $definition) {
         if (!isset($definition['entity'], $definition['attributes'])) {
             continue;
         }
         $entity = $definition['entity'];
         $definition['attributes'] = (array) $definition['attributes'];
         /** @var yii\base\Model $model */
         $models = ArrayHelper::getValue($actionData->entities, $entity, []);
         $model = is_object($models) ? $models : reset($models);
         if ($model === null) {
             Yii::info("Entities list: " . yii\helpers\VarDumper::dumpAsString($actionData->entities));
             Yii::info((array) ArrayHelper::getValue($actionData->entities, $entity, []));
             Yii::info("Searching for " . $entity);
             throw new \RuntimeException("Model is empty");
         }
         foreach ($definition['attributes'] as $index => $attribute) {
             $materials = $model->{$attribute};
             if (is_array($materials) || is_object($materials)) {
                 $monsterContentConfigs[] = ['materials' => $materials, 'uniqueContentId' => $model::className() . ":{$index}:" . $model->id];
             } else {
                 Yii::warning("Model attribute {$attribute} of entity {$entity} is not array or object");
             }
         }
     }
     $content = '';
     foreach ($monsterContentConfigs as $index => $config) {
         $content .= "<!-- MonsterContent::{$index} -->\n" . MonsterContent::widget($config) . "\n\n";
     }
     $actionData->content = $content;
 }
Example #4
Show file File: JS.php Project: rmrevin/yii2-minify-view
0
 /**
  * @param integer $position
  * @param array $files
  */
 protected function process($position, $files)
 {
     $resultFile = sprintf('%s/%s.js', $this->view->minify_path, $this->_getSummaryFilesHash($files));
     if (!file_exists($resultFile)) {
         $js = '';
         foreach ($files as $file => $html) {
             $file = $this->getAbsoluteFilePath($file);
             $content = '';
             if (!file_exists($file)) {
                 \Yii::warning(sprintf('Asset file not found `%s`', $file), __METHOD__);
             } elseif (!is_readable($file)) {
                 \Yii::warning(sprintf('Asset file not readable `%s`', $file), __METHOD__);
             } else {
                 $content .= file_get_contents($file) . ';' . "\n";
             }
             $js .= $content;
         }
         $this->removeJsComments($js);
         if ($this->view->minifyJs) {
             $js = (new \JSMin($js))->min();
         }
         file_put_contents($resultFile, $js);
         if (false !== $this->view->file_mode) {
             @chmod($resultFile, $this->view->file_mode);
         }
     }
     $file = $this->prepareResultFile($resultFile);
     $this->view->jsFiles[$position][$file] = Html::jsFile($file);
 }
Example #5
Show file File: Bundle.php Project: DevGroup-ru/dotplant-monster
0
 /**
  * @param string $parentPath
  * @return void
  */
 public function process($parentPath = '')
 {
     $this->loadManifest();
     if ($this->namespace === '' || $this->namespace === null) {
         $this->namespace = 'unknown';
     }
     if (empty($this->name)) {
         $this->name = $this->id;
     }
     if (empty($this->name)) {
         $this->name = basename($this->getFsLocation());
     }
     $this->fullPath = $this->namespace . '.' . $this->id;
     $groupsDirectories = $this->getChildrenDirectories();
     $this->groups = [];
     foreach ($groupsDirectories as $directory) {
         $group = $this->newChild($directory);
         try {
             $group->process($this->fullPath);
             if ($group->id === null) {
                 Yii::error("Group for path {$directory} is in unknown format(no id or bad manifest)" . " - bundle: {$this->id}");
                 unset($group);
                 continue;
             }
             $this->groups[$group->id] = $group;
         } catch (\RuntimeException $e) {
             Yii::warning($e);
         }
     }
 }
Example #6
Show file File: ClientEmployeeController.php Project: noikiy/wowewe
0
 /**
  * Lists all ClientEmployee models.
  * @return mixed
  */
 public function actionIndex()
 {
     $searchModel = new ClientEmployeeSearch();
     $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
     if (isset($_GET['download'])) {
         $datetime_start = str_replace('\'', '', $_GET['datetime_start']);
         $datetime_end = str_replace('\'', '', $_GET['datetime_end']);
         $filename = Yii::$app->getRuntimePath() . "/员工会员推广排行榜-" . $datetime_start . '到' . $datetime_end . '.csv';
         $fh = fopen($filename, 'w');
         fprintf($fh, "排名,会员推广数量,员工姓名,电话,营业厅" . PHP_EOL);
         $i = 1;
         \Yii::warning('yjhu:' . $datetime_start);
         $rows = \app\models\MUser::getMemberPromotionTopList(0, 5000, $datetime_start . ' 00:00:00', $datetime_end . ' 23:59:59');
         foreach ($rows as $row) {
             $staff = \app\models\MStaff::findOne(['scene_id' => $row['scene_pid']]);
             fprintf($fh, $i++ . ',');
             fprintf($fh, $row['members'] . ',');
             fprintf($fh, $staff->name . ',');
             fprintf($fh, $staff->mobile . ',');
             fprintf($fh, (empty($staff->office) ? '' : $staff->office->title) . PHP_EOL);
         }
         fclose($fh);
         Yii::$app->response->sendFile($filename);
         return;
     }
     return $this->render('index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider]);
 }
Example #7
Show file File: BonusDiscount.php Project: just-leo/cardgame-serial
0
 /**
  * @inheritdoc
  */
 public function apply($model)
 {
     if ($this->isDue() && in_array($model->ClassID, [6, 12])) {
         $userID = $model->contractor->id;
         \Yii::info('Проверка и применение акции "' . self::$name . '"' . "({$this->getModel()->id})" . ' для пользователя ' . Html::a($userID, ['/user/admin/update', 'id' => $userID]), 'info');
         $settings = $this->getModel()->parseSettings();
         if (empty($settings['attributes'])) {
             return false;
         }
         ArrayHelper::multisort($settings['attributes'], 'payment', SORT_DESC);
         $account = $model->contractor->account;
         foreach ($settings['attributes'] as $attributes) {
             $discount = $this->getModel()->getDiscount();
             $discount->setAttributes($attributes);
             if ($model->CashSum >= $discount->payment && $discount->bonus !== null) {
                 \Yii::warning('Применение акции с атрибутами: ' . Json::encode($attributes), 'info');
                 $account->Bonuses = $account->Bonuses + $discount->bonus;
                 $account->ChargedBonuses = $account->ChargedBonuses + $discount->bonus;
                 if ($account->save(false, ['Bonuses', 'ChargedBonuses'])) {
                     $finance = new FinanceRecord();
                     $finance->CashSum = $discount->bonus;
                     $finance->Coins = $discount->bonus;
                     $finance->ClassID = 18;
                     $finance->ContractorID = $model->ContractorID;
                     $finance->Comment = $this->getDescription();
                     return $finance->save();
                 }
             }
         }
     } else {
         //            var_export(in_array($model->ClassID, [6, 12]));
     }
     return false;
 }
Example #8
Show file File: ClientEmployeeSearch.php Project: noikiy/wowewe
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = ClientEmployee::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     \Yii::warning('yjhu_debugging: ' . \yii\helpers\Json::encode($params));
     \Yii::warning('yjhu_debugging: ' . \yii\helpers\Json::encode($this));
     $this->load($params);
     \Yii::warning('yjhu_debugging: ' . \yii\helpers\Json::encode($this));
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query = $query->joinWith('organizations');
     $query->andFilterWhere(['employee_id' => $this->employee_id, 'client_id' => $this->client_id]);
     $query->andFilterWhere(['like', 'name', $this->name]);
     $root_org = ClientOrganization::findOne(['organization_id' => $this->organization_id]);
     if (empty($root_org)) {
         $this->organization_id = 1;
         $root_org = ClientOrganization::findOne(['organization_id' => 1]);
     }
     $query->andFilterWhere(['client_organization.organization_id' => $root_org->getSubordinateIdArray()]);
     if (!empty($this->search_keyword)) {
         $query->leftJoin('client_employee_mobile', 'client_employee_mobile.employee_id = client_employee.employee_id');
         $query->andFilterWhere(['like', 'name', $this->search_keyword]);
         $query->orFilterWhere(['like', 'client_employee_mobile.mobile', $this->search_keyword]);
     }
     return $dataProvider;
 }
Example #9
Show file File: SwiftMessage.php Project: sjoorm/yii2-mailer
0
 /** @inheritdoc */
 public function saveCopy(callable $callback, $body = true)
 {
     $tos = $this->getTo();
     $froms = $this->getFrom();
     $to = empty($tos) ? null : array_keys($tos);
     $from = empty($froms) ? null : array_keys($froms);
     $inserted = $callback($this->getId(), $to[0], $from[0], $this->getSubject(), $body ? $this->getContent() : null, $this->mailer->getService());
     if ($inserted === 0) {
         \Yii::warning("Can not insert email copy of [{$this->getSubject()}|{$to}]");
     }
 }
Example #10
Show file File: XHProf.php Project: sjoorm/yii2-xhprof
0
 /**
  * Initializing XHProf
  */
 public function init()
 {
     if (extension_loaded('xhprof')) {
         parent::init();
         require_once $this->includeLibrary;
         require_once $this->includeRuns;
         xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
         $this->isInitialized = true;
     } else {
         \Yii::warning('PHP extension [xhprof] was not loaded.', 'XHProf');
     }
 }
Example #11
Show file File: Books.php Project: aekkapun/yii2-mylib
0
 /**
  * (non-PHPdoc)
  * @see \yii\db\BaseActiveRecord::afterDelete()
  */
 public function afterDelete()
 {
     $filename_utf8 = \Yii::$app->mycfg->library->directory . $this->filename;
     $filename_encoded = \Yii::$app->mycfg->Encode($filename_utf8);
     if (\Yii::$app->mycfg->library->sync) {
         if (!file_exists($filename_encoded)) {
             \Yii::warning("file '{$filename_utf8}' was removed before record deletion with sync enabled");
         } else {
             unlink($filename_encoded);
         }
     }
     parent::afterDelete();
 }
Example #12
Show file File: CSS.php Project: rmrevin/yii2-minify-view
0
 /**
  * @param array $files
  */
 protected function process(array $files)
 {
     $resultFile = $this->view->minify_path . DIRECTORY_SEPARATOR . $this->_getSummaryFilesHash($files) . '.css';
     if (!file_exists($resultFile)) {
         $css = '';
         foreach ($files as $file => $html) {
             $path = dirname($file);
             $file = $this->getAbsoluteFilePath($file);
             $content = '';
             if (!file_exists($file)) {
                 \Yii::warning(sprintf('Asset file not found `%s`', $file), __METHOD__);
             } elseif (!is_readable($file)) {
                 \Yii::warning(sprintf('Asset file not readable `%s`', $file), __METHOD__);
             } else {
                 $content = file_get_contents($file);
             }
             $result = [];
             preg_match_all('|url\\(([^)]+)\\)|is', $content, $m);
             if (!empty($m[0])) {
                 foreach ($m[0] as $k => $v) {
                     if (in_array(strpos($m[1][$k], 'data:'), [0, 1], true)) {
                         continue;
                     }
                     $url = str_replace(['\'', '"'], '', $m[1][$k]);
                     if ($this->isUrl($url)) {
                         $result[$m[1][$k]] = $url;
                     } else {
                         $result[$m[1][$k]] = $path . '/' . $url;
                     }
                 }
                 $content = strtr($content, $result);
             }
             $css .= $content;
         }
         $this->expandImports($css);
         $this->removeCssComments($css);
         if ($this->view->minifyCss) {
             $css = (new \CSSmin())->run($css, $this->view->css_linebreak_pos);
         }
         $charsets = false !== $this->view->force_charset ? '@charset "' . (string) $this->view->force_charset . '";' . "\n" : $this->collectCharsets($css);
         $imports = $this->collectImports($css);
         $fonts = $this->collectFonts($css);
         file_put_contents($resultFile, $charsets . $imports . $fonts . $css);
         if (false !== $this->view->file_mode) {
             @chmod($resultFile, $this->view->file_mode);
         }
     }
     $file = $this->prepareResultFile($resultFile);
     $this->view->cssFiles[$file] = Html::cssFile($file);
 }
Example #13
Show file File: Logger.php Project: rmrevin/yii2-rollbar
0
 /**
  * @param string $level
  * @param string $msg
  */
 public function log($level, $msg)
 {
     switch ($level) {
         default:
         case 'INFO':
             \Yii::info($msg, static::LOG_CATEGORY);
             break;
         case 'WARNING':
             \Yii::warning($msg, static::LOG_CATEGORY);
             break;
         case 'ERROR':
             \Yii::error($msg, static::LOG_CATEGORY);
             break;
     }
 }
Example #14
Show file File: Notification.php Project: gofmanaa/yii2-notification
0
 public function beforeValidate()
 {
     try {
         if ($this->isNewRecord && empty($this->created_at)) {
             $this->created_at = self::createDateTime();
         } else {
             if (!$this->isNewRecord) {
                 $this->updated_at = self::createDateTime();
             }
         }
     } catch (\Exception $e) {
         \Yii::warning($e->getMessage(), __METHOD__);
     }
     return parent::beforeValidate();
 }
Example #15
Show file File: RosskoRpcServiceClient.php Project: debrsky/parts-rpc
0
 public function GetSearch($search_string)
 {
     try {
         $result = $this->client->GetSearch(['KEY1' => $this->key1, 'KEY2' => $this->key2, 'TEXT' => $search_string]);
     } catch (\SoapFault $exception) {
         \Yii::warning($exception->getMessage(), 'rossko_api');
         return false;
     } catch (\Exception $e) {
         \Yii::warning($e->getMessage(), 'rossko_api');
         return false;
     }
     if ($result->SearchResults->SearchResult->Success) {
         return $result->SearchResults->SearchResult->PartsList->Part;
     } else {
         return false;
     }
 }
Example #16
Show file File: ClientEditForm.php Project: cookyii/module-client
0
 /**
  * @return bool
  */
 public function save()
 {
     $Client = $this->Client;
     \Yii::warning($Client->isNewRecord);
     $Client->name = $this->name;
     $Client->email = $this->email;
     $Client->phone = $this->phone;
     $result = $Client->validate() && $Client->save();
     if ($Client->hasErrors()) {
         $this->populateErrors($Client, 'name');
     }
     if (AuthManager() instanceof \yii\rbac\DbManager) {
         AuthManager()->invalidateCache();
     }
     $this->Client = $Client;
     return $result;
 }
Example #17
Show file File: WatcherDaemonController.php Project: vyants/yii2-daemon
0
 /**
  * Job processing body
  *
  * @param $job array
  *
  * @return boolean
  */
 protected function doJob($job)
 {
     $pid_file = $this->getPidPath($job['daemon']);
     \Yii::trace('Check daemon ' . $job['daemon']);
     if (file_exists($pid_file)) {
         $pid = file_get_contents($pid_file);
         if ($this->isProcessRunning($pid)) {
             if ($job['enabled']) {
                 \Yii::trace('Daemon ' . $job['daemon'] . ' running and working fine');
                 return true;
             } else {
                 \Yii::warning('Daemon ' . $job['daemon'] . ' running, but disabled in config. Send SIGTERM signal.');
                 if (isset($job['hardKill']) && $job['hardKill']) {
                     posix_kill($pid, SIGKILL);
                 } else {
                     posix_kill($pid, SIGTERM);
                 }
                 return true;
             }
         }
     }
     \Yii::error('Daemon pid not found.');
     if ($job['enabled']) {
         \Yii::trace('Try to run daemon ' . $job['daemon'] . '.');
         $command_name = $job['daemon'] . DIRECTORY_SEPARATOR . 'index';
         //flush log before fork
         $this->flushLog(true);
         //run daemon
         $pid = pcntl_fork();
         if ($pid === -1) {
             $this->halt(self::EXIT_CODE_ERROR, 'pcntl_fork() returned error');
         } elseif ($pid === 0) {
             $this->cleanLog();
             \Yii::$app->requestedRoute = $command_name;
             \Yii::$app->runAction("{$command_name}", ['demonize' => 1]);
             $this->halt(0);
         } else {
             $this->initLogger();
             \Yii::trace('Daemon ' . $job['daemon'] . ' is running with pid ' . $pid);
         }
     }
     \Yii::trace('Daemon ' . $job['daemon'] . ' is checked.');
     return true;
 }
Example #18
Show file File: ClientOutletSearch.php Project: noikiy/wowewe
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = ClientOutlet::find();
     $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => 24]]);
     \Yii::warning(__METHOD__ . \yii\helpers\Json::encode($params));
     \Yii::warning(__METHOD__ . \yii\helpers\Json::encode($this));
     $this->load($params);
     \Yii::warning(__METHOD__ . \yii\helpers\Json::encode($this));
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['outlet_id' => $this->outlet_id, 'client_id' => $this->client_id, 'supervision_organization_id' => $this->supervision_organization_id, 'category' => $this->category, 'longitude' => $this->longitude, 'latitude' => $this->latitude, 'original_office_id' => $this->original_office_id]);
     $query->andFilterWhere(['like', 'title', $this->title])->andFilterWhere(['like', 'address', $this->address])->andFilterWhere(['like', 'telephone', $this->telephone])->andFilterWhere(['like', 'pics', $this->pics]);
     $query->andFilterWhere(['supervision_organization_id' => ClientOrganization::findOne(['organization_id' => $this->msc_id])->getMscIdArray()]);
     \Yii::warning(__METHOD__ . \yii\helpers\Json::encode($query));
     return $dataProvider;
 }
Example #19
Show file File: WatcherController.php Project: voodoo-mobile/yii2-bg-tasks
0
 /**
  * Job processing body
  *
  * @param $job array
  * @return boolean
  */
 protected function doJob($job)
 {
     $pidfile = \Yii::getAlias($this->pidDir) . DIRECTORY_SEPARATOR . $job['className'];
     \Yii::trace('Check daemon ' . $job['className']);
     if (file_exists($pidfile)) {
         $pid = file_get_contents($pidfile);
         if ($this->isProcessRunning($pid)) {
             if ($job['enabled']) {
                 \Yii::trace('Daemon ' . $job['className'] . ' running and working fine');
                 return true;
             } else {
                 \Yii::warning('Daemon ' . $job['className'] . ' running, but disabled in config. Send SIGTERM signal.');
                 if (isset($job['hardKill']) && $job['hardKill']) {
                     posix_kill($pid, SIGKILL);
                 } else {
                     posix_kill($pid, SIGTERM);
                 }
                 return true;
             }
         }
     }
     \Yii::trace('Daemon pid not found.');
     if ($job['enabled']) {
         \Yii::trace('Try to run daemon ' . $job['className'] . '.');
         $command_name = $this->getCommandNameBy($job['className']);
         //flush log before fork
         \Yii::$app->getLog()->getLogger()->flush(true);
         //run daemon
         $pid = pcntl_fork();
         if ($pid == -1) {
             $this->halt(self::EXIT_CODE_ERROR, 'pcntl_fork() returned error');
         } elseif (!$pid) {
             $this->initLogger();
             \Yii::trace('Daemon ' . $job['className'] . ' is running.');
         } else {
             $this->halt(0 === \Yii::$app->runAction("{$command_name}", ['demonize' => 1]) ? self::EXIT_CODE_NORMAL : self::EXIT_CODE_ERROR);
         }
     }
     \Yii::trace('Daemon ' . $job['className'] . ' is checked.');
     return true;
 }
Example #20
Show file File: SentinelConnection.php Project: AscendDai/yii2-redis-ha
0
 /**
  * Connects to redis sentinel 
  **/
 protected function open()
 {
     if ($this->_socket !== null) {
         return;
     }
     $connection = $this->unixSocket ?: $this->hostname . ':' . $this->port;
     Yii::trace('Opening redis sentinel connection: ' . $connection, __METHOD__);
     Yii::beginProfile("Connect to sentinel", __CLASS__);
     $this->_socket = @stream_socket_client($this->unixSocket ? 'unix://' . $this->unixSocket : 'tcp://' . $this->hostname . ':' . $this->port, $errorNumber, $errorDescription, $this->connectionTimeout ? $this->connectionTimeout : ini_get("default_socket_timeout"), STREAM_CLIENT_CONNECT);
     Yii::endProfile("Connect to sentinel", __CLASS__);
     if ($this->_socket) {
         if ($this->connectionTimeout !== null) {
             stream_set_timeout($this->_socket, $timeout = (int) $this->connectionTimeout, (int) (($this->connectionTimeout - $timeout) * 1000000));
         }
         return true;
     } else {
         \Yii::warning('Failed opening redis sentinel connection: ' . $connection, __METHOD__);
         $this->_socket = false;
         return false;
     }
 }
Example #21
Show file File: AssetBundle.php Project: dmstr/yii2-web
0
 /**
  * Initializes asset bundle with optional CSS/LESS development settings
  *
  * If `APP_ASSET_FORCE_PUBLISH` is set, touch the asset folder with the highest mtime
  * of all contained files.
  * This will create a new folder in web/assets for every change and request made to the app assets.
  */
 public function init()
 {
     parent::init();
     if (getenv('APP_ASSET_FORCE_PUBLISH')) {
         $path = \Yii::getAlias($this->sourcePath);
         if (!$path) {
             \Yii::warning('Empty path', __METHOD__);
             return;
         }
         $files = FileHelper::findFiles($path);
         $mtimes = [];
         foreach ($files as $file) {
             $mtimes[] = filemtime($file);
         }
         try {
             touch($path, max($mtimes));
             \Yii::info('Touched path', __METHOD__);
         } catch (ErrorException $e) {
             \Yii::warning([$path, $e->getMessage()], __METHOD__);
         }
     }
 }
Example #22
Show file File: Module.php Project: cookyii/module-media
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     if ((int) ini_get('upload_max_filesize') < $this->maxUploadFileSize) {
         \Yii::warning(sprintf('The parameter `%s` in php.ini must be equal to`%s`', 'upload_max_filesize', $this->maxUploadFileSize . 'M'), __METHOD__);
     }
     if ((int) ini_get('post_max_size') < $this->maxUploadFileSize) {
         \Yii::warning(sprintf('The parameter `%s` in php.ini must be equal to`%s`', 'post_max_size', $this->maxUploadFileSize . 'M'), __METHOD__);
     }
     $this->uploadWebPath = \Yii::getAlias($this->uploadWebPath);
     $this->uploadPath = \Yii::getAlias($this->uploadPath);
     $this->storageWebPath = \Yii::getAlias($this->storageWebPath);
     $this->storagePath = \Yii::getAlias($this->storagePath);
     if (empty($this->uploadPath)) {
         throw new \yii\base\InvalidConfigException(\Yii::t('cookyii.media', 'Unable to determine the path to the upload directory (Media::$uploadPath).'));
     }
     if (empty($this->storagePath)) {
         throw new \yii\base\InvalidConfigException(\Yii::t('cookyii.media', 'Unable to determine the path to the storage directory (Media::$storagePath).'));
     }
     if (!file_exists($this->uploadPath) || !is_dir($this->uploadPath)) {
         FileHelper::createDirectory($this->uploadPath);
     }
     if (!file_exists($this->storagePath) || !is_dir($this->storagePath)) {
         FileHelper::createDirectory($this->storagePath);
     }
     if (!is_readable($this->uploadPath)) {
         throw new \RuntimeException(\Yii::t('cookyii.media', 'Upload directory not available for reading (Media::$uploadPath).'));
     }
     if (!is_writable($this->uploadPath)) {
         throw new \RuntimeException(\Yii::t('cookyii.media', 'Upload directory not available for writing (Media::$uploadPath).'));
     }
     if (!is_readable($this->storagePath)) {
         throw new \RuntimeException(\Yii::t('cookyii.media', 'Storage directory not available for reading (Media::$storagePath).'));
     }
     if (!is_writable($this->storagePath)) {
         throw new \RuntimeException(\Yii::t('cookyii.media', 'Storage directory not available for writing (Media::$storagePath).'));
     }
 }
Example #23
Show file File: AmqpListenerController.php Project: hzted123/yii2-amqp
0
 public function callback(AMQPMessage $msg)
 {
     $routingKey = $msg->delivery_info['routing_key'];
     $method = 'read' . Inflector::camelize($routingKey);
     if (!isset($this->interpreters[$this->queue])) {
         $interpreter = $this;
     } elseif (class_exists($this->interpreters[$this->queue])) {
         $interpreter = new $this->interpreters[$this->queue]();
         if (!$interpreter instanceof AmqpInterpreter) {
             throw new Exception(sprintf("Class '%s' is not correct interpreter class.", $this->interpreters[$this->queue]));
         }
     } else {
         throw new Exception(sprintf("Interpreter class '%s' was not found.", $this->interpreters[$this->queue]));
     }
     if (method_exists($interpreter, $method)) {
         $info = ['exchange' => $msg->get('exchange'), 'queue' => $this->queue, 'routing_key' => $msg->get('routing_key'), 'reply_to' => $msg->has('reply_to') ? $msg->get('reply_to') : null];
         try {
             $interpreter->{$method}(Json::decode($msg->body, true), $info);
         } catch (\Exception $exc) {
             $error_info = "consumer fail:" . $exc->getMessage() . PHP_EOL . "info:" . print_r($info, true) . PHP_EOL . "body:" . PHP_EOL . print_r($msg->body, true) . PHP_EOL . $exc->getTraceAsString();
             \Yii::warning($error_info, __METHOD__);
             $format = [Console::FG_RED];
             Console::stdout(Console::ansiFormat($error_info . PHP_EOL, $format));
             Console::stdout(Console::ansiFormat($exc->getTraceAsString() . PHP_EOL, $format));
         }
     } else {
         if (!isset($this->interpreters[$this->queue])) {
             $interpreter = new AmqpInterpreter();
         }
         $error_info = "Unknown routing key '{$routingKey}' for exchange '{$this->queue}'.";
         $error_info .= PHP_EOL . $msg->body;
         \Yii::warning($error_info, __METHOD__);
         $interpreter->log(sprintf("Unknown routing key '%s' for exchange '%s'.", $routingKey, $this->queue), $interpreter::MESSAGE_ERROR);
         // debug the message
         $interpreter->log(print_r(Json::decode($msg->body, true), true), $interpreter::MESSAGE_INFO);
     }
 }
Example #24
Show file File: IssuesController.php Project: yiisoft-contrib/github-bot
0
 public function actionIndex()
 {
     \Yii::$app->response->format = Response::FORMAT_JSON;
     // content of $params should look like here: https://developer.github.com/v3/activity/events/types/#issuesevent
     $params = \Yii::$app->request->bodyParams;
     $event = \Yii::$app->request->headers->get('X-Github-Event');
     if (!$event) {
         \Yii::warning('event request without X-Github-Event header.');
         throw new BadRequestHttpException('Event request without X-Github-Event header.');
     }
     Yii::$app->github->verifyRequest(Yii::$app->request->rawBody);
     if ($event === 'ping') {
         return ['success' => true, 'action' => 'pong'];
     }
     if ($event !== 'issues') {
         throw new BadRequestHttpException('Only issues events should be deployed here.');
     }
     if ($params['sender']['login'] === Yii::$app->params['github_username']) {
         \Yii::warning('ignoring event triggered by myself.');
         return ['success' => true, 'action' => 'ignored'];
     }
     switch ($params['action']) {
         case 'labeled':
             // if label is added, check for actions
             if (isset($params['label'])) {
                 foreach (\Yii::$app->params['actions'] as $action) {
                     if ($params['label']['name'] == $action['label']) {
                         $this->performAction($action, $params);
                     }
                 }
             }
             return ['success' => true, 'action' => 'processed'];
             break;
     }
     return ['success' => true, 'action' => 'ignored'];
 }
Example #25
Show file File: MemCache.php Project: rockefys/yii2-liuxy-extension
0
 /**
  * Trims duration to 30 days (2592000 seconds).
  * @param integer $duration the number of seconds
  * @return int the duration
  */
 protected function trimDuration($duration)
 {
     if ($duration > 2592000) {
         \Yii::warning('Duration has been truncated to 30 days due to Memcache/Memcached limitation.', __METHOD__);
         return 2592000;
     }
     if ($duration < 0) {
         return 0;
     }
     return $duration;
 }
Example #26
Show file File: Mailer.php Project: Nuffic/yii2-mandrill
0
 /**
  * parse the mandrill response and returns false if any message was either invalid or rejected
  *
  * @param array $mandrillResponse
  * @return boolean
  */
 private function wasMessageSentSuccesfully($mandrillResponse)
 {
     $this->_mandrillResponse = $mandrillResponse;
     $return = true;
     foreach ($mandrillResponse as $recipient) {
         switch ($recipient['status']) {
             case self::STATUS_INVALID:
                 $return = false;
                 \Yii::warning('the email for "' . $recipient['email'] . '" has not been sent: status "' . $recipient['status'] . '"', self::LOG_CATEGORY);
                 break;
             case self::STATUS_QUEUED:
                 \Yii::info('the email for "' . $recipient['email'] . '" is now in a queue waiting to be sent.', self::LOG_CATEGORY);
                 break;
             case self::STATUS_REJECTED:
                 $return = false;
                 \Yii::warning('the email for "' . $recipient['email'] . '" has been rejected: reason "' . $recipient['reject_reason'] . '"', self::LOG_CATEGORY);
                 break;
             case self::STATUS_SCHEDULED:
                 \Yii::info('the email submission for "' . $recipient['email'] . '" has been scheduled.', self::LOG_CATEGORY);
                 break;
             case self::STATUS_SENT:
                 \Yii::info('the email for "' . $recipient['email'] . '" has been sent.', self::LOG_CATEGORY);
                 break;
         }
     }
     return $return;
 }
Example #27
Show file File: User.php Project: sergeymakinen/yii2-jwt-user
0
 /**
  * Tries to read, verify, validate and return a JWT claims stored in the identity cookie.
  *
  * @param int $currentTime
  * @param string $audience
  *
  * @return array|false
  * @since 1.1
  */
 protected function getTokenClaims($currentTime = null, $audience = null)
 {
     $jwt = \Yii::$app->getRequest()->getCookies()->getValue($this->identityCookie['name']);
     if (!isset($jwt)) {
         return false;
     }
     try {
         $token = (new Parser())->parse($jwt);
         if (!$token->verify(new Sha256(), $this->token)) {
             throw new InvalidValueException('Invalid signature');
         }
         if (!$token->validate($this->initClaims(new ValidationData($currentTime), null, $audience))) {
             throw new InvalidValueException('Invalid claims');
         }
         $claims = [];
         foreach (array_keys($token->getClaims()) as $name) {
             $claims[$name] = $token->getClaim($name);
         }
         return $claims;
     } catch (\Exception $e) {
         $error = $e->getMessage();
     }
     $ip = \Yii::$app->getRequest()->getUserIP();
     \Yii::warning("Invalid JWT cookie from {$ip}: {$error}.", __METHOD__);
     \Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie));
     return false;
 }
Example #28
Show file File: HtmlCompressor.php Project: NecroMan/yii2-minify
0
 /**
  * Returns the next line from an open file handle or a string
  * @param $data
  * @return bool|string
  * @deprecated
  * @codeCoverageIgnore
  */
 private function get_line(&$data)
 {
     \Yii::warning(sprintf('You are using an deprecated method `%s`.', 'get_line'));
     return $this->getLine($data);
 }
Example #29
Show file File: CDNAssetBundle.php Project: iwansusanto/jurnalrumah
0
 public function init()
 {
     parent::init();
     \Yii::warning(sprintf('You are using an deprecated class `%s`.', __CLASS__));
 }
Example #30
Show file File: backend-test.php Project: yii2tech/project-template
0
<?php

/**
 * Configuration file for the "backend" test (web/admin-test.php) web application
 */
return yii\helpers\ArrayHelper::merge(require __DIR__ . '/backend.php', ['bootstrap' => [function () {
    if (isset($_SERVER['REMOTE_ADDR']) && !empty($GLOBALS['developerIPs'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
        $allowedIPs = $GLOBALS['developerIPs'];
        foreach ($allowedIPs as $filter) {
            if ($filter === '*' || $filter === $ip || ($pos = strpos($filter, '*')) !== false && !strncmp($ip, $filter, $pos)) {
                return;
            }
        }
        Yii::warning('Access to Test Application is denied due to IP address restriction. The requested IP is ' . $ip);
        die('You are not allowed to access this file.');
    }
}], 'components' => ['urlManager' => ['showScriptName' => true]]]);