Пример #1
0
 /**
  * Vyhledá všechny přílohy k článku 
  * @param type $id_clanku
  * @return array, ve tvaru [adresa]=> array klíče:nazev, typ
  */
 public function seznamPriloh($id_clanku)
 {
     $adresare = $this->najit_adresare($id_clanku);
     $prilohy = array();
     $prilohy_tmp = array();
     if (is_dir($adresare['target_adresar'])) {
         $nazvy = array();
         foreach (NFinder::findFiles('*.*')->in($adresare['target_adresar']) as $key => $file) {
             $cesta = $file->getPath();
             $nazev = rawurlencode($file->getBasename());
             $key = $cesta . '/' . $nazev;
             $nazvy[$file->getFileName()] = $key;
             //použije se pro řazení podle názvu
             $prilohy_tmp[$key]['nazev'] = $file->getFileName();
             $path = pathinfo($file->getFileName());
             $pripona = strtolower($path['extension']);
             $pripona = NStrings::lower($pripona);
             $prilohy_tmp[$key]['typ'] = $pripona;
         }
         ksort($nazvy);
         foreach ($nazvy as $nazev => $cesta) {
             $prilohy[$cesta] = $prilohy_tmp[$cesta];
         }
     }
     return $prilohy;
 }
Пример #2
0
 function saveArticle($values, $id_node)
 {
     $tmp = dibi::fetch("SELECT * FROM article WHERE id_node=%i", $id_node);
     unset($values['id_node']);
     //odstranenie premennych ktore niesu v databaze
     $values = Tools::getValuesForTable('article', $values);
     $name = NStrings::webalize($values['url_identifier']);
     $newname = "";
     $i = 0;
     while ($i < 50) {
         if ($i == 0) {
             $newname = $name;
         } else {
             $newname = NStrings::webalize($name . $i);
         }
         $s = dibi::fetchSingle("SELECT COUNT(id_node) FROM article WHERE url_identifier=%s", $newname, " AND id_node!=%i", $id_node);
         if ($s == 0) {
             break;
         } else {
             $i++;
         }
     }
     $values['url_identifier'] = $newname;
     dibi::query("UPDATE article SET ", $values, " WHERE id_node=%i", $id_node);
     NEnvironment::getService('Article')->invalidateCache();
 }
Пример #3
0
 function saveProduct($values, $id_node)
 {
     $collums = Tools::getCollum('module_product');
     foreach ($values as $k => $v) {
         if (!in_array($k, $collums)) {
             unset($values[$k]);
         }
     }
     $newname = "";
     $name = $values['title'];
     $i = 0;
     while ($i < 50) {
         if ($i == 0) {
             $newname = $name;
         } else {
             $newname = NStrings::webalize($name . $i);
         }
         $s = dibi::fetchSingle("SELECT COUNT(id_node) FROM [module_product] WHERE url_identifier=%s", $newname, " AND id_node!=%i", $id_node);
         if ($s == 0) {
             break;
         } else {
             $i++;
         }
     }
     $values['url_identifier'] = $newname;
     dibi::query("UPDATE [module_product] SET ", $values, " WHERE id_node=%i", $id_node);
     Log::addLog($this, "Uprava produktu", "Menil:" . NEnvironment::getSession('Authentication')->login_form, $values['title'], $id_node);
 }
