public function renderPairMulti(array $controls)
 {
     $rendered = parent::renderPairMulti($controls);
     $class = $this->getValue('control .buttons');
     $firstReplace = Nette\Utils\Strings::replace($rendered, '~(form-group">\\s*<div) class="~', "\\0{$class} ");
     return Nette\Utils\Strings::replace($firstReplace, '~(form-group">\\s*<div)>~', "\\1 class=\"{$class}\">");
 }
Ejemplo n.º 2
0
 /**
  * @param double|double[] $price
  * @param null|string     $units
  * @param int             $decimalLength
  *
  * @return string|string[]
  */
 public static function priceCreate($price, $units = NULL, $decimalLength = 2)
 {
     if (is_array($price)) {
         $out = [];
         foreach ($price as $v) {
             $out[] = static::priceCreate($v, $units, $decimalLength);
         }
         return $out;
     } else {
         $workPrice = floor(abs($price * pow(10, $decimalLength)));
         $workDecimalPrice = floor(abs($price * pow(10, $decimalLength + 1)));
         $integerPrice = floor($workPrice / pow(10, $decimalLength));
         $integerLength = strlen($integerPrice);
         $decimalPrice = Nette\Utils\Strings::padLeft(round(static::numberAt($workDecimalPrice, 0, $decimalLength + 1) / 10), $decimalLength, '0');
         $integerTernary = ceil($integerLength / 3);
         $outPrice = '';
         for ($i = $integerTernary - 1; $i >= 0; $i--) {
             if ($outPrice != "") {
                 $outPrice .= '.';
             }
             $outPrice .= Nette\Utils\Strings::padLeft(static::numberAt($integerPrice, $i * 3, 3), 3, '0');
         }
         $outPrice = Nette\Utils\Strings::replace($outPrice, ['~^[0]*~' => '']);
         return ($price < 0 ? '-' : '') . $outPrice . ',' . (in_array($decimalPrice, ['', '0']) ? '-' : $decimalPrice) . (is_null($units) ? '' : ' ' . $units);
     }
 }
Ejemplo n.º 3
0
 public static function formatRecordString($record, $formatString)
 {
     return Strings::replace($formatString, '#%[^%]*%#u', function ($m) use($record) {
         $m = Strings::trim($m[0], '%');
         return $m != '' ? $record[$m] : "%";
     });
 }
Ejemplo n.º 4
0
 /**
  * @param string|array $file
  * @param int $time
  * @param bool $debugMode
  *
  * @return string
  */
 public static function computeHash($file, $time, $debugMode)
 {
     $debug = $debugMode ? 1 : 0;
     $file = is_array($file) ? implode(',', $file) : $file;
     $md5Raw = md5("{$debug};{$file};{$time}", TRUE);
     $base64 = Strings::replace(base64_encode($md5Raw), '~\\W~');
     return Strings::substring(Strings::webalize($base64), 0, 8);
 }
 public function macroSet(MacroNode $node, PhpWriter $writer)
 {
     $parts = Strings::replace($node->args, '~(\\s*(=>|=)\\s*|\\s+)~', '~~~', 1);
     $parts = Strings::split($parts, '/~~~/');
     $variable = $parts[0];
     $rest = $parts[1];
     return $writer->write($variable . ' = %modify(' . $rest . ')');
 }
Ejemplo n.º 6
0
 /**
  * Formats view template file names.
  *
  * @param string $subMethod
  * @return array
  */
 protected function formatTemplateFiles($subMethod)
 {
     $controlName = $this->getReflection()->getShortName();
     $control = Strings::replace($controlName, '~Control$~');
     $dir = dirname($this->getReflection()->getFileName());
     $dir = is_dir("{$dir}/templates") ? $dir : dirname($dir);
     $view = $subMethod ?: 'default';
     return ["{$dir}/templates/{$control}/{$view}.latte", "{$dir}/templates/{$control}.{$view}.latte"];
 }
Ejemplo n.º 7
0
 /**
  * Format given value for LIKE statement
  *
  * @param string $value
  * @param string $replacement
  * @return string
  */
 public static function formatLikeStatementWildcards($value, $replacement = '%')
 {
     // Escape wildcard character used in PDO
     $value = str_replace($replacement, '\\' . $replacement, $value);
     // Replace asterisks
     $value = \Nette\Utils\Strings::replace($value, '~(?!\\\\)(.?)\\*~', '\\1' . $replacement);
     // Replace escaped asterisks
     return str_replace('\\*', '*', $value);
 }
