/**
  * Computes salted password hash.
  * @param  string
  * @return string
  */
 public static function calculateHash($password, $salt = null)
 {
     if ($salt === null) {
         $salt = '$2a$07$' . Nette\Utils\Strings::random(32) . '$';
     }
     return crypt($password, $salt);
 }
Exemplo n.º 2
0
 public function save()
 {
     $this->competition->code = Nette\Utils\Strings::webalize($this->competition->name);
     if ($this->competition->id != "") {
         $this->wherePrimary($this->competition->id);
         $this->update($this->competition);
     } else {
         $this->competition->created = new DibiDateTime();
         $this->insert($this->competition);
     }
 }
Exemplo n.º 3
0
    static function text($len = 300)
    {
        return Nette\Utils\Strings::truncate('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam quis porttitor nisl. Nullam feugiat euismod nisi at condimentum. Phasellus pulvinar dui non commodo efficitur. Maecenas dapibus mi sit amet ligula varius, non blandit ipsum tempus. Vestibulum suscipit urna sed nunc fringilla, vel consectetur felis posuere. Mauris pellentesque risus vel libero viverra ultricies. Aliquam hendrerit feugiat lacus sed ultrices. Vestibulum convallis enim id nibh mollis semper.

Cras a efficitur tellus. Duis mattis finibus augue at bibendum. Curabitur suscipit nisl ut est volutpat, id dignissim purus efficitur. Donec pellentesque nisi sit amet gravida commodo. Pellentesque porta eros sit amet elit porttitor, id semper purus luctus. Nunc sit amet rutrum lorem, at mattis enim. Pellentesque enim risus, efficitur sit amet aliquet in, tempor nec est.

Maecenas euismod metus id tellus sodales viverra. Proin a neque in metus tincidunt egestas. Donec in interdum felis, non eleifend tortor. Nunc a erat turpis. Phasellus congue viverra tellus, sed vulputate metus ultrices a. Curabitur a justo fringilla, semper augue ut, efficitur nisi. Nunc ultrices sed lorem vitae scelerisque.

Donec lobortis dolor sem, non ornare enim sodales a. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam erat volutpat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum quis imperdiet dolor. Phasellus eleifend sed mi sit amet faucibus. Phasellus lobortis tincidunt convallis. Ut felis felis, dignissim ac tempus non, fringilla a orci. Sed lacinia mauris nulla, sed tempor metus mattis vitae. Aliquam sagittis orci mauris, a ultrices sapien molestie sit amet. Nunc elementum sit amet lacus sed condimentum. Fusce sed ipsum a enim fermentum lacinia. Aenean faucibus ipsum a ullamcorper rutrum.

Sed blandit interdum bibendum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum viverra feugiat felis eu sollicitudin. Nullam enim mauris, ultricies nec risus sed, mattis scelerisque ex. Quisque nec auctor augue. Proin porttitor commodo mi, vitae maximus mauris semper ut. Mauris blandit quis nisl ac dignissim. Vivamus cursus, dui at molestie dignissim, elit elit mattis dui, vitae fermentum nunc orci at ligula.', $len);
    }
Exemplo n.º 4
0
    public function getBySources(array $urls)
    {
        // get articles
        $sql = '
			SELECT a.*, ia.place_id, p.lat, p.lng, s.url AS source
			FROM article AS a
			JOIN source AS s
			ON a.source_id = s.id
			JOIN is_about AS ia
			ON ia.article_id = a.id
			JOIN place AS p
			ON ia.place_id = p.id
			WHERE s.url IN (?)
		';
        $pm = array();
        $articles = $this->db->query($sql, $urls)->fetchAll();
        // get tags
        $places = array();
        foreach ($articles as $article) {
            $places[] = $article->place_id;
        }
        $sql = '
			SELECT t.*, ht.place_id
			FROM tag AS t
			JOIN has_tag AS ht
			ON ht.tag_id = t.id
			WHERE ht.place_id IN (?)
		';
        $tags = array();
        foreach ($this->db->query($sql, $places) as $tag) {
            if (isset($tags[$tag->place_id])) {
                $tags[$tag->place_id][] = $tag;
            } else {
                $tags[$tag->place_id] = array($tag);
            }
        }
        // prepare placemarks
        foreach ($articles as $article) {
            $pm[] = (object) array('name' => $article->title, 'url' => $article->url, 'photo' => $article->photo_url, 'tags' => isset($tags[$article->place_id]) ? $tags[$article->place_id] : array(), 'lat' => $article->lat, 'lng' => $article->lng, 'icon' => Nette\Utils\Strings::webalize(self::$icons[$article->source]), 'source' => $article->source);
        }
        return $pm;
    }
Exemplo n.º 5
0
/**
 * @param DibiConnection
 * @param string table name
 * @param string file path
 *
 * @return int
 * @throws DibiException
 * @throws Nette\IOException
 * @throws Nette\UnexpectedValueException
 */
function dumpStructure(DibiConnection $db, $table, $file)
{
    // Return code
    // 0: Not changed
    // 1: Created
    // 2: Updated
    $result = 0;
    $row = $db->query("SHOW CREATE TABLE %n", $table)->fetch();
    if (!$row) {
        throw new Nette\UnexpectedValueException("Cannot gather create table syntax for: {$table}");
    }
    $createSyntax = $row->{'Create Table'};
    $createSyntax = preg_replace("/\\sAUTO_INCREMENT=([0-9]+)\\s/", " ", $createSyntax);
    // Check for existing SQL script
    if (file_exists($file)) {
        $lines = file($file);
        if ($lines === FALSE) {
            throw new Nette\IOException("Cannot read file {$file}");
        }
        $oldCreateSyntax = "";
        foreach ($lines as $line) {
            if (!Nette\Utils\Strings::startsWith($line, '--')) {
                $oldCreateSyntax .= "{$line}\n";
            }
        }
        $new = rtrim(trim(preg_replace('/[\\s\\r\\n]+/', ' ', $createSyntax)), ';');
        $old = rtrim(trim(preg_replace('/[\\s\\r\\n]+/', ' ', $oldCreateSyntax)), ';');
        $result = $old != $new ? 2 : 0;
        // No existing SQL script
    } else {
        $result = 1;
    }
    // ----
    // If we need to create new dump
    if ($result) {
        $createSyntax = "" . "--\n" . "-- Create table: {$table}\n" . "-- Generated: " . date("Y-m-d H:i:s") . "\n" . "--\n" . $createSyntax . ";";
        if (file_put_contents($file, $createSyntax) === FALSE) {
            throw new Nette\IOException("Cannot write to file '{$file}'");
        }
    }
    return $result;
}
Exemplo n.º 6
0
        exit(1);
    }
}
// -----------------------------------------------------------------------------
// DB
// -----------------------------------------------------------------------------
$existingTables = $db->getDatabaseInfo()->getTableNames();
foreach ($tables as $table => $script) {
    echo "{$table}: ";
    if (in_array($table, $existingTables)) {
        echo "exists";
        // TODO: some table syntax check
        /* $r = $db->query("SHOW CREATE TABLE %n", $table)->fetch();
        		if($r) {
        			$createSyntax = $r->{'Create Table'};
        			d($createSyntax);
        		} else
        			throw new Nette\InvalidStateException("Cannot gather create table syntax for: $table"); */
    } else {
        echo "creating from ";
        if (Nette\Utils\Strings::startsWith($script, __DIR__ . '/../')) {
            echo mb_substr($script, mb_strlen(__DIR__ . '/../'));
        } else {
            echo $script;
        }
        echo "";
        $db->loadFile($script);
    }
    echo "\n";
}
echo "\nDone :-)\n\n";
Exemplo n.º 7
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) && preg_match('#^text/html(?:;|$)#', $this->getHeader('Content-Type', 'text/html'))) {
         echo Nette\Utils\Strings::random(2000.0, " \t\r\n");
         // sends invisible garbage for IE
         self::$fixIE = FALSE;
     }
 }