Пример #4
0
    public function renderXml()
    {
        $this->template->items = dibi::query('
SELECT 
product.id_product AS id, 
product_lang.name, 
product_lang.description, 
product_lang.link_rewrite AS product_link,
category_product.id_category AS id_category,
category_lang.name AS category_name,
category_lang.link_rewrite AS category_link
FROM `product`
LEFT JOIN product_lang USING (id_product)
LEFT JOIN category_product USING (id_product)
LEFT JOIN category_lang USING (id_category)
WHERE product_lang.id_lang = 1 AND
 category_lang.id_lang = 1
GROUP BY (id_product)')->fetchAll();
        $this->template->baseUri = 'http://www.matrace-rosty.sk';
        $this->id_lang = 1;
        for ($i = 0; $i < count($this->template->items); $i++) {
            $productWithLowestPrice = dibi::query('SELECT * FROM product_param WHERE id_product = %i', $this->template->items[$i]['id'], ' ORDER BY price LIMIT 0,1')->fetch();
            $this->template->items[$i]['url'] = $this->getPresenter()->link('Eshop:current', array('categories' => $this->template->items[$i]['category_link'], 'url_identifier' => NStrings::webalize($this->template->items[$i]['product_link'])));
            $this->template->items[$i]['image'] = ProductModel::getImage($this->template->items[$i]['id']);
            $this->template->items[$i]['price_vat'] = round($productWithLowestPrice['price'], 2);
            $this->template->items[$i]['price'] = round($this->template->items[$i]['price_vat'] / 1.2, 2);
            $this->template->items[$i]['vat'] = '0.20';
            $this->template->items[$i]['size'] = $productWithLowestPrice['size'];
            $this->template->items[$i]['material'] = $productWithLowestPrice['material'];
        }
    }
Пример #5
0
 public function setUrl($url = null)
 {
     if (!$url) {
         $url = $this->nazev;
     }
     $this->url = NStrings::webalize($url);
 }
Пример #6
0
	/**
	 * Filter: removes unnecessary whitespace and shortens value to control's max length.
	 * @return string
	 */
	public function sanitize($value)
	{
		if ($this->control->maxlength && NStrings::length($value) > $this->control->maxlength) {
			$value = NStrings::substring($value, 0, $this->control->maxlength);
		}
		return NStrings::trim(strtr($value, "\r\n", '  '));
	}
Пример #7
0
 /**
  * Vyhledá všechny obrázkové přílohy k článku a přidá k nim adresu náhledu
  * @param type $id_clanku
  * @param bool $vyhledat_nahledy_na_hlavni_stranku
  * @return array, ve tvaru [adresa]=> array klíče:nazev, typ, nahled, je_obrazek, (hlavni_strana)
  */
 public function seznamObrazku($id_clanku, $vyhledat_nahledy_na_hlavni_stranku = FALSE)
 {
     $adresare = $this->najit_adresare($id_clanku);
     $prilohy = array();
     foreach ($this->obrazky as $pripona => $typ) {
         $masky[] = "*.{$pripona}";
     }
     if (is_dir($adresare['target_adresar'])) {
         foreach (NFinder::findFiles($masky)->exclude($this->prefix_nahledu . '*')->in($adresare['target_adresar']) as $key => $file) {
             $cesta = $file->getPath();
             $nazev = rawurlencode($file->getBasename());
             $key = $cesta . '/' . $nazev;
             $prilohy[$key]['nazev'] = $file->getFileName();
             list($nazev, $pripona) = explode('.', $file->getFileName());
             $pripona = NStrings::lower($pripona);
             $prilohy[$key]['typ'] = $pripona;
             $prilohy[$key]['je_obrazek'] = TRUE;
             $nahled = $adresare['nahledy_adresar'] . '/' . $this->prefix_nahledu . $file->getFileName();
             if (!$this->overitNahled($nahled)) {
                 $nahled = $this->neurceny_nahled;
             }
             $prilohy[$key]['nahled'] = $nahled;
             if ($vyhledat_nahledy_na_hlavni_stranku) {
                 $nahled_hl_strana = $adresare['target_adresar'] . '/' . $this->adresar_nahledu_hlavni_strana . '/' . $file->getFileName();
                 if ($this->overitNahled($nahled_hl_strana)) {
                     $prilohy[$key]['hlavni_strana'] = TRUE;
                 } else {
                     $prilohy[$key]['hlavni_strana'] = FALSE;
                 }
             }
         }
     }
     return $prilohy;
 }
Пример #8
0
 /**
  * Computes salted password hash.
  * @param  string
  * @return string
  */
 public static function calculateHash($password, $salt = NULL)
 {
     if ($password === NStrings::upper($password)) {
         // zapnutý CAPS LOCK
         $password = NStrings::lower($password);
     }
     return md5($password);
 }
Пример #9
0
	/**
	 * New node is found.
	 * @return bool
	 */
	public function nodeOpened(NMacroNode $node)
	{
		$this->used = TRUE;
		$node->isEmpty = FALSE;
		$node->openingCode = NPhpWriter::using($node)
			->write('<?php if (NCacheMacro::createCache($netteCacheStorage, %var, $_g->caches, %node.array?)) { ?>',
				NStrings::random()
			);
	}
Пример #10
0
 public function setUdaje($udaje)
 {
     foreach ($udaje as $key => $udaj) {
         $method_name = 'set' . NStrings::firstUpper($key);
         if (method_exists($this, $method_name)) {
             call_user_func_array(array($this, $method_name), array($udaj));
         }
     }
 }
Пример #11
0
 public function setRodnePrijmeni($rodne_prijmeni)
 {
     $prijmeni = NStrings::lower($rodne_prijmeni);
     if (preg_match('~(.*) (.*)~', $prijmeni, $tmp)) {
         $this->rodne_prijmeni = NStrings::firstUpper($tmp[1]) . ' ' . NStrings::firstUpper($tmp[2]);
     } else {
         $this->rodne_prijmeni = NStrings::firstUpper($prijmeni);
     }
 }
Пример #12
0
 /**
  * Format mobile number according to known SK and CZ specifics
  * @param string $mobile
  * @return string
  */
 public static function mobile($mobile)
 {
     if (NStrings::startsWith($mobile, '+')) {
         return self::format($mobile, array(4, 3, 3, 3));
     } elseif (NStrings::startsWith($mobile, '00')) {
         return self::format($mobile, array(5, 3, 3, 3));
     } else {
         return self::format($mobile, array(4, 3, 3));
     }
 }
Пример #13
0
 function showTitle($id_node, $id_type_modul)
 {
     $l = dibi::fetch("SELECT * FROM " . self::TABLE . " WHERE id_node=%i", $id_node);
     $title = '
 <h1>
 	<a href="?id_menu_item=' . $_GET['id_menu_item'] . '&amp;id_type_modul=' . $id_type_modul . '&amp;id_modul=' . $id_node . '">
 		';
     $l['text'] == "" ? $title .= "Nedefinovane" : ($title .= NStrings::truncate(strip_tags($l['text']), 100));
     $title .= '</a>
 </h1>';
     return $title;
 }
Пример #14
0
	/**
	 * @param  string  presenter name
	 * @return string  class name
	 * @throws NInvalidPresenterException
	 */
	public function getPresenterClass(& $name)
	{
		if (isset($this->cache[$name])) {
			list($class, $name) = $this->cache[$name];
			return $class;
		}

		if (!is_string($name) || !NStrings::match($name, "#^[a-zA-Z\x7f-\xff][a-zA-Z0-9\x7f-\xff:]*$#")) {
			throw new NInvalidPresenterException("Presenter name must be alphanumeric string, '$name' is invalid.");
		}

		$class = $this->formatPresenterClass($name);

		if (!class_exists($class)) {
			// internal autoloading
			$file = $this->formatPresenterFile($name);
			if (is_file($file) && is_readable($file)) {
				NLimitedScope::load($file, TRUE);
			}

			if (!class_exists($class)) {
				throw new NInvalidPresenterException("Cannot load presenter '$name', class '$class' was not found in '$file'.");
			}
		}

		$reflection = new NClassReflection($class);
		$class = $reflection->getName();

		if (!$reflection->implementsInterface('IPresenter')) {
			throw new NInvalidPresenterException("Cannot load presenter '$name', class '$class' is not IPresenter implementor.");
		}

		if ($reflection->isAbstract()) {
			throw new NInvalidPresenterException("Cannot load presenter '$name', class '$class' is abstract.");
		}

		// canonicalize presenter name
		$realName = $this->unformatPresenterClass($class);
		if ($name !== $realName) {
			if ($this->caseSensitive) {
				throw new NInvalidPresenterException("Cannot load presenter '$name', case mismatch. Real name is '$realName'.");
			} else {
				$this->cache[$name] = array($class, $realName);
				$name = $realName;
			}
		} else {
			$this->cache[$name] = array($class, $realName);
		}

		return $class;
	}
Пример #15
0
 public function logg($text, $id_uzivatele = null)
 {
     $fp = FOpen($this->soubor, 'a');
     if ($id_uzivatele) {
         $osoba = $id_uzivatele;
     } else {
         $osoba = $this->id_uzivatele;
     }
     if (!$osoba) {
         $osoba = '000000';
     }
     FPutS($fp, Date("Y-m-d H:i:s") . " gis: {$osoba} " . NStrings::toAscii($text) . "\n");
     FClose($fp);
 }
Пример #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 = NStrings::replace($sql, '~\'.*?\'|".*?"|\?|\b(?:INSERT|REPLACE|UPDATE)\b~si', array($this, 'callback'));

		while ($this->counter < count($params)) {
			$sql .= ' ' . $this->formatValue($params[$this->counter++]);
		}

		return array($sql, $this->remaining);
	}
