Exemplo n.º 1
0
 public function process()
 {
     $eg_node = $this->PWE->getNode();
     //var_dump($eg_node);
     if (!isset($eg_node['!a']['src'])) {
         throw new HTTP4xxException("File to display not specified", HTTP4xxException::NOT_FOUND);
     }
     if (!$this->isHTMfile($eg_node['!a']['src'])) {
         throw new HTTP4xxException("File is not HTML: " . $eg_node['!a']['src'], HTTP4xxException::PRECONDITION_FAILED);
     }
     // файл с содержимым
     $src = self::getHTMLDirectory($this->PWE) . '/' . FilesystemHelper::protectAgainsRelativePaths($eg_node['!a']['src']);
     // если таковой есть
     if (is_file($src)) {
         PWELogger::debug("HTML File: %s", $src);
         // показываем его
         $smarty = $this->PWE->getSmarty();
         $smarty->assign('content', file_get_contents($src));
         $smarty->setTemplateFile(__DIR__ . "/HTMLPage.tpl");
         $this->PWE->addContent($smarty);
     } else {
         // иначе пишем во внутренний лог
         // и культурно ругаемся
         PWELogger::warn("File not found: %s", $src);
         throw new HTTP4xxException("This page is not ready yet", HTTP4xxException::NOT_FOUND);
     }
 }
Exemplo n.º 2
0
 public function process()
 {
     try {
         $data = $this->getData();
     } catch (HTTP2xxException $e) {
         throw $e;
     } catch (HTTP3xxException $e) {
         throw $e;
     } catch (\Exception $e) {
         PWELogger::warn("Error processing API call: %s", $e);
         if ($e->getCode() >= 100 && $e->getCode() <= 999) {
             $this->PWE->sendHTTPStatusCode($e->getCode());
         } else {
             $this->PWE->sendHTTPStatusCode(HTTP5xxException::RUNTIME_ERROR);
         }
         $msg = $e->getMessage();
         if (!$e instanceof HTTP4xxException && !$e instanceof HTTP5xxException) {
             if (strrpos($msg, ':')) {
                 $msg = substr($msg, strrpos($msg, ':') + 1);
             }
         }
         $data = array("code" => $e->getCode(), "type" => get_class($e), "message" => $msg);
     }
     $smarty = $this->PWE->getSmarty();
     // TODO: maybe use caches
     $smarty->setTemplateFile(__DIR__ . '/json.tpl');
     $smarty->assign("data", $data);
     $this->PWE->sendHTTPHeader('Content-Type: application/json');
     $this->PWE->addContent($smarty);
 }
Exemplo n.º 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");
     }
 }
Exemplo n.º 4
0
 public function process()
 {
     $latest = $this->getLatestVersion();
     $resp = array("latest" => $latest, "needsUpgrade" => version_compare($latest, $_REQUEST['version'], '>'));
     \PWE\Core\PWELogger::warn("Check update: %s %s %s %s", $_REQUEST['version'], $resp['latest'], $resp['needsUpgrade'], $_REQUEST['installID']);
     $smarty = $this->PWE->getSmarty();
     $smarty->setTemplateFile(__DIR__ . '/dat/json.tpl');
     $smarty->assign("data", $resp);
     $this->PWE->addContent($smarty);
 }
Exemplo n.º 5
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);
         }
     }
 }
Exemplo n.º 6
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);
 }
Exemplo n.º 7
0
 public function preprocess($path, $dst)
 {
     PWELogger::warn("Preprocessing %s to %s", $path, $dst);
     $dit = new RecursiveDirectoryIterator($path, FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO);
     $rit = new RecursiveIteratorIterator($dit);
     /** @var $file \SplFileInfo */
     foreach ($rit as $file) {
         $filename = $file->getRealPath();
         if ($file->getExtension() != 'tpl' && $file->getExtension() != 'html') {
             //PWELogger::debug("Skip non-tpl: " . $filename);
             continue;
         }
         PWELogger::warn("Preprocessing %s", $filename);
         $this->preprocess_file_css($filename, $dst);
         $this->preprocess_file_js($filename, $dst);
     }
 }
Exemplo n.º 8
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);
     }
 }
Exemplo n.º 9
0
 protected function saveRegistry()
 {
     if (!$this->registryFile) {
         PWELogger::warn("No registry file set, won't try to save registry");
         return;
     }
     try {
         PWEXML::cleanEmptyNodes($this->registryArray['registry'][0]);
     } catch (PHPFatalException $e) {
         PWELogger::warn("Failed cleaning empty nodes: %s", $e);
     }
     PWELogger::info("Saving registry file: %s", $this->registryFile);
     $XML = new PWEXML($this->PWE->getTempDirectory());
     $XML->ArrayToFile($this->registryArray, $this->registryFile);
     $XML->FileToArray($this->registryFile, $this->registryArray);
 }
