Пример #1
0
 public static function setup(PWECore $pwe, array &$registerData)
 {
     if (!is_dir(self::getHTMLDirectory($pwe))) {
         PWELogger::info("Creating HTML directory: %s", self::getHTMLDirectory($pwe));
         mkdir(self::getHTMLDirectory($pwe), null, true);
     }
 }
Пример #2
0
 protected function loadRegistry($force = false)
 {
     if (is_file($this->registryFile)) {
         parent::loadRegistry();
     } else {
         PWELogger::debug("File not found: %s", $this->registryFile);
     }
 }
Пример #3
0
 public static function setup(PWECore $pwe, array &$registerData)
 {
     if (is_writable($pwe->getStaticDirectory())) {
         PWELogger::debug("Copying into %s/design", $pwe->getStaticDirectory());
         FilesystemHelper::fsys_copydir(__DIR__ . '/../../design', $pwe->getStaticDirectory() . '/design');
     } else {
         PWELogger::warn("Can't copy resources to %s, it's not writable");
     }
 }
Пример #4
0
 public function getPypiInfo()
 {
     $fname = $this->PWE->getTempDirectory() . "/bzt-pypi.json";
     if (!file_exists($fname) || time() - filemtime($fname) > 60 * 60) {
         $url = "https://pypi.python.org/pypi/bzt/json";
         \PWE\Core\PWELogger::info("Refresh PyPi cache: %s", $url);
         file_put_contents($fname, fopen($url, 'r'));
     }
     return json_decode(file_get_contents($fname), true);
 }
Пример #5
0
 static function getTestPWECore()
 {
     $pwe = new PWECore();
     PWEAutoloader::setPWE($pwe);
     $temp = PWEUnitTests::utGetCleanTMP();
     $pwe->setDataDirectory($temp);
     $pwe->setTempDirectory($temp);
     $pwe->setXMLDirectory($temp);
     PWELogger::debug("Finished creating test PWE Core");
     return $pwe;
 }
Пример #6
0
 function __construct($message, $code = HTTP3xxException::REDIRECT)
 {
     parent::__construct($message, $code);
     PWELogger::info("Redirect to address %s: %s", $message, $this);
     if ($code == 301 || $code == 302) {
         if (!headers_sent()) {
             // TODO: use full URI since http 1.1 require it
             header("Location: {$message}");
         } else {
             PWELogger::warn("Cannot send headers to redirect to %s", $message);
         }
     }
 }
Пример #7
0
 /**
  * функция находит в массиве узлов атрибут с именем
  * $name и значением этого атрибута $val и возвращает его индекс
  * @param $nodes array массив узлов для поиска
  * @param $name string имя атрибута
  * @param $val string значение атрибута
  * @return integer Индекс найденного узла. Eсли ничего не найдено - возвращаем -1
  */
 public static function findNodeWithAttributeValue(&$nodes, $name, $val)
 {
     $cnt = sizeof($nodes ? $nodes : array());
     for ($k = 0; $k < $cnt; $k++) {
         $matches = $nodes[$k]['!a'][$name] == $val;
         $nullMatches = $val === null && !isset($nodes[$k]['!a'][$name]);
         if ($matches || $nullMatches) {
             return $k;
         }
     }
     PWELogger::debug("%s=%s not found in xml data", $name, $val);
     return -1;
 }
Пример #8
0
 /**
  * @param \PWE\Core\PWECore $pwe
  * @return PWEUserAuthController
  */
 public static function getAuthControllerInstance(PWECore $pwe)
 {
     try {
         $node = $pwe->getNode();
     } catch (HTTP5xxException $e) {
         PWELogger::warn('Failed to get pwe node in auth controller: %s', $e);
     }
     if (!isset($node['!i']['authController']) || $node['!i']['authController'] == 'none') {
         return new NoneAuthController($pwe);
     }
     if ($node['!i']['authController'] != NoneAuthController::getClassName()) {
         PWELogger::info('Page requires auth: %s', $node['!i']['authController']);
     }
     return new $node['!i']['authController']($pwe);
 }