Exemplo n.º 8
0
UploadiFive
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
*/
// Set the uplaod directory
$uploadDir = __DIR__ . '/../../images/file/' . substr($_POST['timestamp'], 0, 4) . '/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir);
    chmod($uploadDir, 0777);
}
$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
    include_once __DIR__ . '/../../vendor/nette/utils/src/Utils/StaticClass.php';
    include_once __DIR__ . '/../../vendor/nette/utils/src/Utils/Strings.php';
    $tempFile = $_FILES['Filedata']['tmp_name'];
    $fileName = explode('.', $_FILES['Filedata']['name']);
    $postFix = $fileName[count($fileName) - 1];
    unset($fileName[count($fileName) - 1]);
    $fileName = $_POST['timestamp'] . '_' . Nette\Utils\Strings::webalize(implode('.', $fileName)) . '.' . $postFix;
    $targetFile = $uploadDir . $fileName;
    //$targetFile = $uploadDir . $_FILES['Filedata']['name'];
    // Validate the filetype
    $fileParts = pathinfo($_FILES['Filedata']['name']);
    // Save the file
    if (move_uploaded_file($tempFile, $targetFile) == TRUE) {
        echo $fileName;
    } else {
        echo 'ERROR';
    }
} else {
    echo 'ERROR - token';
}
Exemplo n.º 9
0
<?php