Ejemplo n.º 8
0
 /**
  * 
  * @param string $word
  * @param string $genus (rod)
  * @param string $number (číslo - jednotné nebo množné)
  * @param string $case (pád)
  * @return string
  */
 public function inflect($word, $genus = 'n', $number = 's', $case = 'nom')
 {
     foreach ($this->dictionary as $key => $shapes) {
         if (Strings::match($word, $key) && isset($this->dictionary[$key][$genus][$number][$case])) {
             $inflectedWord = Strings::replace($word, $key, $shapes[$genus][$number][$case]);
             return $inflectedWord;
         }
     }
     return $inflectedWord;
 }
Ejemplo n.º 9
0
 /**
  * Invoke filter
  *
  * @param string code
  * @param WebLoader loader
  * @param string file
  * @return string
  */
 public function __invoke($code, \Lohini\WebLoader\WebLoader $loader, $file = NULL)
 {
     $regexp = '/@charset ["\']utf\\-8["\'];(\\n)?/i';
     $removed = Strings::replace($code, $regexp);
     // At least one charset was in the code
     if (Strings::length($removed) < Strings::length($code)) {
         $code = self::CHARSET . "\n" . $removed;
     }
     return $code;
 }
Ejemplo n.º 10
0
 /**
  * @param Github $github
  */
 protected function reformatMarkdownLinks(Github $github)
 {
     $github->content = Strings::replace($github->content, '#\\[(.*)\\]\\((.+)\\)#iU', function ($matches) use($github) {
         list($all, $title, $url) = $matches;
         if (!Validators::isUrl($url)) {
             $url = $github->linker->getBlobUrl($matches[2]);
         }
         return sprintf('[%s](%s)', $title, $url);
     });
 }
Ejemplo n.º 11
0
 /**
  * Formats column name.
  * @param  string
  * @return string
  */
 public function formatColumnName($key)
 {
     static $cache = array();
     $name =& $cache[$key];
     if ($name === NULL) {
         $name = Strings::replace($key, '#[A-Z]#', function ($match) {
             return '_' . strtolower($match[0]);
         });
     }
     return $name;
 }
Ejemplo n.º 12
0
 /**
  * @param string name of current render method, typically __METHOD__ (containing "ClassName::render")
  * @return void
  */
 protected function doRender($renderMethod)
 {
     $template = $this->getTemplate();
     $classFile = $this->getReflection()->getFileName();
     list(, $view) = Strings::match($renderMethod, '~::render(.*)\\z~');
     $templateFile = Strings::replace($classFile, '~(?<=/)(.+)\\.php\\z~i', function ($m) use($view) {
         return $m[1] . ($view ? ".{$view}" : '') . '.latte';
     });
     $template->setFile($templateFile);
     $template->render();
 }
Ejemplo n.º 13
0
 public function startup()
 {
     parent::startup();
     $this->template->addFilter("dicomString", function ($text) {
         return \Nette\Utils\Strings::replace($text, "/\\^/", " ");
     });
     $this->template->addFilter("dicomDate", function ($text) {
         return date("d-m-Y", strtotime($text));
     });
     return;
 }
Ejemplo n.º 14
0
 /**
  * @param string $config
  * @return TokenIterator tokens
  * @throws ConfigException
  */
 public function lex($config)
 {
     $normalized = Strings::normalize($config);
     // remove meaningless leading spacing to simplify T_KEYWORD
     $simplified = Strings::replace($normalized, '~^\\s+~m', '');
     try {
         $tokens = $this->getTokenizer()->tokenize($simplified);
         return new TokenIterator($tokens);
     } catch (TokenizerException $e) {
         throw ConfigException::createFromLexerException($e);
     }
 }
