Example #1
0
 static function init()
 {
     $version_file = APP_PATH . '/../version';
     if (file_exists($version_file)) {
         self::$version = trim(@file_get_contents($version_file));
     }
     $config_file = APP_PATH . '/config/config.php';
     if (!file_exists($config_file)) {
         throw new Exception("No config file");
     }
     $config = (include $config_file);
     self::$config = $config;
     self::$env = $config['env'];
     #self::$context = new stdClass();
     self::$context = new Context();
     Logger::init($config['logger']);
     if (isset($config['db'])) {
         Db::init($config['db']);
     }
     if (get_magic_quotes_gpc()) {
         foreach ($_GET as $k => $v) {
             $_GET[$k] = Text::stripslashes($v);
         }
         foreach ($_POST as $k => $v) {
             $_POST[$k] = Text::stripslashes($v);
         }
         foreach ($_COOKIE as $k => $v) {
             $_COOKIE[$k] = Text::stripslashes($v);
         }
     }
     $_REQUEST = $_GET + $_POST + $_COOKIE;
 }
Example #2
0
 function __construct($token = null, $timeout = 1)
 {
     if ($token) {
         $this->token = $token;
     }
     Logger::init('vkApi', LOG_PERROR);
     $this->http_context = stream_context_create(array('http' => array('timeout' => $timeout)));
 }
Example #3
0
 function __construct()
 {
     parent::__construct(Config::TG_TOKEN);
     $dboptions = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
     $this->db = new PDO('mysql:dbname=' . Config::DB_NAME . ';host=' . Config::DB_HOST, Config::DB_LOGIN, Config::DB_PASSWORD, $dboptions);
     $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     Logger::init('tgTools', LOG_PERROR);
 }
Example #4
0
 public function run()
 {
     global $config;
     session_start();
     Logger::init();
     if ($config["test"]) {
         $config["siteUrl"] = "http://127.0.0.1:8090/";
     }
     extract($config["database"]);
     $db = $config["database"];
     DAO::connect($db["dbName"], @$db["serverName"], @$db["port"], @$db["user"], @$db["password"]);
     $url = $_GET["c"];
     if (!$url) {
         $url = $config["documentRoot"];
     }
     if (StrUtils::endswith($url, "/")) {
         $url = substr($url, 0, strlen($url) - 1);
     }
     $this->urlParts = explode("/", $url);
     $u = $this->urlParts;
     $urlSize = sizeof($this->urlParts);
     if (class_exists($this->urlParts[0]) && StrUtils::startswith($this->urlParts[0], "_") === false) {
         //Construction de l'instance de la classe (1er élément du tableau)
         try {
             $obj = new $this->urlParts[0]();
             $obj->initialize();
             try {
                 switch ($urlSize) {
                     case 1:
                         $obj->index();
                         break;
                     case 2:
                         //Appel de la méthode (2ème élément du tableau)
                         if (method_exists($obj, $u[1])) {
                             $obj->{$u}[1]();
                         } else {
                             print "La méthode `{$u[1]}` n'existe pas sur le contrôleur `" . $u[0] . "`<br/>";
                         }
                         break;
                     default:
                         //Appel de la méthode en lui passant en paramètre le reste du tableau
                         $obj->{$u}[1](array_slice($u, 2));
                         break;
                 }
             } catch (\Exception $e) {
                 print "Error!: " . $e->getMessage() . "<br/>";
                 die;
             }
         } catch (\Exception $e) {
             print "Error!: " . $e->getMessage() . "<br/>";
             die;
         }
         $obj->finalize();
     } else {
         print "Le contrôleur `" . $u[0] . "` n'existe pas <br/>";
     }
 }