require __DIR__ . '/../vendor/autoload.php';
$configurator = new Nette\Configurator();
$environment = $configurator->setDebugMode('x.x.x.x');
$configurator->enableDebugger(__DIR__ . '/../log');
$configurator->setTempDirectory(__DIR__ . '/../temp');
$configurator->createRobotLoader()->addDirectory(__DIR__)->register();
$environment = (Nette\Configurator::detectDebugMode('127.0.0.1') or PHP_SAPI == 'cli' && Nette\Utils\Strings::startsWith(getHostByName(getHostName()), "192.168.")) ? 'development' : 'production';
$configurator->addConfig(__DIR__ . '/config/config.neon');
$configurator->addConfig(__DIR__ . "/config/config.{$environment}.neon");
$container = $configurator->createContainer();
$container->getService('application')->errorPresenter = 'Front:Error';
return $container;
Exemplo n.º 10
0
/**
 * Vrati nazev zmenseneho souboru stazeneho z ciziho serveru
 * @param string $file
 * @param int $height
 * @param int $width
 * @param bool $exact
 * @param bool $topCut
 * @return string
 */
function getRemoteResizedFilename($file, $height, $width, $exact, $topCut)
{
    $file = DIR_FOR_REMOTE . '/' . Nette\Utils\Strings::webalize($file, '.');
    return getBaseResizedFilename($file, $height, $width, $exact, $topCut);
}
Exemplo n.º 11
0
function nbsp($str)
{
    $str = trim($str);
    return Nette\Utils\Strings::replace($str, '~[ ]~', " ");
}
Exemplo n.º 12
0
 public function update($data, $checkData = FALSE)
 {
     if ($checkData) {
         $data['code'] = Nette\Utils\Strings::webalize($data['subject_name'] . " " . $data['name']);
     }
     $coords = Geolocation::getCoordsFromText($data['subject_gps']);
     $data['lat'] = $coords[0];
     $data['lon'] = $coords[1];
     $data['last_edit_id'] = isset($this->context->user->id) ? $this->context->user->id : NULL;
     parent::update($data);
 }
 /**
  * Sets selected items (by keys).
  * @param  array
  * @return self
  * @internal
  */
 private function setMultipleValue($values)
 {
     if (is_scalar($values) || $values === NULL) {
         $values = (array) $values;
     } elseif (!is_array($values)) {
         throw new Nette\InvalidArgumentException(sprintf("Value must be array or NULL, %s given in field '%s'.", gettype($values), $this->name));
     }
     $flip = array();
     foreach ($values as $value) {
         if (!is_scalar($value) && !method_exists($value, '__toString')) {
             throw new Nette\InvalidArgumentException(sprintf("Values must be scalar, %s given in field '%s'.", gettype($value), $this->name));
         }
         $flip[(string) $value] = TRUE;
     }
     $values = array_keys($flip);
     if ($this->checkAllowedValues && ($diff = array_diff($values, array_keys($this->items)))) {
         $set = Nette\Utils\Strings::truncate(implode(', ', array_map(function ($s) {
             return var_export($s, TRUE);
         }, array_keys($this->items))), 70, '...');
         $vals = (count($diff) > 1 ? 's' : '') . " '" . implode("', '", $diff) . "'";
         throw new Nette\InvalidArgumentException("Value{$vals} are out of allowed set [{$set}] in field '{$this->name}'.");
     }
     $this->value = $values;
     return $this;
 }