Exemplo n.º 1
0
 public static function lookup($hostname)
 {
     self::init();
     Profiler::StartTimer("DNSResolver::lookup()", 2);
     $data = DataManager::singleton();
     $records = $apc = NULL;
     $cachekey = "dnsresolver.lookup.{$hostname}";
     if (self::$cache && !empty($data->caches["apc"]) && $data->caches["apc"]["default"]->enabled) {
         $apc = $data->caches["apc"]["default"];
         $cached = $apc->get($cachekey);
         if ($cached !== false) {
             $records = unserialize($cached);
             Logger::Info("DNSResolver: found '{$hostname}' in APC cache");
         }
     }
     if ($records === NULL) {
         Logger::Info("DNSResolver: Looking up '{$hostname}'");
         foreach (self::$search as $suffix) {
             $fqdn = $hostname . (!empty($suffix) ? "." . $suffix : "");
             $records = dns_get_record($fqdn, DNS_A);
             if (!empty($records)) {
                 break;
             }
         }
         if (self::$cache && !empty($records) && $apc !== NULL && $apc->enabled) {
             $ttl = any(self::$ttl, $records[0]["ttl"]);
             $apc->set($cachekey, serialize($records), array("lifetime" => $ttl));
         }
     }
     Profiler::StopTimer("DNSResolver::lookup()");
     return $records;
 }
 function controller_pause($args, $output = "inline")
 {
     Profiler::StartTimer("audio.playback.pause");
     Profiler::StartTimer("audio.playback.pause - get status");
     $playback = $this->parent->getMPDPlayback();
     $status = $playback->getStatus();
     Profiler::StopTimer("audio.playback.pause - get status");
     Profiler::StartTimer("audio.playback - init");
     if ($status['state'] == 'play' || $status['state'] == 'pause') {
         $playback->pause();
     } else {
         $playback->play();
     }
     Profiler::StopTimer("audio.playback.pause");
 }
Exemplo n.º 3
0
/**
 * Smarty {img} plugin
 *
 * Type:     function<br>
 * Name:     img<br>
 * Purpose:  Get the correct image (cobranded, server, etc)
 *
 * @author Ben HOLLAND!!!
 * @param array
 * @param Smarty
 * @return string|null if the assign parameter is passed, Smarty assigns the
 *                     result to a template variable
 */
function smarty_function_img($args, &$smarty)
{
    global $webapp;
    static $heirarchy;
    static $imgcache;
    Profiler::StartTimer("smarty_function_img", 2);
    if ($heirarchy === null) {
        $cfgmgr = ConfigManager::singleton();
        $heirarchy = $cfgmgr->GetConfigHeirarchy("cobrand." . $webapp->cobrand);
    }
    $imagedir = any(DependencyManager::$locations["images"], "htdocs/images");
    $imagedirwww = any(DependencyManager::$locations["imageswww"], "/images");
    if (!empty($args["src"]) && !preg_match("/^https?:/", $args["src"])) {
        if (isset($imgcache[$args["src"]])) {
            $args["src"] = $imgcache[$args["src"]];
        } else {
            $origsrc = $args["src"];
            $found = false;
            foreach ($heirarchy as $cfgname) {
                if (preg_match("/^cobrand\\.(.*)\$/", $cfgname, $m)) {
                    // FIXME - most general-purpose would be to use the cobrand key as imagedir (s/\./\//g?)
                    if (file_exists($imagedir . "/cobrands/{$m[1]}/{$args["src"]}")) {
                        $args["src"] = $imagedirwww . "/cobrands/{$m[1]}/{$args["src"]}";
                        $found = true;
                        break;
                    }
                }
            }
            if (!$found) {
                $args["src"] = $imagedirwww . "/" . $args["src"];
            }
            $imgcache[$origsrc] = $args["src"];
        }
    }
    $ret = "<img ";
    foreach ($args as $k => $v) {
        $ret .= "{$k}=\"{$v}\" ";
    }
    $ret .= "/>";
    Profiler::StopTimer("smarty_function_img");
    if (!empty($args["src"])) {
        return $ret;
    }
}
Exemplo n.º 4
0
 public function Query($queryid, $query, $args = array())
 {
     Profiler::StartTimer("TwitterWrapper::Query()", 1);
     Profiler::StartTimer("TwitterWrapper::Query({$query})", 2);
     $method = $responseType = $authNeeded = $twitterCallback = null;
     if (array_key_exists('method', $args)) {
         $method = $args['method'];
         unset($args['method']);
     }
     if (array_key_exists('responseType', $args)) {
         $responseType = $args['responseType'];
         unset($args['responseType']);
     }
     if (array_key_exists('authNeeded', $args)) {
         $responseType = $args['authNeeded'];
         unset($args['authNeeded']);
     }
     try {
         if ($responseType && $authNeeded && $method) {
             $response = $this->twitter->api($query, $args, $responseType, $authNeeded, $method);
         } else {
             if ($responseType && $authNeeded) {
                 $response = $this->twitter->api($query, $args, $responseType, $authNeeded);
             } else {
                 if ($responseType) {
                     $response = $this->twitter->api($query, $args, $responseType);
                 } else {
                     $response = $this->twitter->api($query, $args);
                 }
             }
         }
     } catch (Exception $e) {
         Logger::Error($e->getMessage());
     }
     Profiler::StopTimer("TwitterWrapper::Query()");
     Profiler::StopTimer("TwitterWrapper::Query({$query})");
     return $response;
 }
