protected function prepare() { if (PATCHWORK_I18N) { $this->lang = Patchwork::__LANG__(); if (!isset($this->alt)) { $a = array(); $base = preg_quote($_SERVER['PATCHWORK_BASE'], "'"); $base = explode('__', $base, 2); $base[1] = '/' === $base[1] ? '[^?/]+(/?)' : ".+?({$base[1]})"; $base = "'^({$base[0]}){$base[1]}(.*)\$'D"; if (preg_match($base, Patchwork::__URI__(), $base)) { unset($base[0]); foreach ($GLOBALS['CONFIG']['i18n.lang_list'] as $k => $v) { if ('' === $k) { continue; } $v = $base[1] . $v . $base[2] . ($this->lang === $k ? $base[3] : Patchwork::translateRequest($base[3], $k)); $a[] = (object) array('lang' => $k, 'title' => isset(self::$nativeLang[$k]) ? self::$nativeLang[$k] : $k, 'href' => $v); } } else { user_error('Something is wrong between Patchwork::__URI__() and PATCHWORK_BASE'); } $this->alt =& $a; } return count($this->alt); } else { return 0; } }
function control() { parent::control(); if ($this->entity) { return; } $u = empty($this->entityUrl) ? explode('_', substr(get_class($this), 6)) : explode('/', $this->entityUrl); if ('new' === end($u)) { $this->entityIsNew = true; array_pop($u); } $this->entityUrl = implode('/', $u); $this->entityClass = self::$entityNs . "\\"; foreach ($u as $u) { $this->entityClass .= ucfirst($u); //TODO: Ugly } if ($this->entityIsNew) { $this->entity = new $this->entityClass(); } else { if (!empty($this->get->__1__)) { // Use this to manage composite primary keys $id = !empty($this->entityIdentifier) ? $this->entityIdentifier : $this->get->__1__; $this->entity = EM()->find($this->entityClass, $id); $this->entity || Patchwork::forbidden(); } else { if ($this instanceof agent_pForm_entity_indexable) { $this->template = $this->entityUrl . '/index'; } else { Patchwork::forbidden(); } } } }
protected function setHeaders() { $headers =& $this->headers; self::cleanHeaders($headers, 'Return-Path|From|Sender|Reply-To|Message-Id|To|Cc|Bcc|Subject'); foreach (array('To', 'Cc', 'Bcc', 'Reply-To') as $sql) { isset($headers[$sql]) && is_array($headers[$sql]) && ($headers[$sql] = implode(', ', $headers[$sql])); } $message_id = 'pM' . p::uniqId(); $headers['Message-Id'] = '<' . $message_id . '@' . $_SERVER['HTTP_HOST'] . '>'; if (empty($headers['Sender'])) { if ($CONFIG['pMail.sender']) { $headers['Sender'] = $CONFIG['pMail.sender']; } } if (empty($headers['From'])) { if (empty($headers['Sender'])) { user_error("Email is likely not to be sent: From header is empty."); } else { $headers['From'] =& $headers['Sender']; unset($headers['Sender']); } } if (empty($headers['Return-Path'])) { if (isset($headers['Sender'])) { $headers['Return-Path'] = $headers['Sender']; } else { if (isset($headers['From'])) { $headers['Return-Path'] = $headers['From']; } } } isset($headers['Return-Path']) && preg_match('/' . FILTER::EMAIL_RX . '/', $headers['Return-Path'], $m) && ($headers['Return-Path'] = '<' . $m[0] . '>'); }
static function php($string, $urlInterpolation = false) { $string = (string) $string; false !== strpos($string, '&') && ($string = str_replace(array(''', '"', '>', '<', '&'), array("'", '"', '>', '<', '&'), $string)); $urlInterpolation && false !== strpos($string, '{') && ($string = str_replace(array('{/}', '{~}'), array(Patchwork::__HOST__(), Patchwork::__BASE__()), $string)); return $string; }
protected function composeEditor($o) { if (!$this->get->sql) { $f = new pForm($o); $f->setPrefix(''); $f->add('hidden', 'low'); $f->add('hidden', 'high'); $sql = $f->add('textarea', 'sql'); if ($sql->isOn()) { $sql = trim($sql->getValue()); $sql || Patchwork::redirect(); if (!($db = $this->getDb($o))) { return $o; } if (self::isReadOnlyQuery($db, $sql, $o->error_msg)) { $sql = urlencode($sql); $uri = Patchwork::__URI__(); $uri = $uri !== strtr($uri, '?&', '--') ? preg_replace("'([?&]sql=)[^&]*'", '$1' . $sql, $uri) : $uri . '?sql=' . $sql; Patchwork::redirect($uri); } @$db->queryExec($sql, $o->error_msg); $o->write_sql = pStudio_highlighter::highlight($sql, 'sql', false); } } return $this->composeReader($o); }
static function compose($o) { $o->jquery_ui_theme = self::$uiTheme; $uiLoad = trim(self::$uiLoad); if ('' !== $uiLoad) { $uiLoad = explode(' ', $uiLoad); while (list(, $v) = each($uiLoad)) { $o->{strtr($v, '.', '_')} = 1; if (isset(self::$uiDependency[$v])) { $v = self::$uiDependency[$v]; foreach (explode(' ', $v) as $v) { $v && ($uiLoad[] = $v); } } } } if (!empty($o->ui_datepicker)) { $lang = Patchwork::__LANG__(); if (isset(self::$langMap[$lang])) { $lang = self::$langMap[$lang]; } else { if (!in_array($lang, explode(' ', self::$langAvail))) { $lang = substr($lang, 0, 2); if (!in_array($lang, explode(' ', self::$langAvail))) { $lang = ''; } } } $lang && ($o->ui_datepicker_lang = $lang); } return $o; }
protected function composeEditor($o) { $o = self::composeReader($o); if (!empty($o->is_binary)) { unset($o->is_binary, $o->is_auth_edit); $o = $this->composeReader($o); } else { $this->editorTemplate && ($this->template = $this->editorTemplate); $f = new pForm($o); $f->add('textarea', 'code', array('default' => $o->text)); $send = $f->add('submit', 'save'); $send->attach('code', '', ''); if ($send->isOn()) { $code = $send->getData(); $code = $code['code']; if ('' !== $code && "\n" !== substr($code, -1)) { $code .= "\n"; } file_put_contents($this->realpath, $code); pStudio::syncCache($this->path, $this->depth); Patchwork::redirect(); } unset($o->text); } return $o; }
function convertData($html) { // Style according to the Netiquette $html = preg_replace('#<(?:b|strong)\\b[^>]*>(\\s*)#iu', '$1*', $html); $html = preg_replace('#(\\s*)</(?:b|strong)\\b[^>]*>#iu', '*$1', $html); $html = preg_replace('#<u\\b[^>]*>(\\s*)#iu', '$1_', $html); $html = preg_replace('#(\\s*)</u\\b[^>]*>#iu', '_$1', $html); // Remove <sub> and <sup> tags $html = preg_replace('#<(/?)su[bp]\\b([^>]*)>#iu', '<$1span$2>', $html); // Fill empty alt attributes with whitespace, clear src attributes $html = preg_replace('#(<[^>]+\\balt=")"#iu', '$1 "', $html); $html = preg_replace('#(<[^>]+\\bsrc=")(?:[^"]*)"#iu', '$1"', $html); // Inline URLs $html = preg_replace_callback('#<a\\b[^>]*\\shref="([^"]*)"[^>]*>(.*?)</a\\b[^>]*>#isu', array(__CLASS__, 'buildTextAnchor'), $html); // Convert html-entities to UTF-8 for w3m $html = str_replace(array('"', '<', '>', ''', '"', '<', '>', "'"), array('&quot;', '&lt;', '&gt;', '&#039;', '"', '<', '>', '''), FILTER::get($html, 'text')); $html = html_entity_decode($html, ENT_COMPAT, 'UTF-8'); $file = tempnam(PATCHWORK_ZCACHE, 'converter'); Patchwork::writeFile($file, $html); $html = escapeshellarg($file); $html = `w3m -dump -cols {$this->cols} -T text/html -I UTF-8 -O UTF-8 {$html}`; $html = str_replace(self::$charMap[0], self::$charMap[1], $html); $html = strtr($html, self::$textAnchor); self::$textAnchor = array(); unlink($file); return $html; }
function compose($o) { if ($this->debug || $this->get->src) { $o = parent::compose($o); $o->cookie_path = $CONFIG['session.cookie_path']; $o->cookie_domain = $CONFIG['session.cookie_domain']; $o->document_domain = $CONFIG['document.domain']; $o->maxage = $CONFIG['maxage']; } else { ++self::$recursion; $src = Patchwork\Superloader::class2file(substr(get_class($this), 6)); $src = Patchwork\Serverside::returnAgent($src, (array) $this->get); --self::$recursion; $parser = new JSqueeze(); if ('/*!' != substr(ltrim(substr($src, 0, 512)), 0, 3)) { $o->DATA = Patchwork::__URI__(); $o->DATA .= (false === strpos($o->DATA, '?') ? '?' : '&') . 'src=1'; $o->DATA = "// Copyright & source: {$o->DATA}\n"; foreach (count_chars($o->DATA, 1) as $k => $w) { $parser->charFreq[$k] += $w; } $o->DATA .= $parser->squeeze($src); } else { $o->DATA = $parser->squeeze($src); } } return $o; }
function convertData($data) { $file = tempnam('.', 'converter'); Patchwork::writeFile($file, $data); $data = $this->convertFile($file); unlink($file); return $data; }
public final function __toString() { $catchMeta = Patchwork::$catchMeta; Patchwork::$catchMeta = true; if ($this->loopLength === false) { $this->loopLength = (int) $this->prepare(); } Patchwork::$catchMeta = $catchMeta; return (string) $this->loopLength; }
static function php($text, $url = '', $attributes = '') { $url = (string) $url; $a = strpos($url, '#'); if (false !== $a) { $hash = substr($url, $a); $url = substr($url, 0, $a); } else { $hash = ''; } return $url == htmlspecialchars(substr(Patchwork::__HOST__() . substr($_SERVER['REQUEST_URI'], 1), strlen(Patchwork::__BASE__()))) ? '<b class="linkloop">' . $text . '</b>' : '<a href="' . Patchwork::base($url, true) . $hash . '" ' . $attributes . '>' . $text . '</a>'; }
protected function doSchedule($time) { $db = $this->getPdoConnection(); if ($time < $_SERVER['REQUEST_TIME'] - 366 * 86400) { $time += $_SERVER['REQUEST_TIME']; } $data = array('task' => $this, 'cookie' => &$_COOKIE, 'session' => class_exists('SESSION', false) ? s::getAll() : array()); $sql = "INSERT INTO queue (base, data, run_time)\n VALUES (?,?,?)"; $db->prepare($sql)->execute(array(p::__BASE__(), serialize($data), $time)); $id = $db->lastInsertId(); $this->registerQueue(); return $id; }
function redirect($javascript) { p::disable(); $url = $this->url; if ($javascript) { $url = 'location.replace(' . ('' !== $url ? "'" . addslashes($url) . "'" : 'location') . ')'; header('Content-Length: ' . strlen($url)); echo $url; } else { header('HTTP/1.1 302 Found'); header('Location: ' . ('' !== $url ? $url : $_SERVER['REQUEST_URI'])); } }
static function __free() { self::$adapter->close(); foreach (self::$cache as $file => &$cache) { if ($cache[0]) { $data = serialize($cache[2]); p::writeFile($file, $data); if ($cache[1]) { p::writeWatchTable('translator', $file, false); } } } }
function redirect($javascript) { p::disable(); $url = $this->url; $url = '' === $url ? '' : (preg_match("'^([^:/]+:/|\\.+)?/'", $url) ? $url : p::__BASE__() . ('index' === $url ? '' : $url)); if ($javascript) { $url = 'location.replace(' . ('' !== $url ? "'" . addslashes($url) . "'" : 'location') . ')'; header('Content-Length: ' . strlen($url)); echo $url; } else { header('HTTP/1.1 302 Found'); header('Location: ' . ('' !== $url ? $url : $_SERVER['REQUEST_URI'])); } }
function writeEvent($type, $data) { if ('php-error' === $type || 'php-exception' === $type) { \Patchwork::setMaxage(0); \Patchwork::setExpires('onmaxage'); $GLOBALS['patchwork_private'] = true; } if ($this->isFirstEvent) { // http://bugs.php.net/42098 workaround class_exists('Patchwork\\PHP\\Walker') || eval(';') || __autoload('Patchwork\\PHP\\Walker'); class_exists('Patchwork\\PHP\\Dumper') || eval(';') || __autoload('Patchwork\\PHP\\Dumper'); class_exists('Patchwork\\PHP\\JsonDumper') || eval(';') || __autoload('Patchwork\\PHP\\JsonDumper'); $data['patchwork'] = array('i18n' => PATCHWORK_I18N, 'debug' => DEBUG, 'turbo' => Superloader::$turbo, 'level' => PATCHWORK_PATH_LEVEL, 'zcache' => PATCHWORK_ZCACHE, 'paths' => $GLOBALS['patchwork_path']); } return parent::writeEvent($type, $data); }
function compose($o) { if ($this->get->id) { $this->expires = 'onmaxage'; Patchwork::setPrivate(); if (function_exists('upload_progress_meter_get_info')) { $o = (object) @upload_progress_meter_get_info($this->get->id); } else { if (function_exists('uploadprogress_get_info')) { $o = (object) @uploadprogress_get_info($this->get->id); } } } else { $this->maxage = -1; } return $o; }
/** * Sends the request to the webserver but don't wait for the response. */ static function touch($url) { $url = Patchwork::base($url, true); if (!preg_match("'^http(s?)://([^:/]*)((?::[0-9]+)?)(/.*)\$'", $url, $h)) { throw new Exception('Illegal URL'); } $url = "GET {$h[4]} HTTP/1.0\r\n"; $url .= "Host: {$h[2]}\r\n"; $url .= "Connection: close\r\n\r\n"; try { $h = patchwork_http_socket($h[2], substr($h[3], 1), $h[1], 5); socket_set_blocking($h, 0); do { $len = fwrite($h, $url); $url = substr($url, $len); } while (false !== $len && false !== $url); fclose($h); } catch (Exception $h) { user_error($h->getMessage()); } }
static function scriptAlert() { p::setMaxage(0); if (p::$catchMeta) { p::$metaInfo[1] = array('private'); } if ('-' === strtr(self::$requestMode, '-tpax', '#----')) { $a = ''; $cache = p::getContextualCachePath('agentArgs/' . p::$agentClass, 'txt'); if (file_exists($cache)) { $h = fopen($cache, 'r+b'); if (!($a = fread($h, 1))) { rewind($h); fwrite($h, $a = '1'); p::touch('public/templates/js'); p::updateAppId(); } fclose($h); } throw new e\PrivateResource($a); } user_error('Potential JavaScript-Hijacking. Stopping !'); p::disable(true); }
protected function pushMail($mailer, &$headers, &$options) { if (isset($options['testMode'])) { $this->testMode = $options['testMode']; } else { if ($this->testMode) { $options['testMode'] = 1; } } $sent = -(int) (bool) (!empty($options['testMode'])); $archive = (int) (!(empty($options['archive']) && empty($options['testMode']))); $time = isset($options['time']) ? $options['time'] : 0; if ($time < $_SERVER['REQUEST_TIME'] - 366 * 86400) { $time += $_SERVER['REQUEST_TIME']; } if (!empty($options['attachments']) && is_array($options['attachments'])) { $tmpToken = false; foreach ($options['attachments'] as &$file) { if (is_uploaded_file($file) || PATCHWORK_ZCACHE === substr($file, 0, strlen(PATCHWORK_ZCACHE))) { $tmpToken || ($tmpToken = p::strongId(8)); $base = PATCHWORK_ZCACHE . p::strongId(8) . '~' . $tmpToken; copy($file, $base); $file = $base; } } unset($file, $options['attachments.tmpToken']); $tmpToken && ($options['attachments.tmpToken'] = $tmpToken); } $data = array('mailer' => $mailer, 'headers' => &$headers, 'options' => &$options, 'cookie' => &$_COOKIE, 'session' => class_exists('SESSION', false) ? s::getAll() : array()); $db = $this->getPdoConnection(); $sql = "INSERT INTO queue (base, data, send_time, archive, sent_time)\n VALUES (?,?,?,?,?)"; $db->prepare($sql)->execute(array(p::__BASE__(), serialize($data), $time, $archive, $sent)); $sql = $db->lastInsertId(); $this->registerQueue(); return $sql; }
static function __init() { self::$savePath = $CONFIG['session.save_path']; self::$cookiePath = $CONFIG['session.cookie_path']; self::$cookieDomain = $CONFIG['session.cookie_domain']; $CONFIG['session.auth_vars'] && (self::$authVars = array_merge(self::$authVars, $CONFIG['session.auth_vars'])); $CONFIG['session.group_vars'] && (self::$groupVars = array_merge(self::$groupVars, $CONFIG['session.group_vars'])); self::$authVars = array_flip(self::$authVars); self::$groupVars = array_flip(self::$groupVars); if (self::$maxIdleTime < 1 && self::$maxLifeTime < 1) { user_error('At least one of the SESSION::$max*Time variables must be strictly positive.'); } if (mt_rand(1, self::$gcProbabilityDenominator) <= self::$gcProbabilityNumerator) { $adapter = new self('0lastGC'); $i = $adapter->read(); $j = max(self::$maxIdleTime, self::$maxLifeTime); if ($j && $_SERVER['REQUEST_TIME'] - $i > $j) { $adapter->write($_SERVER['REQUEST_TIME']); register_shutdown_function(array(__CLASS__, 'gc'), $j); } unset($adapter); } if (isset($_COOKIE['SID'])) { self::setSID($_COOKIE['SID']); self::$adapter = new self(self::$SID); $i = self::$adapter->read(); } else { $i = false; } if ($i) { $i = unserialize($i); self::$lastseen = $i[0]; self::$birthtime = $i[1]; if (self::$maxIdleTime && $_SERVER['REQUEST_TIME'] - self::$lastseen > self::$maxIdleTime) { // Session has idled self::onIdle(); self::$isIdled = true; } else { if (self::$maxLifeTime && $_SERVER['REQUEST_TIME'] - self::$birthtime > self::$maxLifeTime) { // Session has expired self::onExpire(); } else { self::$DATA =& $i[2]; } } if (isset($_SERVER['HTTPS']) && (!isset($_COOKIE['SSL']) || $i[3] != $_COOKIE['SSL'])) { self::regenerateId(true); } else { self::$sslid = $i[3]; if ('-' == self::$sslid[0] && isset($_SERVER['HTTPS'])) { self::$sslid = p::strongId(); setcookie('SSL', self::$sslid, 0, self::$cookiePath, self::$cookieDomain, true, true); unset($_SERVER['HTTP_IF_NONE_MATCH'], $_SERVER['HTTP_IF_MODIFIED_SINCE']); } } } else { self::regenerateId(true); } }
function setFile($isfile) { if ($isfile && !$this->hasfile) { $this->hasfile = true; if (function_exists('upload_progress_meter_get_info') || function_exists('uploadprogress_get_info')) { $elt = $this->elt['UPLOAD_IDENTIFIER'] = new pForm_hidden($this, 'UPLOAD_IDENTIFIER', array(), $this->sessionLink); $elt->setValue(p::uniqId()); array_unshift($this->hidden, $elt); } } }
function control() { Patchwork::redirect('pStudio/explorer'); }
protected function getToken() { $token = patchworkPath($this->queueFolder) . $this->queueName . '.token'; //XXX user right problem? file_exists($token) || file_put_contents($token, p::strongId()); return trim(file_get_contents($token)); }
protected static function sendDebugInfo() { ob_start(function_exists('ob_gzhandler') ? 'ob_gzhandler' : null, 1 << 14); header('Content-Type: text/html; charset=utf-8'); header('Cache-Control: max-age=0,private,must-revalidate'); set_time_limit(0); ignore_user_abort(true); ?> <!doctype html> <html> <head> <title>Debug Window</title> <link rel="stylesheet" href="<?php echo p::__BASE__() . 'css/patchwork-console.css?' . $GLOBALS['patchwork_appId']; ?> "> </head> <body> <script src="<?php echo p::__BASE__() . 'js/patchwork-console.js?' . $GLOBALS['patchwork_appId']; ?> "></script> <div id="events" style="display:none"> <?php for (;;) { $continue = false; foreach (scandir(PATCHWORK_ZCACHE) as $log) { if ('.log' !== substr($log = PATCHWORK_ZCACHE . $log, -4)) { continue; } /**/ // On Windows only, rename() fails if the file is opened in an other process. /**/ // We use this behavior to detect this and cancel sending the file. /**/ if ('\\' === DIRECTORY_SEPARATOR) { if (!@rename($log, $log .= '~')) { $continue = true; continue; } /**/ } if (!($h = @fopen($log, 'rb'))) { /**/ if ('\\' === DIRECTORY_SEPARATOR) { rename($log, substr($log, 0, -1)); } continue; } /**/ if ('\\' !== DIRECTORY_SEPARATOR) { usleep(1); // Give priority for locking to the error handler process if (@flock($h, LOCK_EX | LOCK_NB, $j) && !$j) { unlink($log); } else { $continue = true; continue; } /**/ } $it = new p\PHP\JsonDumpIterator($h); try { unset($j); foreach ($it as $j) { echo '<script>patchworkConsole.log(', $it->jsonStr($j['type']), ',', $j['json'], ',', $it->jsonStr(substr(md5($log), -10)), ')</script>', "\n"; ob_flush(); flush(); if (connection_aborted()) { $continue = false; break; } } } catch (p\PHP\JsonDumpIteratorException $it) { } flock($h, LOCK_UN); fclose($h); /**/ if ('\\' === DIRECTORY_SEPARATOR) { unlink($log); } } if ($continue && isset($j)) { usleep(150000); } else { break; } } ?> </div> <script> scrollTo(0,0); var i, b = window.parent && parent.E && parent.E.buffer; for (i in b) patchworkConsole.log("client-dump", b[i]); parent.E.buffer = []; </script> <?php }
static function send($agent) { header('Content-Type: text/javascript'); p::setMaxage(-1); echo 'w.k(', p::$appId, ',', jsquote(p::$base), ',', jsquote('agent_index' === $agent ? '' : p\Superloader::class2file(substr($agent, 6))), ',', jsquote(isset($_GET['__0__']) ? $_GET['__0__'] : ''), ',', '[', implode(',', array_map('jsquote', p::agentArgs($agent))), ']', ')'; }
function compose($o) { $o->DATA = '/*<script>/**/q="' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $this->getJs($this->data)) . '"//</script>' . '<script src="' . Patchwork::__BASE__() . 'js/QJsrsHandler"></script>'; return $o; }
protected static function sendDebugInfo() { ob_start(function_exists('ob_gzhandler') ? 'ob_gzhandler' : null, 1 << 14); header('Content-Type: text/html; charset=utf-8'); header('Cache-Control: max-age=0,private,must-revalidate'); set_time_limit(0); ignore_user_abort(true); ?> <!doctype html> <html> <head> <title>Debug Window</title> <link type="text/css" rel="stylesheet" href="<?php echo p::__BASE__() . 'css/patchwork-console.css?' . $GLOBALS['patchwork_appId']; ?> "> </head> <body> <script src="<?php echo p::__BASE__() . 'js/patchwork-console.js?' . $GLOBALS['patchwork_appId']; ?> "></script> <div id="events" style="display:none"> <?php $handlers = array(); for (;;) { foreach (scandir(PATCHWORK_ZCACHE) as $log) { if ('.log' === substr($log = PATCHWORK_ZCACHE . $log, -4)) { if (rename($log, $log .= '~')) { ($h = fopen($log, 'rb')) ? $handlers[$log] = $h : unlink($log); } } } $count = 0; foreach ($handlers as $log => $h) { if (false === ($next_line = fgets($h))) { ++$count; } else { while (false !== ($line = $next_line)) { $next_line = fgets($h); self::parseLine($line, $next_line); for (;;) { if (false !== ($line = reset(self::$buffer))) { echo implode('', $line); if ($line && false === end($line)) { unset(self::$buffer[key(self::$buffer)]); ob_flush(); flush(); if (connection_aborted()) { break 4; } else { continue; } } else { self::$buffer[key(self::$buffer)] = array(); } } break; } } } } if ($count === count($handlers)) { break; } usleep(150000); } foreach ($handlers as $log => $h) { fclose($h) + unlink($log); } ?> </div> <script> scrollTo(0,0); var i, b = window.parent && parent.E && parent.E.buffer; for (i in b) patchworkConsole.log("client-dump", b[i]); parent.E.buffer = []; </script> <?php }
static function render($agent, $liveAgent) { $config_maxage = $CONFIG['maxage']; // Get the calling URI if (isset($_COOKIE['R$'])) { p::$uri = $_COOKIE['R$']; setcookie('R$', '', 1, '/'); // Check the Referer header // T$ starts with 2 when the Referer's confidence is unknown // 1 when it is trusted if (isset($_SERVER['HTTP_REFERER']) && $_COOKIE['R$'] === $_SERVER['HTTP_REFERER']) { if (class_exists('SESSION', false)) { $_COOKIE['T$'] = '1'; s::regenerateId(); } else { self::$antiCsrfToken[0] = '1'; setcookie('T$', self::$antiCsrfToken, 0, $CONFIG['session.cookie_path'], $CONFIG['session.cookie_domain']); } } } else { p::$uri = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : p::$base; } if ($liveAgent) { // The output is both html and js, but iframe transport layer needs html p::$binaryMode = true; header('Content-Type: text/html'); echo '/*<script>/**/q="'; } else { echo 'w('; } p::openMeta($agent); try { if (isset($_GET['T$']) && !p::$antiCsrfMatch) { throw new e\PrivateResource(); } $a = new $agent($_GET); $group = p::closeGroupStage(); if ($is_cacheable = 'POST' !== $_SERVER['REQUEST_METHOD'] && !in_array('private', $group)) { $cagent = p::agentCache($agent, $a->get, 'js.ser', $group); $dagent = p::getContextualCachePath('jsdata.' . $agent, 'js.ser', $cagent); if ($liveAgent) { if (file_exists($dagent)) { if (filemtime($dagent) > $_SERVER['REQUEST_TIME']) { $data = unserialize(file_get_contents($dagent)); p::setMaxage($data['maxage']); p::setExpires($data['expires']); p::writeWatchTable($data['watch']); array_map('header', $data['headers']); p::closeMeta(); echo str_replace(array('\\', '"', '</'), array('\\\\', '\\"', '<\\/'), $data['rawdata']), '"//</script><script src="' . p::__BASE__() . 'js/QJsrsHandler"></script>'; return; } else { @(unlink($cagent) + unlink($dagent)); } } } else { if (file_exists($cagent)) { if (filemtime($cagent) > $_SERVER['REQUEST_TIME']) { $data = unserialize(file_get_contents($cagent)); p::setMaxage($data['maxage']); p::setExpires($data['expires']); p::writeWatchTable($data['watch']); array_map('header', $data['headers']); p::closeMeta(); echo $data['rawdata']; return; } else { @(unlink($cagent) + unlink($dagent)); } } } } ob_start(); ++p::$ob_level; try { $data = (object) $a->compose((object) array()); if (!p::$is_enabled) { p::closeMeta(); return; } $template = $a->getTemplate(); echo '{'; $comma = ''; foreach ($data as $key => $value) { $key = jsquote($key); is_string($key) || ($key = "'" . $key . "'"); echo $comma, $key, ':'; if ($value instanceof \loop) { self::writeAgent($value); } else { echo jsquote($value); } $comma = ','; } echo '}'; } catch (e\PrivateResource $data) { ob_end_clean(); --p::$ob_level; p::closeMeta(); throw $data; } $data = ob_get_clean(); --p::$ob_level; $a->metaCompose(); list($maxage, $group, $expires, $watch, $headers) = p::closeMeta(); } catch (e\PrivateResource $data) { if ($liveAgent) { echo 'false";(window.E||alert)("You must provide an auth token to get this liveAgent:\\n"+', jsquote($_SERVER['REQUEST_URI']), ')'; echo '//</script><script src="' . p::__BASE__() . 'js/QJsrsHandler"></script>'; } else { if ($data->getMessage()) { echo 'w.r(0,' . (int) (!DEBUG) . '));'; } else { echo ');window.E&&E("You must provide an auth token to get this agent:\\n"+', jsquote($_SERVER['REQUEST_URI']), ')'; } } exit; } if ($liveAgent) { echo str_replace(array('\\', '"', '</'), array('\\\\', '\\"', '<\\/'), $data), '"//</script><script src="' . p::__BASE__() . 'js/QJsrsHandler"></script>'; } else { echo $data; } if ('ontouch' === $expires && !($watch || $config_maxage == $maxage)) { $expires = 'auto'; } $expires = 'auto' === $expires && ($watch || $config_maxage == $maxage) ? 'ontouch' : 'onmaxage'; $is_cacheable = $is_cacheable && !in_array('private', $group) && ($maxage || 'ontouch' === $expires); if (!$liveAgent || $is_cacheable) { if ($is_cacheable) { ob_start(); } if ($config_maxage == $maxage && Superloader::$turbo) { $ctemplate = p::getContextualCachePath("templates/{$template}", 'txt'); $readHandle = true; if ($h = p::fopenX($ctemplate, $readHandle)) { p::openMeta('agent__template/' . $template, false); $template = new \ptlCompiler_js($template); echo $template = ',' . $template->compile() . ')'; fwrite($h, $template); flock($h, LOCK_UN); fclose($h); list(, , , $template) = p::closeMeta(); p::writeWatchTable($template, $ctemplate); } else { fpassthru($readHandle); flock($readHandle, LOCK_UN); fclose($readHandle); } $watch[] = 'public/templates/js'; } else { echo ',[1,', jsquote($template), ',0,0,0])'; } if ($is_cacheable) { $ob = true; $template = array('maxage' => $maxage, 'expires' => $expires, 'watch' => $watch, 'headers' => $headers, 'rawdata' => $data); $expires = 'ontouch' === $expires ? $config_maxage : $maxage; if ($h = p::fopenX($dagent)) { fwrite($h, serialize($template)); flock($h, LOCK_UN); fclose($h); touch($dagent, $_SERVER['REQUEST_TIME'] + $expires); p::writeWatchTable($watch, $dagent); } if ($h = p::fopenX($cagent)) { $ob = false; $template['rawdata'] .= $liveAgent ? ob_get_clean() : ob_get_flush(); fwrite($h, serialize($template)); flock($h, LOCK_UN); fclose($h); touch($cagent, $_SERVER['REQUEST_TIME'] + $expires); p::writeWatchTable($watch, $cagent); } if ($ob) { $liveAgent ? ob_end_clean() : ob_end_flush(); } } } }