Пример #1
0
 /**
  * Generate an absolute URL to the given asset.
  *
  * @param  string $asset
  * @param  mixed $extra
  * @param  bool|null $secure
  * @return string
  */
 public function asset($asset, $extra = [], $secure = null)
 {
     // First we will check if the URL is already a valid URL. If it is we will not
     // try to generate a new one but will simply return the URL as is, which is
     // convenient since developers do not always have to check if it's valid.
     if ($this->isValidUrl($asset)) {
         return $asset;
     }
     $scheme = $this->getScheme($secure);
     $extra = $this->formatParameters($extra);
     $tail = implode('/', array_map('rawurlencode', (array) $extra));
     // Once we have the scheme we will compile the "tail" by collapsing the values
     // into a single string delimited by slashes. This just makes it convenient
     // for passing the array of parameters to this URL as a list of segments.
     $root = $this->getRootUrl($scheme);
     if (defined('LOCALE') && ends_with($root, $search = '/' . LOCALE)) {
         $root = substr_replace($root, '', strrpos($root, $search), strlen($search));
     }
     if (($queryPosition = strpos($asset, '?')) !== false) {
         $query = mb_substr($asset, $queryPosition);
         $asset = mb_substr($asset, 0, $queryPosition);
     } else {
         $query = '';
     }
     return $this->trimUrl($root, $asset, $tail) . $query;
 }
Пример #2
0
 /**
  * 
  */
 public static function normalizeJsFile($content)
 {
     $content = self::removeMultiLineComments($content);
     $fileLines = explode("\n", $content);
     $taken = array();
     $scipSwap = array('//', '--');
     $swap = array('{', '}', '}}', '{{', '},', '};', '});', 'else', '}else{', '}else', 'else{', '})', 'return;', 'return{');
     $swap_start_end = array('?', ':', '.', '+', '||', '&&', ',', ';');
     $swap_end = array('{', '(');
     $swap_start = array('}');
     $swap_end = array_merge($swap_end, $swap_start_end);
     $swap_start = array_merge($swap_start, $swap_start_end);
     foreach ($fileLines as $line) {
         $line = trim($line);
         //Обрежем строчный комментарий
         //Нужно быть осторожным - двойной слеш может использоваться (в RegExt например)
         if ($line && contains_substring($line, '//')) {
             $line = trim(substr($line, 0, strpos($line, '//')));
         }
         if (!$line) {
             continue;
         }
         $tmp = normalize_string($line, true);
         $prevTmp = count($taken) > 0 ? normalize_string($taken[count($taken) - 1], true) : null;
         if ($prevTmp !== null && !contains_substring($prevTmp, $scipSwap) && (in_array($tmp, $swap) || ends_with($prevTmp, $swap_end) || starts_with($tmp, $swap_start))) {
             $taken[count($taken) - 1] .= ' ' . $line;
         } else {
             $taken[] = $line;
         }
     }
     return trim(implode("\n", $taken));
 }
Пример #3
0
 /**
  * Загружает глобальные настройки из файла и кеширует их в массиве GLOBALS.
  * Данный метод вызывается ТОЛЬКО при создании экземпляра класса.
  */
 private function load()
 {
     check_condition(!is_array($this->GLOBALS), 'Недопустима повторная загрузка глобальных настроек');
     $this->GLOBALS = array();
     $this->FileMtimeUpdate();
     $comment = array();
     foreach ($this->DI->getFileLines() as $line) {
         $line = trim($line);
         if (!$line || starts_with($line, '/*') || ends_with($line, '*/')) {
             continue;
         }
         if (starts_with($line, '*')) {
             $line = trim(first_char_remove($line));
             if ($line) {
                 $comment[] = $line;
             }
             continue;
         }
         if (starts_with($line, 'define')) {
             $name = trim(array_get_value(1, explode("'", $line, 3)));
             check_condition($name && defined($name), "Ошибка разбора файла глобальных настроек: свойство [{$name}] не определено.");
             $this->GLOBALS[$name] = new PsGlobalProp($name, implode(' ', $comment));
             $comment = array();
             continue;
         }
     }
 }