Exemplo n.º 5
0
 /**
  * Returns the memcache key value.
  *
  * @param string $key
  * @return mixed
  */
 protected function getData($key)
 {
     $ret = NULL;
     Profiler::StartTimer("MemcacheCache::getData()");
     Profiler::StartTimer("MemcacheCache::getData({$key})", 4);
     if (!empty($this->cache_obj)) {
         $cachedresult = $this->cache_obj->get($key);
         if ($cachedresult) {
             if (is_string($cachedresult)) {
                 $ret = unserialize($cachedresult);
             } else {
                 if (is_array($cachedresult)) {
                     foreach ($cachedresult as $k => $v) {
                         $ret[$k] = unserialize($v);
                     }
                 } else {
                     Logger::Error("Invalid datatype for '%s' in memcache - expected serialized string, found %s", $key, gettype($cachedresult));
                 }
             }
         }
     }
     Profiler::StopTimer("MemcacheCache::getData()");
     Profiler::StopTimer("MemcacheCache::getData({$key})");
     return $ret;
 }
Exemplo n.º 6
0
 /**
  * Load a specific config from the database, without walking the heirarchy
  *
  * @param string $name name of config to load
  * @return array
  */
 public function Load($name, $role)
 {
     Profiler::StartTimer("Config::Load()");
     $data = DataManager::singleton();
     $ret = array();
     $this->name = $name;
     $this->role = $role;
     $ret = $this->GetCobrandidAndRevision();
     if (!empty($ret)) {
         $result_config = DataManager::Query("db.config.cobrand_config.{$name}.{$role}", "SELECT name,value FROM config.cobrand_config WHERE cobrandid=:cobrandid and role=:role ORDER BY name", array(":cobrandid" => $ret["cobrandid"], ":role" => $role));
         if ($result_config && count($result_config->rows) > 0) {
             $settings = array();
             foreach ($result_config->rows as $config_obj) {
                 $settings[$config_obj->name] = $config_obj->value;
             }
             array_set_multi($ret, $settings);
             $this->config = $ret;
         }
     } else {
         Logger::Error("Could not find config '{$name}'");
     }
     Profiler::StopTimer("Config::Load()");
     //print_pre($ret);
     return $ret;
 }
Exemplo n.º 7
0
 static function Quote($id, $str)
 {
     Profiler::StartTimer("DataManager::Quote()");
     $queryid = new DatamanagerQueryID($id);
     if ($source =& DataManager::PickSource($queryid)) {
         $ret = $source->Quote($queryid, $str);
     }
     Profiler::StopTimer("DataManager::Quote()");
     return $ret;
 }
Exemplo n.º 8
0
<?php

