code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
public function output($filename, $input) { $cmdSep = $this->_settings['version'] <= 1 ? ' - ' : ''; $cmd = $this->_settings['node'] . ' ' . $this->_settings['uglify'] . $cmdSep . $this->_settings['options']; $env = array('NODE_PATH' => $this->_settings['node_path']); return $this->_runCmd($cmd, $input, $env); }
Run `uglifyjs` against the output and compress it. @param string $filename Name of the file being generated. @param string $input The uncompressed contents for $filename. @return string Compressed contents.
public function up() { Schema::create('group_role', function (Blueprint $table) { $table->smallInteger('group_id')->unsigned(); $table->integer('page_id')->unsigned()->default(0); $table->smallInteger('role_id')->unsigned()->index('role_id'); $table->boolean('allowed')->nullable(); $table->primary(['group_id', 'role_id', 'page_id']); $table->index(['group_id', 'role_id', 'page_id'], 'permissions_role_id_action_id_where_id'); }); }
Run the migrations. @return void
public function up() { Schema::create('search_texts', function (Blueprint $table) { $table->increments('id'); $table->integer('page_vid') ->unsigned() ->nullable() ->references('id') ->on('page_versions') ->onUpdate('CASCADE') ->onDelete('CASCADE'); $table->integer('page_id') ->unsigned() ->references('id') ->on('pages') ->onUpdate('CASCADE') ->onDelete('CASCADE'); $table->integer('embargoed_until')->unsigned()->nullable(); $table->string('title', 75)->nullable(); $table->string('standfirst', '255')->null(); $table->longText('text')->nullable(); $table->index(['page_id', 'embargoed_until']); }); DB::statement('ALTER TABLE search_texts ENGINE = "MyISAM"'); DB::statement('CREATE FULLTEXT INDEX search_texts_title on search_texts(title)'); DB::statement('CREATE FULLTEXT INDEX search_texts_standfirst on search_texts(standfirst)'); DB::statement('CREATE FULLTEXT INDEX search_texts_text on search_texts(text)'); DB::statement('CREATE FULLTEXT INDEX search_texts_all on search_texts(title, standfirst, text)'); DB::statement('ALTER TABLE chunk_texts drop index text_fulltext'); DB::statement('ALTER TABLE page_versions drop index title_fulltext'); }
Run the migrations. @return void
public function getDependencies(AssetTarget $target) { $children = []; $hasPrefix = (property_exists($this, 'optionalDependencyPrefix') && !empty($this->optionalDependencyPrefix)); foreach ($target->files() as $file) { $imports = CssUtils::extractImports($file->contents()); if (empty($imports)) { continue; } $ext = $this->_settings['ext']; $extLength = strlen($ext); $deps = []; foreach ($imports as $name) { if ('.css' === substr($name, -4)) { // skip normal css imports continue; } if ($ext !== substr($name, -$extLength)) { $name .= $ext; } $deps[] = $name; if ($hasPrefix) { $deps[] = $this->_prependPrefixToFilename($name); } } foreach ($deps as $import) { $path = $this->_findFile($import); try { $file = new Local($path); $newTarget = new AssetTarget('phony.css', [$file]); $children[] = $file; } catch (\Exception $e) { // Do nothing, we just skip missing files. // sometimes these are things like compass or bourbon // internals. $newTarget = false; } // Only recurse through non-css imports as css files are not // inlined by less/sass. if ($newTarget && $ext === substr($import, -$extLength)) { $children = array_merge($children, $this->getDependencies($newTarget)); } } } return $children; }
{@inheritDoc}
protected function _findFile($file) { foreach ($this->_settings['paths'] as $path) { $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; if (file_exists($path . $file)) { return $path . $file; } } return $file; }
Attempt to locate a file in the configured paths. @param string $file The file to find. @return string The resolved file.
protected function _prependPrefixToFilename($name) { $ds = DIRECTORY_SEPARATOR; $parts = explode($ds, $name); $filename = end($parts); if ($name === $filename || $filename[0] === $this->optionalDependencyPrefix) { return $this->optionalDependencyPrefix . $name; } return str_replace( $ds . $filename, $ds . $this->optionalDependencyPrefix . $filename, $name ); }
Prepends filenames with defined prefix if not already defined. @param string $name The file name. @param string The prefixed filename.
public function setSlidesAttribute($slides) { foreach ($slides as &$slide) { if (!$slide instanceof Slideshow\Slide) { $slide['url'] = (isset($slide['page']) && $slide['page'] > 0) ? $slide['page'] : isset($slide['url']) ? $slide['url'] : null; unset($slide['page']); if (isset($slide['asset']) && is_array($slide['asset'])) { $slide['asset_id'] = $slide['asset']['id']; unset($slide['asset']); } $slide = new Slideshow\Slide($slide); } } $this->created(function () use ($slides) { $this->slides()->saveMany($slides); }); }
Persists slide data to the database.
public function handle(Request $request, Closure $next) { $asset = $request->route()->parameter('asset'); if (!$asset->isPublic() && !$this->guard->check()) { abort(401); } if (!Asset::exists($asset)) { abort(404); } return $next($request); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
public function index(Page $page) { $this->auth($page); return view('boomcms::editor.page.settings.acl', [ 'page' => $page, 'allGroups' => GroupFacade::findAll(), 'groupIds' => $page->getAclGroupIds(), ]); }
View the page ACL settings. @param Page $page @return View
public function up() { Schema::create('chunk_calendars', function (Blueprint $table) { $table->increments('id'); $table->integer('page_vid') ->unsigned() ->nullable() ->references('id') ->on('page_versions') ->onUpdate('CASCADE') ->onDelete('CASCADE'); $table->integer('page_id') ->unsigned() ->references('id') ->on('pages') ->onUpdate('CASCADE') ->onDelete('CASCADE'); $table->string('slotname', 50)->nullable(); $table->text('content'); }); }
Run the migrations. @return void
public function output($filename, $input) { $paths = [getcwd(), dirname(dirname(dirname(dirname(__DIR__))))]; $jar = $this->_findExecutable($paths, $this->_settings['path']); $cmd = 'java -jar "' . $jar . '" --type js'; return $this->_runCmd($cmd, $input); }
Run $input through YuiCompressor @param string $filename Filename being generated. @param string $input Contents of file @return Compressed file
public static function setEnvironment(): void { error_reporting(E_ALL); set_error_handler(function ($errno, $errstr, $errfile, $errline, array $errcontext): bool { if (!(error_reporting() & $errno)) { // respect error_reporting() level // libraries used in custom components may emit notices that cannot be fixed return false; } throw new ErrorException($errstr, 0, $errno, $errfile, $errline); }); }
Prepares environment. Sets error reporting for the app to fail on any error, warning or notice. If your code emits notices and cannot be fixed, you can set `error_reporting` in `$application->run()` method.
protected function loadConfig(): void { $configClass = $this->getConfigClass(); $configDefinitionClass = $this->getConfigDefinitionClass(); try { $this->config = new $configClass( $this->getRawConfig(), new $configDefinitionClass() ); } catch (InvalidConfigurationException $e) { throw new UserException($e->getMessage(), 0, $e); } }
Automatically loads configuration from datadir, instantiates specified config class and validates it with specified confing definition class
public static function controller(AssetModel $asset) { $namespace = 'BoomCMS\Http\Controllers\ViewAsset\\'; if (!$asset->getExtension()) { return; } $byExtension = $namespace.ucfirst($asset->getExtension()); if (class_exists($byExtension)) { return $byExtension; } $byType = $namespace.ucfirst($asset->getType()); if (class_exists($byType)) { return $byType; } return $namespace.'BaseController'; }
Return the controller to be used to display an asset. @param Asset $asset @return string
public static function typeFromMimetype($mime) { foreach (static::types() as $type => $mimetypes) { if (array_search($mime, $mimetypes) !== false) { return $type; } } }
@param string $mime @return string
public function up() { Schema::create('roles', function (Blueprint $table) { $table->smallInteger('id', true)->unsigned(); $table->string('name', 30)->unique(); $table->boolean('tree')->default(false); $table->index('tree'); }); }
Run the migrations. @return void
protected function _addConstants($constants) { foreach ($constants as $key => $value) { if (is_resource($value) === false) { if (is_array($value) || strpos($value, DIRECTORY_SEPARATOR) === false) { continue; } if ($value !== DIRECTORY_SEPARATOR && !@file_exists($value)) { continue; } $this->constantMap[$key] = rtrim($value, DIRECTORY_SEPARATOR); } } ksort($this->constantMap); }
Add path based constants to the mapped constants. @param array $constants The constants to map @return void
public function load($path, $prefix = '') { $config = $this->readConfig($path); foreach ($config as $section => $values) { if (in_array($section, self::$_extensionTypes)) { // extension section, merge in the defaults. $defaults = $this->get($section); if ($defaults) { $values = array_merge($defaults, $values); } $this->addExtension($section, $values); } elseif (strtolower($section) === self::GENERAL) { if (!empty($values['timestampPath'])) { $path = $this->_replacePathConstants($values['timestampPath']); $values['timestampPath'] = rtrim($path, '/') . '/'; } $this->set(self::GENERAL, $values); } elseif (strpos($section, self::FILTER_PREFIX) === 0) { // filter section. $name = str_replace(self::FILTER_PREFIX, '', $section); $this->filterConfig($name, $values); } else { $lastDot = strrpos($section, '.') + 1; $extension = substr($section, $lastDot); $key = $section; // must be a build target. $this->addTarget($prefix . $key, $values); } } $this->resolveExtends(); return $this; }
Load a config file into the current instance. @param string $path The config file to load. @param string $prefix The string to prefix all targets in $path with. @return $this
protected function readConfig($filename) { if (empty($filename) || !is_string($filename) || !file_exists($filename)) { throw new RuntimeException(sprintf('Configuration file "%s" was not found.', $filename)); } $this->_modifiedTime = max($this->_modifiedTime, filemtime($filename)); if (function_exists('parse_ini_file')) { return parse_ini_file($filename, true); } else { return parse_ini_string(file_get_contents($filename), true); } }
Read the configuration file from disk @param string $filename Name of the inifile to parse @return array Inifile contents @throws RuntimeException
protected function resolveExtends() { $extend = []; foreach ($this->_targets as $name => $target) { if (empty($target['extend'])) { continue; } $parent = $target['extend']; if (empty($this->_targets[$parent])) { throw new RuntimeException("Invalid extend in '$name'. There is no '$parent' target defined."); } $extend[] = $name; } $expander = function ($target) use (&$expander, $extend) { $config = $this->_targets[$target]; $parentConfig = false; // Recurse through parents to collect all config. if (in_array($target, $extend)) { $parentConfig = $expander($config['extend']); } if (!$parentConfig) { return $config; } $config['files'] = array_merge($parentConfig['files'], $config['files']); $config['filters'] = array_merge($parentConfig['filters'], $config['filters']); $config['theme'] = $parentConfig['theme'] || $config['theme']; return $config; }; foreach ($extend as $target) { $this->_targets[$target] = $expander($target); } }
Once all targets have been built, resolve extend options. @return void @throws RuntimeException
protected function _parseExtensionDef($target) { $paths = array(); if (!empty($target['paths'])) { $paths = array_map(array($this, '_replacePathConstants'), (array)$target['paths']); } $target['paths'] = $paths; if (!empty($target['cachePath'])) { $path = $this->_replacePathConstants($target['cachePath']); $target['cachePath'] = rtrim($path, '/') . '/'; } return $target; }
Parses paths in an extension definition @param array $data Array of extension information. @return array Array of build extension information with paths replaced.
public function set($path, $value) { $parts = explode('.', $path); switch (count($parts)) { case 2: $this->_data[$parts[0]][$parts[1]] = $value; break; case 1: $this->_data[$parts[0]] = $value; break; case 0: throw new RuntimeException('Path was empty.'); default: throw new RuntimeException('Too many parts in path.'); } }
Set values into the config object, You can't modify targets, or filters with this. Use the appropriate methods for those settings. @param string $path The path to set. @param string $value The value to set. @throws RuntimeException
public function get($path) { $parts = explode('.', $path); switch (count($parts)) { case 2: if (isset($this->_data[$parts[0]][$parts[1]])) { return $this->_data[$parts[0]][$parts[1]]; } break; case 1: if (isset($this->_data[$parts[0]])) { return $this->_data[$parts[0]]; } break; case 0: throw new RuntimeException('Path was empty.'); default: throw new RuntimeException('Too many parts in path.'); } }
Get values from the config data. @param string $path The path you want. @throws RuntimeException On invalid paths.
public function filters($ext, $filters = null) { if ($filters === null) { if (isset($this->_data[$ext][self::FILTERS])) { return $this->_data[$ext][self::FILTERS]; } return []; } $this->_data[$ext][self::FILTERS] = $filters; }
Get/set filters for an extension @param string $ext Name of an extension @param array $filters Filters to replace either the global or per target filters. @return array Filters for extension.
public function targetFilters($name) { $ext = $this->getExt($name); $filters = []; if (isset($this->_data[$ext][self::FILTERS])) { $filters = $this->_data[$ext][self::FILTERS]; } if (!empty($this->_targets[$name][self::FILTERS])) { $buildFilters = $this->_targets[$name][self::FILTERS]; $filters = array_merge($filters, $buildFilters); } return array_unique($filters); }
Get the filters for a build target. @param string $name The build target to get filters for. @return array
public function allFilters() { $filters = []; foreach ($this->extensions() as $ext) { if (empty($this->_data[$ext][self::FILTERS])) { continue; } $filters = array_merge($filters, $this->_data[$ext][self::FILTERS]); } foreach ($this->_targets as $target) { if (empty($target[self::FILTERS])) { continue; } $filters = array_merge($filters, $target[self::FILTERS]); } return array_unique($filters); }
Get configuration for all filters. Useful for building FilterRegistry objects @return array Config data related to all filters.
public function filterConfig($filter, $settings = null) { if ($settings === null) { if (is_string($filter)) { return isset($this->_filters[$filter]) ? $this->_filters[$filter] : []; } if (is_array($filter)) { $result = []; foreach ($filter as $f) { $result[$f] = $this->filterConfig($f); } return $result; } } $this->_filters[$filter] = array_map( [$this, '_replacePathConstants'], $settings ); }
Get/Set filter Settings. @param string $filter The filter name @param array $settings The settings to set, leave null to get @return mixed.
public function paths($ext, $target = null, $paths = null) { if ($paths === null) { if (empty($this->_data[$ext]['paths'])) { $paths = array(); } else { $paths = (array)$this->_data[$ext]['paths']; } if ($target !== null && !empty($this->_targets[$target]['paths'])) { $buildPaths = $this->_targets[$target]['paths']; $paths = array_merge($paths, $buildPaths); } return array_unique($paths); } $paths = array_map(array($this, '_replacePathConstants'), $paths); if ($target === null) { $this->_data[$ext]['paths'] = $paths; } else { $this->_targets[$target]['paths'] = $paths; } }
Get/set paths for an extension. Setting paths will replace global or per target existing paths. Its only intended for testing. @param string $ext Extension to get paths for. @param string $target A build target. If provided the target's paths (if any) will also be returned. @param array $paths Paths to replace either the global or per target paths. @return array An array of paths to search for assets on.
public function cachePath($ext, $path = null) { if ($path === null) { if (isset($this->_data[$ext]['cachePath'])) { return $this->_data[$ext]['cachePath']; } return ''; } $path = $this->_replacePathConstants($path); $this->_data[$ext]['cachePath'] = rtrim($path, '/') . '/'; }
Accessor for getting the cachePath for a given extension. @param string $ext Extension to get paths for. @param string $path The path to cache files using $ext to.
public function general($key, $value = null) { if ($value === null) { return isset($this->_data[self::GENERAL][$key]) ? $this->_data[self::GENERAL][$key] : null; } $this->_data[self::GENERAL][$key] = $value; }
Get / set values from the General section. This is preferred to using get()/set() as you don't run the risk of making a mistake in General's casing. @param string $key The key to read/write @param mixed $value The value to set. @return mixed Null when writing. Either a value or null when reading.
public function addTarget($target, array $config) { $ext = $this->getExt($target); $config += [ 'files' => [], 'filters' => [], 'theme' => false, 'extend' => false, 'require' => [], ]; if (!empty($config['paths'])) { $config['paths'] = array_map(array($this, '_replacePathConstants'), (array)$config['paths']); } $this->_targets[$target] = $config; }
Create a new build target. @param string $target Name of the target file. The extension will be inferred based on the last extension. @param array $config Config data for the target. Should contain files, filters and theme key.
public function theme($theme = null) { if ($theme === null) { return isset($this->_data['theme']) ? $this->_data['theme'] : ''; } $this->_data['theme'] = $theme; }
Set the active theme for building assets. @param string $theme The theme name to set. Null to get @return mixed Either null on set, or theme on get
public function write(AssetTarget $build, $content) { $ext = $build->ext(); $path = $build->outputDir(); if (!is_writable($path)) { throw new RuntimeException('Cannot write cache file. Unable to write to ' . $path); } $filename = $this->buildFileName($build); $success = file_put_contents($path . DIRECTORY_SEPARATOR . $filename, $content) !== false; $this->finalize($build); return $success; }
Writes content into a file @param AssetTarget $build The filename to write. @param string $content The contents to write. @throws RuntimeException
public function invalidate(AssetTarget $build) { $ext = $build->ext(); if (empty($this->timestamp[$ext])) { return false; } $this->_invalidated = $build->name(); $this->setTimestamp($build, 0); }
Invalidate a build before re-generating the file. @param string $build The build to invalidate. @return void
public function finalize(AssetTarget $build) { $ext = $build->ext(); if (empty($this->timestamp[$ext])) { return; } $data = $this->_readTimestamp(); $name = $this->buildCacheName($build); if (!isset($data[$name])) { return; } $time = $data[$name]; unset($data[$name]); $this->_invalidated = null; $name = $this->buildCacheName($build); $data[$name] = $time; $this->_writeTimestamp($data); }
Finalize a build after written to filesystem. @param AssetTarget $build The build to finalize. @return void
public function setTimestamp(AssetTarget $build, $time) { $ext = $build->ext(); if (empty($this->timestamp[$ext])) { return; } $data = $this->_readTimestamp(); $name = $this->buildCacheName($build); $data[$name] = $time; $this->_writeTimestamp($data); }
Set the timestamp for a build file. @param AssetTarget $build The name of the build to set a timestamp for. @param int $time The timestamp. @return void
protected function _readTimestamp() { $data = array(); if (empty($data) && file_exists($this->path . static::BUILD_TIME_FILE)) { $data = file_get_contents($this->path . static::BUILD_TIME_FILE); if ($data) { $data = unserialize($data); } } return $data; }
Read timestamps from either the fast cache, or the serialized file. @return array An array of timestamps for build files.
protected function _writeTimestamp($data) { $data = serialize($data); file_put_contents($this->path . static::BUILD_TIME_FILE, $data); chmod($this->path . static::BUILD_TIME_FILE, 0644); }
Write timestamps to either the fast cache, or the serialized file. @param array $data An array of timestamps for build files. @return void
public function buildFileName(AssetTarget $target, $timestamp = true) { $file = $target->name(); if ($target->isThemed() && $this->theme) { $file = $this->theme . '-' . $file; } if ($timestamp) { $time = $this->getTimestamp($target); $file = $this->_timestampFile($file, $time); } return $file; }
Get the final filename for a build. Resolves theme prefixes and timestamps. @param AssetTarget $target The build target name. @return string The build filename to cache on disk.
public function buildCacheName($build) { $name = $this->buildFileName($build, false); if ($build->name() == $this->_invalidated) { return '~' . $name; } return $name; }
Get the cache name a build. @param string $build The build target name. @return string The build cache name.
public function clearTimestamps() { $path = $this->path . static::BUILD_TIME_FILE; if (file_exists($path)) { unlink($this->path . static::BUILD_TIME_FILE); } }
Clear timestamps for assets. @return void
protected function _timestampFile($file, $time) { if (!$time) { return $file; } $pos = strrpos($file, '.'); $name = substr($file, 0, $pos); $ext = substr($file, $pos); return $name . '.v' . $time . $ext; }
Modify a file name and append in the timestamp @param string $file The filename. @param int $time The timestamp. @return string The build filename to cache on disk.
protected function _normalizePaths() { foreach ($this->_paths as &$path) { $ds = DIRECTORY_SEPARATOR; $path = $this->_normalizePath($path, $ds); $path = rtrim($path, $ds) . $ds; } }
Ensure all paths end in a directory separator and expand any APP/WEBROOT constants. Normalizes the Directory Separator as well. @return void
protected function _expandPaths() { $expanded = array(); foreach ($this->_paths as $path) { if (preg_match('/[*.\[\]]/', $path)) { $tree = $this->_generateTree($path); $expanded = array_merge($expanded, $tree); } else { $expanded[] = $path; } } $this->_paths = $expanded; }
Expands constants and glob() patterns in the searchPaths. @return void
protected function _generateTree($path) { $paths = glob($path, GLOB_ONLYDIR); if (!$paths) { $paths = array(); } array_unshift($paths, dirname($path)); return $paths; }
Discover all the sub directories for a given path. @param string $path The path to search @return array Array of subdirectories.
public function find($file) { $found = false; $expanded = $this->_expandPrefix($file); if (file_exists($expanded)) { return $expanded; } foreach ($this->_paths as $path) { $file = $this->_normalizePath($file, DIRECTORY_SEPARATOR); $fullPath = $path . $file; if (file_exists($fullPath)) { $found = $fullPath; break; } } return $found; }
Find a file in the connected paths, and check for its existance. @param string $file The file you want to find. @return mixed Either false on a miss, or the full path of the file.
public function up() { DB::statement('alter table chunk_texts drop foreign key chunk_texts_page_id_foreign'); DB::statement('alter table chunk_texts drop foreign key chunk_texts_ibfk_1'); DB::statement('alter table chunk_texts engine = "MyISAM"'); DB::statement('CREATE FULLTEXT INDEX text_fulltext on chunk_texts(text)'); DB::statement('create index chunk_texts_page_id on chunk_texts(page_id)'); DB::statement('create index chunk_texts_page_vid on chunk_texts(page_vid)'); DB::statement('alter table page_versions drop foreign key page_versions_ibfk_1'); DB::statement('alter table chunk_features drop foreign key chunk_features_ibfk_1'); DB::statement('alter table chunk_assets drop foreign key chunk_assets_ibfk_1'); DB::statement('alter table chunk_slideshows drop foreign key chunk_slideshows_ibfk_1'); DB::statement('alter table chunk_linksets drop foreign key chunk_linksets_ibfk_1'); DB::statement('alter table chunk_timestamps drop foreign key chunk_timestamps_ibfk_1'); DB::statement('alter table page_versions engine = "MyISAM"'); DB::statement('CREATE FULLTEXT INDEX title_fulltext on page_versions(title)'); }
Run the migrations. @return void
public function getDelete(Page $page) { $this->authorize('delete', $page); return view($this->viewPrefix.'.delete', [ 'children' => $page->countChildren(), 'page' => $page, ]); }
Show the delete page confirmation. @param Page $page @return View
public function getHistory(Page $page) { $this->authorize('edit', $page); return view("$this->viewPrefix.history", [ 'versions' => PageVersionFacade::history($page), 'page' => $page, 'diff' => new Diff(), ]); }
Show the page version history. @param Page $page @return View
public function postAdmin(Request $request, Page $page) { $this->authorize('editAdmin', $page); $page ->setInternalName($request->input('internal_name')) ->setAddPageBehaviour($request->input('add_behaviour')) ->setChildAddPageBehaviour($request->input('child_add_behaviour')) ->setDisableDelete($request->has('disable_delete')); PageFacade::save($page); }
Save the page admin settings. @param Request $request @param Page $page
public function postChildren(Request $request, Page $page) { $this->authorize('editChildrenBasic', $page); $post = $request->input(); $page->setChildTemplateId($request->input('children_template_id')); if (Gate::allows('editChildrenAdvanced', $page)) { $page ->setChildrenUrlPrefix($request->input('children_url_prefix')) ->setChildrenVisibleInNav($request->has('children_visible_in_nav')) ->setChildrenVisibleInNavCms($request->has('children_visible_in_nav_cms')) ->setGrandchildTemplateId($request->input('grandchild_template_id')); } if (isset($post['children_ordering_policy']) && isset($post['children_ordering_direction'])) { $page->setChildOrderingPolicy($post['children_ordering_policy'], $post['children_ordering_direction']); } PageFacade::save($page); }
Save the child page settings. @param Request $request @param Page $page
public function postFeature(Request $request, Page $page) { $this->authorize('editFeature', $page); $page->setFeatureImageId($request->input('feature_image_id')); PageFacade::save($page); }
Save the page feature image. @param Request $request @param Page $page
public function postNavigation(Request $request, Page $page) { $this->authorize('editNavBasic', $page); if (Gate::allows('editNavAdvanced', $page)) { $parent = Page::find($request->input('parent_id')); if ($parent) { $page->setParent($parent); } } $page ->setVisibleInNav($request->has('visible_in_nav')) ->setVisibleInCmsNav($request->has('visible_in_nav_cms')); PageFacade::save($page); }
Save the page navigation settings. @param Request $request @param Page $page
public function postSortChildren(Request $request, Page $page) { $this->authorize('editChildrenBasic', $page); Bus::dispatch(new ReorderChildPages($page, $request->input('sequences'))); }
Save the order of child pages. @param Request $request @param Page $page
public function postVisibility(Request $request, Page $page) { $this->authorize('publish', $page); $wasVisible = $page->isVisible(); $page->setVisibleAtAnyTime($request->input('visible')); if ($page->isVisibleAtAnyTime()) { if ($request->has('visible_from')) { $page->setVisibleFrom(new DateTime($request->input('visible_from'))); } $visibleTo = ($request->has('toggle_visible_to')) ? new DateTime($request->input('visible_to')) : null; $page->setVisibleTo($visibleTo); } PageFacade::save($page); if (!$wasVisible && $page->isVisible()) { Event::fire(new Events\PageWasMadeVisible($page, auth()->user())); } return (int) $page->isVisible(); }
Save the page visibility settings. @param Request $request @param Page $page @return int
public function input($filename, $content) { $this->_currentFile = $filename; return preg_replace_callback( $this->_pattern, array($this, '_replace'), $content ); }
Input filter - preprocesses //=require statements @param string $filename @param string $content @return string content
protected function _replace($matches) { $file = $this->_currentFile; if ($matches[1] === '"') { // Same directory include $file = $this->_findFile($matches[2], dirname($file) . DIRECTORY_SEPARATOR); } else { // scan all paths $file = $this->_findFile($matches[2]); } // prevent double inclusion if (isset($this->_loaded[$file])) { return ""; } $this->_loaded[$file] = true; $content = file_get_contents($file); if ($return = $this->input($file, $content)) { return $return . "\n"; } return ''; }
Performs the replacements and inlines dependencies. @param array $matches @return string content
protected function _findFile($filename, $path = null) { if (substr($filename, -2) !== 'js') { $filename .= '.js'; } if ($path && file_exists($path . $filename)) { return $path . $filename; } $file = $this->_scanner()->find($filename); if ($file) { return $file; } throw new \Exception('Sprockets - Could not locate file "' . $filename . '"'); }
Locates sibling files, or uses AssetScanner to locate <> style dependencies. @param string $filename The basename of the file needing to be found. @param string $path The path for same directory includes. @return string Path to file. @throws \Exception when files can't be located.
public function getDependencies(AssetTarget $target) { $children = []; foreach ($target->files() as $file) { $contents = $file->contents(); preg_match_all($this->_pattern, $contents, $matches, PREG_SET_ORDER); if (empty($matches)) { continue; } foreach ($matches as $match) { if ($match[1] === '"') { // Same directory include $path = $this->_findFile($match[2], dirname($file->path()) . DIRECTORY_SEPARATOR); } else { // scan all paths $path = $this->_findFile($match[2]); } $dep = new Local($path); $children[] = $dep; $newTarget = new AssetTarget('phony.js', [$dep]); $children = array_merge($children, $this->getDependencies($newTarget)); } } return $children; }
{@inheritDoc}
protected function getFilepath(string $key):string{ $h = hash('sha256', $key); return $this->cachedir.$h[0].DIRECTORY_SEPARATOR.$h[0].$h[1].DIRECTORY_SEPARATOR.$h; }
@param string $key @return string
public function handle(Request $request, Closure $next) { $response = $this->router->routePage($request->route()->parameter('location')); if ($response) { return $response; } return $next($request); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
public function addVersion(array $attrs = []): PageVersionInterface { if ($oldVersion = $this->getCurrentVersion()) { $attrs += $oldVersion->toArray(); } // Chunk type and ID fields shouldn't be copied. unset($attrs[PageVersion::ATTR_CHUNK_TYPE]); unset($attrs[PageVersion::ATTR_CHUNK_ID]); unset($attrs[PageVersion::ATTR_RESTORED_FROM]); $newVersion = new PageVersion($attrs); $newVersion->setPage($this); /* * Only make the new version a draft if the old version is published. * When a new page is created we set the edited_at time to make the first version published */ if ($oldVersion->isPublished()) { $newVersion->makeDraft(); } $newVersion->save(); $this->setCurrentVersion($newVersion); return $this->getCurrentVersion(); }
Adds a new version to the page. If the current version is embargoed then the new version is also embargoed. If the current version is published then the new version becomes a draft.
public function getChildOrderingPolicy(): array { $order = $this->{self::ATTR_CHILD_ORDERING_POLICY}; $column = 'sequence'; if ($order & static::ORDER_TITLE) { $column = 'title'; } elseif ($order & static::ORDER_VISIBLE_FROM) { $column = 'visible_from'; } $direction = ($order & static::ORDER_ASC) ? 'asc' : 'desc'; return [$column, $direction]; }
Returns an array of [column, direction] indicating the page's child ordering policy.
public function getDefaultChildTemplateId(): int { if (!empty($this->{self::ATTR_CHILD_TEMPLATE})) { return (int) $this->{self::ATTR_CHILD_TEMPLATE}; } $parent = $this->getParent(); return ($parent && !empty($parent->getGrandchildTemplateId())) ? $parent->getGrandchildTemplateId() : $this->getTemplateId(); }
Returns the default template ID that child pages should use.
public function getDefaultGrandchildTemplateId(): int { $grandchildTemplateId = $this->getGrandchildTemplateId(); return empty($grandchildTemplateId) ? $this->getTemplateId() : (int) $grandchildTemplateId; }
If a default grandchild template ID is set then that is returned. Otherwise the current template ID of this page is returned.
public function getVisibleTo() { return empty($this->{self::ATTR_VISIBLE_TO}) ? null : new DateTime('@'.$this->{self::ATTR_VISIBLE_TO}); }
Returns the visible to date, or null if none is set. @return null|DateTime
public function setEmbargoTime(DateTime $time): PageInterface { $this->addVersion([ PageVersion::ATTR_PENDING_APPROVAL => false, PageVersion::ATTR_EMBARGOED_UNTIL => $time->getTimestamp(), ]); return $this; }
Set an embargo time for any unpublished changes. If the time is in the past then the changes become published.
public function url() { if ($this->{self::ATTR_PRIMARY_URI} === null) { return; } if ($this->primaryUrl === null) { $this->primaryUrl = new URL([ 'page' => $this, 'location' => $this->{self::ATTR_PRIMARY_URI}, 'is_primary' => true, ]); } return $this->primaryUrl; }
Returns the URL object for the page's primary URI. The URL can be displayed by casting the returned object to a string: (string) $page->url(); @return URLInterface|null
public function scopeAutocompleteTitle(Builder $query, $title, $limit) { return $query ->currentVersion() ->select('title', 'primary_uri') ->where('title', 'like', '%'.$title.'%') ->limit($limit) ->orderBy(DB::raw('length(title)'), 'asc'); }
@param Builder $query @param string $title @param int $limit @return Builder
public function scopeCurrentVersion(Builder $query) { $subquery = $this->getCurrentVersionQuery(); return $query ->select('version.*') ->addSelect('version.id as version:id') ->addSelect('version.created_at as version:created_at') ->addSelect('version.created_by as version:created_by') ->addSelect('pages.*') ->join(DB::raw('('.$subquery->toSql().') as v2'), 'pages.id', '=', 'v2.page_id') ->mergeBindings($subquery) ->join('page_versions as version', function (JoinClause $join) { $join ->on('pages.id', '=', 'version.page_id') ->on('v2.id', '=', 'version.id'); }); }
Scope for getting pages with the current version. This doesn't work as a global scope as changing the select columns breaks queries which add select columns. e.g. finding pages by related tags. @param Builder $query @return Builder
public function up() { Schema::create('page_urls', function (Blueprint $table) { $table->increments('id'); $table->integer('page_id')->unsigned(); $table->string('location', 2048); $table->boolean('is_primary')->nullable(); $table->index(['page_id', 'is_primary'], 'page_uri_page_id_primary_uri'); }); DB::statement('ALTER TABLE page_urls ADD FULLTEXT page_urls_location(location)'); }
Run the migrations. @return void
public function toArray() { if (isset($this->attributes[self::ATTR_PUBLISHED_AT]) && $this->attributes[self::ATTR_PUBLISHED_AT] === '0000-00-00 00:00:00' ) { $this->attributes[self::ATTR_PUBLISHED_AT] = null; } $attributes = $this->attributesToArray(); $version = $this->getLatestVersion()->toArray(); $attributes['edited_at'] = $version['created_at']; $attributes['edited_by'] = $version['created_by']; return array_merge($version, $attributes, $this->relationsToArray()); }
Convert the model instance to an array. @return array
public static function fromTitle($base, $title) { $url = static::sanitise($title); // If the base URL isn't empty and there's no trailing / then add one. if ($base && substr($base, -1) != '/') { $base = $base.'/'; } $url = ($base == '/') ? $url : $base.$url; return static::makeUnique($url); }
Generate a unique URL from a page title. @param string $base @param string $title
public static function getInternalPath($url) { $path = parse_url($url, PHP_URL_PATH); return ($path === '/') ? $path : ltrim($path, '/'); }
Returns a path which can be used to query the database of internal URLs. Removes the leading forward slash for non-root URLs And removes everything except the path portion of the URL @param string $url @return string
public static function isInternal($url) { $relative = static::makeRelative($url); if (substr($relative, 0, 1) !== '/') { return false; } $path = static::getInternalPath($relative); return !URLFacade::isAvailable($path); }
Determine whether a path is valid internal path. @param string $url @return bool
public static function sanitise($url) { $url = trim($url); $url = strtolower($url); $url = parse_url($url, PHP_URL_PATH); // Make sure it doesn't contain a hostname $url = preg_replace('|/+|', '/', $url); // Remove duplicate forward slashes. if ($url !== '/') { // Remove trailing or preceeding slashes $url = trim($url, '/'); } $url = preg_replace('|[^'.preg_quote('-').'\/\pL\pN\s]+|u', '', $url); // Remove all characters that are not a hypeh, letters, numbers, or forward slash $url = preg_replace('|['.preg_quote('-').'\s]+|u', '-', $url); // Replace all hypens and whitespace by a single hyphen return $url; }
Remove invalid characters from a URL. @param string $url
public function output($filename, $content) { if (!class_exists('Patchwork\JSqueeze')) { throw new \Exception(sprintf('Cannot not load filter class "%s".', 'Patchwork\JSqueeze')); } $jz = new JSqueeze(); return $jz->squeeze( $content, $this->_settings['singleLine'], $this->_settings['keepImportantComments'], $this->_settings['specialVarRx'] ); }
Apply JSqueeze to $content. @param string $filename target filename @param string $content Content to filter. @throws \Exception @return string
public function up() { Schema::create('asset_downloads', function (Blueprint $table) { $table->bigInteger('id', true)->unsigned(); $table->integer('asset_id')->unsigned()->index('asset_downloads_asset_id'); $table->integer('time')->unsigned()->nullable(); $table->integer('ip')->nullable(); $table->index(['ip', 'asset_id', 'time'], 'asset_downloads_ip_asset_id_time'); }); }
Run the migrations. @return void
protected function getDefaultParameters(): array { $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); $last = end($trace); $debugMode = static::detectDebugMode(); return [ 'appDir' => isset($trace[2]['file']) ? dirname($trace[2]['file']) : null, 'wwwDir' => isset($last['file']) ? dirname($last['file']) : null, 'debugMode' => $debugMode, 'productionMode' => !$debugMode, 'consoleMode' => PHP_SAPI === 'cli', ]; }
Collect default parameters @return mixed[]
public function up() { Schema::table('page_urls', function (Blueprint $table) { $table->foreign('page_id', 'page_urls_ibfk_1')->references('id')->on('pages')->onUpdate('CASCADE')->onDelete('CASCADE'); }); }
Run the migrations. @return void
protected function _replace($matches) { $required = empty($matches[2]) ? $matches[4] : $matches[2]; $filename = $this->scanner()->find($required); if (!$filename) { throw new RuntimeException(sprintf('Could not find dependency "%s"', $required)); } if (empty($this->_loaded[$filename])) { return $this->input($filename, file_get_contents($filename)); } return ''; }
Does file replacements. @param array $matches @throws RuntimeException
public function attributes() { return [ $this->attributePrefix.'address' => (int) $this->address, $this->attributePrefix.'title' => (int) $this->title, ]; }
Returns the array of chunk attributes. @return array
public function getLocation() { if ($this->location === null) { $this->location = new GeoLocation($this->getLat(), $this->getLng()); } return $this->location; }
Returns a Lootils\Geo\Location object for the current lat/lng. @return GeoLocation
public function show() { return View::make($this->viewPrefix."location.$this->template", [ 'lat' => $this->getLat(), 'lng' => $this->getLng(), 'address' => $this->getAddress(), 'title' => $this->getTitle(), 'postcode' => $this->getPostcode(), 'location' => $this->getLocation(), ]); }
Show a chunk where the target is set.
public function editSuperuser(Person $user, Person $editing) { return $user->isSuperUser() && !$user->is($editing); }
Whether a user can edit the superuser status of another. @param Person $user @param Person $editing @return bool
public function before(Person $person, $ability) { if ($person->isSuperUser()) { return true; } if (!$person->hasSite(Router::getActiveSite())) { return false; } }
@param Person $person @param string $ability @return bool
public function environment($env = null) { if ($env !== null) { // Windows nodejs needs these environment variables. $winenv = $this->_getenv(array('SystemDrive', 'SystemRoot')); $this->_env = array_merge($winenv, $env); return $this; } return $this->_env; }
Get/set the environment for the command. @param array $env Environment variables. @return The environment variables that are set, or this.
public function run($input = null) { $descriptorSpec = array( 0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w') ); $process = proc_open( $this->_command, $descriptorSpec, $pipes, null, $this->_env ); if (is_resource($process)) { fwrite($pipes[0], $input); fclose($pipes[0]); $this->_output = stream_get_contents($pipes[1]); fclose($pipes[1]); $this->_error = stream_get_contents($pipes[2]); fclose($pipes[2]); proc_close($process); } return $this->_output; }
Run the command and capture the output as the return. @param string $input STDIN for the command. @param string Output from the command.
public function handle(Request $request, Closure $next) { if ($this->auth->check()) { return new RedirectResponse('/'); } return $next($request); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
public function handle(Request $request, Closure $next) { $asset = $request->route()->parameter('asset'); if (!$asset) { return $next($request); } $etag = $asset->getLastModified()->getTimestamp(); if ($request->header('If-None-Match') == $etag) { abort(304)->header('etag', $etag); } $response = $next($request); if ($response instanceof StreamedResponse || $response instanceof BinaryFileResponse) { return $response; } return $response ->header('Cache-Control', 'public, must-revalidate') ->header('etag', $etag); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
protected function checkKey($key):string{ if(!is_string($key) || empty($key)){ $msg = 'invalid cache key: "'.$key.'"'; $this->logger->error($msg); throw new InvalidArgumentException($msg); } return $key; }
@param string|mixed $key @return string @throws \Psr\SimpleCache\InvalidArgumentException
protected function getData($data):array{ if(is_array($data)){ return $data; } elseif($data instanceof Traversable){ return iterator_to_array($data); // @codeCoverageIgnore } $msg = 'invalid data'; $this->logger->error($msg); throw new InvalidArgumentException($msg); }
@param mixed $data @return array @throws \Psr\SimpleCache\InvalidArgumentException
protected function getTTL($ttl):?int{ if($ttl instanceof DateInterval){ return (new DateTime)->add($ttl)->getTimeStamp() - time(); } else if((is_int($ttl) && $ttl > 0) || $ttl === null){ return $ttl; } $msg = 'invalid ttl'; $this->logger->error($msg); throw new InvalidArgumentException($msg); }
@param mixed $ttl @return int|null @throws \Psr\SimpleCache\InvalidArgumentException
protected function checkReturn(array $booleans):bool{ foreach($booleans as $bool){ if(!(bool)$bool){ return false; // @codeCoverageIgnore } } return true; }
@param bool[] $booleans @return bool
protected function _generateScript($file, $filename, $input) { $id = str_replace($this->_settings['ext'], '', basename($filename)); $filepath = str_replace($this->_settings['ext'], '', $filename); foreach ($this->_settings['paths'] as $path) { $path = rtrim($path, '/') . '/'; if (strpos($filepath, $path) === 0) { $filepath = str_replace($path, '', $filepath); } } $config = [ 'asString' => true, ]; $text = <<<JS var hogan = require('hogan.js'), util = require('util'); try { var template = hogan.compile(%s, %s); util.print('\\nwindow.JST["%s"] = window.JST["%s"] = ' + template + ';'); process.exit(0); } catch (e) { console.error(e); process.exit(1); } JS; $contents = sprintf( $text, json_encode($input), json_encode($config), $id, $filepath ); file_put_contents($file, $contents); }
Generates the javascript passed into node to precompile the the mustache template. @param string $file The tempfile to put the script in. @param string $id The template id in window.JST @param string input The mustache template content. @return void
public function input($filename, $input) { if (substr($filename, strlen($this->_settings['ext']) * -1) !== $this->_settings['ext']) { return $input; } $tmpfile = tempnam(TMP, 'asset_compress_less'); $this->_generateScript($tmpfile, $input); $bin = $this->_settings['node'] . ' ' . $tmpfile; $env = array('NODE_PATH' => $this->_settings['node_path']); $return = $this->_runCmd($bin, '', $env); unlink($tmpfile); return $return; }
Runs `lessc` against any files that match the configured extension. @param string $filename The name of the input file. @param string $input The content of the file. @return string
public function getCreatedAt() { $metadata = $this->getMetadata(); try { if (isset($metadata['CreationDate'])) { $timestamp = is_array($metadata['CreationDate']) ? $metadata['CreationDate'][0] ?? null : $metadata['CreationDate']; } return isset($timestamp) ? Carbon::parse($timestamp) : null; } catch (Exception $e) { return; } }
{@inheritdoc} @return null|Carbon
public function getThumbnail(): Imagick { $image = new Imagick($this->file->getPathname().'[0]'); $image->setImageFormat('png'); return $image; }
Generates a thumbnail for the PDF from the first page of the document. @return Imagick
public function getTitle(): string { $metadata = $this->getMetadata(); if (isset($metadata['Title'])) { return is_array($metadata['Title']) ? $metadata['Title'][0] ?? '' : $metadata['Title']; } return parent::getTitle(); }
{@inheritdoc} @return string
public function readMetadata(): array { try { $parser = new Parser(); $pdf = $parser->parseFile($this->file->getPathname()); return $pdf->getDetails(); } catch (Exception $e) { return []; } }
Extracts metadata from a PDF. @return array