Пример #4
0
 public function getProps()
 {
     if (is_array($this->props)) {
         return $this->props;
     }
     $this->props = array();
     if (!$this->di->isFile()) {
         return $this->props;
     }
     $prop = null;
     $content = array();
     foreach ($this->di->getFileLines() as $line) {
         $line = trim($line);
         if (!$line) {
             continue;
         }
         if (starts_with($line, '[') && ends_with($line, ']')) {
             //Нашли свойство. Приверим, а нет ли информации о предыдущем свойстве
             if ($prop) {
                 $this->props[$prop] = trim(implode("\n", $content));
                 $content = array();
             }
             $prop = trim(cut_string_end(cut_string_start($line, '['), ']'));
             continue;
         }
         if (!$prop) {
             continue;
         }
         $content[] = $line;
     }
     if ($prop) {
         $this->props[$prop] = trim(implode("\n", $content));
     }
     return $this->props;
 }
 /**
  * @param  \Illuminate\View\View|string|array $view View object or view path
  * @param  array $data Data that should be made available to the view. Only used when $view is a string path
  * @param  string|boolean $layout Master layout path
  *
  * @return \Illuminate\View\View|\Illuminate\Http\Response
  */
 public function render($view, $data = [], $layout = null)
 {
     $format = null;
     if (is_array($view) && count($view) === 1) {
         $format = array_keys($view)[0];
         $view = array_values($view)[0];
         if (!ends_with($view, '_' . $format)) {
             $view = $view . '_' . $format;
         }
     }
     if (is_string($view)) {
         $view = View::make($view, $data);
     }
     // short circuit
     if ($format) {
         $response = Response::make($view);
         $response->header('Content-Type', Request::getMimeType($format));
         return $response;
     }
     if (!is_null($layout)) {
         $this->layout = $layout;
         $this->setupLayout();
     }
     if ($this->layout) {
         $this->layout->content = $view;
         return $this->layout;
     } else {
         return $view;
     }
 }
Пример #6
0
function ensure_trailing_slash($path)
{
    if (!ends_with($path, '/')) {
        return $path . '/';
    }
    return $path;
}
Пример #7
0
 static function unwrap($token, $domains, $address = null)
 {
     if ($package = base64_decode($token, true)) {
         if ($package = json::decode($package)) {
             if (isset($package->value) and isset($package->domain) and isset($package->expire_at) and isset($package->digest)) {
                 $digest = $package->digest;
                 unset($package->digest);
                 if ($digest === self::digest($package)) {
                     if (isset($package->address)) {
                         if (is_null($address) or $package->address !== $address) {
                             return null;
                         }
                     }
                     if ($package->expire_at === 0 or $package->expire_at > @time()) {
                         foreach ($domains as $domain) {
                             if (ends_with('.' . $package->domain, '.' . $domain)) {
                                 return $package->value;
                             }
                         }
                     }
                 }
             }
         }
     }
     return null;
 }
Пример #8
0
 /**
  * Convert a blade view into a site page.
  *
  * @param SplFileInfo $file
  *
  * @return void
  */
 public function handle(SplFileInfo $file, $viewsData)
 {
     $this->viewsData = $viewsData;
     $this->file = $file;
     $this->viewPath = $this->getViewPath();
     $this->directory = $this->getDirectoryPrettyName();
     $this->appendViewInformationToData();
     $content = $this->getFileContent();
     $this->filesystem->put(sprintf('%s/%s', $this->prepareAndGetDirectory(), ends_with($file->getFilename(), ['.blade.php', 'md']) ? 'index.html' : $file->getFilename()), $content);
     // copy images to public folder
     foreach ($file->images as $media) {
         $copyFrom = ORCA_CONTENT_DIR . "/{$file->getRelativePath()}/{$media}";
         $copyTo = "{$this->directory}/{$media}";
         if (!$this->filesystem->copy($copyFrom, $copyTo)) {
             echo "failed to copy {$media}...\n";
         }
     }
     // copy documents
     foreach ($file->documents as $media) {
         $copyFrom = ORCA_CONTENT_DIR . "/{$file->getRelativePath()}/{$media}";
         $copyTo = "{$this->directory}/{$media}";
         if (!$this->filesystem->copy($copyFrom, $copyTo)) {
             echo "failed to copy {$media}...\n";
         }
     }
 }