Ejemplo n.º 15
0
 /**
  * Expands @fooModule/path/....
  * @static
  * @param $path
  * @param array $modules
  * @return string
  * @throws InvalidArgumentException
  */
 public function expandPath($path, $localPrefix = '')
 {
     if (substr($path, 0, 1) !== '@' || ($pos = strpos($path, 'Module')) === FALSE) {
         return $path;
     }
     $module = lcfirst(substr($path, 1, $pos - 1));
     if (!isset($this->modules[$module])) {
         throw new InvalidArgumentException("Module '{$module}' does not exist.");
     }
     $path = $this->modules[$module]['path'] . ($localPrefix ? '/' . $localPrefix : '') . substr($path, $pos + 6);
     return \Nette\Utils\Strings::replace($path, '~\\\\~', '/');
 }
Ejemplo n.º 16
0
 /**
  * @param  string
  * @param  array
  * @return array of [sql, params]
  */
 public function process($sql, $params)
 {
     $this->params = $params;
     $this->counter = 0;
     $this->remaining = array();
     $this->arrayMode = 'assoc';
     $sql = Nette\Utils\Strings::replace($sql, '~\'.*?\'|".*?"|\\?|\\b(?:INSERT|REPLACE|UPDATE)\\b|/\\*.*?\\*/|--[^\\n]*~si', array($this, 'callback'));
     while ($this->counter < count($params)) {
         $sql .= ' ' . $this->formatValue($params[$this->counter++]);
     }
     return array($sql, $this->remaining);
 }
Ejemplo n.º 17
0
class Pokladnicka extends Table
{
    /** @var string */
    protected $tableName = 'pokladnicka';
    /**
   * Vrati vsetky polozky v poradi od najnovsej
   * @return \Nette\Database\Table\Selection */
    public function pokladnicka()
    {
        return $this->getTable()->order('created ASC');
    }
    /**
   * 
   * @param Nette\Utils\ArrayHash $values
 public function loadConfiguration()
 {
     $builder = $this->getContainerBuilder();
     $config = $this->getConfig($this->defaults);
     if (empty($config['url'])) {
         return;
     }
     $builder->addDefinition($this->prefix('client'))->setClass('Gitlab\\Client', [$config['url'] . '/api/v3/'])->setAutowired(TRUE)->addSetup('authenticate', [$config['token']]);
     if (empty($config['ci-url'])) {
         return;
     }
     $builder->addDefinition($this->prefix('ci.client'))->setClass('GitlabCi\\Client', [$config['ci-url'] . '/api/v1/'])->setAutowired(TRUE)->addSetup('authenticate', [$config['token'], Strings::replace($config['url'], '~(.*/)api/.*~', '\\1'), Client::AUTH_URL_TOKEN]);
 }
 public function orderSongs(Form $form)
 {
     $songsArray = $form->getValues();
     $songIds = [];
     foreach ($songsArray as $song => $selected) {
         if ($selected) {
             $songIds[] = Strings::replace($song, '~_~', '-');
         }
     }
     $amount = $this->pricePerSong * count($songIds);
     $address = $this->addressProvider->getFreeAddress();
     $this->queueManager->orderSongs($songIds, $amount, $address);
     $this->redirectUrl("bitcoin:{$address->getAddress()}?amount={$amount}");
 }
Ejemplo n.º 20
0
 public function match(Nette\Http\IRequest $httpRequest)
 {
     $url = $httpRequest->getUrl();
     $basePath = Strings::replace($url->getBasePath(), '/\\//', '\\/');
     $cleanPath = Strings::replace($url->getPath(), "/^{$basePath}/", '');
     $pathRegExp = '#' . preg_quote($this->prefix, '#') . '(' . implode('|', $this->availableResource) . ')/?$#';
     $matches = Strings::match($cleanPath, $pathRegExp);
     if (!$matches) {
         return NULL;
     }
     $presenter = self::path2presenter($matches[1]);
     $params = ['action' => $this->detectAction($httpRequest), 'query' => $this->readInput()];
     $request = new Request($presenter, $this->detectMethod($httpRequest), $params, $httpRequest->getPost());
     return $request;
 }