Пример #9
0
 public function test_directory_sorted()
 {
     $pwe = new UnitTestPWECore();
     $pwe->setURL('/');
     $tmp = $pwe->getTempDirectory();
     $pwe->setRootDirectory($tmp);
     $pwe->setTempDirectory($tmp);
     PWELogger::info("Create dir " . $tmp);
     file_put_contents($tmp . '/first', time());
     file_put_contents($tmp . '/second', time());
     PWELogger::debug("File 1 " . file_get_contents($tmp . '/first'));
     PWELogger::debug("File 2 " . file_get_contents($tmp . '/second'));
     $node =& $pwe->getNode();
     $node['!a']['files_base'] = '.';
     $obj = new FileDownloads($pwe);
     $res = $obj->getDirectoryBlock('.');
     PWELogger::debug("DIR: " . $res);
     $this->assertGreaterThan(strpos($res, 'second'), strpos($res, 'first'));
 }
Пример #10
0
 public function testProcess()
 {
     $pwe = new UnitTestPWECore();
     copy(__DIR__ . '/preprocess.tpl', $pwe->getTempDirectory() . '/test.tpl');
     $obj = new CSSJSPreprocessor($pwe);
     $obj->preprocess($pwe->getTempDirectory(), $pwe->getTempDirectory());
     $test_tpl = file_get_contents($pwe->getTempDirectory() . '/test.tpl');
     $pwe_js = file_get_contents($pwe->getTempDirectory() . '/pwe.js');
     $pwe_css = file_get_contents($pwe->getTempDirectory() . '/pwe.css');
     PWELogger::debug("TPL: {$test_tpl}");
     PWELogger::debug("JS: {$pwe_js}");
     PWELogger::debug("CSS: {$pwe_css}");
     $this->assertContains("do_process_css", $pwe_css);
     $this->assertNotContains("not_process_css", $pwe_css);
     $this->assertContains("not_process_css", $test_tpl);
     $this->assertNotContains("do_process_css", $test_tpl);
     $this->assertContains("do_process_js", $pwe_js);
     $this->assertNotContains("not_process_js", $pwe_js);
     $this->assertContains("not_process_js", $test_tpl);
     $this->assertNotContains("do_process_js", $test_tpl);
 }
Пример #11
0
 public function process()
 {
     $eg_node = $this->PWE->getNode();
     $shown = false;
     foreach ($eg_node['!a'] as $attr => $value) {
         if (strpos($attr, 'tpl') === false) {
             continue;
         }
         if (!is_file($value)) {
             PWELogger::warn("File not found: %s", $value);
             throw new HTTP4xxException("This page is not ready yet", HTTP4xxException::NOT_FOUND);
         }
         $part = substr($attr, strlen("tpl_"));
         PWELogger::debug("TPL File: %s / %s", $part, $value);
         $smarty = $this->PWE->getSmarty();
         $smarty->setTemplateFile($value);
         $this->PWE->addContent($smarty, $part);
         $shown = true;
     }
     if (!$shown) {
         throw new HTTP4xxException("No tpl files set", HTTP4xxException::NOT_FOUND);
     }
 }
Пример #12
0
 private function preprocess_file_gen($filename, $dst, $tagType, $ext)
 {
     $startTag = "<{$tagType} ";
     $endTag = "</{$tagType}>";
     $orig = file_get_contents($filename);
     $origSize = strlen($orig);
     $result = "";
     $pos = 0;
     $prevPos = 0;
     while (($pos = strpos($orig, $startTag, $pos)) !== false) {
         $pos_end = strpos($orig, $endTag, $pos);
         if ($pos_end !== FALSE) {
             $result .= substr($orig, $prevPos, $pos - $prevPos);
             $cand = substr($orig, $pos, $pos_end - $pos + strlen($endTag));
             $marker = $this->getPreprocessMarker($cand, $tagType);
             if ($marker) {
                 PWELogger::info("Found block to write into: %s%s", $marker, $ext);
                 $dst_file = $dst . '/' . $marker . $ext;
                 $inner = $this->getInner($cand, $filename);
                 if ($inner) {
                     file_put_contents($dst_file, "/* {$filename} */\n" . $inner . "\n\n", FILE_APPEND);
                 }
                 $pos += strlen($cand);
             }
         }
         $prevPos = $pos;
         $pos++;
         if ($pos > $origSize) {
             break;
         }
     }
     $result .= substr($orig, $prevPos, strlen($orig) - $prevPos);
     if ($result != $orig) {
         copy($filename, $filename . $ext . ".bak");
         file_put_contents($filename, $result);
     }
 }