Пример #9
0
 private function stripExtension($hash)
 {
     if (ends_with($hash, '.png')) {
         return substr($hash, 0, -4);
     }
     return $hash;
 }
Пример #10
0
 /**
  * recurse method
  *
  * @param array  $items
  * @param string $parentId
  */
 protected function recurse($items = [], $parentId = 'root')
 {
     foreach ($items as $item) {
         $link = '#';
         $type = null;
         if (array_key_exists('document', $item)) {
             $type = 'document';
             // remove .md extension if present
             $path = ends_with($item['document'], ['.md']) ? Str::remove($item['document'], '.md') : $item['document'];
             $link = $this->codex->url($this->ref->getProject(), $this->ref->getName(), $path);
         } elseif (array_key_exists('href', $item)) {
             $type = 'href';
             $link = $item['href'];
         }
         $id = md5($item['name'] . $link);
         $node = $this->menu->add($id, $item['name'], $parentId);
         $node->setAttribute('href', $link);
         $node->setAttribute('id', $id);
         if (isset($path)) {
             $node->setMeta('path', $path);
         }
         if (isset($item['icon'])) {
             $node->setMeta('icon', $item['icon']);
         }
         if (isset($item['children'])) {
             $type = 'parent';
         }
         $node->setMeta('type', $type);
         if (isset($item['children'])) {
             $this->recurse($item['children'], $id);
         }
     }
 }
Пример #11
0
 /**
  * Constructor.
  *
  * Configure path config.
  *
  * @param  string $assetsPath   Base path to assets, within public directory
  * @param  string $manifestPath Full path to asset version manifest
  * @param  string $url          Optional URL prefix for assets
  * @return void
  */
 public function __construct($assetsPath, $manifestPath, $url = null)
 {
     $this->assetsPath = ends_with($assetsPath, '/') ? rtrim($assetsPath, '/') : $assetsPath;
     $this->manifestPath = $manifestPath;
     $this->url = $url;
     $this->manifest = null;
 }
Пример #12
0
 /**
  * Register opinionated controllers
  * 
  * @param array		$controllers	the controllers and config
  * @param string	$bundle			the bundle where the controller can be found
  * @param string	$url_prefix		a global url prefix
  * @param string	$route_type		the type of the route (pages or api)
  * @param array		$parents
  */
 public static function opinionated($controllers, $bundle, $url_prefix, $route_type, $parents = array())
 {
     if (!ends_with($url_prefix, '/')) {
         $url_prefix .= '/';
     }
     foreach ($controllers as $controller => $options) {
         list($types, $children) = $options;
         foreach ($types as $type) {
             list($method, $plural, $has_identity, $postfix) = static::$types[$type];
             $segment = $controller;
             $action = ($bundle ? $bundle . '::' : '') . implode('.', $parents) . (count($parents) > 0 ? '.' : '') . $segment . '@' . $type;
             if ($plural) {
                 $segment = Str::plural($segment);
             }
             $prefixes = array_map(function ($parent) {
                 return $parent ? $parent . '/(:any)/' : '(:any)/';
             }, $parents);
             $prefix = implode('', $prefixes);
             $route = $url_prefix . $prefix . $segment . ($has_identity ? '/(:any)' : '') . ($route_type == 'pages' && $postfix ? '/' . $postfix : '');
             if ($route_type == 'pages') {
                 $method = '*';
             }
             Router::register($method, $route, $action);
         }
         $parents[] = $controller;
         if (is_array($children)) {
             static::opinionated($children, $bundle, $url_prefix, $route_type, $parents);
         }
         $parents = array();
     }
 }