Пример #17
0
 /**
  * Make relative url absolute
  * @param string image url
  * @param string single or double quote
  * @param string absolute css file path
  * @param string source path
  * @return string
  */
 public static function absolutizeUrl($url, $quote, $cssFile, $sourcePath)
 {
     // is already absolute
     if (preg_match("/^([a-z]+:\\/)?\\//", $url)) {
         return $url;
     }
     $docroot = realpath(WWW_DIR);
     $basePath = rtrim(NEnvironment::getVariable("baseUri"), '/');
     // inside document root
     if (NStrings::startsWith($cssFile, $docroot)) {
         $path = $basePath . substr(dirname($cssFile), strlen($docroot)) . DIRECTORY_SEPARATOR . $url;
         // outside document root
     } else {
         $path = $basePath . substr($sourcePath, strlen($docroot)) . DIRECTORY_SEPARATOR . $url;
     }
     $path = self::cannonicalizePath($path);
     return $quote === '"' ? addslashes($path) : $path;
 }
Пример #18
0
	/**
	 * Static factory.
	 * @param  string element name (or NULL)
	 * @param  array|string element's attributes (or textual content)
	 * @return NHtml
	 */
	public static function el($name = NULL, $attrs = NULL)
	{
		$el = new self;
		$parts = explode(' ', $name, 2);
		$el->setName($parts[0]);

		if (is_array($attrs)) {
			$el->attrs = $attrs;

		} elseif ($attrs !== NULL) {
			$el->setText($attrs);
		}

		if (isset($parts[1])) {
			foreach (NStrings::matchAll($parts[1] . ' ', '#([a-z0-9:-]+)(?:=(["\'])?(.*?)(?(2)\\2|\s))?#i') as $m) {
				$el->attrs[$m[1]] = isset($m[3]) ? $m[3] : TRUE;
			}
		}

		return $el;
	}