Пример #13
0
 function __construct($message, $code, \Exception $previous = NULL)
 {
     parent::__construct($message, $code, $previous);
     PWELogger::debug("Exception %s: %s", $code, $code == 200 ? strlen($message) . " bytes to display" : $message);
 }
Пример #14
0
 private function detectSubdirectory()
 {
     $docroot = explode(DIRECTORY_SEPARATOR, $_SERVER['DOCUMENT_ROOT']);
     $script_dir = explode(DIRECTORY_SEPARATOR, dirname($_SERVER['SCRIPT_FILENAME']));
     foreach ($docroot as $k => $docroot_item) {
         if ($script_dir[$k] != $docroot_item) {
             PWELogger::warn("SCRIPT_FILENAME points outside of DOCUMENT_ROOT");
             return;
         } else {
             if (strlen($docroot_item)) {
                 unset($script_dir[$k]);
             }
         }
     }
     $this->baseDirectory = implode('/', $script_dir);
     if (strlen($this->baseDirectory)) {
         $this->baseDirectory = str_replace('\\', '/', $this->baseDirectory);
         foreach (explode('/', $this->baseDirectory) as $k => $v) {
             if ($k) {
                 unset($this->URLArray[$k]);
             }
         }
         $this->URLArray = array_values($this->URLArray);
     }
 }
Пример #15
0
 public function run()
 {
     $this->setRegistryFile($this->PWE->getModulesManager()->getRegistryFile());
     PWELogger::debug("Dumping config");
     $this->loadRegistry();
     $this->xml_as_options($this->registryArray);
 }
Пример #16
0
 /**
  *  Jump to first child feature
  */
 private function jumpToFirstChild()
 {
     $eg_node = $this->getNode();
     if (isset($eg_node['!a']['class']) || sizeof($this->URL->getParamsAsArray()) || !isset($eg_node['!c']['url'])) {
         return;
     }
     foreach ($eg_node['!c']['url'] as $v) {
         PWELogger::info('Jump To First Сhild: %s', $v['!a']['link']);
         $jumpTo = $v['!a']['link'] . '/';
         if (isset($_SERVER["QUERY_STRING"]) && strlen($_SERVER["QUERY_STRING"])) {
             $jumpTo .= '?' . $_SERVER["QUERY_STRING"];
         }
         throw new HTTP3xxException($jumpTo, HTTP3xxException::REDIRECT);
     }
 }
Пример #17
0
 public function run()
 {
     // prevent from interrupting the long upgrade
     set_time_limit(0);
     // have to add j:c:r: from index.php
     $opts = $this->getOpts();
     PWELogger::debug("Opts", $opts);
     if (!$opts["m"] || !$opts["p"]) {
         throw new \InvalidArgumentException("Both -m and -p options required");
     }
     $DB = self::getConnection($this->PWE, true, $opts["a"]);
     $this->processDBUpgrade($DB, $opts["m"], $opts["p"]);
 }
Пример #18
0
Файл: cfg.php Проект: undera/pwe
<?php

use PWE\Core\PWELogger;
use PWE\Core\PWEAutoloader;
header('Server: Apache');
header('X-Powered-By: PWE');
$root = str_replace('\\', '/', __DIR__);
PWELogger::setLevel(PWELogger::WARNING);
$PWECore->setStaticDirectory($root . '/img');
$PWECore->setStaticHref('/img');
$PWECore->setDataDirectory($root . '/dat');
$PWECore->setTempDirectory($root . '/dat/tmp');
PWEAutoloader::addSourceRoot($root . '/PWE');
Пример #19
0
<?php

