/** * Import Exchange Rates */ public function ratesAction() { $lock = $this->getLock('/tmp/rates-import.lock'); if ($lock !== false) { $logger = new FileAdapter(realpath(__DIR__ . '/../logs') . '/rates-import.log'); $di = \Phalcon\DI::getDefault(); $guzzle = $di['guzzle']; $config = $di['config']['rates_api']; $url = $config['url'] . '?access_key=' . $config['access_key'] . '¤cies=' . $config['currencies'] . '&source=' . $config['source']; try { $request = $guzzle->createRequest('GET', $url); $response = $guzzle->send($request); $response = (string) $response->getBody(); $rates = json_decode($response); if ($rates->success == true) { foreach ($rates->quotes as $currencyCode => $exchangeRate) { $currencyCode = preg_replace('/^USD/', '', $currencyCode); $currency = Rate::updateRate($currencyCode, $exchangeRate); if (!$currency) { $logger->log('Failed to update currency : ' . $currencyCode . ' to rate: ' . $exchangeRate, \Phalcon\Logger::ERROR); } } } else { $logger->log('Rates import failed : ' . $response, \Phalcon\Logger::ERROR); } } catch (Exception $e) { $logger->log('Rates import failed : ' . $e->getMessage(), \Phalcon\Logger::ERROR); } $this->releaseLock($lock); } }
public static function log($type, $message = null, array $context = []) { static::$logger or static::$logger = Di::getDefault()->getShared('log'); $context['host'] = static::$hostname; $context['request'] = fnGet($_SERVER, 'REQUEST_METHOD') . ' ' . fnGet($_SERVER, 'REQUEST_URI'); static::$logger->log($type, $message, $context); }
/** * Registers the module-only services * * @param Phalcon\DI $di */ public function registerServices($di) { /** * Read configuration */ $config = (include __DIR__ . "/config/config.php"); $di['view']->setViewsDir(__DIR__ . '/views/'); /** * Database connection is created based in the parameters defined in the configuration file */ $di['db'] = function () use($config) { $connection = new DbAdapter(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname)); $eventsManager = new EventsManager(); $logger = new FileLogger(__DIR__ . "/logs/db.log"); //Listen all the database events $eventsManager->attach('db:beforeQuery', function ($event, $connection) use($logger) { $sqlVariables = $connection->getSQLVariables(); if (count($sqlVariables)) { $logger->log($connection->getSQLStatement() . ' ' . join(', ', $sqlVariables), Logger::INFO); } else { $logger->log($connection->getSQLStatement(), Logger::INFO); } }); //Assign the eventsManager to the db adapter instance $connection->setEventsManager($eventsManager); return $connection; }; }
/** * This action is executed before execute any action in the application * @param Event $event * @param Dispatcher $dispatcher */ public function beforeException(Event $event, MvcDispatcher $dispatcher, Exception $exception) { if ($exception instanceof DispatcherException) { switch ($exception->getCode()) { case Dispatcher::EXCEPTION_HANDLER_NOT_FOUND: case Dispatcher::EXCEPTION_ACTION_NOT_FOUND: $dispatcher->forward(array('controller' => 'errors', 'action' => 'resourceNotFound')); return false; } } $logDir = $this->config->application->logDir; $logger = new FileAdapter(APP_PATH . "/{$logDir}/TestZilla.log"); $logger->log($exception->getMessage(), Logger::ERROR); $logger->log($exception->getTraceAsString(), Logger::ERROR); $dispatcher->forward(array('controller' => 'errors', 'action' => 'internalServerError')); return false; }
/** * 保存日志 * @param string $logString 日志信息 * @param string $level 日志级别 */ public function log($logString, $level = 'info') { $logger = new FileLogger($this->logDir . $this->logFile); $lineFormatter = new LineFormatter(); $lineFormatter->setDateFormat('Y-m-d H:i:s'); $logger->setFormatter($lineFormatter); $logger->log($logString, $this->log_level[$level]); }
/** * Log error to syslog * * @param int php error number * @param string php error description * @param string php file where the error occured * @param int php line where the error occured * @return bool */ public static function logToSyslog($errNo, $errStr, $errFile, $errLine) { $msg = sprintf("%s (errno: %d) in %s:%d", $errStr, $errNo, $errFile, $errLine); $logfile = config('config')->logger->path . date('/Ym/') . 'errors_' . date('Ymd') . '.log'; if (!is_dir(dirname($logfile))) { mkdir(dirname($logfile), 0755, true); } $logger = new File($logfile); return $logger->log($msg, Logger::INFO); }
private function setDB() { $connection = new DatabaseConnection($this->database->toArray()); $debug = $this->application->debug; if ($debug) { $eventsManager = new EventsManager(); $logger = new FileLogger(__DIR__ . "/../Logs/db.log"); //Listen all the database events $eventsManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $variables = $connection->getSQLVariables(); if ($variables) { $logger->log($connection->getSQLStatement() . ' [' . join(',', $variables) . ']', \Phalcon\Logger::INFO); } else { $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO); } } }); $connection->setEventsManager($eventsManager); } return $connection; }
/** * Handle post data * * @return type */ public function handleCardSubmitAction() { $seri = $this->request->getPost('txtseri'); $sopin = $this->request->getPost('txtpin'); $mang = $this->request->getPost('chonmang'); $user = $this->request->getPost('txtuser'); $charid = $this->request->getPost('charguid'); $chargeDescription = $this->request->getPost('txtDescription'); if ($mang == 'MOBI') { $ten = "Mobifone"; } else { if ($mang == 'VIETEL') { $ten = "Viettel"; } else { if ($mang == 'GATE') { $ten = "Gate"; } else { if ($mang == 'VTC') { $ten = "VTC"; } else { $ten = "Vinaphone"; } } } } $arrayPost = array('merchant_id' => $this->config->baokim->merchant_id, 'api_username' => $this->config->baokim->api_username, 'api_password' => $this->config->baokim->api_password, 'transaction_id' => time(), 'card_id' => $mang, 'pin_field' => $sopin, 'seri_field' => $seri, 'algo_mode' => 'hmac'); // Prepare array post for CURL ksort($arrayPost); //mat khau di kem ma website dang kí trên B?o Kim $secure_code = $this->config->baokim->secure_code; $data_sign = hash_hmac('SHA1', implode('', $arrayPost), $secure_code); $arrayPost['data_sign'] = $data_sign; $userPwd = $this->config->baokim->CORE_API_HTTP_USR . ':' . $this->config->baokim->CORE_API_HTTP_PWD; // Init curl $curl = curl_init($this->config->baokim->restUrl); curl_setopt_array($curl, array(CURLOPT_POST => true, CURLOPT_HEADER => false, CURLINFO_HEADER_OUT => true, CURLOPT_TIMEOUT => 30, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_HTTPAUTH => CURLAUTH_DIGEST | CURLAUTH_BASIC, CURLOPT_USERPWD => $userPwd, CURLOPT_POSTFIELDS => http_build_query($arrayPost))); $data = curl_exec($curl); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); $result = json_decode($data, true); $logger = new FileAdapter($this->config->application->logFile); // if ($status == 200) { if ($status == 401) { $logger->log("This is a message"); return $this->response->redirect('index/success'); } else { $errorData = sprintf("Eror: %d | User: %s | Ma The: %s | Seri: %s", $status, $user, $seri, $sopin); $logger->error($errorData); return $this->response->redirect('index'); } }
/** * Tests new format logs correctly * * @author Nikos Dimopoulos <*****@*****.**> * @since 2012-09-17 */ public function testLoggerFormatterLineNewFormatLogsCorrectly() { $this->specify("Line formatted does not set format correctly", function () { $I = $this->tester; $fileName = $I->getNewFileName('log', 'log'); $logger = new File($this->logPath . $fileName); $formatter = new Line('%type%|%date%|%message%'); $logger->setFormatter($formatter); $logger->log('Hello'); $logger->close(); $I->amInPath($this->logPath); $I->openFile($fileName); $I->seeInThisFile(sprintf('DEBUG|%s|Hello', date('D, d M y H:i:s O'))); $I->deleteFile($fileName); }); }
/** * Tests new format logs correctly * * @author Nikos Dimopoulos <*****@*****.**> * @since 2012-09-17 */ public function testLoggerFormatterNewFormatFormatsDateCorrectly() { $fileName = newFileName('log', 'log'); $logger = new PhTLoggerAdapterFile($this->logPath . $fileName); $formatter = new PhLoggerFormatterLine('%type%|%date%|%message%'); $logger->setFormatter($formatter); $logger->log('Hello'); $logger->close(); $contents = file($this->logPath . $fileName); $message = explode('|', $contents[0]); cleanFile($this->logPath, $fileName); $date = new \DateTime($message[1]); $expected = date('Y-m-d H'); $actual = $date->format('Y-m-d H'); $this->assertEquals($expected, $actual, 'Date format not set properly'); }
/** * 记录起始请求日志 * 记录成功返回true,失败或没记录日志返回false * * @return bool */ public static function request_start_log() { if (!BaseLog::isLog('debug')) { return false; } if (!Config::getEnv("app.request_start_log")) { return false; } $data = Request::nonPostParam(); if (Config::getEnv("app.request_log_post")) { $data = Request::param(); } $file_path = BaseLog::handle_log_file('framework', 'debug'); $log_time = date("Y-m-d H:i:s", QP_RUN_START); $ip = Request::getIp(); $router_url = \Qp\Kernel\Http\Router\QpRouter::getRouterStr(); $prefix = "[{$log_time}] [{$ip}] [router : {$router_url}] "; $msg = "【请求日志】" . json_encode(['data' => $data]); $logger = new FileAdapter($file_path); $logger->setFormatter(new LineFormatter("%message%")); return (bool) $logger->log($prefix . $msg); }
public function initialize() { $this->_app = $this->dispatcher->getParam("app"); // 设置时区 ini_set("date.timezone", $this->config->setting->timezone); // 日志记录 if ($this->config->setting->recordRequest) { if (isset($_REQUEST['_url'])) { $_url = $_REQUEST['_url']; unset($_REQUEST['_url']); } else { $_url = '/'; } $log = empty($_REQUEST) ? $_url : $_url . '?' . urldecode(http_build_query($_REQUEST)); $logger = new FileLogger(BASE_DIR . $this->config->application->logsDir . date("Ym") . '.log'); $logger->log($log, Logger::INFO); } // 检查登录 $this->_user_id = $this->session->get('user_id'); if (!$this->_user_id || !$this->session->get('isLogin')) { header('Location:/login'); exit; } }
public function saveAction() { $this->view->title = "Збереження студента"; $errors = array(); !file_exists($this->logFileName) ? $attr = array('mode' => 'w') : ($attr = array()); $logger = new FileAdapter($this->logFileName, $attr); $manager = new \Phalcon\Mvc\Model\Transaction\Manager(); $transaction = $manager->get(); $indCode = $this->request->get("ind_code"); if ($indCode != NULL) { $logger->log("indCode not NULL"); if ($this->request->isPost()) { $logger->log("POST request finded"); //debug($this->request->get()); if ($this->request->get("uid") == NULL) { $user = new \Users(); $logger->log("new User created"); } else { $user = \Users::findFirst($this->request->get("uid")); if (!$user) { $logger->warning("this User is not finded!"); $user = new \Users(); $logger->log("new User created"); } else { $logger->log("User id is " . $user->id); } } $user->setTransaction($transaction); $logger->log("Transaction started"); $user->name = $this->request->get("name"); $user->last_name = $this->request->get("last_name"); $user->second_name = $this->request->get("second_name"); $user->login = $this->request->get("login"); $user->password = MD5($this->request->get("password")); $user->is_male = $this->request->get("is_male"); $user->is_active = 1; $user->email = $this->request->get("email"); $user->date_registration = date('Y-m-d H:i:s'); $user->birthday = $this->request->get("birthday"); $user->address_home = $this->request->get("address_home"); $user->phome = $this->request->get("phome"); $user->pmobile = $this->request->get("pmobile"); if ($this->request->get("id") == NULL) { $student = new \Students(); $logger->log("new Student created"); } else { $student = \Students::findFirst($this->request->get("id")); if (!$student) { $logger->warning("this Student is not finded!"); $student = new \Students(); $logger->log("new Student created"); } else { $logger->log("Student id is " . $user->id); } } //добавление студента $student->ind_code = $indCode; if (count($this->request->get("student_education")) > 0) { $logger->log("student educations from request count>0, so start to add its"); $studentEducations = array(); //добавление образований $c = 0; foreach ($this->request->get("student_education") as $educ) { $logger->log("Educ cycle #" . $c++); $educJSON = json_decode($educ, true); $se = new \StudentsEducation(); if (!array_key_exists("education_child_id", $educJSON)) { $se->education_id = $educJSON["education_id"]; } else { $se->education_id = $educJSON["education_child_id"]; } $se->institution = $educJSON["institution"]; $se->speciality = $educJSON["speciality"]; $se->qualify = $educJSON["qualify"]; $se->diploma_number = $educJSON["diploma_number"]; $se->diploma_date = $educJSON["diploma_date"]; $logger->log("Educ id = " . $educJSON["education_id"]); $studentEducations[] = $se; } } else { $logger->warning("No educations in request!"); $studentEducations = NULL; } if ($student->StudentsEducation->count() > 0) { $logger->warning("Finded old education(s) (" . $student->StudentsEducation->count() . ") in this Student. Trying to delete all its"); $c = 0; foreach ($student->StudentsEducation as $se) { $logger->log("Educ delation cycle #" . $c++); $se->delete(); } } else { $logger->warning("no old educations finded!"); } $student->StudentsEducation = $studentEducations; //debug($student->StudentsEducation); if (count($this->request->get("student_post")) > 0) { $logger->log("There is Posts in request"); $studentPosts = array(); //добавление должностей $logger->log("new Posts addition"); $c = 0; foreach ($this->request->get("student_post") as $spost) { $logger->log("Posts cycle #" . $c++); $spostJSON = json_decode($spost, true); if (!array_key_exists("brands", $spostJSON)) { $spostJSON = array_values($spostJSON)[0]; } $sp = new \StudentsPosts(); if (array_key_exists("dealer", $spostJSON)) { $sp->dealer = $spostJSON["dealer"]; } if (array_key_exists("post", $spostJSON)) { $sp->post = $spostJSON["post"]; } if (array_key_exists("rate", $spostJSON)) { $sp->rate = $spostJSON["rate"]; } if (array_key_exists("appoint_date", $spostJSON)) { $sp->appoint_date = strtotime($spostJSON["appoint_date"]); } if (array_key_exists("brands", $spostJSON) && count($spostJSON["brands"]) > 0) { // Добавление брендов $logger->log("Brands finded. Triying to add all of " . count($spostJSON["brands"]) . " brands"); $studentsPostsBrands = array(); foreach ($spostJSON["brands"] as $brand) { $spb = new \StudentsPostsBrands(); $spb->brand_id = $brand; $studentsPostsBrands[] = $spb; } $sp->StudentsPostsBrands = $studentsPostsBrands; } else { $logger->warning("no Brands in this Post finded!"); } if (array_key_exists("activities", $spostJSON) && count($spostJSON["activities"]) > 0) { // Добавление напр. деятельности $logger->log("Activities finded. Triying to add all of " . count($spostJSON["activities"]) . " activities"); $studentPostsActivities = array(); foreach ($spostJSON["activities"] as $activity) { $spa = new \StudentsPostsActivities(); $spa->activity_id = $activity; $studentPostsActivities[] = $spa; } $sp->StudentsPostsActivities = $studentPostsActivities; } else { $logger->warning("no Activities in this Post finded!"); } $studentPosts[] = $sp; } } else { $logger->warning("no Posts finded in request!"); $studentPosts = NULL; } if ($student->StudentsPosts->count() > 0) { $logger->log("There is old Posts"); $c = 0; foreach ($student->StudentsPosts as $sp) { $logger->log("old Posts deletion cycle #" . $c++); if ($sp->StudentsPostsActivities->count() > 0) { $logger->log("there is some (" . $sp->StudentsPostsActivities->count() . ") Activities in old Post. Deletion all of it."); foreach ($sp->StudentsPostsActivities as $spa) { if ($spa->delete()) { $logger->log("StudentsPostsActivities id = " . $spa->activity_id . " deleted"); } else { $logger->warning("StudentsPostsActivities id = " . $spa->activity_id . " deletion error!"); } } } else { $logger->warning("No one Activities in old Posts"); } if ($sp->StudentsPostsBrands->count() > 0) { $logger->log("there is some (" . $sp->StudentsPostsBrands->count() . ") Brands in old Post. Deletion all of it."); foreach ($sp->StudentsPostsBrands as $spb) { if ($spb->delete()) { $logger->log("StudentsPostsBrand id = " . $spb->brand_id . " deleted"); } else { $logger->warning("StudentsPostsBrand id = " . $spb->brand_id . " deletion error!"); } } } else { $logger->warning("No one Brands in old Posts"); } $logger->log("Posts id " . $sp->id . " deletion"); if ($sp->delete()) { $logger->log("StudentsPosts id = " . $sp->id . " deleted"); } else { $logger->warning("StudentsPosts id = " . $sp->id . " deletion error!"); } } } else { $logger->warning("no old Posts finded!"); } $logger->log("Add all new Posts to Student"); $student->StudentsPosts = $studentPosts; $logger->log("Add all new Students to User"); $user->Students = array($student); if ($user->save() === false) { $logger->log("User not saved!"); echo '<div class="alert alert-warning" role="alert">Під час збереження студента виникли наступні помилки: <br><ul>'; foreach ($user->getMessages() as $msg) { echo "<li>" . $msg . "</li>"; } echo "</ul></div>"; $transaction->rollback("Під час збереження студента виникли помилки"); } else { if ($transaction->commit()) { if ($this->request->get("id") == NULL) { echo '<div class="alert alert-success" role="alert">Студент доданий успішно!</div>'; } else { echo '<div class="alert alert-success" role="alert">Студент збережений успішно!</div>'; } $logger->log("User saved!"); } else { echo '<div class="alert alert-warning" role="alert">Під час збереження студента виникла помилка транзакції <br><ul>'; $logger->warning("Transaction save errors:"); foreach ($transaction->getMessages() as $msg) { $logger->warning("--- " . $msg); } } } //$user->Students = array(); } } else { echo '<div class="alert alert-warning" role="alert">Під час збереження студента виникла помилка. Вiдсутній ІНН!</div>'; $transaction->rollback("Вiдсутній ІНН!"); $logger->error("No INN!"); } }
/** * 数据库连接 */ protected function initDatabase() { $config = $this->config; $debug = $this->debug; if ($config->offsetExists('database') == false) { return; } $this->di['db'] = function () use($config, $debug) { if ($debug && $config->offsetExists('logger') && $config->logger->offsetExists('sqlPath')) { $eventsManager = new EventsManager(); $path = $config->logger->sqlPath; $path = str_replace('{{date}}', date("Ymd"), $path); $logger = new LoggerFile($path); //Listen all the database events $eventsManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($connection->getSQLStatement(), Logger::INFO); } }); $connection = new DbAdapter($config->database->toArray()); //Assign the eventsManager to the db adapter instance $connection->setEventsManager($eventsManager); return $connection; } else { return new DbAdapter($config->database->toArray()); } }; }
/** * 默认服务依赖注入 * */ protected function commonServices() { $mode = $this->mode; $di = $this->mode === 'CLI' ? new Cli() : new FactoryDefault(); // 日志 $di->set('logger', function () { $config = load('logger'); $adapter = $config['adapter']; $filename = $config[$adapter]['filename']; $filedir = dirname($filename); if (empty($config)) { throw new \Exception('logger config Require failed'); } if (!is_dir($filedir)) { mkdir($filedir, 0755, true); } $logger = new File($filename); $formatter = new Line(null, 'Y-m-d H:i:s'); $loglevel = config('app.loglevel'); $logger->setFormatter($formatter); $logger->setLogLevel($loglevel ? $loglevel : \Phalcon\Logger::ERROR); return $logger; }, true); $this->application->setDI($di); // 命名空间 $di->set('dispatcher', function () use($mode) { $dispatcher = new Dispatcher(); $dispatcher = $mode === 'CLI' ? new \Phalcon\CLI\Dispatcher() : new Dispatcher(); $bootstrap = load('bootstrap'); $default = $bootstrap['dispatcher']; $dispatcher->setDefaultNamespace($mode === 'CLI' ? $default['cli'] : $default['default']); return $dispatcher; }, true); // 路由 if ($load = load('router', null, true)) { if ($load instanceof Router) { $di->set('router', $load); } } // 视图 $di->set('view', function () { $view = new View(); $view->setViewsDir(APP_VIEW); return $view; }, true); // 加解密 if ($config = config('crypt')) { $di->set('crypt', function () use($config) { $crypt = new Crypt(); $crypt->setKey($config['authkey']); return $crypt; }, true); } // 默认缓存 if ($config = config('cache')) { $di->set('cache', function () use($config) { $cache = null; $adapter = strtolower($config['adapter']); $options = $config[$adapter]; $frontend = new Data(array('lifetime' => $config['lifetime'])); switch ($adapter) { case 'memcache': $cache = new Memcache($frontend, $options); break; case 'redis': if (empty($options['auth'])) { unset($options['auth']); } $cache = new \Phalcon\Extend\Cache\Backend\Redis($frontend, $options); break; } return $cache; }, true); } // Cookies if ($config = config('cookies')) { $di->set('cookies', function () use($config) { $cookies = new \Phalcon\Extend\Http\Response\Cookies($config); if (!config('crypt.authkey')) { $cookies->useEncryption(false); } return $cookies; }, true); } // Session if ($config = config('session')) { $di->set('session', function () use($config) { if (!empty($config['options'])) { foreach ($config['options'] as $name => $value) { ini_set("session.{$name}", $value); } } $adapter = strtolower($config['adapter']); $options = $config[$adapter]; switch ($adapter) { case 'memcache': $session = new SessionMemcache($options); break; case 'redis': $session = new \Phalcon\Extend\Session\Adapter\Redis($options); break; default: $session = new SessionFiles(); break; } $session->start(); return $session; }, true); } // Db if ($config = config('db')) { $di->set('db', function () use($config) { $mysql = new Mysql($config); if (debugMode()) { $eventsManager = new Manager(); $logger = new File(APP_LOG . DS . 'Mysql' . LOGEXT); $formatter = new Line(null, 'Y-m-d H:i:s'); $logger->setFormatter($formatter); $eventsManager->attach('db', function ($event, $mysql) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($mysql->getSQLStatement(), Logger::INFO); } if ($event->getType() == 'afterQuery') { } }); $mysql->setEventsManager($eventsManager); } return $mysql; }, true); } // DB 元信息 if ($config = config('metadata')) { $di->set('modelsMetadata', function () use($config) { $modelsMetadata = null; $adapter = strtolower($config['adapter']); $options = $config[$adapter]; switch ($adapter) { case 'memcache': $modelsMetadata = new MetaDataMemcache($options); break; case 'redis': if (empty($options['auth'])) { unset($options['auth']); } $modelsMetadata = new MetaDataRedis($options); break; } return $modelsMetadata; }, true); } $this->application->setDI($di); }
/** * Tests the begin/rollback * * @author Nikos Dimopoulos <*****@*****.**> * @since 2012-11-30 */ public function testRollback() { $fileName = $this->getFileName('log', 'log'); $logger = new PhLoggerAdapterFile($this->logPath . $fileName); $logger->log('Hello'); $contents = file($this->logPath . $fileName); $expected = 1; $actual = count($contents); $this->assertEquals($expected, $actual, 'Log does not contain correct number of messages before rollback'); $logger->begin(); $logger->log('Message 1'); $logger->log('Message 2'); $logger->log('Message 3'); $logger->rollback(); $logger->close(); $contents = file($this->logPath . $fileName); $expected = 1; $actual = count($contents); $this->cleanFile($this->logPath, $fileName); $this->assertEquals($expected, $actual, 'Log does not contain correct number of messages after rollback'); }
<?php use Phalcon\Logger, Phalcon\Events\Manager as EventsManager, Phalcon\Logger\Adapter\File as Logger; $eventsManager = new EventsManager(); $logger = new Logger("app/logs/db.log"); //Listen all the database events $eventsManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($connection->getSQLStatement(), Logger::INFO); } }); //Assign the eventsManager to the db adapter instance $connection->setEventsManager($eventsManager); //Execute some SQL statement $connection->insert("products", array("Hot pepper", 3.5), array("name", "price"));
$di->set('dispatcher', function () use($config, $eventsManager) { $dispatcher = new Dispatcher(); $dispatcher->setDefaultNamespace('MyApp\\Controllers'); if ($config->setting->securityPlugin) { $eventsManager->attach('dispatch', new SecurityPlugin()); $dispatcher->setEventsManager($eventsManager); } return $dispatcher; }, true); // Database Event // https://docs.phalconphp.com/zh/latest/reference/dispatching.html#dispatch-loop-events $eventsManager->attach('db', function ($event, $connection) use($config) { if ($event->getType() == 'beforeQuery') { if ($config->setting->recordSQL) { $logger = new FileLogger(BASE_DIR . $config->application->logsDir . "logsSQL.log"); $logger->log($connection->getSQLStatement()); } if (preg_match('/drop|alter/i', $connection->getSQLStatement())) { return false; } } }); // Database connection $di->set('dbData', function () use($config, $eventsManager) { $connection = new DbAdapter(array('host' => $config->db_data->host, 'username' => $config->db_data->username, 'password' => $config->db_data->password, 'dbname' => $config->db_data->dbname, 'charset' => $config->db_data->charset)); $connection->setEventsManager($eventsManager); return $connection; }, true); $di->set('dbBackend', function () use($config, $eventsManager) { $connection = new DbAdapter(array('host' => $config->db_backend->host, 'username' => $config->db_backend->username, 'password' => $config->db_backend->password, 'dbname' => $config->db_backend->dbname, 'charset' => $config->db_backend->charset)); $connection->setEventsManager($eventsManager);
/** * 邮件发送 * @param $toemail 收件人 * @param $subject 发件标题 * @param $email_message 发件内容 * <code> * $mail = new \App\Plugin\Mail(); * $mail->smtp('*****@*****.**','Have a try','This is test content'); * </code> */ public function smtp($toemail, $subject, $email_message) { $email_from = '=?utf-8?B?' . base64_encode($this->sitename) . "?= <" . $this->mail_from . ">"; $email_subject = '=?utf-8?B?' . base64_encode(preg_replace("/[\r|\n]/", '', '[' . $this->sitename . '] ' . $subject)) . '?='; $headers = "From: {$email_from} \r\nX-Priority: 3 \r\n X-Mailer: Chairsma \r\n MIME-Version: 1.0 \r\n Content-type: text/html\r\n charset=utf-8 \r\n Content-Transfer-Encoding: base64 \r\n "; $log = new FileAdapter(LOGS_PATH . 'mail_' . date('Ymd') . '.log'); if (!($fp = pfsockopen($this->smtp_server, $this->smtp_port, $errno, $errstr, 30))) { $log->error('(' . $this->smtp_server . ':' . $this->smtp_port . ') CONNECT - Unable to connect to the SMTP server'); return false; } stream_set_blocking($fp, true); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != '220') { $log->error('(' . $this->smtp_server . ':' . $this->smtp_port . ") CONNECT - {$lastmessage}"); return false; } fputs($fp, "HELO Charisma\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) { $log->error('(' . $this->smtp_server . ':' . $this->smtp_port . ") Charisma - {$lastmessage}"); return false; } while (1) { if (substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) { break; } $lastmessage = fgets($fp, 512); } fputs($fp, "AUTH LOGIN\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 334) { $log->error('(' . $this->smtp_server . ':' . $this->smtp_port . ") AUTH LOGIN - {$lastmessage}"); return false; } fputs($fp, base64_encode($this->mail_user) . "\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 334) { $log->error('(' . $this->smtp_server . ':' . $this->smtp_port . ") USERNAME - {$lastmessage}"); return false; } fputs($fp, base64_encode($this->mail_password) . "\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 235) { $log->error('(' . $this->smtp_server . ':' . $this->smtp_port . ") PASSWORD - {$lastmessage}"); return false; } fputs($fp, "MAIL FROM: <" . preg_replace("/.*\\<(.+?)\\>.*/", "\\1", $email_from) . ">\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 250) { fputs($fp, "MAIL FROM: <" . preg_replace("/.*\\<(.+?)\\>.*/", "\\1", $email_from) . ">\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 250) { $log->error('(' . $this->smtp_server . ':' . $this->smtp_port . ") MAIL FROM - {$lastmessage}"); return false; } } fputs($fp, "RCPT TO: <" . preg_replace("/.*\\<(.+?)\\>.*/", "\\1", $toemail) . ">\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 250) { fputs($fp, "RCPT TO: <" . preg_replace("/.*\\<(.+?)\\>.*/", "\\1", $toemail) . ">\r\n"); $lastmessage = fgets($fp, 512); $log->error('(' . $this->smtp_server . ':' . $this->smtp_port . ") RCPT TO - {$lastmessage}"); return false; } fputs($fp, "DATA\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 354) { $log->error('(' . $this->smtp_server . ':' . $this->smtp_port . ") DATA - {$lastmessage}"); return false; } fputs($fp, "Date: " . gmdate('r') . "\r\n"); $info = "\r\n发送时间:" . date('Y-m-d H:i:s') . "\r\n"; $info .= '发件人:' . $this->mail_from . "\r\n"; fputs($fp, "To: " . $toemail . "\r\n"); $info .= '收件人:' . $toemail . "\r\n"; fputs($fp, "Subject: " . $email_subject . "\r\n"); $info .= '标题:' . $subject . "\r\n"; fputs($fp, $headers); fputs($fp, "\r\n\r\n"); fputs($fp, $email_message . "\r\n.\r\n"); $info .= '内容:' . $email_message . "\r\n"; $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 250) { $log->error('(' . $this->smtp_server . ':' . $this->smtp_port . ") END - {$lastmessage}"); } fputs($fp, "QUIT\r\n"); $log->log($info); return true; }
/** * Registers services related to the module * * @param DiInterface $di */ public function registerServices(DiInterface $di) { $config = $this->config; $debug = $this->debug; /** * Setting up the view component */ $DD = $this::DIR; $di['view'] = function () use($config, $debug, $DD) { $view = new View(); $viewDir = $DD . '/views/'; if ($config->offsetExists('application') && $config->application->offsetExists('viewsDir') && $config->application->offsetExists('viewsDir')) { $viewDir = $config->application->viewsDir; } $view->setViewsDir($viewDir); $viewEngines = ['.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php']; $viewEngines['.volt'] = function ($view, $di) use($config, $debug, $DD) { $cacheDir = $DD . '/../cache/'; $appConfig = $di['appConfig']; if ($appConfig->offsetExists('volt') && $appConfig->volt->offsetExists('cacheDir')) { $cacheDir = $appConfig->volt->cacheDir; } elseif ($config->offsetExists('application') && $config->application->offsetExists('cacheDir') && $config->application->offsetExists('cacheDir')) { $cacheDir = $config->application->cacheDir; } $volt = new VoltEngine($view, $di); $volt->setOptions(array('compiledPath' => $cacheDir, 'compiledExtension' => ".compiled", 'compiledSeparator' => '_', 'compileAlways' => $debug)); $compiler = $volt->getCompiler(); // 扩展 if ($config->offsetExists('volt') && $config->volt->offsetExists('extension')) { foreach ($config->volt->extension as $k => $v) { $compiler->addExtension($v); } } if ($appConfig->offsetExists('volt') && $appConfig->volt->offsetExists('extension')) { foreach ($appConfig->volt->extension as $k => $v) { $compiler->addExtension($v); } } // 函数 if ($config->offsetExists('volt') && $config->volt->offsetExists('func')) { foreach ($config->volt->func as $k => $v) { $compiler->addFunction($k, $v); } } if ($appConfig->offsetExists('volt') && $appConfig->volt->offsetExists('func')) { foreach ($appConfig->volt->func as $k => $v) { $compiler->addFunction($k, $v); } } // 过滤器 if ($config->offsetExists('volt') && $config->volt->offsetExists('filter')) { foreach ($config->volt->filter as $k => $v) { $compiler->addFilter($k, $v); } } if ($appConfig->offsetExists('volt') && $appConfig->volt->offsetExists('filter')) { foreach ($appConfig->volt->filter as $k => $v) { $compiler->addFilter($k, $v); } } return $volt; }; $view->registerEngines($viewEngines); return $view; }; if ($config->offsetExists('database')) { $di['db'] = function () use($config, $di, $debug) { $appConfig = $di['appConfig']; if ($debug && $appConfig->offsetExists('logger') && $appConfig->logger->offsetExists('sqlPath')) { $eventsManager = new EventsManager(); $path = $config->logger->sqlPath; $path = str_replace('{{date}}', date("Ymd"), $path); $logger = new LoggerFile($path); //Listen all the database events $eventsManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($connection->getSQLStatement(), Logger::INFO); } }); $connection = new DbAdapter($config->database->toArray()); //Assign the eventsManager to the db adapter instance $connection->setEventsManager($eventsManager); return $connection; } else { return new DbAdapter($config->database->toArray()); } }; } if ($config->offsetExists('application') && $config->application->offsetExists('baseUri')) { $di['url'] = function () use($config) { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri($config->application->baseUri); return $url; }; } $di['moduleConfig'] = function () use($config) { return $config; }; }
protected function diDbAdapter($adapterName, array $options) { $adapterName = strtolower($adapterName); $adapterMapping = array('mysql' => 'Phalcon\\Db\\Adapter\\Pdo\\Mysql', 'oracle' => 'Phalcon\\Db\\Adapter\\Pdo\\Oracle', 'postgresql' => 'Phalcon\\Db\\Adapter\\Pdo\\Postgresql', 'sqlite' => 'Phalcon\\Db\\Adapter\\Pdo\\Sqlite'); $options['charset'] = isset($options['charset']) && $options['charset'] ? $options['charset'] : 'utf8'; if (!isset($adapterMapping[$adapterName])) { throw new Exception\RuntimeException(sprintf('No matched DB adapter found by %s', $adapterName)); } $dbAdapter = new $adapterMapping[$adapterName]($options); $config = $this->getDI()->getConfig(); if ($config->debug) { $di = $this->getDI(); $eventsManager = $di->getEventsManager(); $logger = new FileLogger($config->logger->path . 'db_query.log'); //database service name hardcore as db $eventsManager->attach('db', function ($event, $dbAdapter) use($logger) { if ($event->getType() == 'beforeQuery') { $sqlVariables = $dbAdapter->getSQLVariables(); if (count($sqlVariables)) { $query = str_replace(array('%', '?'), array('%%', "'%s'"), $dbAdapter->getSQLStatement()); $query = vsprintf($query, $sqlVariables); // $logger->log($query, \Phalcon\Logger::INFO); } else { $logger->log($dbAdapter->getSQLStatement(), \Phalcon\Logger::INFO); } } }); $dbAdapter->setEventsManager($eventsManager); } return $dbAdapter; }
/** * Logs the error and dispatches an error controller. * * @param \Phalcon\Error\Error $error * @return mixed */ public static function handle(Error $error) { $di = Di::getDefault(); $config = $di->getShared('config')->error->toArray(); $logger = $config['logger']; if (!$logger instanceof AdapterInterface) { $logger = new FileLogger($logger); } $type = static::getErrorType($error->type()); $message = "{$type}: {$error->message()} in {$error->file()} on line {$error->line()}"; if (isset($config['formatter'])) { $formatter = null; if ($config['formatter'] instanceof Formatter) { $formatter = $config['formatter']; } elseif (is_array($config['formatter'])) { $format = null; $dateFormat = null; if (isset($config['formatter']['format'])) { $format = $config['formatter']['format']; } if (isset($config['formatter']['dateFormat'])) { $dateFormat = $config['formatter']['dateFormat']; } elseif (isset($config['formatter']['date_format'])) { $dateFormat = $config['formatter']['date_format']; } elseif (isset($config['formatter']['date'])) { $dateFormat = $config['formatter']['date']; } $formatter = new FormatterLine($format, $dateFormat); } if ($formatter) { $logger->setFormatter($formatter); } } $logger->log(static::getLogType($error->type()), $message); switch ($error->type()) { case E_WARNING: case E_NOTICE: case E_CORE_WARNING: case E_COMPILE_WARNING: case E_USER_WARNING: case E_USER_NOTICE: case E_STRICT: case E_DEPRECATED: case E_USER_DEPRECATED: case E_ALL: break; case 0: case E_ERROR: case E_PARSE: case E_CORE_ERROR: case E_COMPILE_ERROR: case E_USER_ERROR: case E_RECOVERABLE_ERROR: if ($di->has('view')) { $dispatcher = $di->getShared('dispatcher'); $view = $di->getShared('view'); $response = $di->getShared('response'); $dispatcher->setControllerName($config['controller']); $dispatcher->setActionName($config['action']); $dispatcher->setParams(['error' => $error]); $view->start(); $dispatcher->dispatch(); $view->render($config['controller'], $config['action'], $dispatcher->getParams()); $view->finish(); return $response->setContent($view->getContent())->send(); } else { echo $message; } } }
/** * @param $event * @param Mysql $connection */ public function afterQuery($event, Mysql $connection) { $this->logger->log($connection->getSQLStatement(), \Phalcon\Logger::ERROR); }
return $view; }; /** * The URL component is used to generate all kind of urls in the application */ $di['url'] = function () use($config) { $url = new UrlResolver(); $url->setBaseUri($config->application->baseUri); return $url; }; /** * Database connection is created based in the parameters defined in the configuration file */ $di['db'] = function () use($config) { $eventsManager = new EventsManager(); $logger = new FileAdapter("/tmp/phalcon-general-sql.log"); // Listen all the database events $eventsManager->attach('db', function ($event, $connection) use($logger) { /** * @var Phalcon\Events\Event $event * @var DbAdapter $connection */ if ($event->getType() == 'beforeQuery') { $logger->log($connection->getSQLStatement(), Logger::DEBUG); } }); $connection = new DbAdapter(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname)); // Assign the eventsManager to the db adapter instance $connection->setEventsManager($eventsManager); return $connection; };
/** * Init Services * * @param mixed $config * @param \Phalcon\DiInterface $di */ public function _initServices($di, $config) { /** * The URL component is used to generate all kind of urls in the application */ $di->set('url', function () use($config) { $url = new UrlResolver(); $url->setBaseUri($config->website->baseUri); return $url; }, true); /** * Start the session the first time some component request the session service */ $di->set('session', function () use($config) { $session = new ZSession(['uniqueId' => $config->auth->salt]); $session->start(); return $session; }, true); /** * Set view cache */ $di->set('viewCache', function () use($config) { //Cache data for one day by default $frontCache = new FrontendOutput(['lifetime' => $config->viewCache->lifetime]); //File backend settings $cache = new CacheFile($frontCache, ['cacheDir' => ROOT_PATH . $config->viewCache->dir]); return $cache; }); if ($config->modelMetadataCache->status) { /** * Set models metadata */ $di->set('modelsMetadata', function () use($config) { if ($config->modelMetadataCache->type == 'apc') { return new MetaDataApc(['lifetime' => $config->modelMetadataCache->lifetime, 'prefix' => $config->modelMetadataCache->prefix]); } else { return new MetadataFiles(['metaDataDir' => ROOT_PATH . '/cache/metadata/', 'lifetime' => $config->modelMetadataCache->lifetime]); } }); } /** * Crypt service */ $di->set('crypt', function () use($config) { $crypt = ZCrypt::getInstance(); $crypt->setKey($config->crypt->key); return $crypt; }); /** * Set security */ $di->set('security', function () { $security = new Security(); $security->setWorkFactor(8); return $security; }); /** * Set up database connection */ $di->set('db', function () use($config) { $adapter = 'Phalcon\\Db\\Adapter\\Pdo\\' . $config->database->adapter; /** * @var \Phalcon\Db\Adapter\Pdo\Postgresql $db */ if ($config->database->adapter == 'Mysql') { $db = new $adapter($config->database->toArray()); } else { $db = new $adapter(array('host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->dbname)); } if ($config->database->log) { $eventsManager = new EventsManager(); if (!file_exists(ROOT_PATH . '/cache/logs/db.log')) { file_put_contents(ROOT_PATH . '/cache/logs/db.log', ''); } $logger = new FileLogger(ROOT_PATH . '/cache/logs/db.log'); //Listen all the database events $eventsManager->attach('db', function ($event, $db) use($logger) { /** * @var \Phalcon\Events\Event $event */ if ($event->getType() == 'beforeQuery') { /** * @var \Phalcon\Db\Adapter\Pdo\Postgresql $db */ $logger->log($db->getSQLStatement(), Logger::INFO); } }); //Assign the eventsManager to the db adapter instance $db->setEventsManager($eventsManager); } return $db; }); /** * Set a models manager */ $di->set('modelsManager', new ModelsManager()); /** * Set up model cache for Phalcon model */ $di->set('modelsCache', function () { return ZCache::getInstance('_ZCMS_MODEL'); }); /** * Set up asset add css, js */ $di->set('assets', new ZAssets()); /** * Loading routes from the routes.php file */ $di->set('router', function () { return require APP_DIR . '/config/router.php'; }); $di->set('acl', ZAcl::getInstance()); /** * Set up the flash service (custom with bootstrap) */ $di->set('flashSession', function () { $flashSession = new FlashSession(['warning' => 'alert alert-warning', 'notice' => 'alert alert-info', 'success' => 'alert alert-success', 'error' => 'alert alert-danger']); return $flashSession; }); /** * Set up cache */ $di->set('cache', ZCache::getInstance('_ZCMS_GLOBAL')); }
/** * Initializes the database * * @param array $options */ protected function initDatabase($options = array()) { $config = $this->di['config']; // setup database service $this->di['db'] = function () use($config) { $connection = new PhMysql(array('host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->dbname)); // log sql statements if ('1' == $config->application->debug) { $eventsManager = new EventsManager(); $logger = new PhLogFileAdapter($config->application->logDir . "/db.log"); //Listen all the database events $eventsManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO); } }); // Assign the eventsManager to the db adapter instance $connection->setEventsManager($eventsManager); } return $connection; }; }
public static function diDbAdapter($adapterKey, array $options, $di) { $adapterKey = false === strpos($adapterKey, '\\') ? strtolower($adapterKey) : $adapterKey; $adapterMapping = array('mysql' => 'Phalcon\\Db\\Adapter\\Pdo\\Mysql', 'oracle' => 'Phalcon\\Db\\Adapter\\Pdo\\Oracle', 'postgresql' => 'Phalcon\\Db\\Adapter\\Pdo\\Postgresql', 'sqlite' => 'Phalcon\\Db\\Adapter\\Pdo\\Sqlite'); $adapterClass = empty($adapterMapping[$adapterKey]) ? $adapterKey : $adapterMapping[$adapterKey]; if (false === class_exists($adapterClass)) { throw new Exception\RuntimeException(sprintf('No matched DB adapter found by %s', $adapterClass)); } $options['charset'] = isset($options['charset']) && $options['charset'] ? $options['charset'] : 'utf8'; $dbAdapter = new $adapterClass($options); $config = $di->getConfig(); if ($config->debug) { $eventsManager = $di->getEventsManager(); $logger = new FileLogger($config->logger->path . 'db_query.log'); //database service name hardcore as db $eventsManager->attach('db', function ($event, $dbAdapter) use($logger) { if ($event->getType() == 'beforeQuery') { $sqlVariables = $dbAdapter->getSQLVariables(); if (count($sqlVariables)) { $query = str_replace(array('%', '?'), array('%%', "'%s'"), $dbAdapter->getSQLStatement()); $query = vsprintf($query, $sqlVariables); // $logger->log($query, \Phalcon\Logger::INFO); } else { $logger->log($dbAdapter->getSQLStatement(), \Phalcon\Logger::INFO); } } }); $dbAdapter->setEventsManager($eventsManager); } return $dbAdapter; }
/** * Tests the begin/rollback * * @author Nikolaos Dimopoulos <*****@*****.**> * @since 2014-09-13 */ public function testLoggerAdapterFileRollback() { $this->specify("Logging does not contain correct number of messages before rollback", function () { $fileName = newFileName('log', 'log'); $logger = new PhTLoggerAdapterFile($this->logPath . $fileName); $logger->log('Hello'); $logger->close(); $contents = file($this->logPath . $fileName); cleanFile($this->logPath, $fileName); $expected = 1; $actual = count($contents); expect($actual)->equals($expected); }); $this->specify("Logging does not contain correct number of messages after rollback", function () { $fileName = newFileName('log', 'log'); $logger = new PhTLoggerAdapterFile($this->logPath . $fileName); $logger->log('Hello'); $logger->begin(); $logger->log('Message 1'); $logger->log('Message 2'); $logger->log('Message 3'); $logger->rollback(); $logger->close(); $contents = file($this->logPath . $fileName); cleanFile($this->logPath, $fileName); $expected = 1; $actual = count($contents); expect($actual)->equals($expected); }); }
* Database connection is created based in the parameters defined in the configuration file */ $di->set('db', function () use($config) { $connection = new DatabaseConnection($config->database->toArray()); $debug = $config->application->debug; if ($debug) { $eventsManager = new EventsManager(); $logger = new FileLogger(APP_PATH . "/app/logs/db.log"); //Listen all the database events $eventsManager->attach('db', function ($event, $connection) use($logger) { /** @var Phalcon\Events\Event $event */ if ($event->getType() == 'beforeQuery') { /** @var DatabaseConnection $connection */ $variables = $connection->getSQLVariables(); if ($variables) { $logger->log($connection->getSQLStatement() . ' [' . join(',', $variables) . ']', \Phalcon\Logger::INFO); } else { $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO); } } }); //Assign the eventsManager to the db adapter instance $connection->setEventsManager($eventsManager); } return $connection; }); /** * If the configuration specify the use of metadata adapter use it or use memory otherwise */ $di->set('modelsMetadata', function () use($config) { if ($config->application->debug) {
/** * Runs the various logging function testLoggerAdapterFiles * * @author Nikos Dimopoulos <*****@*****.**> * @since 2014-09-13 * * @param mixed $level * @param null $name */ protected function runLogging($level, $name = null) { $fileName = newFileName('log', 'log'); $logger = new PhTLoggerAdapterFile($this->logPath . $fileName); if (is_null($name)) { $logger->log($level); $name = 'DEBUG'; } else { $logger->log($level, 'Hello'); } $logger->close(); $contents = file($this->logPath . $fileName); cleanFile($this->logPath, $fileName); $position = strpos($contents[0], '[' . $name . ']'); $actual = $position !== false; expect($actual)->true(); $position = strpos($contents[0], 'Hello'); $actual = $position !== false; expect($actual)->true(); }