コード例 #1
0
ファイル: HTMLPage.php プロジェクト: undera/pwe
 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);
     }
 }
コード例 #2
0
ファイル: PWEURL.php プロジェクト: undera/pwe
 private function recursiveNodeSearch(array $search_uri)
 {
     $link = reset($search_uri);
     $ix = PWEXMLFunctions::findNodeWithAttributeValue($this->node['!c']['url'], 'link', $link);
     if ($ix >= 0) {
         $this->URLArrayMatched[] = array_shift($search_uri);
         $inherited_attrs = $this->node['!i'];
         $this->node =& $this->node['!c']['url'][$ix];
         $this->node['!i'] = (isset($this->node['!a']) ? $this->node['!a'] : array()) + $inherited_attrs;
         if ($search_uri && isset($this->node['!c']['url'])) {
             $this->recursiveNodeSearch($search_uri);
             return;
         }
     }
     PWELogger::debug("Search: %s", $search_uri);
     if ($search_uri && isset($this->node['!c']['params'])) {
         $paramsNode =& $this->node['!c']['params'][0];
         PWELogger::debug("Params branch");
         $count = $paramsNode['!a']['count'];
         if (!$count) {
             $count = 1;
         }
         for ($n = 0; $search_uri && $n < $count; $n++) {
             $this->URLArrayParams[] = array_shift($search_uri);
         }
         $inherited_attrs = $this->node['!i'];
         $paramsNode['!i'] = (isset($paramsNode['!a']) ? $paramsNode['!a'] : array()) + $inherited_attrs;
         if ($search_uri && isset($paramsNode['!c']['url'])) {
             $this->node =& $paramsNode;
             $this->recursiveNodeSearch($search_uri);
             return;
         } else {
             $this->node['!i'] = $paramsNode['!i'];
         }
     }
     if (end($this->URLArray) && !$this->hadTrailingSlash) {
         if ($this->node['!i']['force_trailing_slash'] || !isset($this->node['!i']['force_trailing_slash'])) {
             if (!strstr(end($this->URLArray), '.')) {
                 $url = $this->URL . '/';
                 if ($_GET) {
                     $url .= '?' . http_build_query($_GET);
                 }
                 PWELogger::debug("Node attributes: %s", $this->node['!i']);
                 throw new HTTP3xxException($url, HTTP3xxException::PERMANENT);
             }
         }
     }
     // check params count
     if ($search_uri && isset($this->node['!i']['accept'])) {
         for ($n = 0; $search_uri && $n < $this->node['!i']['accept']; $n++) {
             $this->URLArrayParams[] = array_shift($search_uri);
         }
     }
     if (sizeof($search_uri)) {
         if (strlen(end($search_uri)) || sizeof($search_uri) > 1) {
             $this->failure = new HTTP4xxException("Requested page not found", HTTP4xxException::NOT_FOUND);
         }
     }
 }
コード例 #3
0
ファイル: CMDLineModulesManager.php プロジェクト: undera/pwe
 protected function loadRegistry($force = false)
 {
     if (is_file($this->registryFile)) {
         parent::loadRegistry();
     } else {
         PWELogger::debug("File not found: %s", $this->registryFile);
     }
 }
コード例 #4
0
ファイル: SmartyWrapper.php プロジェクト: undera/pwe
 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");
     }
 }
コード例 #5
0
ファイル: PWEUnitTests.php プロジェクト: undera/pwe
 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
ファイル: PWEXMLFunctions.php プロジェクト: undera/pwe
 /**
  * функция находит в массиве узлов атрибут с именем
  * $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;
 }
コード例 #7
0
ファイル: FileDownloads.php プロジェクト: undera/pwe
 public function getDirectoryBlock($subdir)
 {
     $fi = new FilesystemIterator($this->getRealFile($subdir));
     $res = array();
     /** @var $file \SplFileInfo */
     foreach ($fi as $file) {
         if (!self::filter_out_cnt($file)) {
             PWELogger::debug("Filtered out %s", $file);
             continue;
         }
         $res[$file->getMTime() . " " . $file->getBasename()] = $this->getFileBlock($subdir . '/' . $file->getBasename(), '') . "\n\n";
     }
     krsort($res);
     return implode("\n", $res);
 }