Пример #13
0
 /**
  * Play/stream a song.
  *
  * @link https://github.com/phanan/koel/wiki#streaming-music
  *
  * @param Song      $song      The song to stream.
  * @param null|bool $transcode Whether to force transcoding the song.
  *                             If this is omitted, by default Koel will transcode FLAC.
  * @param null|int  $bitRate   The target bit rate to transcode, defaults to OUTPUT_BIT_RATE.
  *                             Only taken into account if $transcode is truthy.
  *
  * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
  */
 public function play(Song $song, $transcode = null, $bitRate = null)
 {
     if ($song->s3_params) {
         return (new S3Streamer($song))->stream();
     }
     // If `transcode` parameter isn't passed, the default is to only transcode FLAC.
     if ($transcode === null && ends_with(mime_content_type($song->path), 'flac')) {
         $transcode = true;
     }
     $streamer = null;
     if ($transcode) {
         $streamer = new TranscodingStreamer($song, $bitRate ?: config('koel.streaming.bitrate'), request()->input('time', 0));
     } else {
         switch (config('koel.streaming.method')) {
             case 'x-sendfile':
                 $streamer = new XSendFileStreamer($song);
                 break;
             case 'x-accel-redirect':
                 $streamer = new XAccelRedirectStreamer($song);
                 break;
             default:
                 $streamer = new PHPStreamer($song);
                 break;
         }
     }
     $streamer->stream();
 }
Пример #14
0
 public function test02EndsWith()
 {
     $this->assertTrue(function_exists('ends_with'));
     $this->assertTrue(ends_with('ends_with', 'ith'));
     $this->assertFalse(ends_with('ith', 'ends_with'));
     $this->assertTrue(ends_with('ends_with', ''));
 }
Пример #15
0
 public static function isPathSupported($path)
 {
     $extension = array_first(array_keys(static::$compilers), function ($key, $value) use($path) {
         return ends_with($path, $value);
     });
     return $extension !== null;
 }
Пример #16
0
 /**
  * Play a song.
  *
  * @link https://github.com/phanan/koel/wiki#streaming-music
  *
  * @param Song $song
  */
 public function play(Song $song, $transcode = null, $bitrate = null)
 {
     if (is_null($bitrate)) {
         $bitrate = env('OUTPUT_BIT_RATE', 128);
     }
     if ($song->s3_params) {
         return (new S3Streamer($song))->stream();
     }
     // If transcode parameter isn't passed, the default is to only transcode flac
     if (is_null($transcode) && ends_with(mime_content_type($song->path), 'flac')) {
         $transcode = true;
     } else {
         $transcode = (bool) $transcode;
     }
     if ($transcode) {
         return (new TranscodingStreamer($song, $bitrate, request()->input('time', 0)))->stream();
     }
     switch (env('STREAMING_METHOD')) {
         case 'x-sendfile':
             return (new XSendFileStreamer($song))->stream();
         case 'x-accel-redirect':
             return (new XAccelRedirectStreamer($song))->stream();
         default:
             return (new PHPStreamer($song))->stream();
     }
 }
Пример #17
0
 protected function validateCampaignCode($code)
 {
     if (ends_with($code, '.png')) {
         $this->trackingMode = true;
         $code = substr($code, 0, -4);
     }
     $parts = explode('!', base64_decode($code));
     if (count($parts) < 3) {
         throw new ApplicationException('Invalid code');
     }
     list($campaignId, $subscriberId, $hash) = $parts;
     /*
      * Render unique content for the subscriber
      */
     $this->campaign = Message::find((int) $campaignId);
     $this->subscriber = $this->campaign->subscribers()->where('id', (int) $subscriberId)->first();
     if (!$this->subscriber) {
         $this->subscriber = Subscriber::find((int) $subscriberId);
     }
     if (!$this->campaign || !$this->subscriber) {
         throw new ApplicationException('Invalid code');
     }
     /*
      * Verify unique hash
      */
     $verifyValue = $campaignId . '!' . $subscriberId;
     $verifyHash = md5($verifyValue . '!' . $this->subscriber->email);
     if ($hash != $verifyHash) {
         throw new ApplicationException('Invalid hash');
     }
 }