if (file_exists("../include/elation.php")) {
    require_once "../include/elation.php";
} else {
    require_once "elation.php";
}
$root = preg_replace("|/htdocs\$|", "", getcwd());
chdir($root);
elation_readpaths($root);
include_once "include/webapp_class.php";
include_once "lib/profiler.php";
Profiler::StartTimer("Total");
$req = array();
if (!empty($_GET)) {
    if (isset($_GET["path"])) {
        unset($_GET["path"]);
    }
    $req = array_merge($req, $_GET);
}
if (!empty($_POST)) {
    $req = array_merge($req, $_POST);
}
$webapp = new WebApp($root, $req);
$webapp->Display();
Profiler::StopTimer("Total");
if (!empty($_REQUEST["_timing"])) {
    print Profiler::Display();
}
Exemplo n.º 9
0
 function Display($path = NULL, $args = NULL)
 {
     $path = any($path, $this->request["path"], "/");
     $args = any($args, $this->request["args"], array());
     if (!empty($this->components)) {
         try {
             $output = $this->components->Dispatch($path, $args, $this->request["type"]);
         } catch (Exception $e) {
             //print_pre($e);
             $output["content"] = $this->HandleException($e);
         }
         $this->session->quit();
         $headers = headers_list();
         $isRedirect = false;
         $ctype = null;
         foreach ($headers as $header) {
             list($k, $v) = explode(": ", $header, 2);
             if ($k == "Location") {
                 $isRedirect = true;
             }
             if ($k == "Content-Type") {
                 $ctype = $v;
             }
         }
         if (!$isRedirect) {
             // Load settings from servers.ini
             $contegargs = isset($this->cfg->servers["conteg"]) ? $this->cfg->servers["conteg"] : array();
             $contegargs["charset"] = "UTF-8";
             // FIXME - shouldn't be hardcoded, but we should also replace Conteg...
             $contegargs["cache_control"]["macro"] = "public";
             $contegargs["use_etags"] = true;
             // And also from site config
             $contegcfg = ConfigManager::get("conteg");
             if (is_array($contegcfg)) {
                 $contegargs = array_merge($contegargs, $contegcfg);
             }
             if (empty($contegargs["type"])) {
                 $contegargs["type"] = any($ctype, $this->request["contenttype"], $output["responsetype"]);
             }
             // Merge type-specific policy settings from config if applicable
             if (isset($contegargs["policy"]) && is_array($contegargs["policy"][$contegargs["type"]])) {
                 $contegargs = array_merge($contegargs, $contegargs["policy"][$contegargs["type"]]);
             }
             if (empty($contegargs["modified"])) {
                 // Set modified time to mtime of base directory if not set
                 $contegargs["modified"] = filemtime($this->rootdir);
             }
             if ($output["type"] == "ajax" || $output["type"] == "jsonp") {
                 print $this->tplmgr->PostProcess($output["content"], true);
             } else {
                 print $this->tplmgr->PostProcess($output["content"]);
                 if (!empty($this->request["args"]["timing"])) {
                     print Profiler::Display();
                 }
             }
             if ($output["http_status"]) {
                 $contegargs["http_status"] = $output["http_status"];
             }
             Profiler::StopTimer("WebApp::TimeToDisplay");
             Profiler::StartTimer("WebApp::Display() - Conteg", 1);
             new Conteg($contegargs);
             Profiler::StopTimer("WebApp::Display() - Conteg");
         }
         if (Profiler::$log) {
             Profiler::Log(DependencyManager::$locations["tmp"], $this->components->pagecfg["pagename"]);
         }
     }
 }
Exemplo n.º 10
0
 /**
  * mysql session write handler.
  * Persist the entire portion of $_SESSION["persist"] to DB.
  * Refresh memcache with $_SESSION.
  *
  * @param string session id
  * @param string data to write
  */
 public function write($id, $data)
 {
     Profiler::StartTimer("SessionManager::write", 1);
     // Save user, and all associated lists, settings, etc.
     Profiler::StartTimer("SessionManager::write - save user");
     $user = User::singleton();
     $user->save();
     Profiler::StopTimer("SessionManager::write - save user");
     $pdata = $_SESSION["persist"];
     strip_nulls($pdata);
     // compare the persist data before and after for changes
     $pdata_serialize = serialize($pdata);
     //Logger::Warn($pdata_serialize);
     //$data = $this->cache_obj->get($id);
     $data = DataManager::fetch("memcache.session#{$id}", $id);
     $pdata_before = $data["persist"];
     $pdata_before_serialize = serialize($pdata_before);
     // update the memcache with the entire $_SESSION
     //$session_serialize = serialize($_SESSION);
     //$this->cache_obj->set($id, $_SESSION, 0);
     $data = DataManager::update("memcache.session#{$id}", $id, $_SESSION);
     if (empty($pdata) || is_null($pdata)) {
         $new_crc = 0;
     } else {
         $new_crc = strlen($pdata_serialize) . crc32($pdata_serialize);
     }
     if ($this->crc != $new_crc) {
         // if the user does not have a record already, create one first
         // NOTE from James - removed  '&& (! $pdata["user"]["userid"]' from below, didn't seem to make sense...
         if ($this->has_db_record == false) {
             $this->create_new_persist_record();
             // need to set the session cache again with we set the has_db_record param
             //$session_serialize = serialize($_SESSION);
             //$this->cache_obj->set($id, $_SESSION, 0, $this->session_cache_expire);
             DataManager::update("memcache.session#{$id}", $id, $_SESSION);
         } else {
             $result = $this->data->QueryUpdate($this->sessionsource . "#{$this->fluid}", $this->sessiontable, array($this->fluid => array("data" => $pdata_serialize)), array("fl_uid" => $this->fluid));
             Logger::Info("Updating userdata.usersession record for {$this->fluid}");
         }
     }
     Profiler::StopTimer("SessionManager::write");
 }
