Example #1
0
 private function maybeReplacePlaceholderWithPrefix($key)
 {
     if (Strings::startsWith($key, self::PREFIX_PLACEHOLDER)) {
         return $this->dbPrefix . Strings::substring($key, Strings::length(self::PREFIX_PLACEHOLDER));
     }
     return $key;
 }
 /**
  * @param \Nette\Application\Application $application
  * @param \Nette\Application\Request $request
  */
 public function __invoke(Application $application, Request $request)
 {
     if (PHP_SAPI === 'cli') {
         newrelic_background_job(TRUE);
     }
     $params = $request->getParameters();
     $action = $request->getPresenterName();
     if (isset($params[$this->actionKey])) {
         $action = sprintf('%s:%s', $action, $params[$this->actionKey]);
     }
     if (!empty($this->map)) {
         foreach ($this->map as $pattern => $appName) {
             if ($pattern === '*') {
                 continue;
             }
             if (Strings::endsWith($pattern, '*')) {
                 $pattern = Strings::substring($pattern, 0, -1);
             }
             if (Strings::startsWith($pattern, ':')) {
                 $pattern = Strings::substring($pattern, 1);
             }
             if (Strings::startsWith($action, $pattern)) {
                 \VrtakCZ\NewRelic\Tracy\Bootstrap::setup($appName, $this->license);
                 break;
             }
         }
     }
     newrelic_name_transaction($action);
     newrelic_disable_autorum();
 }
 /**
  * Filter: removes unnecessary whitespace and shortens value to control's max length.
  *
  * @return string
  */
 public function sanitize($value)
 {
     if ($this->control->maxlength && Nette\Utils\Strings::length($value) > $this->control->maxlength) {
         $value = Nette\Utils\Strings::substring($value, 0, $this->control->maxlength);
     }
     return Nette\Utils\Strings::trim(strtr($value, "\r\n", '  '));
 }
Example #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);
 }
 /**
  * Model\Entity\SomeEntity -> some_entity
  * @param string $entityClass
  * @return string
  */
 public function getTable($entityClass)
 {
     if (Strings::endsWith($entityClass, 'y')) {
         return $this->camelToUnderdash(Strings::substring($this->trimNamespace($entityClass), 0, Strings::length($entityClass))) . 'ies';
     } else {
         return $this->camelToUnderdash($this->trimNamespace($entityClass)) . 's';
     }
 }
Example #6
0
 /**
  * Converts the given string to "camelCase".
  * @param string $string
  * @return string
  */
 public static function toCamelCase($string)
 {
     static $canUse = null;
     if (is_null($canUse)) {
         $canUse = method_exists(Strings::class, 'firstLower');
         // Nette/Utils >= 2.3 only
     }
     $pascal = self::toPascalCase($string);
     return $canUse ? Strings::firstLower($pascal) : Strings::lower(Strings::substring($pascal, 0, 1)) . Strings::substring($pascal, 1);
 }
 /**
  * @param string
  * @return string
  */
 public static function normalizeGithubRepositoryUrl($url)
 {
     self::assertGithubRepositoryUrl($url);
     $url = str_replace('github.com:', 'github.com/', $url);
     if (Strings::endsWith($url, '.git')) {
         $url = Strings::substring($url, 0, -4);
     }
     $match = Strings::match($url, '~' . self::GITHUB_REGEXP . '~');
     return 'https://' . Strings::lower($match[0]);
 }
Example #8
0
 public function createRoute($title, $contentId, $sectionId)
 {
     $route = array();
     $route['contentId'] = $contentId;
     $webalize = \Nette\Utils\Strings::webalize($title);
     $webalize = \Nette\Utils\Strings::substring($webalize, 0, 50);
     $route['url'] = "program/" . $sectionId . "/" . $webalize;
     $route['creationTime'] = date("Y-m-d G:i:s");
     return $route;
 }
Example #9
0
 /**
  * @param FileUpload $fileUpload
  * @return string
  */
 public static function sanitizeFileName(FileUpload $fileUpload)
 {
     $filename = $fileUpload->getSanitizedName();
     $filename = Strings::lower($filename);
     $fileInfo = new \SplFileInfo($filename);
     $suffix = $fileInfo->getExtension();
     $basename = $fileInfo->getBasename(".{$suffix}");
     $hash = md5($fileUpload->getContents());
     $hash = Strings::substring($hash, 0, 9);
     return Strings::substring($basename, 0, 50) . "_{$hash}.{$suffix}";
 }
 /**
  * @return string|NULL
  */
 private function getNormalizedRouterName()
 {
     $config = $this->getConfig($this->defaults);
     if (empty($config['router'])) {
         return NULL;
     }
     if (Strings::startsWith($config['router'], '@')) {
         return Strings::substring($config['router'], 1);
     }
     return $config['router'];
 }