Ejemplo n.º 21
0
    public function filter(\Nette\Latte\MacroNode $node, $writer)
    {
        $path = $node->tokenizer->fetchWord();
        $params = $writer->formatArray();
        $path = $this->moduleHelpers->expandPath($path, 'Resources/public');
        $path = \Nette\Utils\Strings::replace($path, '~\\\\~', '/');
        if (!$this->debugMode) {
            $less = new \lessc();
            $file = new \SplFileInfo($path);
            $targetFile = $file->getBasename() . '-' . md5($path . filemtime($path)) . '.css';
            $targetDir = $this->wwwCacheDir . '/less';
            $target = $targetDir . '/' . $targetFile;
            $targetUrl = substr($target, strlen($this->wwwDir));
            if (!file_exists($targetDir)) {
                umask(00);
                mkdir($targetDir, 0777, true);
            }
            $less->compileFile($path, $target);
            return '$control->getPresenter()->getContext()->getService("assets.assetManager")->addStylesheet("' . $targetUrl . '", ' . $params . '); ';
        } else {
            return '
				$_less_file = new \\SplFileInfo("' . $path . '");
				$_less_targetFile = $_less_file->getBasename() .  \'-\' . md5(\'' . $path . '\') . \'-\' . md5(\'' . $path . '\' . filemtime("' . $path . '")) . \'.css\';
				$_less_targetDir = \'' . $this->wwwCacheDir . '/less\';
				$_less_target = $_less_targetDir  . \'/\' . $_less_targetFile;
				$_less_targetUrl = substr($_less_target, strlen(\'' . $this->wwwDir . '\'));

				if (!file_exists($_less_target)) {
					$_less = new \\lessc();
					if (!file_exists($_less_targetDir)) {
						umask(0000);
						mkdir($_less_targetDir, 0777, true);
					}

					// Remove old files
					foreach (\\Nette\\Utils\\Finder::findFiles($_less_file->getBasename() . \'-\' . md5(\'' . $path . '\') . \'-*\')->from($_less_targetDir) as $_less_old) {
						unlink($_less_old->getPathname());
					}

					$_less->compileFile(\'' . $path . '\', $_less_target);
				}

				$control->getPresenter()->getContext()->getService("assets.assetManager")->addStylesheet($_less_targetUrl, ' . $params . ');
			';
        }
    }
Ejemplo n.º 22
0
 /**
  * @param  array
  * @return array of [sql, params]
  */
 public function process($params)
 {
     $this->params = $params;
     $this->counter = 0;
     $this->remaining = array();
     $this->arrayMode = 'assoc';
     $res = array();
     while ($this->counter < count($params)) {
         $param = $params[$this->counter++];
         if ($this->counter === 2 && count($params) === 2 || !is_scalar($param)) {
             $res[] = $this->formatValue($param);
         } else {
             $res[] = Nette\Utils\Strings::replace($param, '~\'.*?\'|".*?"|\\?|\\b(?:INSERT|REPLACE|UPDATE|WHERE|HAVING|ORDER BY|GROUP BY)\\b|/\\*.*?\\*/|--[^\\n]*~si', array($this, 'callback'));
         }
     }
     return array(implode(' ', $res), $this->remaining);
 }
Ejemplo n.º 23
0
 /**
  * Send error to image
  *
  * @param \Nette\Http\IResponse $response
  * @param string|\Exception $error
  */
 private function sendError(HttpResponse $response, $error, $width, $height)
 {
     $response->setCode(HttpResponse::S500_INTERNAL_SERVER_ERROR);
     $response->setContentType('image/gif');
     if (!$error instanceof \Exception) {
         $response->setHeader('X-Imager-Error-Message', $error);
     } else {
         $response->setHeader('X-Imager-Error-Message', get_class($error) . ': ' . $error->getMessage());
         // detailed information only in debug mode
         if ($this->factory->getDebugger()) {
             $response->setHeader('X-Imager-Error-File', $error->getFile() . ' (' . $error->getLine() . ')');
             $trace = $error->getTraceAsString();
             $trace = Strings::replace($trace, '~[\\n|\\n\\r]~', '>>>');
             $response->setHeader('X-Imager-Error-Trace', $trace);
         }
     }
     $this->factory->sendErrorImage($width, $height);
 }
Ejemplo n.º 24
0
 /**
  * @param  string
  * @param  array
  * @return array of [sql, params]
  */
 public function process($sql, $params)
 {
     $this->params = $params;
     $this->counter = 0;
     $this->remaining = array();
     $cmd = strtoupper(substr(ltrim($sql), 0, 6));
     // detect array mode
     $this->arrayMode = $cmd === 'INSERT' || $cmd === 'REPLAC' ? 'values' : 'assoc';
     /*~
     			\'.*?\'|".*?"|   ## string
     			\?               ## placeholder
     		~xs*/
     $sql = Nette\Utils\Strings::replace($sql, '~\'.*?\'|".*?"|\\?~s', array($this, 'callback'));
     while ($this->counter < count($params)) {
         $sql .= ' ' . $this->formatValue($params[$this->counter++]);
     }
     return array($sql, $this->remaining);
 }
 /**
  * Parse search query.
  *
  * @param  string
  * @return array associative array with keys 'query' and 'tags'
  */
 public function parseQuery($input)
 {
     // normalize input
     $input = Strings::lower(Strings::trim($input));
     $input = Strings::replace($input, '/\\s+/', ' ');
     // extract tags
     $matches = Strings::matchAll($input, '/(?<=^|\\s)tag:\\s*(?<tag_list>[\\pL\\d_-]+(?:\\s*,\\s*(?&tag_list))?)/u');
     $tags = array();
     $query = $input;
     foreach ($matches as $m) {
         $tmp = Strings::split($m['tag_list'], '/\\s*,\\s*/');
         $tmp = array_map('Nette\\Utils\\Strings::webalize', $tmp);
         $tmp = array_unique($tmp);
         $tags = array_merge($tags, $tmp);
         $query = str_replace($m[0], '', $query);
     }
     $query = Strings::trim($query) ?: null;
     return array('query' => $query, 'tags' => $tags);
 }
Ejemplo n.º 26
0
 /**
  * Expands @foo/path/....
  *
  * @param string $path
  * @param string|null $localPrefix
  * @return string
  */
 public function expandPath($path, $localPrefix = '')
 {
     $path = Strings::replace($path, '~\\\\~', '/');
     if (substr($path, 0, 1) !== '@') {
         return $path;
     }
     $pos = strpos($path, '/');
     if ($pos) {
         $package = substr($path, 1, $pos - 1);
     } else {
         $package = substr($path, 1);
     }
     $package = str_replace('.', '/', $package);
     if (!isset($this->packages[$package])) {
         throw new InvalidArgumentException(sprintf('Package \'%s\' does not exist.', $package));
     }
     $path = $this->packages[$package]['path'] . ($localPrefix ? '/' . $localPrefix : '') . ($pos ? substr($path, $pos) : '');
     return Strings::replace($path, '~\\\\~', '/');
 }
Ejemplo n.º 27
0
 /**
  * @param string|int
  * @return boolean
  */
 public static function isCreditCard($number)
 {
     if (strlen($s = Nette\Utils\Strings::replace($number, '([ -])', '')) !== 16) {
         return FALSE;
     }
     $s = str_split($s);
     for ($i = 1; $i <= 15; $i += 2) {
         $digits[$i] = $s[$i - 1] * 2;
         $digits[$i + 1] = $s[$i];
     }
     $splitAndSum = function ($string) {
         $int = 0;
         foreach (str_split($string) as $i) {
             $int += $i;
         }
         return $int;
     };
     return $splitAndSum(implode('', $digits)) % 10 === 0;
 }
Ejemplo n.º 28
0
 protected function formatSqls($message)
 {
     $message = Nette\Utils\Strings::replace($message, "~((?:CREATE|ALTER|DROP)\\s+TABLE|(?:DROP|CREATE)\\s+INDEX)[^;]+;~i", function (array $match) {
         $output = Nette\Utils\Strings::replace($match[0], '~(?<=\\b)([^\\s]*[a-z]+[^\\s]*)(?=\\b)~', function ($id) {
             return '<info>' . $id[0] . '</info>';
         });
         $output = Nette\Utils\Strings::replace($output, '~(?<=\\b)(CREATE|ALTER|DROP|TABLE|INDEX|ADD|CHANGE|PRIMARY\\s+KEY|UNIQUE|CONSTRAINT|FOREIGN\\s+KEY|REFERENCES|COMMENT|ENGINE)(?=\\b)~', function ($id) {
             return '<fg=cyan>' . $id[0] . '</fg=cyan>';
         });
         return $output;
     });
     $message = Nette\Utils\Strings::replace($message, '~(?<=\\b)(INSERT|UPDATE|SELECT|DELETE|INTO|VALUES|ON\\s+DUPLICATE\\s+KEY\\s+UPDATE|SET|FROM|JOIN|LEFT|RIGHT|INNER|OUTER|NATURAL|CROSS|FULL|ON|WHERE|GROUP\\s+BY|HAVING|ORDER\\s+BY|LIMIT|OFFSET|UNION)(?=\\b)~', function ($id) {
         return '<comment>' . $id[0] . '</comment>';
     });
     $message = Nette\Utils\Strings::replace($message, '~(?<=\\b)(AS|ASC|DESC|USING|DEFAULT|DISTINCT|AND|OR|IN|BETWEEN|IS|LIKE|NOT|NULL|ALL|ANY|SOME|EXISTS|SET\\s+NULL|AUTO_INCREMENT|CASCADE|RESTRICT|INT|SMALLINT|TINYINT|NUMERIC|VARCHAR|DATETIME|TIMESTAMP|TEXT)(?=\\b)~', function ($id) {
         return '<fg=magenta>' . $id[0] . '</fg=magenta>';
     });
     return $message;
 }
 public function __construct($htmlPurifierCachePath)
 {
     $markdown = new \Michelf\MarkdownExtra();
     $htmlPurifierConfig = \HTMLPurifier_Config::createDefault();
     $htmlPurifierConfig->set('Cache.SerializerPath', $htmlPurifierCachePath);
     $htmlPurifier = new \HTMLPurifier($htmlPurifierConfig);
     $this->converter = function ($description) use($markdown, $htmlPurifier) {
         $description = Strings::replace($description, '/([^#]*)(#{1,6})(.*)/', function ($matches) {
             return $matches[1] . (strlen($matches[2]) < 6 ? '#' : '') . $matches[2] . $matches[3];
         });
         $description = Strings::replace($description, '/```(php|neon|javascript|js|css|html|htmlcb|latte|sql)?\\h*\\v(.+?)\\v```/s', function ($matches) {
             $fshl = new Highlighter(new Html(), Highlighter::OPTION_TAB_INDENT);
             switch (strtolower($matches[1])) {
                 case 'php':
                     $fshl->setLexer(new Lexer\Php());
                     break;
                 case 'neon':
                     $fshl->setLexer(new Lexer\Neon());
                     break;
                 case 'javascript':
                 case 'js':
                     $fshl->setLexer(new Lexer\Javascript());
                     break;
                 case 'css':
                     $fshl->setLexer(new Lexer\Css());
                     break;
                 case 'html':
                 case 'htmlcb':
                 case 'latte':
                     $fshl->setLexer(new Lexer\Html());
                     break;
                 case 'sql':
                     $fshl->setLexer(new Lexer\Sql());
                     break;
                 default:
                     $fshl->setLexer(new Lexer\Minimal());
                     break;
             }
             return '<pre' . ($matches[1] ? ' class="src-' . strtolower($matches[1]) . '"' : '') . '><code>' . $fshl->highlight(ltrim($matches[2])) . '</code></pre>';
         });
         return $htmlPurifier->purify($markdown->transform($description));
     };
 }
Ejemplo n.º 30
0
    /**
	 * Add pokladnicka form component factory.
	 * @return Nette\Application\UI\Form
	 */
    protected function createComponentPokladnickaForm()
    {
        $form = new Form();
        $form->addProtection();
        $form->addText('suma', 'Suma:', 50, 80)->addRule(Form::FILLED, 'Suma musí byť zadaná!');
        $form->addText('ucel', 'Účel:', 50, 80)->addRule(Form::FILLED, 'Účel musí byť zadaný!');
        $vklad = array('1' => 'vklad', '-1' => 'výber');
        $form->addRadioList('vklad', 'Pohyb:', $vklad);
        $form->addHidden("id");
        $form->addHidden("created");
        $form->addSubmit('uloz', 'Ulož');
        $form->onSuccess[] = $this->pokladnickaFormSubmitted;
        return $form;
    }
    public function pokladnickaFormSubmitted($form)
    {
        $values = $form->getValues();