if ($_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
    $level = \PWE\Core\PWELogger::DEBUG;
} else {
    $level = \PWE\Core\PWELogger::WARNING;
}
$logfile = sys_get_temp_dir() . "/pwe.log";
$tempdir = sys_get_temp_dir();
\PWE\Core\PWELogger::setStdErr($logfile);
\PWE\Core\PWELogger::setStdOut($logfile);
\PWE\Core\PWELogger::setLevel($level);
/** @var $PWECore PWE\Core\PWECore */
$PWECore->setRootDirectory(__DIR__);
$PWECore->setXMLDirectory($PWECore->getDataDirectory());
$PWECore->setTempDirectory($tempdir);
Пример #20
0
 /**
  * Should implement partial update
  * @param string|int $item
  * @param mixed $data
  */
 protected function handlePatch($item, $data)
 {
     PWELogger::debug($_SERVER['REQUEST_METHOD'] . ": %s %s", $item, $data);
     throw new HTTP5xxException('Not supported method for this call: ' . $_SERVER['REQUEST_METHOD'], HTTP5xxException::UNIMPLEMENTED);
 }
Пример #21
0
 /**
  * рекурсивная функция формирования кэш-файла
  * для иерархического массива, ускоряющего парсинг
  * @param array $harray
  * @param $index
  * @param bool $filename
  * @param bool|$md5_xml контрольная
  * @param array|bool $path
  * @param bool|$comment комментарий
  * @internal param \PWE\Utils\комментарий $comment , который будет добавлен в начало файла кэша
  * @internal param \PWE\Utils\контрольная $md5_xml сумма исходного ХМЛ-файла
  * @return bool|string
  */
 private function ArrayToPHP(array &$harray, $index, $filename = false, $md5_xml = false, $path = array(), $comment = false)
 {
     $result = '';
     // цикл по типам узлов
     foreach ($harray as $ek => $ev) {
         $result .= $index . "'{$ek}'=>array(\n";
         // цикл по узлам
         foreach ($ev as $nk => $nv) {
             $result .= $index . "\t{$nk}=>array(\n";
             // attributes
             $result .= $index . "\t\t'!a'=>array(";
             foreach ($nv['!a'] as $ak => $av) {
                 $result .= "'{$ak}'=>\"" . $this->escapeCacheValue($av) . "\", ";
             }
             $result .= "),\n";
             // value
             $result .= $index . "\t\t'!v'=>\"" . $this->escapeCacheValue($nv['!v']) . '",' . "\n";
             // parent
             if (sizeof($path)) {
                 $result .= $index . "\t\t'!p'=>&\$arr";
                 foreach ($path as $k => $v) {
                     $result .= "['{$k}'][{$v}]";
                 }
                 $result .= ",\n";
             }
             // children
             if (isset($nv['!c'])) {
                 $newpath = $path;
                 $newpath[$ek] = $nk;
                 $result .= $index . "\t'!c'=>array(\n" . $this->ArrayToPHP($nv['!c'], $index . "\t\t", false, false, $newpath) . "),";
             }
             $result .= $index . "\t),\n";
         }
         $result .= $index . "),\n";
     }
     // сохраняем файлик
     if ($filename) {
         $f = fopen($filename, 'w+');
         if ($f) {
             $res = "<?php // {$comment}\n";
             $res .= "\$arr=array();\n";
             $res .= "\$arr=array(\n{$result});\n\n";
             $res .= '$md5_cache="' . $md5_xml . '"; // checksum' . "\n" . '?' . '>';
             fputs($f, $res);
             fclose($f);
         } else {
             PWELogger::warn('Unable to save file: %s', $filename);
         }
         return true;
     }
     // возврат из рекурсивных функций
     return $result;
 }
