Exemple #1
0
	public static function install(NParser $parser)
	{
		$me = new self($parser);
		$me->addMacro('include', array($me, 'macroInclude'));
		$me->addMacro('includeblock', array($me, 'macroIncludeBlock'));
		$me->addMacro('extends', array($me, 'macroExtends'));
		$me->addMacro('layout', array($me, 'macroExtends'));
		$me->addMacro('block', array($me, 'macroBlock'), array($me, 'macroBlockEnd'));
		$me->addMacro('define', array($me, 'macroBlock'), array($me, 'macroBlockEnd'));
		$me->addMacro('snippet', array($me, 'macroBlock'), array($me, 'macroBlockEnd'));
		$me->addMacro('ifset', array($me, 'macroIfset'), 'endif');

		$me->addMacro('widget', array($me, 'macroControl')); // deprecated - use control
		$me->addMacro('control', array($me, 'macroControl'));

		$me->addMacro('@href', create_function('NMacroNode $node, $writer', 'extract(NCFix::$vars['.NCFix::uses(array('me'=>$me)).'], EXTR_REFS);
			return \' ?> href="<?php \' . $me->macroLink($node, $writer) . \' ?>"<?php \';
		'));
		$me->addMacro('plink', array($me, 'macroLink'));
		$me->addMacro('link', array($me, 'macroLink'));
		$me->addMacro('ifCurrent', array($me, 'macroIfCurrent'), 'endif'); // deprecated; use n:class="$presenter->linkCurrent ? ..."

		$me->addMacro('contentType', array($me, 'macroContentType'));
		$me->addMacro('status', array($me, 'macroStatus'));
	}
Exemple #2
0
    public static function initializePanel(Application $application)
    {
        Debugger::$blueScreen->addPanel(create_function('$e', 'extract(NCFix::$vars[' . NCFix::uses(array('application' => $application)) . '], EXTR_REFS);
			return $e ? NULL : array(
				\'tab\' => \'Nette Application\',
				\'panel\' => \'<h3>Requests</h3>\' . DebugHelpers::clickableDump($application->getRequests())
					. \'<h3>Presenter</h3>\' . DebugHelpers::clickableDump($application->getPresenter())
			);
		'));
    }
	public static function initialize(NApplication $application, IHttpRequest $httpRequest)
	{
		NDebugger::$bar->addPanel(new self($application->getRouter(), $httpRequest));
		NDebugger::$blueScreen->addPanel(create_function('$e', 'extract(NCFix::$vars['.NCFix::uses(array('application'=>$application)).'], EXTR_REFS);
			if ($e === NULL) {
				return array(
					\'tab\' => \'Nette Application\',
					\'panel\' => \'<h3>Requests</h3>\' . NDebugHelpers::clickableDump($application->getRequests())
						. \'<h3>Presenter</h3>\' . NDebugHelpers::clickableDump($application->getPresenter())
				);
			}
		'));
	}
Exemple #4
0
	/**
	 * Expands %node.word, %node.array, %node.args, %escape(), %modify(), %var, %raw in code.
	 * @param  string
	 * @return string
	 */
	public function write($mask)
	{
		$args = func_get_args();
		array_shift($args);
		$word = strpos($mask, '%node.word') === FALSE ? NULL : $this->argsTokenizer->fetchWord();
		$me = $this;
		$mask = NStrings::replace($mask, '#%escape(\(([^()]*+|(?1))+\))#', callback(create_function('$m', 'extract(NCFix::$vars['.NCFix::uses(array('me'=>$me)).'], EXTR_REFS);
			return $me->escape(substr($m[1], 1, -1));
		')));
		$mask = NStrings::replace($mask, '#%modify(\(([^()]*+|(?1))+\))#', callback(create_function('$m', 'extract(NCFix::$vars['.NCFix::uses(array('me'=>$me)).'], EXTR_REFS);
			return $me->formatModifiers(substr($m[1], 1, -1));
		')));

		return NStrings::replace($mask, '#([,+]\s*)?%(node\.word|node\.array|node\.args|var|raw)(\?)?(\s*\+\s*)?()#',
			callback(create_function('$m', 'extract(NCFix::$vars['.NCFix::uses(array('me'=>$me,'word'=> $word, 'args'=>& $args)).'], EXTR_REFS);
			list(, $l, $macro, $cond, $r) = $m;

			switch ($macro) {
			case \'node.word\':
				$code = $me->formatWord($word); break;
			case \'node.args\':
				$code = $me->formatArgs(); break;
			case \'node.array\':
				$code = $me->formatArray();
				$code = $cond && $code === \'array()\' ? \'\' : $code; break;
			case \'var\':
				$code = var_export(array_shift($args), TRUE); break;
			case \'raw\':
				$code = (string) array_shift($args); break;
			}

			if ($cond && $code === \'\') {
				return $r ? $l : $r;
			} else {
				return $l . $code . $r;
			}
		')));
	}
Exemple #5
0
    /**
     * Caches results of function/method calls.
     * @param  mixed
     * @param  array  dependencies
     * @return Closure
     */
    public function wrap($function, array $dp = NULL)
    {
        $cache = $this;
        return create_function('', 'extract(NCFix::$vars[' . NCFix::uses(array('cache' => $cache, 'function' => $function, 'dp' => $dp)) . '], EXTR_REFS);
			$key = array($function, func_get_args());
			$data = $cache->load($key);
			if ($data === NULL) {
				$data = $cache->save($key, Callback::create($function)->invokeArgs($key[1]), $dp);
			}
			return $data;
		');
    }
Exemple #6
0
	protected function tryDelimite($s)
	{
		$driver = $this->connection->getSupplementalDriver();
		return preg_replace_callback('#(?<=[\s,<>=]|^)[a-z_][a-z0-9_.]*(?=[\s,<>=]|$)#i', create_function('$m', 'extract(NCFix::$vars['.NCFix::uses(array('driver'=>$driver)).'], EXTR_REFS);
			return strtoupper($m[0]) === $m[0]
				? $m[0]
				: implode(\'.\', array_map(array($driver, \'delimite\'), explode(\'.\', $m[0])));
		'), $s);
	}
Exemple #7
0
    /**
     * Creates an iterator scaning directory for PHP files, subdirectories and 'netterobots.txt' files.
     * @return Iterator
     */
    private function createFileIterator($dir)
    {
        if (!is_dir($dir)) {
            return new ArrayIterator(array(new SplFileInfo($dir)));
        }
        $ignoreDirs = is_array($this->ignoreDirs) ? $this->ignoreDirs : preg_split('#[,\\s]+#', $this->ignoreDirs);
        $disallow = array();
        foreach ($ignoreDirs as $item) {
            if ($item = realpath($item)) {
                $disallow[$item] = TRUE;
            }
        }
        $iterator = Finder::findFiles(is_array($this->acceptFiles) ? $this->acceptFiles : preg_split('#[,\\s]+#', $this->acceptFiles))->filter(create_function('$file', 'extract(NCFix::$vars[' . NCFix::uses(array('disallow' => &$disallow)) . '], EXTR_REFS);
				return !isset($disallow[$file->getPathname()]);
			'))->from($dir)->exclude($ignoreDirs)->filter($filter = create_function('$dir', 'extract(NCFix::$vars[' . NCFix::uses(array('disallow' => &$disallow)) . '], EXTR_REFS);
				$path = $dir->getPathname();
				if (is_file("$path/netterobots.txt")) {
					foreach (file("$path/netterobots.txt") as $s) {
					if (preg_match(\'#^(?:disallow\\\\s*:)?\\\\s*(\\\\S+)#i\', $s, $matches)) {
							$disallow[$path . str_replace(\'/\', DIRECTORY_SEPARATOR, rtrim(\'/\' . ltrim($matches[1], \'/\'), \'/\'))] = TRUE;
						}
					}
				}
				return !isset($disallow[$path]);
			'));
        $filter(new SplFileInfo($dir));
        return $iterator;
    }
Exemple #8
0
 /**
  * Returns flattened array.
  * @param  array
  * @return array
  */
 public static function flatten(array $arr)
 {
     $res = array();
     array_walk_recursive($arr, create_function('$a', 'extract(NCFix::$vars[' . NCFix::uses(array('res' => &$res)) . '], EXTR_REFS); $res[] = $a; '));
     return $res;
 }
	/**
	 * Scan a directory for PHP files, subdirectories and 'netterobots.txt' file.
	 * @param  string
	 * @return void
	 */
	private function scanDirectory($dir)
	{
		if (is_dir($dir)) {
			$ignoreDirs = is_array($this->ignoreDirs) ? $this->ignoreDirs : NStrings::split($this->ignoreDirs, '#[,\s]+#');
			$disallow = array();
			foreach ($ignoreDirs as $item) {
				if ($item = realpath($item)) {
					$disallow[$item] = TRUE;
				}
			}
			$iterator = NFinder::findFiles(is_array($this->acceptFiles) ? $this->acceptFiles : NStrings::split($this->acceptFiles, '#[,\s]+#'))
				->filter(create_function('$file', 'extract(NCFix::$vars['.NCFix::uses(array('disallow'=>&$disallow)).'], EXTR_REFS);
					return !isset($disallow[$file->getPathname()]);
				'))
				->from($dir)
				->exclude($ignoreDirs)
				->filter($filter = create_function('$dir', 'extract(NCFix::$vars['.NCFix::uses(array('disallow'=>&$disallow)).'], EXTR_REFS);
					$path = $dir->getPathname();
					if (is_file("$path/netterobots.txt")) {
						foreach (file("$path/netterobots.txt") as $s) {
							if ($matches = NStrings::match($s, \'#^disallow\\\\s*:\\\\s*(\\\\S+)#i\')) {
								$disallow[$path . str_replace(\'/\', DIRECTORY_SEPARATOR, rtrim(\'/\' . ltrim($matches[1], \'/\'), \'/\'))] = TRUE;
							}
						}
					}
					return !isset($disallow[$path]);
				'));
			$filter(new SplFileInfo($dir));
		} else {
			$iterator = new ArrayIterator(array(new SplFileInfo($dir)));
		}

		foreach ($iterator as $entry) {
			$path = $entry->getPathname();
			if (!isset($this->files[$path]) || $this->files[$path] !== $entry->getMTime()) {
				$this->scanScript($path);
			}
		}
	}
	/**
	 * Formats PHP statement.
	 * @return string
	 */
	private function formatPhp($statement, $args, $self = NULL)
	{
		$that = $this;
		array_walk_recursive($args, create_function('&$val', 'extract(NCFix::$vars['.NCFix::uses(array('self'=>$self,'that'=> $that)).'], EXTR_REFS);
			list($val) = $that->normalizeEntity(array($val));

			if ($val instanceof NDIStatement) {
				$val = new NPhpLiteral($that->formatStatement($val, $self));

			} elseif ($val === \'@\' . NDIContainerBuilder::THIS_CONTAINER) {
				$val = new NPhpLiteral(\'$this\');

			} elseif ($service = $that->getServiceName($val, $self)) {
				$val = $service === $self ? \'$service\' : $that->formatStatement(new NDIStatement($val));
				$val = new NPhpLiteral($val, $self);
				}
		'));
		return NPhpHelpers::formatArgs($statement, $args);
	}
Exemple #11
0
    protected function tryDelimite($s)
    {
        $driver = $this->connection->getSupplementalDriver();
        return preg_replace_callback('#(?<=[^\\w`"\\[]|^)[a-z_][a-z0-9_]*(?=[^\\w`"(\\]]|$)#i', create_function('$m', 'extract(NCFix::$vars[' . NCFix::uses(array('driver' => $driver)) . '], EXTR_REFS);
			return strtoupper($m[0]) === $m[0] ? $m[0] : $driver->delimite($m[0]);
		'), $s);
    }
	/**
	 * Template factory.
	 * @param  string
	 * @param  callback
	 * @return ITemplate
	 */
	public function createTemplate($class = NULL, $latteFactory = NULL)
	{
		$template = $class ? new $class : new NFileTemplate;

		$template->setParameters($this->request->getParameters());
		$template->presenter = $this;
		$template->context = $context = $this->context;
		$url = $context->getByType('IHttpRequest')->getUrl();
		$template->baseUrl = rtrim($url->getBaseUrl(), '/');
		$template->basePath = rtrim($url->getBasePath(), '/');

		$template->registerHelperLoader('NTemplateHelpers::loader');
		$template->setCacheStorage($context->templateCacheStorage);
		$template->onPrepareFilters[] = create_function('$template', 'extract(NCFix::$vars['.NCFix::uses(array('latteFactory'=>$latteFactory,'context'=> $context)).'], EXTR_REFS);
			$template->registerFilter($latteFactory ? $latteFactory() : new NLatteFilter);
		');
		return $template;
	}
Exemple #13
0
    /**
     * Restricts the search by modified time.
     * @param  string  "[operator] [date]" example: >1978-01-23
     * @param  mixed
     * @return Finder  provides a fluent interface
     */
    public function date($operator, $date = NULL)
    {
        if (func_num_args() === 1) {
            // in $operator is predicate
            if (!preg_match('#^(?:([=<>!]=?|<>)\\s*)?(.+)$#i', $operator, $matches)) {
                throw new InvalidArgumentException('Invalid date predicate format.');
            }
            list(, $operator, $date) = $matches;
            $operator = $operator ? $operator : '=';
        }
        $date = DateTime53::from($date)->format('U');
        return $this->filter(create_function('$file', 'extract(NCFix::$vars[' . NCFix::uses(array('operator' => $operator, 'date' => $date)) . '], EXTR_REFS);
			return Finder::compare($file->getMTime(), $operator, $date);
		'));
    }
Exemple #14
0
    /**
     * Dumps variable.
     * @param  string
     * @return string
     */
    public static function clickableDump($dump, $collapsed = FALSE)
    {
        return '<pre class="nette-dump">' . preg_replace_callback('#^( *)((?>[^(\\r\\n]{1,200}))\\((\\d+)\\) <code>#m', create_function('$m', 'extract(NCFix::$vars[' . NCFix::uses(array('collapsed' => $collapsed)) . '], EXTR_REFS);
				return "$m[1]<a href=\'#\' rel=\'next\'>$m[2]($m[3]) "
					. (($m[1] || !$collapsed) && ($m[3] < 7)
					? \'<abbr>&#x25bc;</abbr> </a><code>\'
					: \'<abbr>&#x25ba;</abbr> </a><code class="nette-collapsed">\');
			'), self::htmlDump($dump)) . '</pre>';
    }
Exemple #15
0
 public static function log($message, $priority = self::INFO)
 {
     if (self::$logDirectory === FALSE) {
         return;
     } elseif (!self::$logDirectory) {
         throw new InvalidStateException('Logging directory is not specified in NDebugger::$logDirectory.');
     }
     if ($message instanceof Exception) {
         $exception = $message;
         $message = ($message instanceof FatalErrorException ? 'Fatal error: ' . $exception->getMessage() : get_class($exception) . ": " . $exception->getMessage()) . " in " . $exception->getFile() . ":" . $exception->getLine();
         $hash = md5($exception . (method_exists($exception, 'getPrevious') ? $exception->getPrevious() : (isset($exception->previous) ? $exception->previous : '')));
         $exceptionFilename = "exception-" . @date('Y-m-d-H-i-s') . "-{$hash}.html";
         foreach (new DirectoryIterator(self::$logDirectory) as $entry) {
             if (strpos($entry, $hash)) {
                 $exceptionFilename = $entry;
                 $saved = TRUE;
                 break;
             }
         }
     }
     self::$logger->log(array(@date('[Y-m-d H-i-s]'), $message, self::$source ? ' @  ' . self::$source : NULL, !empty($exceptionFilename) ? ' @@  ' . $exceptionFilename : NULL), $priority);
     if (!empty($exceptionFilename)) {
         $exceptionFilename = self::$logDirectory . '/' . $exceptionFilename;
         if (empty($saved) && ($logHandle = @fopen($exceptionFilename, 'w'))) {
             ob_start();
             ob_start(create_function('$buffer', 'extract(NCFix::$vars[' . NCFix::uses(array('logHandle' => $logHandle)) . '], EXTR_REFS); fwrite($logHandle, $buffer); '), 4096);
             self::$blueScreen->render($exception);
             ob_end_flush();
             ob_end_clean();
             fclose($logHandle);
         }
         return strtr($exceptionFilename, '\\/', DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR);
     }
 }
Exemple #16
0
	/**
	 * Returns syntax highlighted source code.
	 * @param  string
	 * @param  int
	 * @param  int
	 * @return string
	 */
	public static function highlightFile($file, $line, $count = 15, $vars = array())
	{
		if (function_exists('ini_set')) {
			ini_set('highlight.comment', '#998; font-style: italic');
			ini_set('highlight.default', '#000');
			ini_set('highlight.html', '#06B');
			ini_set('highlight.keyword', '#D24; font-weight: bold');
			ini_set('highlight.string', '#080');
		}

		$start = max(1, $line - floor($count * 2/3));

		$source = @file_get_contents($file); // intentionally @
		if (!$source) {
			return;
		}
		$sourcex = explode("\n", $source);
		$source = explode("\n", highlight_string($source, TRUE));
		$spans = 1;
		$out = $source[0]; // <code><span color=highlight.html>
		$source = explode('<br />', $source[1]);
		array_unshift($source, NULL);

		$i = $start; // find last highlighted block
		while (--$i >= 1) {
			if (preg_match('#.*(</?span[^>]*>)#', $source[$i], $m)) {
				if ($m[1] !== '</span>') {
					$spans++; $out .= $m[1];
				}
				break;
			}
		}

		$source = array_slice($source, $start, $count, TRUE);
		end($source);
		$numWidth = strlen((string) key($source));

		foreach ($source as $n => $s) {
			$spans += substr_count($s, '<span') - substr_count($s, '</span');
			$s = str_replace(array("\r", "\n"), array('', ''), $s);
			preg_match_all('#<[^>]+>#', $s, $tags);
			if ($n === $line) {
				$out .= sprintf(
					"<span class='highlight'>%{$numWidth}s:    %s\n</span>%s",
					$n,
					strip_tags($s),
					implode('', $tags[0])
				);
			} else {
				$out .= sprintf("<span class='line'>%{$numWidth}s:</span>    %s\n", $n, $s);
			}
		}
		$out .= str_repeat('</span>', $spans) . '</code>';

		$out = preg_replace_callback('#">\$(\w+)(&nbsp;)?</span>#', create_function('$m', 'extract(NCFix::$vars['.NCFix::uses(array('vars'=>$vars)).'], EXTR_REFS);
			return isset($vars[$m[1]])
				? \'" title="\' . str_replace(\'"\', \'&quot;\', strip_tags(NDebugHelpers::htmlDump($vars[$m[1]]))) . $m[0]
				: $m[0];
		'), $out);

		return $out;
	}
Exemple #17
0
	/**
	 * Caches results of function/method calls.
	 * @param  mixed
	 * @return NClosure
	 */
	public function wrap($function)
	{
		$cache = $this;
		return create_function('', 'extract(NCFix::$vars['.NCFix::uses(array('cache'=>$cache,'function'=> $function)).'], EXTR_REFS);
			$key = array($function, func_get_args());
			$data = $cache->load($key);
			if ($data === NULL) {
				$data = $cache->save($key, call_user_func_array($function, $key[1]));
			}
			return $data;
		');
	}