Example #5
0
	public function run(){
		$config=$GLOBALS["config"];
		set_error_handler(array($this, 'errorHandler'));
		$config=$GLOBALS["config"];
		try {
			if(array_key_exists("templateEngine", $config)){
				$engine=new $config["templateEngine"]();
				if ($engine instanceof TemplateEngine)
					$GLOBALS["config"]["templateEngine"]=$engine;
			}
		} catch (\Exception $e) {
			echo $e->getTraceAsString();
		}
		session_start();
		\Logger::init();
		if($config["test"]){
			$GLOBALS["config"]["siteUrl"]="http://127.0.0.1:8090/";
		}
		extract($config["database"]);
		$db=$config["database"];
		DAO::connect($db["dbName"],@$db["serverName"],@$db["port"],@$db["user"],@$db["password"]);
		$url=$_GET["c"];

		if(!$url){
			$url=$config["documentRoot"];
		}
		if(StrUtils::endswith($url, "/"))
			$url=substr($url, 0,strlen($url)-1);
		$this->urlParts=explode("/", $url);

		$u=$this->urlParts;

		if(class_exists($u[0]) && StrUtils::startswith($u[0],"_")===false){
			//Construction de l'instance de la classe (1er élément du tableau)
			try{
				if(array_key_exists("onStartup", $config)){
					if(is_callable($config['onStartup'])){
						$config["onStartup"]($u);
					}
				}
				self::runAction($u);
			}catch (\Exception $e){
				print "Error!: " . $e->getMessage() . "<br/>";
				die();
			}

		}else{
			print "Le contrôleur `".$u[0]."` n'existe pas <br/>";
		}
	}
Example #6
0
File: Task.php Project: hihus/newpi
 protected function _initLogger()
 {
     //获得log path
     if (!defined("LOG_PATH")) {
         define("LOG_PATH", Pi::get('log.path', ''));
     }
     if (!is_dir(LOG_PATH)) {
         die('pi.err can not find the log path');
     }
     Pi::inc(Pi::get('LogLib'));
     $logFile = $this->task_name;
     $logLevel = $this->debug === true ? Logger::LOG_DEBUG : Pi::get('log.level', Logger::LOG_TRACE);
     $roll = Pi::get('log.roll', Logger::DAY_ROLLING);
     $basic = array('logid' => $this->appId);
     Logger::init(LOG_PATH, $logFile, $logLevel, array(), $roll);
     Logger::addBasic($basic);
 }
 /**
  * Initialize the environment loading the php files
  * @param bool $quiet Set the quiet flag to $quiet
  */
 public static function init($quiet = false)
 {
     if (Controller::$alreadyInited) {
         return;
     }
     global $argv;
     if (!isset($argv) || isset($_SERVER['REQUEST_METHOD'])) {
         define("CONSOLE", false);
     } else {
         define("CONSOLE", true);
     }
     define("QUIET", $quiet);
     Logger::init();
     date_default_timezone_set("UTC");
     Controller::initDB();
     Controller::loadClasses();
     Controller::$alreadyInited = true;
 }
Example #8
0
 function __construct($user_id = null)
 {
     $dboptions = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4');
     $this->db = new PDO('mysql:dbname=' . Config::DB_NAME . ';host=' . Config::DB_HOST, Config::DB_LOGIN, Config::DB_PASSWORD, $dboptions);
     $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     Logger::init('vkTools', LOG_PERROR);
     $this->tg = new tgTools();
     if (isset($user_id)) {
         $sth = $this->db->prepare('SELECT token FROM access_tokens WHERE vk_user_id = :user_id AND (till > UNIX_TIMESTAMP() OR till IS NULL)');
         $sth->execute(array('user_id' => $user_id));
         if (!($result = $sth->fetch(PDO::FETCH_ASSOC))) {
             parent::__construct(null, Config::VK_API_TIMEOUT);
         } else {
             parent::__construct($result['token'], Config::VK_API_TIMEOUT);
             $this->user_id = $user_id;
         }
     } else {
         parent::__construct(null, Config::VK_API_TIMEOUT);
     }
 }
Example #9
0
 /**
  * Получить идентификатор платежа из HTML-кода страницы
  *
  * @param string $sHtml
  *
  * @return int
  */
 private function parsePaymentId($sHtml)
 {
     $aMatches = [];
     Logger::init()->debug(print_r($sHtml, true), 'Data for parsePaymentId');
     if (is_array($sHtml)) {
         return 0;
     }
     preg_match("|Payment ID</div>.*<span>([0-9]*)</span>.*Amount|s", $sHtml, $aMatches);
     return isset($aMatches[1]) ? $aMatches[1] : 0;
 }