Example #11
0
 /**
  * Returns control's value.
  * @return string
  */
 public function getValue()
 {
     $value = $this->value;
     if (!empty($this->control->maxlength)) {
         $value = Strings::substring($value, 0, $this->control->maxlength);
     }
     foreach ($this->filters as $filter) {
         $value = (string) call_user_func($filter, $value);
     }
     return $value === Strings::trim($this->translate($this->emptyValue)) ? '' : $value;
 }
Example #12
0
 /**
  * @param string $source
  * @param string $zipFile
  */
 public function zipDirToFile($source, $zipFile)
 {
     $archive = new ZipArchive();
     $archive->open($zipFile, ZipArchive::CREATE);
     $directory = basename($zipFile, '.zip');
     /** @var SplFileInfo $file */
     foreach (Finder::findFiles('*')->from($source) as $file) {
         $relativePath = Strings::substring($file->getRealPath(), strlen($source) + 1);
         $archive->addFile($file, $directory . '/' . $relativePath);
     }
     $archive->close();
 }
Example #13
0
 /**
  * Match request
  * @param  IRequest $request 
  * @return Request            
  */
 public function match(Http\IRequest $request)
 {
     $path = $request->url->getPathInfo();
     if (!Strings::contains($path, $this->prefix)) {
         return NULL;
     }
     $path = Strings::substring($path, strlen($this->prefix) + 1);
     $pathParts = explode('/', $path);
     $pathArguments = array_slice($pathParts, 1);
     $action = $this->getActionName($request->getMethod(), $pathArguments);
     $params = $this->getPathParameters($pathArguments);
     $params[Route::MODULE_KEY] = $this->module;
     $params[Route::PRESENTER_KEY] = $pathParts[0];
     $params['action'] = $action;
     $presenter = ($this->module ? $this->module . ':' : '') . $params[Route::PRESENTER_KEY];
     $appRequest = new Application\Request($presenter, $request->getMethod(), $params, $request->getPost(), $request->getFiles());
     return $appRequest;
 }
 /**
  * @param string
  */
 public function renderSitemap($type = 'html')
 {
     $this->template->addons = $this->addons->findAll();
     $this->template->vendors = $this->addons->findVendors();
     $this->template->categories = $this->tags->findMainTags();
     $pages = array();
     foreach (Finder::findFiles('*.texy')->from($this->pagesDataPath) as $file) {
         /** @var \SplFileInfo $file */
         $slug = Strings::substring($file->getRealPath(), Strings::length($this->pagesDataPath) + 1, -5);
         $data = $this->pageProcessor->process(file_get_contents($file->getRealPath()));
         $createdAt = new \DateTime();
         $createdAt->setTimestamp($file->getMTime());
         $pages[] = (object) array('slug' => $slug, 'name' => $data['title'], 'createdAt' => $createdAt);
     }
     $this->template->pages = $pages;
     if ($type == 'xml') {
         $this->setView('sitemap.xml');
     }
 }
 public function translate($message, $count = NULL, $parameters = array(), $domain = NULL, $locale = NULL)
 {
     $translationString = $message instanceof Phrase ? $message->message : $message;
     $prefix = $this->prefix . '.';
     if (Strings::startsWith($message, '//')) {
         $prefix = NULL;
         $translationString = Strings::substring($translationString, 2);
     }
     if ($message instanceof Phrase) {
         return $this->translator->translate(new Phrase($prefix . $translationString, $message->count, $message->parameters, $message->domain, $message->locale));
     }
     if (is_array($count)) {
         $locale = $domain ?: NULL;
         $domain = $parameters ?: NULL;
         $parameters = $count ?: array();
         $count = NULL;
     }
     return $this->translator->translate($prefix . $translationString, $count, (array) $parameters, $domain, $locale);
 }
