Ejemplo n.º 1
1
 /**
  * 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'] . '&currencies=' . $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);
     }
 }
Ejemplo n.º 2
0
 /**
  * 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;
     };
 }
Ejemplo n.º 3
0
 /**
  * 保存日志
  * @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]);
 }
Ejemplo n.º 4
0
 /**
  * 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);
 }
Ejemplo n.º 5
0
 private function getLogger($name)
 {
     $logfile_dir = join(DIRECTORY_SEPARATOR, array(APP_PATH, "logs", date("Ymd", time())));
     if (!is_dir($logfile_dir)) {
         @mkdir($logfile_dir, 0777, true);
         chmod($logfile_dir, 0777);
     }
     $logger = new LoggerEngine($logfile_dir . DIRECTORY_SEPARATOR . $name . ".log");
     $logfile = $logger->getPath();
     chmod($logfile, 0777);
     return $logger;
 }
Ejemplo n.º 6
0
 /**
  * Registers services related to the module
  *
  * @param DiInterface $di
  */
 public function registerServices(DiInterface $di)
 {
     /**
      * Read configuration
      */
     $config = (include APP_PATH . "/apps/backend/config/config.php");
     /**
      * Setting up the view component
      */
     $di['view'] = function () use($config) {
         $view = new View();
         $view->setViewsDir(__DIR__ . '/views/');
         $view->registerEngines(array('.volt' => function ($view, $di) use($config) {
             $volt = new VoltEngine($view, $di);
             $volt->setOptions(array('compiledPath' => __DIR__ . '/cache/', 'compiledSeparator' => '_'));
             $compiler = $volt->getCompiler();
             // format number
             $compiler->addFilter('number', function ($resolvedArgs) {
                 return 'Helpers::number(' . $resolvedArgs . ');';
             });
             return $volt;
         }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php'));
         return $view;
     };
     /**
      * Database connection is created based in the parameters defined in the configuration file
      */
     $di['db'] = function () use($config) {
         $config = $config->database->toArray();
         $dbAdapter = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $config['adapter'];
         unset($config['adapter']);
         return new $dbAdapter($config);
     };
     /**
      * Logger service
      */
     $di->set('logger', function ($filename = null, $format = null) use($config) {
         $format = $format ?: $config->get('logger')->format;
         $filename = trim($filename ?: $config->get('logger')->filename, '\\/');
         $path = rtrim($config->get('logger')->path, '\\/') . DIRECTORY_SEPARATOR;
         $formatter = new FormatterLine($format, $config->get('logger')->date);
         $logger = new FileLogger($path . $filename);
         $logger->setFormatter($formatter);
         $logger->setLogLevel($config->get('logger')->logLevel);
         return $logger;
     });
     $di->set('url', function () use($config) {
         $url = new UrlResolver();
         $url->setBaseUri("/backend/");
         return $url;
     });
 }
Ejemplo n.º 7
0
 /**
  * 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');
     }
 }
Ejemplo n.º 8
0
 /**
  * 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');
 }
Ejemplo n.º 9
0
 public function initPersistentDB($di)
 {
     // Setup the database service
     $di->set('db', function () {
         $eventsManager = new EventsManager();
         $logger = new FileLogger(__DIR__ . '/' . date('Y-m-d') . '.sql.log');
         $eventsManager->attach('db', function ($event, $connection) use($logger) {
             if ($event->getType() == 'beforeQuery') {
                 $logger->info($connection->getSQLStatement());
             }
         });
         $db = new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => "127.0.0.1", "username" => "root", "password" => "123456", "dbname" => "rookie", "charset" => "utf8", "persistent" => true));
         $db->setEventsManager($eventsManager);
         return $db;
     });
 }
Ejemplo n.º 10
0
 /**
  * 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);
     });
 }
Ejemplo n.º 11
0
 /**
  * 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);
     });
 }
Ejemplo n.º 12
0
 /**
  * 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;
 }
Ejemplo n.º 13
0
 public static function register(Di $di)
 {
     static::$hostname = gethostname();
     $di->remove('log');
     static::$logger = null;
     $di->setShared('log', function () {
         $filePath = storagePath('logs');
         is_dir($filePath) or mkdir($filePath, 0777, true);
         $filePath .= '/' . Config::get('app.log.file', 'phwoolcon.log');
         $logger = new File($filePath);
         $formatter = $logger->getFormatter();
         if ($formatter instanceof Line) {
             $formatter->setDateFormat('Y-m-d H:i:s');
             $formatter->setFormat('[%date%]{host}[%type%] {request} %message%');
         }
         return $logger;
     });
 }
Ejemplo n.º 14
0
 /**
  * 记录起始请求日志
  * 记录成功返回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);
 }
Ejemplo n.º 15
0
 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;
 }
Ejemplo n.º 16
0
 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;
     }
 }
Ejemplo n.º 17
0
        $url->setStaticBaseUri($config->application->production->staticBaseUri);
    } else {
        $url->setBaseUri($config->application->development->baseUri);
        $url->setStaticBaseUri($config->application->development->staticBaseUri);
    }
    return $url;
}, true);
/**
 * 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);
Ejemplo n.º 18
0
 /**
  * 邮件发送
  * @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;
 }
 /**
  * Initializes the logger
  *
  * @param array $options
  */
 protected function initLogger($options = array())
 {
     $config = $this->_di->get('config');
     $this->_di->set('logger', function () use($config) {
         $logger = new PhLoggerFile(ROOT_PATH . $config->app->logger->file);
         $formatter = new PhLoggerFormatter($config->app->logger->format);
         $logger->setFormatter($formatter);
         return $logger;
     });
 }
Ejemplo n.º 20
0
    return new Flash(array('error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info', 'warning' => 'alert alert-warning'));
});
/**
 * Start the session the first time some component request the session service
 */