Exemplo n.º 11
0
 /**
  * Returns the memcache key value.
  *
  * @param string $key
  * @return mixed
  */
 protected function getData($key)
 {
     $diskcache = $this->getCachePaths($key);
     $ret = false;
     if (file_exists($diskcache["fullpath"])) {
         if (filemtime($diskcache["fullpath"]) < $this->lifetime) {
             Logger::Warn("Unlinking stale cachefile '" . $diskcache["fullpath"] . "'");
             unlink($diskcache["fullpath"]);
         } else {
             $fp = fopen($diskcache["fullpath"], "r");
             if (flock($fp, LOCK_SH)) {
                 //$cachedresult = file_get_contents($diskcache["fullpath"]);
                 $cachedresult = fread($fp, filesize($diskcache["fullpath"]));
                 flock($fp, LOCK_UN);
                 if (!empty($cachedresult)) {
                     Profiler::StartTimer("DataManager::Query() - load from cachefile");
                     Logger::Info("Loaded cached result for '%s' from file: '%s'", $key, $diskcache["fullpath"]);
                     $result = unserialize(gzdecode($cachedresult));
                     if ($result !== false) {
                         $ret = $result;
                     }
                     Profiler::StopTimer("DataManager::Query() - load from cachefile");
                 }
             } else {
                 Logger::Error("Failed to get shared lock for '%s' (%s)", $key, $diskcache["fullpath"]);
             }
         }
     }
     return $ret;
 }
Exemplo n.º 12
0
function unfucked_base_convert($numstring, $frombase, $tobase)
{
    Profiler::StartTimer("unfucked_base_convert", 3);
    $chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_^";
    $tostring = substr($chars, 0, $tobase);
    $length = strlen($numstring);
    $result = '';
    for ($i = 0; $i < $length; $i++) {
        $number[$i] = strpos($chars, $numstring[$i]);
    }
    do {
        $divide = 0;
        $newlen = 0;
        for ($i = 0; $i < $length; $i++) {
            $divide = $divide * $frombase + $number[$i];
            if ($divide >= $tobase) {
                $number[$newlen++] = (int) ($divide / $tobase);
                $divide = $divide % $tobase;
            } elseif ($newlen > 0) {
                $number[$newlen++] = 0;
            }
        }
        $length = $newlen;
        $result = $tostring[$divide] . $result;
    } while ($newlen != 0);
    Profiler::StopTimer("unfucked_base_convert");
    return $result;
}
Exemplo n.º 13
0
 function HandlePayload(&$args, $output = "inline")
 {
     Profiler::StartTimer("Component: " . $this->fullname, 2);
     try {
         $ret = call_user_func($this->payload, $args, $output);
     } catch (Exception $e) {
         global $webapp;
         $ret = $webapp->HandleException($e);
     }
     Profiler::StopTimer("Component: " . $this->fullname);
     return $ret;
 }