Example #16
0
 private function createPresenterName($string)
 {
     $presenter = '';
     $enlarge = false;
     for ($i = 0; $i < \Nette\Utils\Strings::length($string); $i++) {
         $char = \Nette\Utils\Strings::substring($string, $i, 1);
         if ($char == '-') {
             $enlarge = true;
         }
         if (ord($char) >= 65 && ord($char) <= 90 || ord($char) >= 97 && ord($char) <= 122) {
             if ($i == 0 || $enlarge) {
                 $presenter .= \Nette\Utils\Strings::upper($char);
                 if ($enlarge) {
                     $enlarge = false;
                 }
             } else {
                 $presenter .= $char;
             }
         }
     }
     return $presenter;
 }
Example #17
0
 /**
  * Render method hook
  *
  * @param string $func
  * @param array $args
  * @return mixed|void
  */
 public function __call($func, $args = [])
 {
     if (Nette\Utils\Strings::startsWith($func, 'render')) {
         // Fix array-in-array when passing parameters from template
         // See http://forum.nette.org/cs/21090-makro-control-obaluje-pojmenovane-parametry-polem (in czech)
         $tmp = @array_reduce($args, 'array_merge', []);
         // @ - intentionally
         if ($tmp === NULL) {
             $tmp = $args;
         }
         // Capitalize and validate view syntax
         $this->view = Nette\Utils\Strings::firstUpper($this->view);
         $this->checkView();
         // Call view and render methods
         $render = Nette\Utils\Strings::substring($func, 6);
         $this->callViewRender($render, $tmp);
         // Life cycle
         if ($this instanceof IHasControlLifeCycle) {
             return $this->run($render, $tmp);
         }
     }
     return parent::__call($func, $args);
 }
 public function formatTemplateFile(Control $control)
 {
     $templateFiles = [];
     if ($control instanceof Presenter) {
         $namespaceName = $control->getReflection()->getNamespaceName();
         $trimmedName = $control->getReflection()->getShortName();
         if (Strings::endsWith($trimmedName, 'Presenter')) {
             $trimmedName = Strings::substring($trimmedName, 0, Strings::length($trimmedName) - 9);
         }
         $templateFiles[] = $this->unifyDirectorySeparators($this->getThemeManager()->getThemesDir() . DIRECTORY_SEPARATOR . $this->getThemeManager()->getCurrentTheme() . DIRECTORY_SEPARATOR . $namespaceName . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $trimmedName . DIRECTORY_SEPARATOR . $control->getView() . '.latte');
         $templateFiles[] = $this->unifyDirectorySeparators($this->getThemeManager()->getThemesDir() . DIRECTORY_SEPARATOR . $this->getThemeManager()->getFallbackTheme() . DIRECTORY_SEPARATOR . $namespaceName . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $trimmedName . DIRECTORY_SEPARATOR . $control->getView() . '.latte');
         if (Strings::endsWith($namespaceName, '\\Presenters')) {
             $trimmedNamespaceName = Strings::substring($control->getReflection()->getNamespaceName(), 0, Strings::length($namespaceName) - 11);
             // trim /Presenters from namespace
             $templateFiles[] = $this->unifyDirectorySeparators($this->getThemeManager()->getThemesDir() . DIRECTORY_SEPARATOR . $this->getThemeManager()->getCurrentTheme() . DIRECTORY_SEPARATOR . $trimmedNamespaceName . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $trimmedName . DIRECTORY_SEPARATOR . $control->getView() . '.latte');
             $templateFiles[] = $this->unifyDirectorySeparators($this->getThemeManager()->getThemesDir() . DIRECTORY_SEPARATOR . $this->getThemeManager()->getFallbackTheme() . DIRECTORY_SEPARATOR . $trimmedNamespaceName . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $trimmedName . DIRECTORY_SEPARATOR . $control->getView() . '.latte');
         }
     } else {
         $templateFiles[] = $this->unifyDirectorySeparators($this->getThemeManager()->getThemesDir() . DIRECTORY_SEPARATOR . $this->getThemeManager()->getCurrentTheme() . DIRECTORY_SEPARATOR . $control->getReflection()->getNamespaceName() . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $control->getReflection()->getShortName() . '.latte');
         $templateFiles[] = $this->unifyDirectorySeparators($this->getThemeManager()->getThemesDir() . DIRECTORY_SEPARATOR . $this->getThemeManager()->getFallbackTheme() . DIRECTORY_SEPARATOR . $control->getReflection()->getNamespaceName() . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $control->getReflection()->getShortName() . '.latte');
     }
     return $templateFiles;
 }
 public function getEntityFilename($id, $parentId = null)
 {
     $sanitizedEntityId = urlencode($this->maybeReplacePrefixWithPlaceholder($id));
     $sanitizedEntityId = str_replace('.', '%2E', $sanitizedEntityId);
     $vpidPath = Strings::substring($sanitizedEntityId, 0, 2) . '/' . $sanitizedEntityId;
     return $this->directory . '/' . $vpidPath . '.ini';
 }
 /**
  * @param array $parameters
  * @param $redirectToAction - etc. 'Front:Sign:in'
  * @param string $method
  * @param int $userId
  * @param string $userRole
  * @param bool $ignoreRedirectUrlParameters
  * @throws \Nette\Application\UI\InvalidLinkException
  */
 public function checkRedirectTo($parameters = array(), $redirectToAction, $method = 'GET', $userId = NULL, $userRole = self::DEFAULT_USER_ROLE, $ignoreRedirectUrlParameters = TRUE)
 {
     $response = $this->sendRequest($parameters, $method, $userId, $userRole);
     $this->assertTrue($response instanceof \Nette\Application\Responses\RedirectResponse);
     if ($ignoreRedirectUrlParameters) {
         $responseUrl = $response->getUrl();
         $endPos = strrpos($responseUrl, '?');
         $responseUrlWithoutParameters = Strings::substring($responseUrl, 0, $endPos === FALSE ? NULL : $endPos);
         $this->assertSame($this->linkGenerator->link($redirectToAction), $responseUrlWithoutParameters);
     } else {
         $this->assertSame($this->linkGenerator->link($redirectToAction), $response->getUrl());
     }
 }