Example #10
0
<?php

require_once 'include/vkTools.php';
require_once 'include/tgTools.php';
Logger::init('tg_handler', 0);
Logger::debug(true);
try {
    Logger::log(LOG_DEBUG, 'starting');
    $tg_tools = new tgTools();
    $message = $tg_tools->parseMessage($HTTP_RAW_POST_DATA);
    $tg_tools->saveUser($message->getFrom());
    $vk_tools = new vkTools($tg_tools->getVkUser());
    $command = NULL;
    $text = $message->getText();
    $command = $tg_tools->getCommand($text);
    Logger::log(LOG_DEBUG, "command: {$command}");
    Logger::log(LOG_DEBUG, "text: {$text}");
    $tg_tools->processMessage($vk_tools, $command, $text, $message);
    Logger::log(LOG_DEBUG, 'finished');
} catch (\TelegramBot\Api\Exception $e) {
    Logger::log(LOG_ERR, $e->getMessage());
}
Example #11
0
    }
    private static function appendLogMessage($message)
    {
        if (self::$historyLength <= count(self::$logHistory)) {
            array_shift(self::$logHistory);
        }
        self::$logHistory[] = $message;
        file_put_contents(self::$logPath, $message . "\n", FILE_APPEND | LOCK_EX);
    }
    private static function getTimeString()
    {
        $uTimestamp = microtime(true);
        $timestamp = floor($uTimestamp);
        $milliseconds = '' . round(($uTimestamp - $timestamp) * 1000000);
        $milliseconds = str_pad($milliseconds, 6, '0');
        return date(preg_replace('/(?<!\\\\)u/', $milliseconds, self::$timeFormat), $timestamp);
    }
}
$loggerOldErrorHandler = set_error_handler(function ($errLevel, $errMessage, $errFile, $errLine, $errContext) {
    global $loggerOldErrorHandler;
    Logger::error("[{$errFile}:{$errLine}] ({$errLevel}) {$errMessage}");
    if (!is_null($loggerOldErrorHandler)) {
        return $loggerOldErrorHandler($errLevel, $errMessage, $errFile, $errLine, $errContext);
    }
}, E_ALL | E_STRICT);
set_exception_handler(function ($ex) {
    Logger::error('Uncaught exception: ' . $ex->getMessage());
    Logger::info('Exception details: ' . print_r($ex, true));
});
Logger::init();
Example #12
0
    protected function init($config)
    {
        echo <<<STYLE
<style>
    .log-message{
        display:block;
        float:left;
        width:100%;
        margin-left:0;
        margin-top:5px;
        margin-bottom:5px;
        line-height: 18px;
        text-align:center;
        border-radius: 3px;
        font-family:Arial;
        font-size:12px;
        font-weight:100;
    }
        
    .log-message span{
        display:none;
    }    
        
    .log-message b{
        font-weight: bold;
    }
        
    .log-error, .log-critical, .log-emergency{
        box-shadow:0px 0px 3px orangered;
        background:rgb(255,102,0);
        border:1px solid #fff;
        border-left:none;
        border-right:none;
        color:#fff;
    }
        
    .log-emergency{
        text-decoration: underline;
    }
        
    .log-notice, .log-warning, .log-alert{
        box-shadow:0px 0px 3px orangered;
        background:rgba(255,102,0,0.7);
        border:1px solid #fff;
        border-left:none;
        border-right:none;
        color:#fff;
    }
    
    .log-debug, .log-info{
        color:#fff;
        box-shadow:0px 0px 3px limegreen;
        background:limegreen;
        border:1px solid #fff;
        border-left:none;
        border-right:none;
    }
</style>
STYLE;
        parent::init($config);
    }
Example #13
0
<?php