Exemplo n.º 14
0
 function ParseRequest($page = NULL, $post = NULL)
 {
     Profiler::StartTimer("WebApp::Init - parserequest", 1);
     $webroot = "";
     if ($page === NULL) {
         $page = $_SERVER["SCRIPT_URL"];
     }
     if ($page === NULL) {
         if (preg_match("/^(.*?)\\/go\\.php\$/", $_SERVER["SCRIPT_NAME"], $m)) {
             $webroot = $m[1];
         }
         $page = preg_replace("/" . preg_quote($webroot, "/") . "(.*?)(\\?.*)?\$/", "\$1", $_SERVER["REQUEST_URI"]);
     }
     if ($post === NULL) {
         $post = array();
     }
     if (!empty($_GET)) {
         $post = array_merge($post, $_GET);
     }
     if (!empty($_POST)) {
         $post = array_merge($post, $_POST);
     }
     $req = @parse_url($page);
     // FIXME - PHP sucks and throws a warning here on malformed URLs, with no way to catch as an exception
     // GET args
     if (!empty($req["query"])) {
         parse_str($req["query"], $req["args"]);
     } else {
         $req["args"] = array();
     }
     // POST data,
     if (!empty($post)) {
         if (get_magic_quotes_gpc()) {
             $post = array_map('stripslashes_deep', $post);
         }
         $req["args"] = array_merge($req["args"], $post);
     }
     // application/json POST data
     if ($_SERVER["REQUEST_METHOD"] == "POST" && $_SERVER["CONTENT_TYPE"] == "application/json") {
         $postdata = json_decode(file_get_contents("php://input"), true);
         if (!empty($postdata) && is_array($postdata)) {
             $req["args"] = array_merge($req["args"], $postdata);
         }
     }
     // Parse friendly URLs
     $req["friendly"] = false;
     if (preg_match_all("/\\/([^-\\/]+)-([^\\/]+)/", $req["path"], $m, PREG_SET_ORDER)) {
         $req["friendly"] = true;
         $friendlyargs = array();
         foreach ($m as $match) {
             $search[] = $match[0];
             $replace[] = "";
             array_set($friendlyargs, $match[1], decode_friendly($match[2]));
         }
         $req["path"] = str_replace($search, $replace, $req["path"]);
         if (empty($req["path"])) {
             $req["path"] = "/";
         }
         if (!empty($friendlyargs)) {
             $req["args"] = array_merge($friendlyargs, $req["args"]);
         }
     }
     $req["host"] = $_SERVER["HTTP_HOST"];
     $req["ssl"] = !empty($_SERVER["HTTPS"]);
     $req["scheme"] = "http" . ($req["ssl"] ? "s" : "");
     $req["ip"] = $_SERVER["REMOTE_ADDR"];
     $req["user_agent"] = $_SERVER['HTTP_USER_AGENT'];
     $req["referrer"] = $_SERVER["HTTP_REFERER"];
     if (!empty($_SERVER["HTTP_REFERER"])) {
         $req["referer"] = parse_url($_SERVER["HTTP_REFERER"]);
         if (!empty($req["referer"]["query"])) {
             parse_str($req["referer"]["query"], $req["referer"]["args"]);
         } else {
             $req["referer"]["args"] = array();
         }
     }
     $req["ajax"] = !empty($_SERVER["HTTP_X_AJAX"]) || !empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest";
     if (!empty($_SERVER["PHP_AUTH_USER"])) {
         $req["user"] = $_SERVER["PHP_AUTH_USER"];
     }
     if (!empty($_SERVER["PHP_AUTH_PW"])) {
         $req["password"] = $_SERVER["PHP_AUTH_PW"];
     }
     $req["basedir"] = $webroot;
     $req["baseurl"] = $req["scheme"] . "://" . $req["host"] . $req["basedir"];
     //$req["url"] = $req["baseurl"] . $page;
     $req["url"] = $req["baseurl"] . $_SERVER["REQUEST_URI"];
     // FIXME - This probably breaks non-root-level installs...
     if ($req["basedir"] == '/') {
         $req["basedir"] = '';
     }
     if (!empty($req["args"]["req"])) {
         array_set_multi($req, $req["args"]["req"]);
     }
     Profiler::StopTimer("WebApp::Init - parserequest");
     Profiler::StartTimer("WebApp::Init - handleredirects", 1);
     $rewritefile = $this->locations["config"] . "/redirects.xml";
     if (file_exists($rewritefile)) {
         $rewrites = new SimpleXMLElement(file_get_contents($rewritefile));
         $req = $this->ApplyRedirects($req, $rewrites->rule);
     }
     Profiler::StopTimer("WebApp::Init - handleredirects");
     if (!empty($req["contenttype"])) {
         $this->response["type"] = $req["contenttype"];
     }
     return $req;
 }