コード例 #8
0
ファイル: FileDownloadsTest.php プロジェクト: undera/pwe
 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'));
 }
コード例 #9
0
ファイル: CSSJSPreprocessorTest.php プロジェクト: undera/pwe
 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);
 }
コード例 #10
0
ファイル: SmartyPage.php プロジェクト: undera/pwe
 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);
     }
 }
コード例 #11
0
ファイル: PWEDoctrineLogger.php プロジェクト: undera/pwe
 public function stopQuery()
 {
     PWELogger::debug('%s #%s finished ', $this->prefix, $this->count);
 }
コード例 #12
0
ファイル: PWEModulesManager.php プロジェクト: undera/pwe
 public function run()
 {
     $this->setRegistryFile($this->PWE->getModulesManager()->getRegistryFile());
     PWELogger::debug("Dumping config");
     $this->loadRegistry();
     $this->xml_as_options($this->registryArray);
 }
コード例 #13
0
ファイル: SimpleWiki.php プロジェクト: undera/pwe
 /**
  * @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);
 }
コード例 #14
0
ファイル: PWEDoctrineWrapper.php プロジェクト: undera/pwe
 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"]);
 }
コード例 #15
0
ファイル: AbstractRESTCall.php プロジェクト: undera/pwe
 /**
  * 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);
 }
コード例 #16
0
ファイル: PWEXML.php プロジェクト: undera/pwe
 public function ArrayToFile(array &$a, $fname, $comment = false)
 {
     PWELogger::debug("Saving XML file: %s", $fname);
     if (!is_dir(dirname($fname))) {
         throw new InvalidArgumentException("Directory for saving not exists: " . dirname($fname));
     }
     $bak_dir = $this->use_cache ? $this->cache_dir : dirname($fname);
     $bak_file = $bak_dir . '/' . basename($fname) . '.' . posix_geteuid() . ".bak";
     if (is_file($bak_file)) {
         try {
             unlink($bak_file);
         } catch (PHPFatalException $e) {
             PWELogger::warn('Cannot remove old backup file: %s', $bak_file);
         }
     }
     if (is_file($fname)) {
         try {
             copy($fname, $bak_file);
         } catch (PHPFatalException $e) {
             PWELogger::warn("Unable to create backup file: %s", $bak_file);
         }
     }
     try {
         // записываем результат
         $f = fopen($fname, 'w+');
         if ($f && flock($f, LOCK_EX)) {
             // открыли и заблокировались?
             fputs($f, "<?xml version='1.0' encoding='UTF-8'?>");
             if ($comment) {
                 fputs($f, "\n\n<!-- {$comment} -->\n");
             }
             $this->generateNode($a, 0, $f);
             //обратимся к Дзену!
             fflush($f);
             flock($f, LOCK_UN);
             fclose($f);
         } else {
             throw new Exception("Unable to create new result file {$fname}");
         }
         PWELogger::debug("Checking written file results");
         $tmp_arr = array();
         $this->FileToArray($fname, $tmp_arr);
     } catch (Exception $e) {
         PWELogger::error("Resulting xml file is broken: %s", $fname, $e);
         if (is_file($bak_file)) {
             copy($bak_file, $fname);
         } else {
             if (is_file($fname)) {
                 unlink($fname);
             }
         }
         throw $e;
     }
     return true;
 }
コード例 #17
0
ファイル: HTTP5xxExceptionTest.php プロジェクト: undera/pwe
 public function testInst()
 {
     PWELogger::debug("done");
 }
コード例 #18
0
ファイル: PWELoggerTest.php プロジェクト: undera/pwe
 public function testError_exc()
 {
     PWELogger::setStdErr("php://stdout");
     PWELogger::error("Errors are bad: %s", new ExceptionExpected());
     PWELogger::debug(new ExceptionExpected());
 }
コード例 #19
0
ファイル: FilesystemHelper.php プロジェクト: undera/pwe
 public static function fsys_mkdir($dir)
 {
     $notexisted = false;
     $memo = false;
     $dir = str_replace('\\', '/', $dir);
     // корректируем слеши
     $cdir = $dir;
     $cdir = preg_replace('!/$!', '', $cdir);
     while ($cdir != '' && strpos($cdir, '/') !== false) {
         // проходимся по директоиям, проверяя их существование
         if (!is_dir($cdir)) {
             $memo[] = $cdir;
         } else {
             break;
         }
         $cdir = substr($cdir, 0, strrpos($cdir, '/'));
     }
     if ($memo) {
         // если есть несуществующие директории
         $memo = array_reverse($memo);
         foreach ($memo as $cdir) {
             if (!is_dir($cdir)) {
                 // еще раз проверим, на всякий случай
                 PWELogger::debug("Creating directory: %s", $cdir);
                 if (!mkdir($cdir)) {
                     // если создать директорию не вышло, то откат
                     if ($notexisted) {
                         self::fsys_removedir($notexisted);
                     }
                     PWELogger::debug('Failed to create directory %s', $cdir);
                     return false;
                 }
                 if (!$notexisted) {
                     $notexisted = $cdir;
                 }
             }
             if (!is_writable($cdir)) {
                 // если в директорию нельзя писать, то откат
                 if ($notexisted) {
                     self::fsys_removedir($notexisted);
                 }
                 PWELogger::debug('Directory not writable %s', $cdir);
                 return false;
             }
         }
     }
     return true;
 }
コード例 #20
0
ファイル: index.php プロジェクト: undera/pwe
        throw new InvalidArgumentException("Job class must implement PWECMDJob");
    }
    $job->run();
} else {
    require_once __DIR__ . '/PWE/Lib/Smarty/SmartyAssociative.php';
    require_once __DIR__ . '/PWE/Modules/Outputable.php';
    require_once __DIR__ . '/PWE/Core/PWEURL.php';
    require_once __DIR__ . '/PWE/Auth/PWEUserAuthController.php';
    $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>";
コード例 #21
0
ファイル: PWEHTTPException.php プロジェクト: undera/pwe
 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);
 }
コード例 #22
0
ファイル: NoneAuthController.php プロジェクト: undera/pwe
 public function handleLogout()
 {
     PWELogger::debug('None logout');
 }
コード例 #23
0
ファイル: UnitTestPWECore.php プロジェクト: undera/pwe
 public function sendHTTPHeader($header, $replace = null, $http_response_code = null)
 {
     PWELogger::debug("Simulated header: %s, %s, %s", $header, $replace, $http_response_code);
 }
コード例 #24
0
ファイル: SimpleWikiTest.php プロジェクト: undera/pwe
 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);
 }
コード例 #25
0
ファイル: PWECore.php プロジェクト: undera/pwe
 /**
  * Returns array of hierarchical arrays for site structure level $level.
  * Array chosen by current page path in site structure and current pages
  * have key 'selected' set to true
  * @param int $level level to return
  * @return array
  */
 public function getStructLevel($level)
 {
     PWELogger::debug("Building struct level %s", $level);
     $matched = $this->getURL()->getMatchedAsArray();
     if ($level > sizeof($matched)) {
         if (sizeof($this->getURL()->getParamsAsArray())) {
             $module = $this->getCurrentModuleInstance();
             if ($module instanceof MenuGenerator) {
                 PWELogger::debug('Building menu via current module');
                 return $module->getMenuLevel($level);
             }
         }
         return array();
     } else {
         $levelCount = 0;
         $current =& $this->siteStructure['url'];
         while ($levelCount <= $level) {
             $pos = PWEXMLFunctions::findNodeWithAttributeValue($current, 'link', $matched[$levelCount]);
             if ($pos < 0) {
                 //throw new HTTP5xxException("Something gone completely wrong with the structure");
                 break;
             }
             $current[$pos]['selected'] = true;
             //PWELogger::debug("I", $current[$pos]);
             if ($levelCount == $level) {
                 break;
             }
             $current =& $current[$pos]['!c']['url'];
             $levelCount++;
         }
         //PWELogger::debug("Final array: ", $current);
         return $current;
     }
 }