require_once 'include/vkTools.php';
require_once 'include/tgTools.php';
Logger::init('vk_handler', 0);
Logger::debug(true);
try {
    Logger::log(LOG_DEBUG, 'starting');
    $tg_tools = new tgTools();
    $vk_tools = new vkTools();
    if (!array_key_exists('code', $_REQUEST)) {
        throw new Exception('no code in request');
    }
    if (!array_key_exists('state', $_REQUEST)) {
        throw new Exception('no state in request');
    }
    $url = $tg_tools->processCode($vk_tools, $_REQUEST['code'], $_REQUEST['state']);
    header("Location: {$url}");
    Logger::log(LOG_DEBUG, 'finished');
} catch (Exception $e) {
    Logger::log(LOG_ERR, $e->getMessage());
    header('Content-Type: text/plain');
    print $e->getMessage();
}
Example #14
0
    header('HTTP/1.1 503 Service Unavailable');
    echo '<h1>503 Service Unavailable</h1>';
    exit;
}
if (!isset($_POST) && !isset($_GET)) {
    exit;
}
$aData = array_merge($_POST, $_GET);
$aData['ip_address'] = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
require_once 'components/JsBridge.php';
require_once 'components/Logger.php';
Logger::init()->info([], '=== BEGIN ===');
Logger::init()->info($_SERVER, '$_SERVER');
Logger::init()->info($_POST, '$_POST');
Logger::init()->info($_GET, '$_GET');
if (isset($_POST['action'])) {
    $sAction = $_POST['action'];
} elseif (isset($_GET['action'])) {
    $sAction = $_GET['action'];
} else {
    exit;
}
try {
    $oJsBridge = new JsBridge();
    $oJsBridge->setRequest($sAction, $aData);
    echo $oJsBridge->getResponse();
    Logger::init()->info([], '=== END ===');
} catch (Exception $oException) {
    Logger::init()->error($oException);
    exit;
}
Example #15
0
	/**
	 * 初始化配置数据
	 * @param  $config
	 */
	public static function init ($config) {
		SuiShiPHPConfig::setArray($config);
		// set php log
		$phpLogDir = SuiShiPHPConfig::getPhpLogDir();
		if ($phpLogDir) {
			if (is_dir ( $phpLogDir)) {
				if (! is_writable ( $phpLogDir )) {
					trigger_error ( "set php log path is not writable: " . $phpLogDir, E_USER_WARNING);
				} else {
					//设置php log 路径文件
					ini_set("error_log",$phpLogDir. date('Y-m-d') . ".log");
				}
			} else {
				if (! @mkdir ( $phpLogDir, 0777, true )) {
					trigger_error ( "create php log path error: " . $phpLogDir, E_USER_WARNING);
				} else {
					//设置php log 路径文件
					ini_set("error_log",$phpLogDir. date('Y-m-d') . ".log");
				}
			}
		}
		HttpRequest::init();
		Logger::init();
		Template::init();
	}
Example #16
0
 public function onWorkerStart($serv, $worker_id)
 {
     $prefix = $this->name ? $this->name . ': ' : '';
     swoole_set_process_name($prefix . 'rpc worker');
     Logger::init("/tmp/{$this->name}-{$worker_id}.log");
 }
Example #17
0
<?php

require_once 'include/vkTools.php';
require_once 'include/Locker.php';
$l = new Locker('/run/lock/vktools/save_online.lock');
Logger::init('save_online', 0);
if ($argc == 2 && $argv[1] == 'debug') {
    Logger::debug(true);
}
$tools = new vkTools();
$tools->save_all_online();
$tools->merge_sessions(12 * 60);
Example #18
0
 /**
  * Получить реальный адрес страницы, с которой был выполнен запрос на проведение платежа
  *
  * @param string $sResponseUrl
  *
  * @return string
  */
 private function getRealResponseUrl($sResponseUrl)
 {
     Logger::init()->debug([], 'Called');
     $sRealResponseUrl = urldecode(urldecode(substr($sResponseUrl, strpos($sResponseUrl, 'parentUrl=') + 10)));
     return rtrim($sRealResponseUrl, '?&');
 }