Exemplo n.º 15
0
 function compress($refresh = TRUE)
 {
     Profiler::StartTimer("Conteg::compress", 1);
     // sanity checks
     if ($refresh) {
         if (($this->data = ob_get_contents()) === FALSE) {
             return $this->_trigger_error('Conteg::compress(): No ob_contents to compress.', E_USER_ERROR);
         }
     }
     //else if( empty( $this->data )) return $this->_trigger_error( 'Conteg::compress(): No $data contents to compress.', E_USER_NOTICE );
     $encoding = empty($this->encoding) ? 'identity' : (strlen($this->data) > 1000 ? $this->encoding : 'identity');
     // MSIE check
     $this->size = strlen($this->data);
     // blasted MSIE will show `friendly` error pages in certain situations
     // the following is to fix that
     if ($this->size < 513 and !empty($this->_httpStatus) and $this->_noMSErrorFix == FALSE and $this->browserAgent == 'MSIE' and ($this->_httpStatus == 400 or $this->_httpStatus == 403 or $this->_httpStatus == 404 or $this->_httpStatus == 405 or $this->_httpStatus == 406 or $this->_httpStatus == 408 or $this->_httpStatus == 409 or $this->_httpStatus == 410 or $this->_httpStatus == 500 or $this->_httpStatus == 501 or $this->_httpStatus == 505)) {
         // content needs to be > 512 bytes
         $padBytes = 513 - $this->size;
         if (substr_count($this->data, '</body>')) {
             // this is html
             $replace = "<p>&nbsp;</p>\n";
             $i = (int) ceil($padBytes / 14);
             $replace = str_repeat($replace, $i) . '</body>';
             $this->data = str_replace('</body>', $replace, $this->data);
         } elseif (substr_count($this->data, '</BODY>')) {
             // this is HTML
             $replace = "<P>&nbsp;</P>\n";
             $i = (int) ceil($padBytes / 14);
             $replace = str_repeat($replace, $i) . '</BODY>';
             $this->data = str_replace('</BODY>', $replace, $this->data);
         } else {
             // this is plain-text
             $pad = "\n_";
             $i = (int) ceil($padBytes / 2);
             $this->data = $this->data . str_repeat($pad, $i);
         }
         $this->size = strlen($this->data);
     }
     // end MSIE `friendly` error page fix
     // clear to go; init compression variables
     switch ($encoding) {
         case 'gzip':
             // see http://www.faqs.org/rfcs/rfc1952
         // see http://www.faqs.org/rfcs/rfc1952
         case 'x-gzip':
             if (version_compare(PHP_VERSION, '4.2', '>=')) {
                 $this->gzdata = gzencode($this->data, $this->level, FORCE_GZIP);
             } else {
                 // effective kludge for php < 4.2 (no level parameter)
                 $crc = crc32($this->data);
                 $this->gzdata = "‹" . gzcompress($this->data, $this->level);
                 $this->gzdata = substr($this->gzdata, 0, -4) . pack('V', $crc) . pack('V', $this->size);
             }
             $this->gzsize = strlen($this->gzdata);
             $this->stat = round((1 - $this->gzsize / $this->size) * 100);
             break;
         case 'deflate':
             // see http://www.faqs.org/rfcs/rfc1951
             $this->gzdata = gzdeflate($this->data, $this->level);
             $this->gzsize = strlen($this->gzdata);
             $this->stat = round((1 - $this->gzsize / $this->size) * 100);
             break;
         case 'compress':
             // see http://www.faqs.org/rfcs/rfc1950
         // see http://www.faqs.org/rfcs/rfc1950
         case 'x-compress':
             $this->gzdata = gzcompress($this->data, $this->level);
             $this->gzsize = strlen($this->gzdata);
             $this->stat = round((1 - $this->gzsize / $this->size) * 100);
             break;
         case 'identity':
         default:
             $this->crc = NULL;
             $this->gzdata = '';
             $this->gzsize = $this->size;
             $this->stat = '(none)';
             $this->encoding = 'identity';
     }
     // switch( $encoding )
     Profiler::StopTimer("Conteg::compress");
     return TRUE;
 }
Exemplo n.º 16
0
 function Display($path = NULL, $args = NULL)
 {
     $path = any($path, $this->request["path"], "/");
     $args = any($args, $this->request["args"], array());
     if (!empty($this->components)) {
         try {
             $output = $this->components->Dispatch($path, $args, $this->request["type"]);
         } catch (Exception $e) {
             //print_pre($e);
             $output["content"] = $this->HandleException($e);
         }
         $this->session->quit();
         $contegargs = any($this->cfg->servers["conteg"], array());
         $sitecfg = ConfigManager::get("conteg");
         if (is_array($sitecfg)) {
             $contegargs = array_merge($contegargs, $sitecfg);
         }
         if (is_array($this->sitecfg["conteg"])) {
             $contegargs = array_merge($contegargs, $this->sitecfg["conteg"]);
         }
         if (empty($contegargs["type"])) {
             $contegargs["type"] = any($this->request["contenttype"], $output["responsetype"]);
         }
         if (is_array($contegargs["policy"][$contegargs["type"]])) {
             $contegargs = array_merge($contegargs, $contegargs["policy"][$contegargs["type"]]);
         }
         if (empty($contegargs["modified"])) {
             // Set modified time to mtime of base directory if not set
             $contegargs["modified"] = filemtime($this->rootdir);
         }
         if (!empty($contegargs["alloworigin"])) {
             header('Access-Control-Allow-Origin: ' . $contegargs["alloworigin"]);
         }
         //header('Content-type: ' . any($output["type"], "text/html"));
         if ($output["type"] == "ajax" || $output["type"] == "jsonp") {
             print $this->tplmgr->PostProcess($output["content"], true);
         } else {
             print $this->tplmgr->PostProcess($output["content"]);
             $showprofiler = !empty($this->request["args"]["timing"]) || $output["type"] == "text/html" && array_get($this->cfg->servers, "profiler.display");
             if ($showprofiler) {
                 print Profiler::Display();
             }
         }
         Profiler::StopTimer("WebApp::TimeToDisplay");
         Profiler::StartTimer("WebApp::Display() - Conteg", 1);
         new Conteg($contegargs);
         Profiler::StopTimer("WebApp::Display() - Conteg");
         if (Profiler::$log) {
             Profiler::Log(DependencyManager::$locations["tmp"], $this->components->pagecfg["pagename"]);
         }
     }
 }
