/** * Convert a comma separated file into an associated array. * The first row should contain the array keys. * * Example: * * @param string $filename Path to the CSV file * @param string $delimiter The separator used in the file * @return array * @link http://gist.github.com/385876 * @author Jay Williams <http://myd3.com/> * @copyright Copyright (c) 2010, Jay Williams * @license http://www.opensource.org/licenses/mit-license.php MIT License */ function csv_to_array($filename = '', $delimiter = ',', $enclosure = '"') { if (!file_exists($filename) || !is_readable($filename)) { log_fatal("file {$filename} not found"); return FALSE; } $header = NULL; $hcount = 0; $lcount = 0; $data = array(); if (($handle = fopen($filename, 'r')) !== FALSE) { while (($row = fgetcsv($handle, 0, $delimiter, $enclosure)) !== FALSE) { if (!$header) { $header = $row; $hcount = count($header); } else { if ($hcount != count($row)) { echo implode(",", $row) . "\n{$filename}: array broken, header {$hcount} != row " . count($row) . "\n"; continue; } $data[] = array_combine($header, $row); } } fclose($handle); } return $data; }
function cache_memcache_connect() { if (!isset($GLOBALS['remote_cache_conns']['memcache'])) { $host = $GLOBALS['cfg']['memcache_host']; $port = $GLOBALS['cfg']['memcache_port']; $start = microtime_ms(); $memcache = new Memcache(); if (!$memcache->connect($host, $port)) { $memcache = null; } if (!$memcache) { log_fatal("Connection to memcache {$host}:{$port} failed"); } $end = microtime_ms(); $time = $end - $start; log_notice("cache", "connect to memcache {$host}:{$port} ({$time}ms)"); $GLOBALS['remote_cache_conns']['memcache'] = $memcache; $GLOBALS['timings']['memcache_conns_count']++; $GLOBALS['timings']['memcache_conns_time'] += $time; } return $GLOBALS['remote_cache_conns']['memcache']; }
/** * Framework global exception handler * * @param Exception $e */ public static function onUnhandledException($e) { _catch($e); log_fatal("system,error", "charcoal_global_exception_handler:" . $e->getMessage()); Charcoal_Framework::handleException($e); }
/** * Instanciates the previously chosen controller * * Checks what is requested: and object from the object-store, a controller via classname and loads/instaciates it. * Will also die in AJAX requests when something weird is called or throw an exception if in normal mode. * @param mixed $controller_id Whatever system_parse_request_path() returned * @return ICallable Fresh Instance of whatever is needed */ function system_instanciate_controller($controller_id) { if (in_object_storage($controller_id)) { $res = restore_object($controller_id); } elseif (class_exists($controller_id)) { $res = new $controller_id(); } else { WdfException::Raise("ACCESS DENIED: Unknown controller '{$controller_id}'"); } if (system_is_ajax_call()) { if (!$res instanceof Renderable && !$res instanceof WdfResource) { log_fatal("ACCESS DENIED: {$controller_id} is no Renderable"); die("__SESSION_TIMEOUT__"); } } else { if (!$res instanceof ICallable) { WdfException::Raise("ACCESS DENIED: {$controller_id} is no ICallable"); } } return $res; }
/** * Entry point for SimpleID. * * @see user_init() */ function simpleid_start() { global $xtpl, $GETPOST; $xtpl = new XTemplate('html/template.xtpl'); $xtpl->assign('version', SIMPLEID_VERSION); $xtpl->assign('base_path', get_base_path()); // Check if the configuration file has been defined if (!defined('SIMPLEID_BASE_URL')) { log_fatal('No configuration file found.'); indirect_fatal_error('No configuration file found. See the <a href="http://simpleid.koinic.net/documentation/getting-started">manual</a> for instructions on how to set up a configuration file.'); } if (!is_dir(SIMPLEID_IDENTITIES_DIR)) { log_fatal('Identities directory not found.'); indirect_fatal_error('Identities directory not found. See the <a href="http://simpleid.koinic.net/documentation/getting-started">manual</a> for instructions on how to set up SimpleID.'); } if (!is_dir(SIMPLEID_CACHE_DIR) || !is_writeable(SIMPLEID_CACHE_DIR)) { log_fatal('Cache directory not found or not writeable.'); indirect_fatal_error('Cache directory not found or not writeable. See the <a href="http://simpleid.koinic.net/documentation/getting-started">manual</a> for instructions on how to set up SimpleID.'); } if (!is_dir(SIMPLEID_STORE_DIR) || !is_writeable(SIMPLEID_STORE_DIR)) { log_fatal('Store directory not found or not writeable.'); indirect_fatal_error('Store directory not found or not writeable. See the <a href="http://simpleid.koinic.net/documentation/getting-started">manual</a> for instructions on how to set up SimpleID.'); } if (@ini_get('register_globals') === 1 || @ini_get('register_globals') === '1' || strtolower(@ini_get('register_globals')) == 'on') { log_fatal('register_globals is enabled in PHP configuration.'); indirect_fatal_error('register_globals is enabled in PHP configuration, which is not supported by SimpleID. See the <a href="http://simpleid.koinic.net/documentation/getting-started/system-requirements">manual</a> for further information.'); } if (!bignum_loaded()) { log_fatal('gmp/bcmath PHP extension not loaded.'); indirect_fatal_error('One or more required PHP extensions (gmp/bcmath) is not loaded. See the <a href="http://simpleid.koinic.net/documentation/getting-started/system-requirements">manual</a> for further information on system requirements.'); } if (!function_exists('preg_match')) { log_fatal('pcre PHP extension not loaded.'); indirect_fatal_error('One or more required PHP extensions (pcre) is not loaded. See the <a href="http://simpleid.koinic.net/documentation/getting-started/system-requirements">manual</a> for further information on system requirements.'); } if (!function_exists('session_start')) { log_fatal('session PHP extension not loaded.'); indirect_fatal_error('One or more required PHP extensions (session) is not loaded. See the <a href="http://simpleid.koinic.net/documentation/getting-started/system-requirements">manual</a> for further information on system requirements.'); } if (@ini_get('suhosin.get.max_value_length') !== false && @ini_get('suhosin.get.max_value_length') < 1024) { log_fatal('suhosin.get.max_value_length < 1024'); indirect_fatal_error('suhosin.get.max_value_length is less than 1024, which will lead to problems. See the <a href="http://simpleid.koinic.net/documentation/getting-started/system-requirements">manual</a> for further information on system requirements.'); } openid_fix_request(); $GETPOST = array_merge($_GET, $_POST); $q = isset($GETPOST['q']) ? $GETPOST['q'] : ''; extension_init(); user_init($q); log_info('Session opened for "' . $q . '" [' . $_SERVER['REMOTE_ADDR'] . ', ' . gethostbyaddr($_SERVER['REMOTE_ADDR']) . ']'); // Clean stale assocations cache_gc(SIMPLEID_ASSOC_EXPIRES_IN, 'association'); cache_gc(300, 'stateless'); simpleid_route($q); }
<?php include_once 'twitterclass1.php'; include_once 'askhost.php'; error_reporting(E_ALL); ini_set('display_errors', 1); $pg_host = "dbname=twitter user=capsidea password=31337 connect_timeout=30"; $dbconn = pg_connect($pg_host) or log_fatal('Could not connect to application database, please contact support.'); $tmp_dir = "/tmp/"; date_default_timezone_set("UTC"); $schemajson = "&fields=" . urlencode('[{Name: "ts", TypeName:"timestamp" },{Name: "location", TypeName:"string"} ,{Name: "userid", TypeName:"string"},{Name: "rtc", TypeName:"double" },{Name: "placecntry", TypeName:"string"},{Name: "placename", TypeName:"string"}]'); $capsidea_client_secret = "put-your-data-here"; $capsidea_permanent_access_token = "put-your-data-here"; $capsidea_appid = 3097; function get_capsidea_data($capsidea_client_secret) { $ret = array(); $parsed_url = parse_url($_SERVER['HTTP_REFERER']); $var = explode('&', $parsed_url['query']); foreach ($var as $val) { $x = explode('=', $val); $arr[$x[0]] = $x[1]; } unset($val, $x, $var, $qry, $parsed_url, $ref); if (isset($arr["token"])) { $token = $arr["token"]; } else { die("cant find capsidea.com token"); } if (36 != strlen($token)) {
/** * LZH 形式の圧縮ファイルを解凍する。 * LZH には、予めファイル名のわかっているファイルが1コだけ含まれる前提とする。 * 解凍したファイルのファイル名に大文字が含まれる場合は、小文字に変換する。 */ function extract_lzh($lzh, $csv) { $cmd = LHA_COMMAND . PATH_TMP . "/" . $lzh; $return_var = 0; $output = array(); exec($cmd); if ($return_var != 0) { log_fatal("Failed to extract lzh: {$cmd}"); log_fatal($output); exit(1); } $is_csv = false; foreach (glob(PATH_TMP . "/*.{c,C}{s,S}{v,V}", GLOB_BRACE) as $file) { $file = basename($file); if (strtolower($file) != $csv) { continue; } $is_csv = true; log_info("Extracted: {$csv}"); if ($file == $csv) { continue; } move_file(PATH_TMP . "/" . $file, PATH_TMP . "/" . $csv); } if ($is_csv) { return true; } log_info("Faild to extract: {$csv}"); return false; }
/** * Get a database connection. * * @param string $name The datasource alias. * @return DataSource The database connection */ function &model_datasource($name) { global $MODEL_DATABASES; if (strpos($name, "DataSource::") !== false) { $name = explode("::", $name); $name = $name[1]; } if (!isset($MODEL_DATABASES[$name])) { if (function_exists('model_on_unknown_datasource')) { $res = model_on_unknown_datasource($name); return $res; } log_fatal("Unknown datasource '{$name}'!"); $res = null; return $res; } if (is_array($MODEL_DATABASES[$name])) { list($dstype, $constr) = $MODEL_DATABASES[$name]; $dstype = fq_class_name($dstype); $model_db = new $dstype($name, $constr); if (!$model_db) { WdfDbException::Raise("Unable to connect to database '{$name}'."); } $MODEL_DATABASES[$name] = $model_db; } return $MODEL_DATABASES[$name]; }
/** * Entry point for SimpleID upgrade script. * * @see user_init() */ function upgrade_start() { global $xtpl, $GETPOST; $xtpl = new XTemplate('html/template.xtpl'); $xtpl->assign('version', SIMPLEID_VERSION); $xtpl->assign('base_path', get_base_path()); $xtpl->assign('css', '@import url(' . get_base_path() . 'html/upgrade.css);'); // Check if the configuration file has been defined if (!defined('SIMPLEID_BASE_URL')) { indirect_fatal_error('No configuration file found. See the <a href="http://simpleid.koinic.net/documentation/getting-started">manual</a> for instructions on how to set up a configuration file.'); } if (!is_dir(SIMPLEID_IDENTITIES_DIR)) { indirect_fatal_error('Identities directory not found. See the <a href="http://simpleid.koinic.net/documentation/getting-started">manual</a> for instructions on how to set up SimpleID.'); } if (!is_dir(SIMPLEID_CACHE_DIR) || !is_writeable(SIMPLEID_CACHE_DIR)) { indirect_fatal_error('Cache directory not found or not writeable. See the <a href="http://simpleid.koinic.net/documentation/getting-started">manual</a> for instructions on how to set up SimpleID.'); } if (!is_dir(SIMPLEID_STORE_DIR) || !is_writeable(SIMPLEID_STORE_DIR)) { indirect_fatal_error('Store directory not found or not writeable. See the <a href="http://simpleid.koinic.net/documentation/getting-started">manual</a> for instructions on how to set up SimpleID.'); } if (@ini_get('register_globals') === 1 || @ini_get('register_globals') === '1' || strtolower(@ini_get('register_globals')) == 'on') { indirect_fatal_error('register_globals is enabled in PHP configuration, which is not supported by SimpleID. See the <a href="http://simpleid.koinic.net/documentation/getting-started/system-requirements">manual</a> for further information.'); } if (!bignum_loaded()) { log_fatal('gmp/bcmath PHP extension not loaded.'); indirect_fatal_error('One or more required PHP extensions (gmp/bcmath) is not loaded. See the <a href="http://simpleid.koinic.net/documentation/getting-started/system-requirements">manual</a> for further information on system requirements.'); } if (!function_exists('preg_match')) { log_fatal('pcre PHP extension not loaded.'); indirect_fatal_error('One or more required PHP extensions (pcre) is not loaded. See the <a href="http://simpleid.koinic.net/documentation/getting-started/system-requirements">manual</a> for further information on system requirements.'); } if (!function_exists('session_start')) { log_fatal('session PHP extension not loaded.'); indirect_fatal_error('One or more required PHP extensions (session) is not loaded. See the <a href="http://simpleid.koinic.net/documentation/getting-started/system-requirements">manual</a> for further information on system requirements.'); } if (@ini_get('suhosin.get.max_value_length') !== false && @ini_get('suhosin.get.max_value_length') < 1024) { log_fatal('suhosin.get.max_value_length < 1024'); indirect_fatal_error('suhosin.get.max_value_length is less than 1024, which will lead to problems. See the <a href="http://simpleid.koinic.net/documentation/getting-started/system-requirements">manual</a> for further information on system requirements.'); } $q = isset($GETPOST['q']) ? $GETPOST['q'] : ''; $q = explode('/', $q); extension_init(); user_init(NULL); upgrade_user_init(); $routes = array('upgrade-selection' => 'upgrade_selection', 'upgrade-apply' => 'upgrade_apply', '.*' => 'upgrade_info'); simpleweb_run($routes, implode('/', $q)); }
if (false === $res) { $qr = pg_errormessage($dbconn); $line = implode(",", $this_item); file_put_contents("{$my_data_dir}/loader.log", date(DATE_ATOM) . " (line: {$line}) client {$key} ERR {$qr} in query: {$qry} file: {$nfname}\n", FILE_APPEND); log_fatal("ERR error in " . implode(",", array_keys($this_item)) . "values" . implode(",", $this_item)); } if (false === stripos($this_item["case_type"], "NULL")) { // @todo probably bug there file_put_contents("{$my_data_dir}/paypal-m.log", serialize($this_item, true) . " \n", FILE_APPEND); $qry = "insert into cases (cid, creason, cstatus, cmm, camount, mid, ifile ,ikey, filldate, ctype , clag) \n\t\t\tvalues ('" . pg_escape_string($this_item["mid"]) . "','" . pg_escape_string($this_item["creason"]) . "','" . pg_escape_string($this_item["cstatus"]) . "',\n\t\t\t\t\t'" . pg_escape_string($this_item["moneymove"]) . "'," . pg_escape_string($this_item["camount"]) . "," . pg_escape_string($this_item["mid"]) . ",\n\t0, {$key}, '{$case_filldate}', '" . pg_escape_string($this_item["case_type"]) . "',{$case_lag})"; $res = @pg_query($qry); if (false === $res) { $qr = pg_errormessage($dbconn); $line = implode(",", $this_item); file_put_contents("{$my_data_dir}/loader.log", date(DATE_ATOM) . " (line: {$line}) client {$key} ERR {$qr} in query: {$qry} file: {$nfname}\n", FILE_APPEND); log_fatal("ERR error in " . implode(",", array_keys($this_item)) . "values" . implode(",", $this_item)); } } // case? if ($i > 10000) { // @pg_query("commit;"); echo "."; ob_flush(); flush(); ob_flush(); flush(); //@pg_query("begin;"); $lines_processed = $lines_processed + $i; $i = 0; } }
function _db_connect($cluster, $k=null){ $cluster_key = $k ? "{$cluster}-{$k}" : $cluster; $host = $GLOBALS['cfg']["db_{$cluster}"]["host"]; $user = $GLOBALS['cfg']["db_{$cluster}"]["user"]; $pass = $GLOBALS['cfg']["db_{$cluster}"]["pass"]; $name = $GLOBALS['cfg']["db_{$cluster}"]["name"]; if ($k){ $host = $host[$k]; $name = $name[$k]; } if (is_array($host)){ shuffle($host); $host = $host[0]; } if (!$host){ log_fatal("no such cluster: ".$cluster); } # # try to connect # $start = microtime_ms(); $GLOBALS['db_conns'][$cluster_key] = @mysql_connect($host, $user, $pass, 1); if ($GLOBALS['db_conns'][$cluster_key]){ @mysql_select_db($name, $GLOBALS['db_conns'][$cluster_key]); @mysql_query("SET character_set_results='utf8', character_set_client='utf8', character_set_connection='utf8', character_set_database='utf8', character_set_server='utf8'", $GLOBALS['db_conns'][$cluster_key]); } $end = microtime_ms(); # # log # log_notice('db', "DB-$cluster_key: Connect", $end-$start); if (!$GLOBALS['db_conns'][$cluster_key] || (auth_has_role('staff') && $GLOBALS['cfg']['admin_flags_no_db'])){ log_fatal("Connection to database cluster '$cluster_key' failed"); } $GLOBALS['timings']['db_conns_count']++; $GLOBALS['timings']['db_conns_time'] += $end-$start; # # profiling? # if ($GLOBALS['cfg']['db_profiling']){ @mysql_query("SET profiling = 1;", $GLOBALS['db_conns'][$cluster_key]); } }
/** * ファイルを移動する。 * 移動元がファイルで、移動先がディレクトリの場合は、そのディレクトリの下にファイルを移動する。 */ function move_file($src, $trg) { if (!is_file($src) && !is_dir($src)) { log_fatal("Faild to rename: {$src} => {$trg} -- missing {$src}"); exit(1); } if (is_file($src) && is_dir($trg)) { $base_name = basename($src); $trg .= "/{$base_name}"; } if (is_dir($trg)) { rmdirs(array($trg)); } elseif (is_file($trg)) { unlink_files(array($trg)); } if (!rename($src, $trg)) { log_fatal("Faild to rename: {$src} => {$trg}"); exit(1); } }
$dbconn = pg_connect($pg_host) or die('Could not connect: ' . pg_last_error()); $key = (int) $_GET["key"]; //$_FILES["file"]["tmp_name"] if (!check_credentials($_GET["key"], $_GET["hash"], $dbconn)) { log_fatal("ERR hash incorrect for key={$key}, your hash: " . $_GET["hash"]); } //if ((123!=$key)||(123!=$_GET["hash"])) die("ERR hash incorrect for key=$key, your hash: ".$_GET["hash"]); if (isset($_GET["truncate"])) { // truncate all @pg_query("delete from merchant where ikey={$key};"); @pg_query("commit;"); log_fatal("all customer merchant records deleted"); } if (strtolower($_SERVER['REQUEST_METHOD']) != 'post' || empty($_FILES)) { // file_put_contents($my_data_dir."/paypal-m.log", date(DATE_ATOM)."merchant $key no file attached\n", FILE_APPEND); log_fatal("ERR no file attached"); } // это тут, чтобы работал truncate //$startdate=date("Y-m-d H:00:00O",strtotime($_GET["startdate"])); //$enddate=date("Y-m-d H:00:00O",strtotime($_GET["enddate"])); $d = ""; foreach ($_FILES as $this_item) { $fname = $this_item["tmp_name"]; $rname = $this_item["name"]; $fsize = $this_item["size"]; if ($fsize > 20000000) { // too big file file_put_contents($my_data_dir . "/paypal-m.log", date(DATE_ATOM) . "merchant too big file {$key} {$rname} {$fsize}\n", FILE_APPEND); die("ERR too large file, please use bz2 to compress it"); } break;
} else { log_fatal("no reports"); } } // of update dataset if (FALSE === strpos($_GET["type"], "deleteSchema")) { mylog("callback ERR. no method"); die("ERR unknown method"); } // @todo check $capsidea_client_secret $ikey = (int) $_GET["obj_key"]; if (0 == $ikey) { mylog("delete ERR. ikey=0 "); log_fatal("ERR user not found"); } $dbconn = pg_connect($pg_host) or log_fatal('Could not connect to DB'); // . pg_last_error()) // remove if linked $result = @pg_query("select * from client where ikey={$ikey} and iparent>0"); if (@pg_num_rows($result) > 0) { // remove child $row = pg_fetch_assoc($result); $parent = (int) $row['iparent']; @pg_free_result($result); @pg_query("delete from client where ikey={$ikey}"); mylog("child removed: {$ikey} parent {$parent}"); //@pg_query("update client set active=1 where ikey=$ikey"); // is this parent disabled and dont have childs? $ikey = $parent; $result = @pg_query("select * from client where ikey={$ikey} and active=0"); if (0 == @pg_num_rows($result)) {
<? # # $Id$ # include('include/init.php'); # # this is so we can test the logging output # if ($_GET['log_test']){ log_error("This is an error!"); log_fatal("Fatal error!"); } # # this is so we can test the HTTP library # if ($_GET['http_test']){ $ret = http_get("http://google.com"); } # # output #
function _db_connect($cluster, $k = null) { $cluster_key = $k ? "{$cluster}-{$k}" : $cluster; $host = $GLOBALS['cfg']["db_{$cluster}"]["host"]; $user = $GLOBALS['cfg']["db_{$cluster}"]["user"]; $pass = $GLOBALS['cfg']["db_{$cluster}"]["pass"]; $name = $GLOBALS['cfg']["db_{$cluster}"]["name"]; if ($k) { $host = $host[$k]; $name = $name[$k]; } if (!$host) { log_fatal("no such cluster: " . $cluster); } # # try to connect # $start = microtime_ms(); $GLOBALS['db_conns'][$cluster_key] = @mysql_connect($host, $user, $pass, 1); if ($GLOBALS['db_conns'][$cluster_key]) { @mysql_select_db($name, $GLOBALS['db_conns'][$cluster_key]); } $end = microtime_ms(); # # log # log_notice('db', "DB-{$cluster_key}: Connect", $end - $start); if (!$GLOBALS['db_conns'][$cluster_key] || $GLOBALS['cfg']['admin_flags_no_db']) { log_fatal("Connection to database cluster '{$cluster_key}' failed"); } $GLOBALS['timings']['db_conns_count']++; $GLOBALS['timings']['db_conns_time'] += $end - $start; # # profiling? # if ($GLOBALS['cfg']['db_profiling']) { @mysql_query("SET profiling = 1;", $GLOBALS['db_conns'][$cluster_key]); } }
function convert_to_usd(&$curr, $txn_cur, $amount) { if (!isset($curr[$txn_cur])) { $result = askhost("http://rate-exchange.appspot.com/currency?from={$txn_cur}&to=USD"); $jsonres = json_decode($result, true); if (!isset($jsonres['rate'])) { log_fatal("unknown currency {$txn_cur}"); } $curr[$txn_cur] = $jsonres['rate']; } // lookup new currency return floor($curr[$txn_cur] * $amount); }
//$client_dir=$tmp_dir; //$report_fname=$client_dir."report.zip"; $secret = sha1($capsidea_client_secret . $capsidea_permanent_access_token); $host_reply = askhost($server_url . "&schemakey=" . $key . $schemajson, array('file_contents' => '@' . $report_fname), "", "", "", 1800000, array("appid: {$capsidea_appid}", "sig: {$secret}"), true); // defined in askhost.php //echo " time ".$time3=((get_timer()-$stime)/1)." sec "; // $stime=get_timer(); $result = $host_reply["data"]; $error_log = "cube: {$key}" . "secret: " . $secret . "<br>response:<pre>" . $host_reply["data"] . "</pre>" . "<br>connection debug:<pre>" . $host_reply["d"] . "</pre>"; if (500 == $host_reply["httpcode"]) { echo "ERR: {$error_log}\n" . $host_reply["httpcode"]; log_fatal("error 500 from cps: \n {$error_log}"); } // if 500 if (401 == $host_reply["httpcode"]) { echo "ERR: unauthorized {$error_log}\n" . $host_reply["httpcode"]; log_fatal("error 401 from cps \n {$error_log}"); } // if 500 if (200 == $host_reply["httpcode"]) { echo "unlinking " . $report_fname . "\n"; unlink($report_fname); echo "OK (http == 200)\n"; } else { echo "UNK: {$error_log}\n" . $host_reply["httpcode"]; } file_put_contents($logfile, date(DATE_ATOM) . " client-updated {$key} \n", FILE_APPEND); die; } // of update dataset if (FALSE === strpos($_GET["type"], "deleteSchema")) { file_put_contents($logfile, date(DATE_ATOM) . "callback ERR. no method \n", FILE_APPEND);
function _db_connect($cluster, $shard) { $cluster_key = _db_cluster_key($cluster, $shard); $host = $GLOBALS['cfg']["db_{$cluster}"]["host"]; $user = $GLOBALS['cfg']["db_{$cluster}"]["user"]; $pass = $GLOBALS['cfg']["db_{$cluster}"]["pass"]; $name = $GLOBALS['cfg']["db_{$cluster}"]["name"]; if ($shard) { $host = $host[$shard]; $name = $name[$shard]; } if (!$host) { log_fatal("no such cluster: " . $cluster); } # # try to connect # $start = microtime_ms(); $GLOBALS['db_conns'][$cluster_key] = @mysql_connect($host, $user, $pass, 1); if ($GLOBALS['db_conns'][$cluster_key]) { @mysql_select_db($name, $GLOBALS['db_conns'][$cluster_key]); @mysql_query("SET character_set_results='utf8', character_set_client='utf8', character_set_connection='utf8', character_set_database='utf8', character_set_server='utf8'", $GLOBALS['db_conns'][$cluster_key]); } $end = microtime_ms(); # # log # log_notice('db', "DB-{$cluster_key}: Connect", $end - $start); if (!$GLOBALS['db_conns'][$cluster_key] || $GLOBALS['cfg']['admin_flags_no_db']) { log_fatal("Connection to database cluster '{$cluster_key}' failed"); } $GLOBALS['timings']['db_conns_count']++; $GLOBALS['timings']['db_conns_time'] += $end - $start; # # profiling? # if ($GLOBALS['cfg']['db_profiling']) { @mysql_query("SET profiling = 1;", $GLOBALS['db_conns'][$cluster_key]); } }
/** * execute framework main process * * @param Charcoal_Sandbox $sandbox */ private static function _run($sandbox) { // Charcoal_ParamTrait::validateSandbox( 1, $sandbox ); //================================================================== // create exception handler list self::$exception_handlers = new Charcoal_ExceptionHandlerList($sandbox); //================================================================== // create debugtrace renderder list self::$debugtrace_renderers = new Charcoal_DebugTraceRendererList($sandbox); //================================================================== // create logger list self::$loggers = new Charcoal_LoggerList($sandbox); //================================================================== // create core hook list self::$corehooks = new Charcoal_CoreHookList($sandbox); //================================================================== // create cache driver list self::$cache_drivers = new Charcoal_CacheDriverList($sandbox); //================================================================== // load sandbox $profile = NULL; try { $profile = $sandbox->load(); } catch (Exception $ex) { _catch($ex); _throw($ex); } //======================================= // Start bootstrap self::setHookStage(Charcoal_EnumCoreHookStage::START_OF_BOOTSTRAP); //======================================= // フレームワーク初期化処理 // self::setHookStage(Charcoal_EnumCoreHookStage::BEFORE_INIT_FRAMEWORK); // タイムアウトを指定 if (!ini_get('safe_mode')) { $timeout = $profile->getInteger('SCRIPT_TIMEOUT', ini_get("max_execution_time")); set_time_limit(ui($timeout)); } self::setHookStage(Charcoal_EnumCoreHookStage::AFTER_INIT_FRAMEWORK); //======================================= // クラスローダの登録 // self::setHookStage(Charcoal_EnumCoreHookStage::BEFORE_REG_CLASS_LOADERS); $framework_class_loader = $sandbox->createClassLoader('framework'); self::setHookStage(Charcoal_EnumCoreHookStage::CREATE_FRAMEWORK_CLASS_LOADER, $framework_class_loader); Charcoal_ClassLoader::addClassLoader($framework_class_loader); self::setHookStage(Charcoal_EnumCoreHookStage::REG_FRAMEWORK_CLASS_LOADER, $framework_class_loader); try { $class_loaders = $profile->getArray('CLASS_LOADERS'); if ($class_loaders) { foreach ($class_loaders as $loader_name) { if (strlen($loader_name) === 0) { continue; } $loader = $sandbox->createClassLoader($loader_name); self::setHookStage(Charcoal_EnumCoreHookStage::CREATE_CLASS_LOADER, $loader_name); Charcoal_ClassLoader::addClassLoader($loader); self::setHookStage(Charcoal_EnumCoreHookStage::REG_CLASS_LOADER, $loader_name); } } } catch (Charcoal_CreateClassLoaderException $ex) { _catch($ex); _throw(new Charcoal_FrameworkBootstrapException('failed to load class loader:' . $ex->getClassLoaderPath(), $ex)); } // register framework class loader if (!spl_autoload_register('Charcoal_ClassLoader::loadClass', false)) { log_fatal("debug,system,error", 'framework', "registering master class loader failed."); _throw(new Charcoal_ClassLoaderRegistrationException('framework')); } self::setHookStage(Charcoal_EnumCoreHookStage::AFTER_REG_CLASS_LOADERS); //======================================= // Requestパラメータの取得 // /** @var Charcoal_IRequest $request */ $request = $sandbox->createObject(CHARCOAL_RUNMODE, 'request', array(), 'Charcoal_IRequest'); self::$request = $request; // log_debug( "debug,system","request object created: " . print_r($request,true), 'framework' ); self::$proc_path = us($request->getProcedurePath()); // log_debug( "debug,system","proc_path=" . $proc_path, 'framework' ); // if procedure path is not specified in url, forward the procedure to DEFAULT_PROCPATH in profile.ini if (strlen(self::$proc_path) === 0) { self::$proc_path = us($profile->getString('DEFAULT_PROCPATH')); } $sandbox->getEnvironment()->set('%REQUEST_PATH%', self::$proc_path); self::$loggers->init(); //======================================= // 外部ライブラリの使用 // self::setHookStage(Charcoal_EnumCoreHookStage::BEFORE_REG_EXTLIB_DIR); $use_extlib = b($profile->getBoolean('USE_EXTLIB', FALSE)); if ($use_extlib->isTrue()) { $lib_dirs = $profile->getArray('EXTLIB_DIR', array(), TRUE); if ($lib_dirs) { foreach ($lib_dirs as $dir) { if (strlen($dir) === 0) { continue; } if (!file_exists($dir)) { _throw(new Charcoal_ProfileConfigException('EXTLIB_DIR', "directory [{$dir}] does not exists")); } if (!is_dir($dir)) { _throw(new Charcoal_ProfileConfigException('EXTLIB_DIR', "[{$dir}] is not directory")); } ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . $dir); self::setHookStage(Charcoal_EnumCoreHookStage::ADD_EXTLIB_DIR, $dir); } } } self::setHookStage(Charcoal_EnumCoreHookStage::AFTER_REG_EXTLIB_DIR); //======================================= // セッションハンドラの作成 // $use_session = b($profile->getBoolean('USE_SESSION', FALSE)); if ($use_session->isTrue()) { self::setHookStage(Charcoal_EnumCoreHookStage::BEFORE_SET_SESSION_HANDLER); // セッションハンドラ名の取得 $session_handler_name = s($profile->getString('SESSION_HANDLER_NAME')); if ($session_handler_name && !$session_handler_name->isEmpty()) { // セッションハンドラの作成 $session_handler = $sandbox->createObject($session_handler_name, 'session_handler', array(), 'Charcoal_ISessionHandler'); session_set_save_handler(array($session_handler, 'open'), array($session_handler, 'close'), array($session_handler, 'read'), array($session_handler, 'write'), array($session_handler, 'destroy'), array($session_handler, 'gc')); } self::setHookStage(Charcoal_EnumCoreHookStage::AFTER_SET_SESSION_HANDLER); } //======================================= // Create Session // $session = NULL; if ($use_session->isTrue()) { // create session $session = new Charcoal_Session(); self::setHookStage(Charcoal_EnumCoreHookStage::BEFORE_START_SESSION); // start session $session->start(); // log_info( "system",'Session started', 'framework' ); // restore session $session->restore(); // log_info( "system",'Session is restored.', 'framework' ); self::setHookStage(Charcoal_EnumCoreHookStage::AFTER_START_SESSION); } //======================================= // Routing Rule // self::setHookStage(Charcoal_EnumCoreHookStage::BEFORE_ROUTING_RULE); // get routers list from profile $routing_rule_name = $profile->getString('ROUTING_RULE'); $routing_rule_name = us($routing_rule_name); // register routers $routing_rule = NULL; if (!empty($routing_rule_name)) { /** @var Charcoal_IRoutingRule $routing_rule */ $routing_rule = $sandbox->createObject($routing_rule_name, 'routing_rule', array(), 'Charcoal_IRoutingRule'); } self::setHookStage(Charcoal_EnumCoreHookStage::AFTER_ROUTING_RULE); //======================================= // Router // if ($routing_rule) { self::setHookStage(Charcoal_EnumCoreHookStage::BEFORE_ROUTER); // get routers list from profile $router_names = $profile->getArray('ROUTERS'); // register routers if ($router_names) { foreach ($router_names as $router_name) { if (strlen($router_name) === 0) { continue; } /** @var Charcoal_IRouter $router */ $router = $sandbox->createObject($router_name, 'router', array(), 'Charcoal_IRouter'); $res = $router->route($request, $routing_rule); if (is_array($res)) { self::$proc_path = $request->getProcedurePath(); $sandbox->getEnvironment()->set('%REQUEST_PATH%', self::$proc_path); log_debug("debug,system", "routed: proc_path=[" . self::$proc_path . "]", 'framework'); break; } } } self::setHookStage(Charcoal_EnumCoreHookStage::AFTER_ROUTER); } //======================================= // Procedureの作成 // // プロシージャを作成 self::setHookStage(Charcoal_EnumCoreHookStage::BEFORE_CREATE_PROCEDURE, self::$proc_path); $procedure = NULL; try { /** @var Charcoal_IProcedure $procedure */ $procedure = $sandbox->createObject(self::$proc_path, 'procedure', array(), 'Charcoal_IProcedure'); } catch (Exception $e) { _catch($e); _throw(new Charcoal_ProcedureNotFoundException(self::$proc_path, $e)); } self::setHookStage(Charcoal_EnumCoreHookStage::AFTER_CREATE_PROCEDURE, self::$proc_path); // procedure forwarding self::setHookStage(Charcoal_EnumCoreHookStage::BEFORE_PROCEDURE_FORWARD); if ($procedure->hasForwardTarget()) { // get forward target path $object_path = $procedure->getForwardTarget(); // log_debug( "debug,system","procedure forward target:" . $object_path, 'framework' ); self::setHookStage(Charcoal_EnumCoreHookStage::PRE_PROCEDURE_FORWARD, $object_path); // create target procedure $procedure = $sandbox->createObject($object_path, 'procedure', 'Charcoal_IProcedure'); // log_debug( "debug,system","forward procedure created:" . $procedure, 'framework' ); self::setHookStage(Charcoal_EnumCoreHookStage::POST_PROCEDURE_FORWARD, $object_path); } self::setHookStage(Charcoal_EnumCoreHookStage::AFTER_PROCEDURE_FORWARD); // override logger settings by the procedure's settings self::$loggers->overrideByProcedure($procedure); //======================================= // create response object // $response = $sandbox->createObject(CHARCOAL_RUNMODE, 'response', array(), 'Charcoal_IResponse'); //======================================= // ブートストラップ完了 // self::setHookStage(Charcoal_EnumCoreHookStage::END_OF_BOOTSTRAP); //======================================= // Procedureの実行 // self::setHookStage(Charcoal_EnumCoreHookStage::BEFORE_EXECUTE_PROCEDURES); // プロシージャの実行 while ($procedure) { $path = $procedure->getObjectPath()->getVirtualPath(); self::setHookStage(Charcoal_EnumCoreHookStage::PRE_EXECUTE_PROCEDURE, $path); $procedure->execute($request, $response, $session); self::setHookStage(Charcoal_EnumCoreHookStage::POST_EXECUTE_PROCEDURE, $path); // プロシージャをスタックから取得 $procedure = self::popProcedure(); } self::setHookStage(Charcoal_EnumCoreHookStage::AFTER_EXECUTE_PROCEDURES); //======================================= // 終了処理 // self::setHookStage(Charcoal_EnumCoreHookStage::START_OF_SHUTDOWN); self::setHookStage(Charcoal_EnumCoreHookStage::BEFORE_SAVE_SESSION); // セッション情報の保存 if ($use_session->isTrue() && $session) { // セッションを保存 $session->save(); $session->close(); } self::setHookStage(Charcoal_EnumCoreHookStage::AFTER_SAVE_SESSION); //======================================= // コンテナの破棄 // self::setHookStage(Charcoal_EnumCoreHookStage::BEFORE_DESTROY_CONTAINER); $sandbox->getContainer()->terminate(); self::setHookStage(Charcoal_EnumCoreHookStage::AFTER_DESTROY_CONTAINER); self::setHookStage(Charcoal_EnumCoreHookStage::END_OF_SHUTDOWN); }