Пример #22
0
    $PWECore = new PWECore();
    PWEAutoloader::setPWE($PWECore);
    $uri = $_SERVER['REDIRECT_URL'] ? $_SERVER['REDIRECT_URL'] : $_SERVER['REQUEST_URI'];
    $started = microtime(true);
    try {
        require_once dirname($_SERVER['SCRIPT_FILENAME']) . '/cfg.php';
        echo $PWECore->process($uri);
        PWELogger::debug('Response headers: %s', headers_list());
    } catch (\Exception $e) {
        try {
            if ($e->getCode() >= 500 || $e->getCode() <= 100) {
                PWELogger::error('Exception occured at page %s: %s', $uri, $e);
            } elseif ($e->getCode() >= 400) {
                PWELogger::info('Exception occured at page %s: %s', $uri, $e);
            }
            $PWECore->sendHTTPHeader("Content-Type: text/html");
            $PWECore->sendHTTPStatusCode($e->getCode());
            echo $PWECore->getErrorPage($e);
        } catch (\Exception $e2) {
            echo "<textarea cols='100' rows='25' readonly='readonly'>";
            echo $e2->__toString();
            echo "</textarea><br>";
            echo "<p>Caused by:</p>";
            echo "<textarea cols='100' rows='25' readonly='readonly'>";
            echo $e->__toString();
            echo "</textarea><br>";
            die($e2->getMessage());
        }
    }
    PWELogger::info('Done %s %s in %s', php_sapi_name(), $uri, microtime(true) - $started);
}
Пример #23
0
 public function testInst()
 {
     PWELogger::debug("done");
 }
Пример #24
0
 public function testError_exc()
 {
     PWELogger::setStdErr("php://stdout");
     PWELogger::error("Errors are bad: %s", new ExceptionExpected());
     PWELogger::debug(new ExceptionExpected());
 }
Пример #25
0
 public function handleLogout()
 {
     PWELogger::debug('None logout');
 }
Пример #26
0
 /**
  * @param $node
  * @return array
  */
 private function getDirAndExt($node)
 {
     $dir = $node['!i']['wiki_dir'];
     $ext = $node['!i']['wiki_file_ext'] ?: "wiki";
     if ($dir[0] != DIRECTORY_SEPARATOR) {
         $dir = $this->PWE->getDataDirectory() . '/' . $dir;
     }
     PWELogger::debug("Wiki dir: %s", $dir);
     if (!is_dir($dir)) {
         throw new HTTP5xxException("Not configured wiki source dir, or it does not exists");
     }
     PWELogger::debug("Wiki dir: %s", $dir);
     return array($dir, $ext);
 }
Пример #27
0
 public function getFileBlock($orig_file, $comment)
 {
     $orig_file = FilesystemHelper::protectAgainsRelativePaths($orig_file);
     $basename = basename($orig_file);
     $file = $this->getRealFile($orig_file);
     if (!is_file($file)) {
         PWELogger::warn("Broken download: %s", $file);
         return '[broken download: ' . $basename . ']';
     }
     $size = FilesystemHelper::fsys_kbytes(filesize($file));
     $date = date('M d, Y', filemtime($file));
     $link = $this->link_base . '/' . $orig_file;
     $res = "<span class='file_download'>";
     $res .= "<a href='{$link}'><b>{$basename}</b></a>";
     $res .= ", <span class='filesize'>{$size}</span>";
     $res .= ", <span class='filedate'>{$date}</span>";
     $cnt = $this->getDownloadCount($file);
     if ($cnt) {
         $res .= ", <span class='count'>Download count: {$cnt}</span>";
     }
     $res .= "<br/><i>{$comment}</i></span>";
     return $res;
 }
Пример #28
0
 public function stopQuery()
 {
     PWELogger::debug('%s #%s finished ', $this->prefix, $this->count);
 }
Пример #29
0
 public function testProcess_github_small()
 {
     $PWE = new UnitTestPWECore();
     $PWE->setStructFile(__DIR__ . '/SimpleWiki.xml');
     $PWE->setURL('/github/GitHubMarkdownSmall/');
     $node =& $PWE->getNode();
     $node['!i']['wiki_dir'] = __DIR__;
     $obj = new SimpleWiki($PWE);
     $obj->process();
     $content = $PWE->getContent();
     PWELogger::debug("Rendered: %s", $content);
 }
Пример #30
0
 public function sendHTTPHeader($header, $replace = null, $http_response_code = null)
 {
     PWELogger::debug("Simulated header: %s, %s, %s", $header, $replace, $http_response_code);
 }