Exemplo n.º 17
0
 function PostProcess(&$output, $simpledebug = false)
 {
     global $webapp;
     Profiler::StartTimer("TemplateManager::PostProcess()");
     $matchregex = "/\\[\\[(\\w[^\\[\\]{}:|]*)(?:[:|](.*?))?\\]\\]/";
     if (!is_array($output)) {
         // FIXME - we should probably still postprocess if we're returning XML
         if (preg_match_all($matchregex, $output, $matches, PREG_SET_ORDER)) {
             $search = $replace = array();
             foreach ($matches as $m) {
                 $search[] = $m[0];
                 $replace[] = !empty($this->varreplace[$m[1]]) ? htmlspecialchars($this->varreplace[$m[1]]) : (!empty($m[2]) ? $m[2] : "");
             }
             $pos = array_search("[[debug]]", $search);
             if ($pos !== false) {
                 // if there are errors, check for access and force debug
                 $show_debug = $webapp->debug;
                 /*
                 if (Logger::hasErrors()) {
                   $user = User::singleton();
                   if ($user->HasRole("DEBUG") || $user->HasRole("ADMIN") || $user->HasRole("QA")) {
                     $show_debug = true;
                   }
                 }
                 */
                 if ($show_debug) {
                     //$replace[$pos] = $this->GetTemplate("debug.tpl");
                     $replace[$pos] = $simpledebug ? Logger::Display(E_ALL) : ComponentManager::fetch("elation.debug");
                 } else {
                     $replace[$pos] = "";
                 }
             }
             if (($pos = array_search("[[dependencies]]", $search)) !== false) {
                 $replace[$pos] = DependencyManager::display();
                 // Sometimes dependencies also use postprocessing variables, so parse those and add them to the list too
                 // FIXME - could be cleaner, this is copy-pasta of the first parsing pass above
                 if (preg_match_all($matchregex, $replace[$pos], $submatches, PREG_SET_ORDER)) {
                     foreach ($submatches as $sm) {
                         $search[] = $sm[0];
                         $replace[] = !empty($this->varreplace[$sm[1]]) ? htmlspecialchars($this->varreplace[$sm[1]]) : (!empty($sm[2]) ? $sm[2] : "");
                     }
                 }
             }
             $output = str_replace($search, $replace, $output);
         }
     }
     Profiler::StopTimer("TemplateManager::PostProcess()");
     return $output;
 }
Exemplo n.º 18
0
 /**
  * Execute a delete query
  *
  * @param string $queryid
  * @param string $table
  * @param string $where_condition
  * @param array $bind_vars
  * @return int
  */
 function &QueryDelete($queryid, $table, $where_condition, $bind_vars = array())
 {
     // If we passed an array for the where clause, we need to synthesize a string and populate the appropriate bind_vars
     if (is_array($where_condition)) {
         $new_wheres = array();
         foreach ($where_condition as $k => $v) {
             $bind_vars[':where' . $k] = $v;
             $new_wheres[] = $k . "=:where" . $k;
         }
         $where_condition = implode(" AND ", $new_wheres);
     }
     $servers = $this->HashToServer($queryid);
     //print_pre($servers);
     foreach ($servers as $server) {
         $servernum = $server[0];
         // If we're not connected and we're in lazy mode, open the connection.  Bail out if lazy connect fails.
         if (!$this->LazyOpen($servernum)) {
             Logger::Info("Database connection '{$this->name}:{$servernum}' marked as failed, skipping DELETE query");
         } else {
             Profiler::StartTimer("DBWrapper:QueryDelete()");
             // Double check that conn exists before using it (FIXME - could be smarter here)
             $rows_affected = null;
             if ($this->conn[$servernum]) {
                 $realtable = $table . ($server[1] !== NULL ? "_" . $server[1] : "");
                 /*
                 print_pre($realtable);
                 print_pre($where_condition);
                 print_pre($bind_vars);
                 */
                 //Logger::Error("Execute querydelete: $realtable $where_condition");
                 //Logger::Error($bind_vars);
                 try {
                     $rows_affected = $this->conn[$servernum]->delete($realtable, $where_condition, $bind_vars);
                     Logger::Notice("Execute delete query on table {$table} (Using " . $this->dsn . ")");
                 } catch (Exception $e) {
                     Logger::Error("Failed to delete '{$queryid->id}' from '{$realtable}': " . $e->getMessage());
                 }
             } else {
                 Logger::Warn("Tried to use db '{$this->name}:{$servernum}', but no connection was active");
             }
         }
     }
     Profiler::StopTimer("DBWrapper:QueryDelete()");
     return $rows_affected;
 }