$di->setShared('session', function () {
    $session = new SessionAdapter();
    $session->start();
    return $session;
});
/*
 * Routes
 */
#$di->set('router', function(){
#    require 'routes.php';
#    return $router;
#});
/**
 * Logger service
 */
$di->set('logger', function ($filename = null, $format = null) use($config) {
    $format = $format ?: $config->get('logger')->format;
    $filename = trim($filename ?: $config->get('logger')->filename, '\\/');
    $path = rtrim($config->get('logger')->path, '\\/') . DIRECTORY_SEPARATOR;
    #$path = "/temp/system.log";
    $formatter = new FormatterLine($format, $config->get('logger')->date);
    $logger = new FileLogger($path . $filename);
    $logger->setFormatter($formatter);
    $logger->setLogLevel($config->get('logger')->logLevel);
    return $logger;
});
Ejemplo n.º 21
0
 * Include composer autoloader
 */
require APP_PATH . "/vendor/autoload.php";
try {
    /**
     * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
     */
    $di = new FactoryDefault();
    /**
     * Include the application services
     */
    require APP_PATH . "/app/config/services.php";
    /**
     * Handle the request
     */
    $application = new Application($di);
    echo $application->handle()->getContent();
} catch (Exception $e) {
    /**
     * Log the exception
     */
    $logger = new Logger(APP_PATH . '/app/logs/error.log');
    $logger->error($e->getMessage());
    $logger->error($e->getTraceAsString());
    /**
     * Show an static error page
     */
    $response = new Response();
    $response->redirect('505.html');
    $response->send();
}
Ejemplo n.º 22
0
    $gettext = new Gettext();
    $gettext->setOptions(['compileAlways' => $compileAlways, 'locale' => $locale->getBestLocale(), 'supported' => $locale->getSupportedLocales(), 'domains' => $config->locale->domains, 'localeDir' => $config->path->localeDir, 'localeCacheDir' => $config->path->localeCacheDir]);
    return $gettext;
});
/**
 *
 */
$di->setShared('debug', function () use($di) {
    $config = $di->getConfig();
    $logger = new MultipleStreamLogger();
    switch (ENV) {
        case DEV_ENV:
            $logger->push(new ErrorLogger());
            if ('cli' != php_sapi_name()) {
                $debugLogFile = str_replace('{{name}}', $config->site->domains[0], $config->dev->path->debugLog);
                $fileLogger = new FileLogger($debugLogFile);
                $fileLogger->getFormatter()->setFormat('%message%');
                $logger->push($fileLogger);
                $logger->push(new Firelogger());
                $logger->push(new FirephpLogger(''));
            }
            break;
    }
    return $logger;
});
/**
 * Mail service
 */
$di->setShared('mailer', function () use($di) {
    $config = $di->get('config');
    $mailManager = new MailManager($config->mailer, $config->site->mail);
Ejemplo n.º 23
0
 /**
  * The function sending log for nginx or apache, it will to analytic later
  * @return mixed
  */
 public function saveLoger($e)
 {
     //error_log($e);
     $logger = new Logger(ROOT_DIR . 'apps/logs/error.log');
     if (is_object($e)) {
         //d($e);
         $logger->error($e[0]->getMessage());
     }
     if (is_array($e)) {
         foreach ($e as $message) {
             d($e);
         }
     }
     if (is_string($e)) {
         $logger->error($e);
     }
     return $this->indexRedirect();
 }
 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!");
     }
 }
Ejemplo n.º 25
0
 /**
  * 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;
     };
 }
Ejemplo n.º 26
0
 /**
  *
  * @param type $options
  */
 protected function initLogger($options = [])
 {
     $config = $this->_di->get('config');
     $this->_di->setShared('logger', function () use($config) {
         if (!file_exists($config->logger->file)) {
             mkdir($config->logger->file, 0777, true);
         }
         $logger = new LoggerFile($config->logger->file . date('Y-m-d') . '.log');
         $formatter = new LoggerFormatter($config->logger->format);
         $logger->setFormatter($formatter);
         return $logger;
     });
     $this->_di->setShared('loggerDb', function () use($config) {
         if (!file_exists($config->logger->file . '/db/')) {
             mkdir($config->logger->file . '/db/', 0777, true);
         }
         $logger = new LoggerFile($config->logger->file . '/db/' . date('Y-m-d') . '.log');
         $formatter = new LoggerFormatter($config->logger->format);
         $logger->setFormatter($formatter);
         return $logger;
     });
 }
Ejemplo n.º 27
0
 /**
  * 默认服务依赖注入
  *
  */
 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);
 }
Ejemplo n.º 28
0
 /**
  * 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');
 }
Ejemplo n.º 29
0
<?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"));
Ejemplo n.º 30
0
 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;
 }