Exemplo n.º 10
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);
     }
 }
Exemplo n.º 11
0
 public function testWarning()
 {
     PWELogger::setStdErr("php://stdout");
     PWELogger::warn("Warn people");
 }
Exemplo n.º 12
0
 public function sendHTTPStatusCode($code)
 {
     if ($this->statusSent) {
         PWELogger::warn("Trying to send HTTP status more than once for code: %s", $code);
     }
     if (!preg_match("/^[12345][0-9][0-9]\$/", $code)) {
         $code = 500;
     }
     if (!headers_sent()) {
         $status = $_SERVER["SERVER_PROTOCOL"] . ' ' . $code;
         PWELogger::debug("HTTP Status header: %s", $status);
         header($status, true, $code);
     } else {
         PWELogger::warn("Cannot report status, headers has been sent");
     }
     $this->statusSent = true;
 }
Exemplo n.º 13
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;
 }
Exemplo n.º 14
0
 /**
  * @param $args
  * @param $ext
  * @param $dir
  * @return string
  */
 private function getRenderedPage($args, $ext, $dir)
 {
     if (pathinfo($args[0], PATHINFO_EXTENSION) != $ext) {
         $args[0] .= '.' . $ext;
     } else {
         throw new HTTP3xxException(substr($args[0], 0, strlen($args[0]) - strlen($ext) - 1));
     }
     $file = $dir . '/' . str_replace(':', DIRECTORY_SEPARATOR, $args[0]);
     $real_file = realpath($file);
     $pos = strpos($real_file, realpath($dir) . DIRECTORY_SEPARATOR);
     PWELogger::debug("Test path for sanity: %s ; %s ; %s", $file, $real_file, $pos);
     if ($pos === false) {
         PWELogger::warn("Possible injection attempt: %s", $file);
         throw new HTTP4xxException("Wrong wiki page specified", HTTP4xxException::NOT_FOUND);
     }
     PWELogger::info("Wiki file to show: %s", $file);
     if (!is_file($file)) {
         PWELogger::error("Not found wiki file: %s", $file);
         throw new HTTP4xxException("Wiki page not found", HTTP4xxException::NOT_FOUND);
     }
     $contents = $this->renderPage($file);
     return $contents;
 }
Exemplo n.º 15
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;
 }
Exemplo n.º 16
0
 public static function fsys_copydir($from, $to, $is_deep = true, $move = false)
 {
     if (!is_dir($from)) {
         PWELogger::warn("Source directory not exists for copy: %s", $from);
         return false;
     }
     PWELogger::debug("Copying %s to %s", $from, $to);
     if (strrchr($from, '/') != '/') {
         $from .= '/';
     }
     if (strrchr($to, '/') != '/') {
         $to .= '/';
     }
     $files = self::fsys_readdir($from, $is_deep);
     if (!is_dir($to)) {
         if (!self::fsys_mkdir($to)) {
             PWELogger::error("Unable to create destination directory: %s", $to);
             return false;
         }
         if (!is_dir(preg_replace('!/\\w+/$!', '/', $to))) {
             PWELogger::error("Unable to use destination directory: %s", $to);
             return false;
         }
     }
     if (!is_writable($to)) {
         PWELogger::error("Destination dir '%s' is not writable", $to);
         return false;
     }
     foreach ($files as $file => $is_dir) {
         if (!is_readable($from . $file)) {
             PWELogger::error("Source '%s.%s' is not readable", $from, $file);
             return false;
         }
         if ($move && !is_writable($from . $file)) {
             PWELogger::error("Source '%s.%s' is not writable for move", $from, $file);
             return false;
         }
     }
     $existed_files = self::fsys_readdir($to);
     $copied = true;
     foreach ($files as $path => $is_dir) {
         $newpath = $to . $path;
         $oldpath = $from . $path;
         if ($is_dir) {
             if ($is_deep && !is_dir($newpath)) {
                 $copied = self::fsys_mkdir($newpath);
                 if (!$copied) {
                     break;
                 }
             }
         } else {
             $copied = copy($oldpath, $newpath);
             PWELogger::debug("Copy file %s %s -> %s", $copied ? 'success' : 'FAILED', $oldpath, $newpath);
             if (!$copied && (!file_exists($newpath) || filesize($oldpath) > 0)) {
                 break;
             }
         }
     }
     if (!$copied) {
         PWELogger::info("Rolling back...");
         self::fsys_removedir($to, $is_deep, $existed_files);
         return false;
     }
     if ($move && !self::fsys_removedir($from, $is_deep)) {
         return false;
     }
     return true;
 }