Example #21
0
 /**
  * Does the parsing and sets all properties
  *
  * @param array $entitySchema Example:
  *   array('post' => array(
  *     'table' => 'posts',
  *     'id' => 'ID',
  *     'references' => array (
  *        'post_author' => 'user'
  *      )
  *   ))
  */
 public function __construct($entitySchema)
 {
     list($key) = array_keys($entitySchema);
     $this->entityName = $key;
     $schemaInfo = $entitySchema[$key];
     if (isset($schemaInfo['table'])) {
         $this->tableName = $schemaInfo['table'];
     } else {
         $this->tableName = $this->entityName;
     }
     // The schema defines either 'id' or 'vpid', see schema-readme.md. This has this meaning:
     if (isset($schemaInfo['id'])) {
         $this->idColumnName = $schemaInfo['id'];
         $this->vpidColumnName = 'vp_id';
         // convention
         $this->usesGeneratedVpids = true;
         $this->hasNaturalVpid = false;
     } else {
         $this->idColumnName = $schemaInfo['vpid'];
         $this->vpidColumnName = $schemaInfo['vpid'];
         $this->usesGeneratedVpids = false;
         $this->hasNaturalVpid = true;
     }
     if (isset($schemaInfo['parent-reference'])) {
         $this->parentReference = $schemaInfo['parent-reference'];
     }
     if (isset($schemaInfo['references'])) {
         $this->references = $schemaInfo['references'];
         $this->hasReferences = true;
     }
     if (isset($schemaInfo['mn-references'])) {
         foreach ($schemaInfo['mn-references'] as $reference => $targetEntity) {
             if (Strings::startsWith($reference, '@')) {
                 $reference = Strings::substring($reference, 1);
                 $this->virtualReferences[$reference] = true;
             }
             $this->mnReferences[$reference] = $targetEntity;
         }
         $this->hasReferences = true;
     }
     if (isset($schemaInfo['value-references'])) {
         foreach ($schemaInfo['value-references'] as $key => $references) {
             list($keyCol, $valueCol) = explode('@', $key);
             foreach ($references as $reference => $targetEntity) {
                 $key = $keyCol . '=' . $reference . '@' . $valueCol;
                 $this->valueReferences[$key] = $targetEntity;
             }
         }
         $this->hasReferences = true;
     }
 }
Example #22
0
 /**
  * @param string $policyNo
  * @param Response $response
  * @return bool|string
  */
 public function savePdfFile($policyNo, Response $response)
 {
     if ($response->getHeaders()['Content-Type'] !== 'application/pdf') {
         return FALSE;
     }
     $body = $response->getResponse();
     $filename = $this->tempDir . '/' . $policyNo . '-' . Strings::substring(md5($body), 0, 5) . '.pdf';
     $this->toDelete[] = $filename;
     FileSystem::write($filename, $body);
     return $filename;
 }