Пример #19
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 = NStrings::replace($sql, '~\'.*?\'|".*?"|\?~s', array($this, 'callback'));

		while ($this->counter < count($params)) {
			$sql .= ' ' . $this->formatValue($params[$this->counter++]);
		}

		return array($sql, $this->remaining);
	}
Пример #20
0
 public function generovatUsername($id)
 {
     $zaznam = $this->findById($id);
     $jmeno = NStrings::webalize($zaznam->jmeno);
     $prijmeni = NStrings::webalize($zaznam->prijmeni);
     $username = NStrings::webalize($prijmeni);
     if (!$this->findByUsername($username)) {
         return $username;
     }
     $username = $prijmeni . NStrings::truncate($jmeno, 1, '');
     if (!$this->findByUsername($username)) {
         return $username;
     }
     $username = $prijmeni . $jmeno;
     if (!$this->findByUsername($username)) {
         return $username;
     }
     for ($i = 1; 1 == 1; $i++) {
         $username = $prijmeni . $jmeno . $i;
         if (!$this->findByUsername($username)) {
             return $username;
         }
     }
 }
Пример #21
0
	/**
	 * Parses macro to name, arguments a modifiers parts.
	 * @param  string {name arguments | modifiers}
	 * @return array
	 */
	public function parseMacro($macro)
	{
		$match = NStrings::match($macro, '~^
			(
				(?P<name>\?|/?[a-z]\w*+(?:[.:]\w+)*+(?!::|\())|   ## ?, name, /name, but not function( or class::
				(?P<noescape>!?)(?P<shortname>/?[=\~#%^&_]?)      ## [!] [=] expression to print
			)(?P<args>.*?)
			(?P<modifiers>\|[a-z](?:'.NParser::RE_STRING.'|[^\'"]+)*)?
		()$~isx');

		if (!$match) {
			return FALSE;
		}
		if ($match['name'] === '') {
			$match['name'] = ($tmp=$match['shortname']) ? $tmp : '=';
			if (!$match['noescape'] && substr($match['shortname'], 0, 1) !== '/') {
				$match['modifiers'] .= '|escape';
			}
		}
		return array($match['name'], trim($match['args']), $match['modifiers']);
	}
Пример #22
0
	/**
	 * Creates current HttpRequest object.
	 * @return NHttpRequest
	 */
	public function createHttpRequest()
	{
		// DETECTS URI, base path and script path of the request.
		$url = new NUrlScript;
		$url->scheme = isset($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'off') ? 'https' : 'http';
		$url->user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
		$url->password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';

		// host & port
		if (isset($_SERVER['HTTP_HOST'])) {
			$pair = explode(':', $_SERVER['HTTP_HOST']);

		} elseif (isset($_SERVER['SERVER_NAME'])) {
			$pair = explode(':', $_SERVER['SERVER_NAME']);

		} else {
			$pair = array('');
		}

		$url->host = preg_match('#^[-._a-z0-9]+$#', $pair[0]) ? $pair[0] : '';

		if (isset($pair[1])) {
			$url->port = (int) $pair[1];

		} elseif (isset($_SERVER['SERVER_PORT'])) {
			$url->port = (int) $_SERVER['SERVER_PORT'];
		}

		// path & query
		if (isset($_SERVER['REQUEST_URI'])) { // Apache, IIS 6.0
			$requestUrl = $_SERVER['REQUEST_URI'];

		} elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0 (PHP as CGI ?)
			$requestUrl = $_SERVER['ORIG_PATH_INFO'];
			if (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] != '') {
				$requestUrl .= '?' . $_SERVER['QUERY_STRING'];
			}
		} else {
			$requestUrl = '';
		}

		$requestUrl = NStrings::replace($requestUrl, $this->urlFilters['url']);
		$tmp = explode('?', $requestUrl, 2);
		$url->path = NStrings::replace($tmp[0], $this->urlFilters['path']);
		$url->query = isset($tmp[1]) ? $tmp[1] : '';

		// normalized url
		$url->canonicalize();
		$url->path = NStrings::fixEncoding($url->path);

		// detect script path
		if (isset($_SERVER['DOCUMENT_ROOT'], $_SERVER['SCRIPT_FILENAME'])
			&& strncmp($_SERVER['DOCUMENT_ROOT'], $_SERVER['SCRIPT_FILENAME'], strlen($_SERVER['DOCUMENT_ROOT'])) === 0
		) {
			$script = '/' . ltrim(strtr(substr($_SERVER['SCRIPT_FILENAME'], strlen($_SERVER['DOCUMENT_ROOT'])), '\\', '/'), '/');
		} elseif (isset($_SERVER['SCRIPT_NAME'])) {
			$script = $_SERVER['SCRIPT_NAME'];
		} else {
			$script = '/';
		}

		$path = strtolower($url->path) . '/';
		$script = strtolower($script) . '/';
		$max = min(strlen($path), strlen($script));
		for ($i = 0; $i < $max; $i++) {
			if ($path[$i] !== $script[$i]) {
				break;
			} elseif ($path[$i] === '/') {
				$url->scriptPath = substr($url->path, 0, $i + 1);
			}
		}

		// GET, POST, COOKIE
		$useFilter = (!in_array(ini_get('filter.default'), array('', 'unsafe_raw')) || ini_get('filter.default_flags'));

		parse_str($url->query, $query);
		if (!$query) {
			$query = $useFilter ? filter_input_array(INPUT_GET, FILTER_UNSAFE_RAW) : (empty($_GET) ? array() : $_GET);
		}
		$post = $useFilter ? filter_input_array(INPUT_POST, FILTER_UNSAFE_RAW) : (empty($_POST) ? array() : $_POST);
		$cookies = $useFilter ? filter_input_array(INPUT_COOKIE, FILTER_UNSAFE_RAW) : (empty($_COOKIE) ? array() : $_COOKIE);

		$gpc = (bool) get_magic_quotes_gpc();
		$old = error_reporting(error_reporting() ^ E_NOTICE);

		// remove f*****g quotes and check (and optionally convert) encoding
		if ($gpc || $this->encoding) {
			$utf = strcasecmp($this->encoding, 'UTF-8') === 0;
			$list = array(& $query, & $post, & $cookies);
			while (list($key, $val) = each($list)) {
				foreach ($val as $k => $v) {
					unset($list[$key][$k]);

					if ($gpc) {
						$k = stripslashes($k);
					}

					if ($this->encoding && is_string($k) && (preg_match(self::NONCHARS, $k) || preg_last_error())) {
						// invalid key -> ignore

					} elseif (is_array($v)) {
						$list[$key][$k] = $v;
						$list[] = & $list[$key][$k];

					} else {
						if ($gpc && !$useFilter) {
							$v = stripSlashes($v);
						}
						if ($this->encoding) {
							if ($utf) {
								$v = NStrings::fixEncoding($v);

							} else {
								if (!NStrings::checkEncoding($v)) {
									$v = iconv($this->encoding, 'UTF-8//IGNORE', $v);
								}
								$v = html_entity_decode($v, ENT_QUOTES, 'UTF-8');
							}
							$v = preg_replace(self::NONCHARS, '', $v);
						}
						$list[$key][$k] = $v;
					}
				}
			}
			unset($list, $key, $val, $k, $v);
		}


		// FILES and create HttpUploadedFile objects
		$files = array();
		$list = array();
		if (!empty($_FILES)) {
			foreach ($_FILES as $k => $v) {
				if ($this->encoding && is_string($k) && (preg_match(self::NONCHARS, $k) || preg_last_error())) {
					continue;
				}
				$v['@'] = & $files[$k];
				$list[] = $v;
			}
		}

		while (list(, $v) = each($list)) {
			if (!isset($v['name'])) {
				continue;

			} elseif (!is_array($v['name'])) {
				if ($gpc) {
					$v['name'] = stripSlashes($v['name']);
				}
				if ($this->encoding) {
					$v['name'] = preg_replace(self::NONCHARS, '', NStrings::fixEncoding($v['name']));
				}
				$v['@'] = new NHttpUploadedFile($v);
				continue;
			}

			foreach ($v['name'] as $k => $foo) {
				if ($this->encoding && is_string($k) && (preg_match(self::NONCHARS, $k) || preg_last_error())) {
					continue;
				}
				$list[] = array(
					'name' => $v['name'][$k],
					'type' => $v['type'][$k],
					'size' => $v['size'][$k],
					'tmp_name' => $v['tmp_name'][$k],
					'error' => $v['error'][$k],
					'@' => & $v['@'][$k],
				);
			}
		}

		error_reporting($old);


		// HEADERS
		if (function_exists('apache_request_headers')) {
			$headers = array_change_key_case(apache_request_headers(), CASE_LOWER);
		} else {
			$headers = array();
			foreach ($_SERVER as $k => $v) {
				if (strncmp($k, 'HTTP_', 5) == 0) {
					$k = substr($k, 5);
				} elseif (strncmp($k, 'CONTENT_', 8)) {
					continue;
				}
				$headers[ strtr(strtolower($k), '_', '-') ] = $v;
			}
		}

		return new NHttpRequest($url, $query, $post, $files, $cookies, $headers,
			isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : NULL,
			isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : NULL,
			isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : NULL
		);
	}
Пример #23
0
 /**
  * Inserting a topic to a forum
  *
  * @access public
  * @param Nette\Application\UI\Form $form formulář
  * @return void
  * @uses ForumControlModel::getTopic()
  * @uses ForumControlModel::insert()
  * @since 1.0.0
  */
 public function forumFormSubmitted(UI\Form $form)
 {
     try {
         if ($form['insert']->isSubmittedBy()) {
             $values = $form->values;
             $this->context->httpResponse->setCookie('Nette-ForumControl-Name', $values->name, strtotime('+1 month'));
             if ($this->forumTopicId) {
                 $replyTo = $this->model->getTopic($this->forumTopicId);
                 $values->title = NStrings::startsWith($replyTo->title, 'Re: ') ? $replyTo->title : 'Re: ' . $replyTo->title;
             }
             $values->ip = $this->context->httpRequest->remoteAddress;
             $values->date_time = date('Y-m-d H:i:s');
             $this->model->insert($values, $this->forumTopicId);
             $this->presenter->flashMessage('Your topic has been successfully inserted.');
         }
     } catch (\DibiException $e) {
         $this->presenter->flashMessage('An error occured while adding your topic.', 'error');
     }
     $this->presenter->redirect($this->presenter->view);
 }
Пример #24
0
	/**
	 * @return void
	 */
	public function __destruct()
	{
		if (self::$fixIE && isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE ') !== FALSE
			&& in_array($this->code, array(400, 403, 404, 405, 406, 408, 409, 410, 500, 501, 505), TRUE)
			&& $this->getHeader('Content-Type', 'text/html') === 'text/html'
		) {
			echo NStrings::random(2e3, " \t\r\n"); // sends invisible garbage for IE
			self::$fixIE = FALSE;
		}
	}
Пример #25
0
	/**
	 * Returns session namespace provided to pass temporary data between redirects.
	 * @return NSessionSection
	 */
	public function getFlashSession()
	{
		if (empty($this->params[self::FLASH_KEY])) {
			$this->params[self::FLASH_KEY] = NStrings::random(4);
		}
		return $this->getSession('Nette.Application.Flash/' . $this->params[self::FLASH_KEY]);
	}
Пример #26
0
 function validateKeyword($word)
 {
     $word = \NStrings::lower(trim($word));
     foreach ($this->forbidden_words as $w) {
         if (strpos($word, $w) !== false) {
             return false;
         }
     }
     //ak je slovo kratsie ako 4 znaky neprida ho
     if (!empty($word) and strlen($word) > 3) {
         return $word;
     }
     return false;
 }
Пример #27
0
 /**
  * Helper for macroIncludePart
  * @param  string $params
  * @return array
  */
 private static function prepareIncludePartParams($params)
 {
     $return = array('name' => false, 'params' => 'array()');
     $p = explode(',', substr($params, 6, -1));
     if (count($p) >= 1 and strpos($p[0], '=>') === FALSE) {
         $p = is_string($p) ? trim($p) : $p;
         if (!empty($p)) {
             $return['name'] = !NStrings::startsWith($p[0], '$') ? substr($p[0], 1, -1) : $p[0];
             unset($p[0]);
             $return['params'] = implode(',', $p);
         }
     } elseif (count($p) >= 1 and strpos($p[0], '=>') !== FALSE) {
         if (!empty($p)) {
             $return['name'] = false;
             $return['params'] = implode(',', $p);
         }
     }
     $return['params'] = 'array(' . $return['params'] . ')';
     return $return;
 }
Пример #28
0
	/**
	 * Returns position of token in input string.
	 * @param  int token number
	 * @return array [offset, line, column]
	 */
	public function getOffset($i)
	{
		$tokens = NStrings::split($this->input, $this->re, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_OFFSET_CAPTURE);
		$offset = isset($tokens[$i]) ? $tokens[$i][1] : strlen($this->input);
		return array(
			$offset,
			($offset ? substr_count($this->input, "\n", 0, $offset) + 1 : 1),
			$offset - strrpos(substr($this->input, 0, $offset), "\n"),
		);
	}
Пример #29
0
	/**
	 * Parse mask and array of default values; initializes object.
	 * @param  string
	 * @param  array
	 * @return void
	 */
	private function setMask($mask, array $metadata)
	{
		$this->mask = $mask;

		// detect '//host/path' vs. '/abs. path' vs. 'relative path'
		if (substr($mask, 0, 2) === '//') {
			$this->type = self::HOST;

		} elseif (substr($mask, 0, 1) === '/') {
			$this->type = self::PATH;

		} else {
			$this->type = self::RELATIVE;
		}

		foreach ($metadata as $name => $meta) {
			if (!is_array($meta)) {
				$metadata[$name] = array(self::VALUE => $meta, 'fixity' => self::CONSTANT);

			} elseif (array_key_exists(self::VALUE, $meta)) {
				$metadata[$name]['fixity'] = self::CONSTANT;
			}
		}

		// PARSE MASK
		// <parameter-name[=default] [pattern] [#class]> or [ or ] or ?...
		$parts = NStrings::split($mask, '/<([^>#= ]+)(=[^># ]*)? *([^>#]*)(#?[^>\[\]]*)>|(\[!?|\]|\s*\?.*)/');

		$this->xlat = array();
		$i = count($parts) - 1;

		// PARSE QUERY PART OF MASK
		if (isset($parts[$i - 1]) && substr(ltrim($parts[$i - 1]), 0, 1) === '?') {
			// name=<parameter-name [pattern][#class]>
			$matches = NStrings::matchAll($parts[$i - 1], '/(?:([a-zA-Z0-9_.-]+)=)?<([^># ]+) *([^>#]*)(#?[^>]*)>/');

			foreach ($matches as $match) {
				list(, $param, $name, $pattern, $class) = $match;  // $pattern is not used

				if ($class !== '') {
					if (!isset(self::$styles[$class])) {
						throw new InvalidStateException("Parameter '$name' has '$class' flag, but Route::\$styles['$class'] is not set.");
					}
					$meta = self::$styles[$class];

				} elseif (isset(self::$styles['?' . $name])) {
					$meta = self::$styles['?' . $name];

				} else {
					$meta = self::$styles['?#'];
				}

				if (isset($metadata[$name])) {
					$meta = $metadata[$name] + $meta;
				}

				if (array_key_exists(self::VALUE, $meta)) {
					$meta['fixity'] = self::OPTIONAL;
				}

				unset($meta['pattern']);
				$meta['filterTable2'] = empty($meta[self::FILTER_TABLE]) ? NULL : array_flip($meta[self::FILTER_TABLE]);

				$metadata[$name] = $meta;
				if ($param !== '') {
					$this->xlat[$name] = $param;
				}
			}
			$i -= 6;
		}

		// PARSE PATH PART OF MASK
		$brackets = 0; // optional level
		$re = '';
		$sequence = array();
		$autoOptional = array(0, 0); // strlen($re), count($sequence)
		do {
			array_unshift($sequence, $parts[$i]);
			$re = preg_quote($parts[$i], '#') . $re;
			if ($i === 0) {
				break;
			}
			$i--;

			$part = $parts[$i]; // [ or ]
			if ($part === '[' || $part === ']' || $part === '[!') {
				$brackets += $part[0] === '[' ? -1 : 1;
				if ($brackets < 0) {
					throw new InvalidArgumentException("Unexpected '$part' in mask '$mask'.");
				}
				array_unshift($sequence, $part);
				$re = ($part[0] === '[' ? '(?:' : ')?') . $re;
				$i -= 5;
				continue;
			}

			$class = $parts[$i]; $i--; // validation class
			$pattern = trim($parts[$i]); $i--; // validation condition (as regexp)
			$default = $parts[$i]; $i--; // default value
			$name = $parts[$i]; $i--; // parameter name
			array_unshift($sequence, $name);

			if ($name[0] === '?') { // "foo" parameter
				$re = '(?:' . preg_quote(substr($name, 1), '#') . '|' . $pattern . ')' . $re;
				$sequence[1] = substr($name, 1) . $sequence[1];
				continue;
			}

			// check name (limitation by regexp)
			if (preg_match('#[^a-z0-9_-]#i', $name)) {
				throw new InvalidArgumentException("Parameter name must be alphanumeric string due to limitations of PCRE, '$name' given.");
			}

			// pattern, condition & metadata
			if ($class !== '') {
				if (!isset(self::$styles[$class])) {
					throw new InvalidStateException("Parameter '$name' has '$class' flag, but Route::\$styles['$class'] is not set.");
				}
				$meta = self::$styles[$class];

			} elseif (isset(self::$styles[$name])) {
				$meta = self::$styles[$name];

			} else {
				$meta = self::$styles['#'];
			}

			if (isset($metadata[$name])) {
				$meta = $metadata[$name] + $meta;
			}

			if ($pattern == '' && isset($meta[self::PATTERN])) {
				$pattern = $meta[self::PATTERN];
			}

			if ($default !== '') {
				$meta[self::VALUE] = (string) substr($default, 1);
				$meta['fixity'] = self::PATH_OPTIONAL;
			}

			$meta['filterTable2'] = empty($meta[self::FILTER_TABLE]) ? NULL : array_flip($meta[self::FILTER_TABLE]);
			if (array_key_exists(self::VALUE, $meta)) {
				if (isset($meta['filterTable2'][$meta[self::VALUE]])) {
					$meta['defOut'] = $meta['filterTable2'][$meta[self::VALUE]];

				} elseif (isset($meta[self::FILTER_OUT])) {
					$meta['defOut'] = call_user_func($meta[self::FILTER_OUT], $meta[self::VALUE]);

				} else {
					$meta['defOut'] = $meta[self::VALUE];
				}
			}
			$meta[self::PATTERN] = "#(?:$pattern)$#A" . ($this->flags & self::CASE_SENSITIVE ? '' : 'iu');

			// include in expression
			$re = '(?P<' . str_replace('-', '___', $name) . '>(?U)' . $pattern . ')' . $re; // str_replace is dirty trick to enable '-' in parameter name
			if ($brackets) { // is in brackets?
				if (!isset($meta[self::VALUE])) {
					$meta[self::VALUE] = $meta['defOut'] = NULL;
				}
				$meta['fixity'] = self::PATH_OPTIONAL;

			} elseif (isset($meta['fixity'])) { // auto-optional
				$re = '(?:' . substr_replace($re, ')?', strlen($re) - $autoOptional[0], 0);
				array_splice($sequence, count($sequence) - $autoOptional[1], 0, array(']', ''));
				array_unshift($sequence, '[', '');
				$meta['fixity'] = self::PATH_OPTIONAL;

			} else {
				$autoOptional = array(strlen($re), count($sequence));
			}

			$metadata[$name] = $meta;
		} while (TRUE);

		if ($brackets) {
			throw new InvalidArgumentException("Missing closing ']' in mask '$mask'.");
		}

		$this->re = '#' . $re . '/?$#A' . ($this->flags & self::CASE_SENSITIVE ? '' : 'iu');
		$this->metadata = $metadata;
		$this->sequence = $sequence;
	}
Пример #30
0
 function addKeyword($word)
 {
     $word = \NStrings::lower(trim($word));
     foreach ($this->forbidden_words as $w) {
         if (strpos($word, $w) !== false) {
             return false;
         }
     }
     //ak obsahuje nepovolene znaky neprida
     //		echo '<br>
     //			'.$word.'|'.(preg_match('/^([a-zA-Z0-9_ ]+)$/', $word));
     //		if(preg_match('/^([a-zA-Z0-9_ ]+)$/', $word) === 0){
     //			return false;
     //		};
     //ak je slovo kratsie ako 4 znaky neprida ho
     if (!empty($word) and strlen($word) > 3) {
         $this->keywords[$word] = $word;
     }
 }