Пример #18
0
 function __collectResources()
 {
     global $CONFIG;
     $min_js_file = isset($CONFIG['use_compiled_js']) ? $CONFIG['use_compiled_js'] : false;
     $min_css_file = isset($CONFIG['use_compiled_css']) ? $CONFIG['use_compiled_css'] : false;
     if ($min_js_file && $min_css_file) {
         return array($min_css_file, $min_js_file);
     }
     $res = $this->__collectResourcesInternal($this);
     if (!$min_js_file && !$min_css_file) {
         return $res;
     }
     $js = array();
     $css = array();
     foreach ($res as $r) {
         if (ends_with($r, '.js')) {
             if (!$min_js_file) {
                 $js[] = $r;
             }
         } else {
             if (!$min_css_file) {
                 $css[] = $r;
             }
         }
     }
     if ($min_js_file) {
         $css[] = $min_js_file;
         return $css;
     }
     $js[] = $min_css_file;
     return $js;
 }
 /**
  * Execute the console command.
  *
  * @return void
  */
 public function fire()
 {
     $clearableDirs = ['/products', '/categories'];
     $base_path = public_path() . '/' . Config::get('ProductCatalog::app.upload_base_path');
     $initialDirs = File::directories($base_path);
     if ($initialDirs) {
         foreach (File::directories($base_path) as $key => $path) {
             // If the path ends with one of the items in the clearable directories then we can clear it
             if (ends_with($path, $clearableDirs)) {
                 // Go through each product / categorie's directory
                 foreach (File::directories($path) as $key => $path) {
                     $toDelete = $path . '/cached';
                     if (File::isDirectory($toDelete)) {
                         File::deleteDirectory($toDelete);
                         $this->info("Deleted: " . $toDelete);
                     }
                 }
             }
         }
         $this->info("All cache's deleted");
         return;
     }
     $this->error("No valid directories found.");
     return;
 }
 public function handle(Request $request, Closure $next)
 {
     $route = $request->route();
     $parameters = $route->parameters();
     $parameterKeys = array_keys($parameters);
     // Look for parameters that match {*_morph_type} and {*_morph_id}
     $morphTypeName = Arr::first($parameterKeys, function ($item) {
         return ends_with($item, '_type');
     });
     $morphIdName = Arr::first($parameterKeys, function ($item) {
         return ends_with($item, '_id');
     });
     if (!$morphTypeName or !$morphIdName) {
         return $next($request);
     }
     $morphKey = preg_replace("/_type\$/", '', $morphTypeName);
     if ($morphKey !== preg_replace("/_id\$/", '', $morphIdName)) {
         return $next($request);
     }
     $morphTypeName = $morphKey . '_type';
     $morphIdName = $morphKey . '_id';
     $morphType = $parameters[$morphTypeName];
     $morphId = $parameters[$morphIdName];
     // Not going to worry about custom keys here.
     $morphInstance = requireMorphInstance($morphType, $morphId);
     $route->forgetParameter($morphTypeName);
     $route->forgetParameter($morphIdName);
     $route->setParameter($morphKey, $morphInstance);
     return $next($request);
 }
function import_asset_folder($folder)
{
    $uuidRegex = '/^([\\w+\\d+\\s]+\\-\\s*?)??([0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12})\\.(\\w+)$/';
    $mimeMap = array('bodypart' => 'application/vnd.ll.bodypart', 'ogg' => 'application/ogg', 'j2c' => 'image/x-j2c', 'animation' => 'application/vnd.ll.animation', 'clothing' => 'application/vnd.ll.clothing', 'lsl' => 'application/vnd.ll.lsltext');
    if (!ends_with($folder, '/')) {
        $folder .= '/';
    }
    $i = 0;
    if ($handle = opendir($folder)) {
        while ($file = readdir($handle)) {
            if (is_file($folder . $file)) {
                echo 'Opening ' . $folder . $file . '<br/>';
                $parts = pathinfo($folder . $file);
                if (isset($mimeMap[$parts["extension"]]) && preg_match($uuidRegex, $file, $matches)) {
                    $assetID = $matches[2];
                    $creatorID = '00000000-0000-0000-0000-000000000000';
                    $contentType = $mimeMap[$parts["extension"]];
                    $response = create_asset($assetID, $creatorID, $contentType, $folder . $file);
                    if (!empty($response['Success'])) {
                        echo 'Successfully imported ' . $file . '<br/>';
                        ++$i;
                    } else {
                        echo 'Failed to import ' . $file . ': ' . $response['Message'] . '<br/>';
                        return $i;
                    }
                }
            }
        }
    } else {
        echo 'Failed opening folder ' . $folder . '<br/>';
    }
    return $i;
}
Пример #22
0
 public function calculatePercentualOrFixed($value)
 {
     if (ends_with($value, '%')) {
         return $this->calculatePercentual($value);
     }
     return (double) $value;
 }