Exemplo n.º 19
0
 function ParseRequest($page = NULL, $post = NULL)
 {
     Profiler::StartTimer("WebApp::Init - parserequest", 1);
     $webroot = "";
     if ($page === NULL) {
         if (preg_match("/^(.*?)\\/index\\.php\$/", $_SERVER["SCRIPT_NAME"], $m)) {
             $webroot = $m[1];
         }
         //print_pre($_SERVER);
         if (isset($_SERVER["PATH_INFO"])) {
             $page = $_SERVER["PATH_INFO"];
             $webroot = $_SERVER["SCRIPT_NAME"];
         } else {
             if (isset($_SERVER["SCRIPT_URL"])) {
                 $page = $_SERVER["SCRIPT_URL"];
             } else {
                 if (empty($_SERVER["REDIRECT_URL"])) {
                     $webroot = $_SERVER["SCRIPT_NAME"];
                     $page = "/";
                 } else {
                     $page = preg_replace("/" . preg_quote($webroot, "/") . "(.*?)(\\?.*)?\$/", "\$1", $_SERVER["REQUEST_URI"]);
                     if ($page == "/index.php") {
                         $page = "/";
                     }
                 }
             }
         }
     }
     if ($post === NULL) {
         $post = array();
     }
     if (!empty($_GET)) {
         $post = array_merge($post, $_GET);
     }
     if (!empty($_POST)) {
         $post = array_merge($post, $_POST);
     }
     $req = @parse_url($page);
     // FIXME - PHP sucks and throws a warning here on malformed URLs, with no way to catch as an exception
     if (!empty($req["query"])) {
         parse_str($req["query"], $req["args"]);
     } else {
         $req["args"] = array();
     }
     if (!empty($post)) {
         if (get_magic_quotes_gpc()) {
             $post = array_map('stripslashes_deep', $post);
         }
         $req["args"] = array_merge($req["args"], $post);
     }
     $req["friendly"] = false;
     // Parse friendly URLs
     if (preg_match_all("/\\/([^-\\/]+)-([^\\/]+)/", $req["path"], $m, PREG_SET_ORDER)) {
         $req["friendly"] = true;
         $friendlyargs = array();
         foreach ($m as $match) {
             $search[] = $match[0];
             $replace[] = "";
             array_set($friendlyargs, $match[1], decode_friendly($match[2]));
         }
         $req["path"] = str_replace($search, $replace, $req["path"]);
         if (empty($req["path"])) {
             $req["path"] = "/";
         }
         if (!empty($friendlyargs)) {
             $req["args"] = array_merge($friendlyargs, $req["args"]);
         }
     }
     $req["method"] = $_SERVER["REQUEST_METHOD"];
     $req["host"] = $_SERVER["HTTP_HOST"];
     $req["ssl"] = !empty($_SERVER["HTTPS"]);
     $req["scheme"] = "http" . ($req["ssl"] ? "s" : "");
     $req["ip"] = $_SERVER["REMOTE_ADDR"];
     $req["user_agent"] = $_SERVER['HTTP_USER_AGENT'];
     $req["referrer"] = $_SERVER["HTTP_REFERER"];
     if (!empty($_SERVER["HTTP_REFERER"])) {
         $req["referer"] = parse_url($_SERVER["HTTP_REFERER"]);
         if (!empty($req["referer"]["query"])) {
             parse_str($req["referer"]["query"], $req["referer"]["args"]);
         } else {
             $req["referer"]["args"] = array();
         }
     }
     $req["ajax"] = !empty($_SERVER["HTTP_X_AJAX"]) || !empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest";
     if (!empty($_SERVER["PHP_AUTH_USER"])) {
         $req["user"] = $_SERVER["PHP_AUTH_USER"];
     }
     if (!empty($_SERVER["PHP_AUTH_PW"])) {
         $req["password"] = $_SERVER["PHP_AUTH_PW"];
     }
     $req["basedir"] = $webroot;
     $req["baseurl"] = $req["scheme"] . "://" . $req["host"] . $req["basedir"];
     //$req["url"] = $req["baseurl"] . $page;
     $req["url"] = $req["baseurl"] . $_SERVER["REQUEST_URI"];
     // FIXME - This probably breaks non-root-level installs...
     if ($req["basedir"] == '/') {
         $req["basedir"] = '';
     }
     if (!empty($req["args"]["req"])) {
         array_set_multi($req, $req["args"]["req"]);
     }
     Profiler::StopTimer("WebApp::Init - parserequest");
     return $req;
 }