Example #23
0
 /**
  * Filter: removes unnecessary whitespace and shortens value to control's max length.
  * @return string
  */
 public function sanitize($value)
 {
     if ($this->control->maxlength) {
         $value = Nette\Utils\Strings::substring($value, 0, $this->control->maxlength);
     }
     if (strcasecmp($this->control->getName(), 'input') === 0) {
         $value = Nette\Utils\Strings::trim(strtr($value, "\r\n", '  '));
     }
     return $value;
 }
 /**
  * @static
  * @param string $value
  * @param string $type
  * @return array
  */
 public static function prepareFilter($value, $type)
 {
     /* select or boolean can be only equal */
     if ($type == self::SELECT || $type == self::BOOLEAN) {
         return array("condition" => self::EQUAL, "value" => $value);
     } elseif ($type == self::MULTISELECT) {
         return array("condition" => self::IN, "value" => $value);
     } elseif ($type == self::TEXT) {
         foreach (self::getConditionsByType(self::TEXT) as $name => $condition) {
             if (Strings::endsWith($value, $condition) && !Strings::startsWith($value, $condition) && $name == self::STARTSWITH) {
                 return array("condition" => $name, "value" => Strings::substring($value, 0, "-" . Strings::length($condition)));
             } elseif (Strings::startsWith($value, $condition) && !Strings::endsWith($value, $condition) && $name == self::ENDSWITH) {
                 return array("condition" => $name, "value" => Strings::substring($value, Strings::length($condition)));
             }
         }
         return array("condition" => self::CONTAINS, "value" => $value);
     } elseif ($type == self::DATE) {
         foreach (self::getConditionsByType(self::DATE) as $name => $condition) {
             if (Strings::startsWith($value, $condition)) {
                 return array("condition" => $name, "value" => Strings::substring($value, Strings::length($condition)));
             }
         }
         return array("condition" => self::DATE_EQUAL, "value" => $value);
     } elseif ($type == self::NUMERIC) {
         foreach (self::getConditionsByType(self::NUMERIC) as $name => $condition) {
             if (Strings::startsWith($value, $condition)) {
                 return array("condition" => $name, "value" => (int) Strings::substring($value, Strings::length($condition)));
             }
         }
         return array("condition" => self::EQUAL, "value" => (int) $value);
     }
 }
Example #25
0
 /**
  * Create sort list
  * @return array
  */
 protected function createSortList()
 {
     $sortList = array();
     $fields = array_filter(explode(',', $this->request->getQuery(self::SORT_KEY)));
     foreach ($fields as $field) {
         $isInverted = Strings::substring($field, 0, 1) === '-';
         $sort = $isInverted ? self::SORT_DESC : self::SORT_ASC;
         $field = $isInverted ? Strings::substring($field, 1) : $field;
         $sortList[$field] = $sort;
     }
     return $sortList;
 }
Example #26
0
 public function setText($text)
 {
     $name = Strings::substring($text, 0, 30) . '...';
     $this->route->setName($name)->setTitle($name)->setText($text);
 }
Example #27
0
 /**
  * Converts name and surname to short form. E.g. "John Doe" => "John D."
  *
  * @param $name
  * @return string
  * @register
  */
 public static function shortName($name)
 {
     $name = explode(' ', $name, 2);
     if (isset($name[1]) && Strings::length($name[1])) {
         return $name[0] . ' ' . Strings::upper(Strings::substring($name[1], 0, 1)) . '.';
     } else {
         return $name[0];
     }
 }
 /**
  * Funkce vracející heslo k DB na základě údajů klienta
  * @param User $user
  * @return string
  */
 private function getUserDbPassword(User $user)
 {
     return Strings::substring($user->getDbPassword(), 2, 3) . Strings::substring(sha1($user->userId . $user->getDbPassword()), 4, 5);
 }
Example #29
0
 /**
  * Funkce pro dekódování encodedApiKey na pole s userId a apiKey
  * @param string $encodedApiKey
  * @return array
  */
 public static function decodeUserApiKey($encodedApiKey)
 {
     $realKey = Strings::substring($encodedApiKey, 0, 3);
     $number = hexdec(@$encodedApiKey[3]);
     $realKey .= Strings::substring($encodedApiKey, 4, $number) . Strings::substring($encodedApiKey, 4 + $number + 5);
     $userId = Strings::substring($encodedApiKey, 4 + $number, 5);
     $userId -= 18039;
     return ['userId' => $userId, 'apiKey' => $realKey];
 }
Example #30
0
 public function getHandle()
 {
     $s = Strings::webalize($this->title);
     return Strings::substring($s, 0, 4);
 }