Пример #23
0
/**
 * Gets the value of an environment variable. Supports boolean, empty and null.
 *
 * @param  string  $key
 * @param  mixed   $default
 * @return mixed
 * @author Taylor Otwell - Laravel
 */
function env($key, $default = null)
{
    $value = getenv($key);
    if ($value === false) {
        return value($default);
    }
    switch (strtolower($value)) {
        case 'true':
        case '(true)':
            return true;
        case 'false':
        case '(false)':
            return false;
        case 'empty':
        case '(empty)':
            return '';
        case 'null':
        case '(null)':
            return;
    }
    if (starts_with($value, '"') && ends_with($value, '"')) {
        return substr($value, 1, -1);
    }
    return $value;
}
Пример #24
0
 /**
  * Get the segments of the option field.
  *
  * @param  string $field
  * @return array
  * @throws \Exception
  */
 private function parseSegments($field)
 {
     $field = starts_with('\\', $field) ? $field : '\\' . $field;
     $segments = explode(':', $field);
     if (count($segments) < 2) {
         throw new \Exception('--includes option should be consist of string value of model, separated by colon(:),
             and string value of relationship. e.g. App\\User:author, App\\Comment:comments:true.
             If the third element is provided as true, yes, or 1, the command will interpret the include as an collection.');
     }
     $fqcn = array_shift($segments);
     //        if (! class_exists($fqcn)) {
     //            throw new \Exception(
     //                'Not existing Model - ' . $fqcn
     //            );
     //        }
     $relationship = array_shift($segments);
     $type = in_array(array_shift($segments), ['yes', 'y', 'true', true, '1', 1]) ? 'collection' : 'item';
     $namespace = config('api.transformer.namespace');
     $namespace = starts_with($namespace, '\\') ? $namespace : '\\' . $namespace;
     $namespace = ends_with($namespace, '\\') ? $namespace : $namespace . '\\';
     $obj = new \stdClass();
     $obj->type = $type;
     $obj->fqcn = $fqcn;
     $obj->model = ltrim($fqcn, '\\');
     $obj->basename = class_basename($fqcn);
     $obj->relationship = $relationship;
     $obj->method = 'include' . ucfirst($relationship);
     $obj->transformer = $namespace . ucfirst($obj->basename) . 'Transformer';
     return $obj;
 }
Пример #25
0
 function get_list($prefix = '')
 {
     if (!empty($prefix) and !ends_with($prefix, '/')) {
         $prefix .= '/';
     }
     $result = $this->s3_client->listObjects(array('Bucket' => $this->bucket, 'Delimiter' => '/', 'Prefix' => $prefix));
     return $result->toArray();
 }
Пример #26
0
 public function shouldHandle($file)
 {
     if (!ends_with($file->getFilename(), '.blade.php')) {
         return false;
     }
     list($frontMatter, $content) = $this->parser->parse($file->getContents());
     return isset($frontMatter['pagination']);
 }
Пример #27
0
 protected function guessModelName()
 {
     $class = class_basename(get_called_class());
     if (ends_with($class, 'Controller')) {
         return str_replace('Controller', '', $class);
     }
     return $class;
 }
Пример #28
0
 /**
  * __construct 
  */
 protected function __construct(SplFileInfo $file, $relativePath = null)
 {
     $this->title = Content::filename_to_title($file->getFilename());
     $this->slug = Content::str_to_slug($file->getFilename());
     $relativePath = !is_null($relativePath) && !empty($relativePath) ? $relativePath : $file->getRelativePath();
     $this->path = $relativePath . (ends_with($relativePath, '/') ? '' : '/') . $this->slug;
     $this->file = $file;
 }
Пример #29
0
 public function __construct(CodeBase $cmsObject = null, $properties = [])
 {
     parent::__construct($cmsObject, $properties);
     // Remove extra component from end
     if (ends_with($this->dirName, 'component')) {
         $this->dirName = substr($this->dirName, 0, -9);
     }
 }
 protected function getFileName($file)
 {
     $file = basename($file);
     if (!ends_with($file, '.php')) {
         $file = $file . '.php';
     }
     return $file;
 }