code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
protected function getPaymentTransactionStructure()
{
return array_merge(
[
'amount' => \Genesis\Utils\Currency::amountToExponent($this->amount, $this->currency),
'currency' => $this->currency,
],
$this->items instanceof Items ? $this->items->toArray() : []
);
} | Return additional request attributes
@return array |
protected function checkRequirements()
{
parent::checkRequirements();
// verify there is at least one item added
if (empty($this->items) || $this->items->count() === 0) {
throw new \Genesis\Exceptions\ErrorParameter('Empty (null) required parameter: items');
}
} | Perform field validation
@throws \Genesis\Exceptions\ErrorParameter
@return void |
public function cleanExtensions($installedExtensions, \OxidEsales\Eshop\Core\Module\Module $module)
{
$installedExtensions = parent::cleanExtensions($installedExtensions, $module);
$oModules = oxNew( \OxidEsales\EshopCommunity\Core\Module\ModuleList::class );
//ids will include garbage in case there are files that not registered by any module
$ids = $oModules->getModuleIds();
$config = Registry::getConfig();
$knownIds = array_keys($config->getConfigParam('aModulePaths'));
$diff = array_diff($ids,$knownIds);
if ($diff) {
foreach ($diff as $item) {
foreach ($installedExtensions as &$coreClassExtension) {
foreach ($coreClassExtension as $i => $ext) {
if ($ext === $item) {
$this->_debugOutput->writeln("$item will be removed");
unset($coreClassExtension[$i]);
}
}
}
}
}
return $installedExtensions;
} | Removes garbage ( module not used extensions ) from all installed extensions list.
For example: some classes were renamed, so these should be removed.
@param array $installedExtensions
@param \OxidEsales\Eshop\Core\Module\Module $module
@return array |
protected function filterExtensionsByModuleId($modules, $moduleId)
{
$modulePaths = \OxidEsales\Eshop\Core\Registry::getConfig()->getConfigParam('aModulePaths');
$path = '';
if (isset($modulePaths[$moduleId])) {
$path = $modulePaths[$moduleId] . '/';
}
// TODO: This condition should be removed. Need to check integration tests.
if (!$path) {
$path = $moduleId . "/";
}
$filteredModules = [];
foreach ($modules as $class => $extend) {
foreach ($extend as $extendPath) {
if (strpos($extendPath, $path) === 0) {
$filteredModules[$class][] = $extendPath;
}
}
}
return $filteredModules;
} | Returns extensions list by module id.
@param array $modules Module array (nested format)
@param string $moduleId Module id/folder name
@return array |
protected function validate()
{
if (!CommonUtils::isRegexExpr($this->pattern)) {
return false;
}
return (bool) preg_match(
$this->pattern,
$this->getRequestValue()
);
} | Execute field name validation
@return bool |
protected function getPaymentTransactionStructure()
{
return [
'amount' => $this->transformAmount($this->amount, $this->currency),
'currency' => $this->currency,
'return_success_url' => $this->return_success_url,
'return_failure_url' => $this->return_failure_url,
'notification_url' => $this->notification_url,
'source_wallet_id' => $this->source_wallet_id,
'source_wallet_pwd' => $this->transformWalletPassword($this->source_wallet_pwd)
];
} | Return additional request attributes
@return array |
protected function transformWalletPassword($input = '')
{
if (!\Genesis\Utils\Common::isBase64Encoded($input)) {
return base64_encode($input);
}
return $input;
} | Apply transformation:
Encode a string in base64 or return
the input if already in base64
@param string $input
@return mixed |
protected function populateStructure()
{
$treeStructure = [
'chargeback_request' => [
'start_date' => $this->start_date,
'end_date' => $this->end_date,
'page' => $this->page
]
];
$this->treeStructure = \Genesis\Utils\Common::createArrayObject($treeStructure);
} | Create the request's Tree structure
@return void |
public function setVersion($version)
{
$availableVersions = ['v1'];
if (in_array($version, $availableVersions)) {
$this->version = $version;
$this->initConfiguration();
return $this;
}
throw new InvalidArgument(
'Invalid Consumer API version, available versions are: ' . implode(', ', $availableVersions)
);
} | @param $version
@return $this
@throws InvalidArgument |
protected function initConfiguration()
{
$this->initXmlConfiguration();
$this->initApiGatewayConfiguration($this->version . '/' . $this->requestPath, false);
} | Set the per-request configuration
@return void |
protected function populateStructure()
{
$treeStructure = [
$this->requestPath . '_request' => $this->getConsumerRequestStructure()
];
$this->treeStructure = \Genesis\Utils\Common::createArrayObject($treeStructure);
} | Create the request's Tree structure
@return void |
public function execute(InputInterface $input, OutputInterface $output)
{
$output->writeLn('Updating database views...');
$config = Registry::getConfig();
//avoid problems if views are already broken
$config->setConfigParam('blSkipViewUsage', true);
/** @var DbMetaDataHandler $oDbHandler */
$oDbHandler = oxNew(DbMetaDataHandler::class);
if (!$oDbHandler->updateViews()) {
$output->writeLn('Could not update database views!');
exit(1);
}
$output->writeLn('Database views updated successfully');
} | {@inheritdoc} |
public function scopeMeta($query, $alias = null)
{
$alias = (empty($alias)) ? $this->getMetaTable() : $alias;
return $query->join($this->getMetaTable() . ' AS ' . $alias, $this->getQualifiedKeyName(), '=', $alias . '.' . $this->getMetaKeyName())->select($this->getTable() . '.*');
} | Meta scope for easier join
------------------------- |
public function setMeta($key, $value = null)
{
$setMeta = 'setMeta'.ucfirst(gettype($key));
return $this->$setMeta($key, $value);
} | Set Meta Data functions
-------------------------. |
public function getMeta($key = null, $raw = false)
{
if (is_string($key) && preg_match('/[,|]/is', $key, $m)) {
$key = preg_split('/ ?[,|] ?/', $key);
}
$getMeta = 'getMeta'.ucfirst(strtolower(gettype($key)));
return $this->$getMeta($key, $raw);
} | Get Meta Data functions
-------------------------. |
public function metas()
{
$model = new \Kodeine\Metable\MetaData();
$model->setTable($this->getMetaTable());
return new HasMany($model->newQuery(), $this, $this->getMetaKeyName(), $this->getKeyName());
} | Relationship for meta tables |
public function whereMeta($key, $value)
{
return $this->getModelStub()
->whereKey(strtolower($key))
->whereValue($value)
->get();
} | Query Meta Table functions
-------------------------. |
public function getAttribute($key)
{
// parent call first.
if (($attr = parent::getAttribute($key)) !== null) {
return $attr;
}
// there was no attribute on the model
// retrieve the data from meta relationship
return $this->getMeta($key);
} | Get an attribute from the model.
@param string $key
@return mixed |
public function setValueAttribute($value)
{
$type = gettype($value);
if (is_array($value)) {
$this->type = 'array';
$this->attributes['value'] = json_encode($value);
} elseif ($value instanceof DateTime) {
$this->type = 'datetime';
$this->attributes['value'] = $this->fromDateTime($value);
} elseif ($value instanceof Model) {
$this->type = 'model';
$this->attributes['value'] = get_class($value).(!$value->exists ? '' : '#'.$value->getKey());
} elseif (is_object($value)) {
$this->type = 'object';
$this->attributes['value'] = json_encode($value);
} else {
$this->type = in_array($type, $this->dataTypes) ? $type : 'string';
$this->attributes['value'] = $value;
}
} | Set the value and type.
@param $value |
public function routePage($path)
{
$url = URL::findByLocation($path);
if ($url) {
$page = $url->getPage();
if (!$page || $page->isDeleted()) {
// The url is in use but doesn't have a page.
// The page must have been deleted.
throw new GoneHttpException();
}
if (Editor::isDisabled() && !$page->isVisible()) {
throw new NotFoundHttpException();
}
if (!$page->url()->matches($path)) {
return redirect((string) $page->url(), 301);
}
$this->setActivePage($page);
return;
}
throw new NotFoundHttpException();
} | @param string $path
@return mixed |
public function routeHostname($hostname)
{
$hostname = env('BOOMCMS_HOST', $hostname);
$site = Site::findByHostname($hostname);
$site = $site ?: Site::findDefault();
return $this->setActiveSite($site);
} | @param string $hostname
@return $this |
public function setActivePage(PageInterface $page)
{
$this->page = $page;
$this->app->instance(PageModel::class, $page);
return $this;
} | @param PageInterface $page
@return $this |
public function setActiveSite(SiteInterface $site = null)
{
$this->site = $site;
$this->app->instance(SiteModel::class, $site);
return $this;
} | @param SiteInterface $site
@return $this |
public function output($filename, $content)
{
if (function_exists('jsmin')) {
return jsmin($content);
}
if (!class_exists('JSMin')) {
throw new \Exception(sprintf('Cannot not load filter class "%s".', 'JsMin'));
}
return JSMin::minify($content);
} | Apply JsMin to $content.
@param string $filename Name of the file being generated.
@param string $content The uncompress contents of $filename.
@throws \Exception
@return string |
public function generate(AssetTarget $build)
{
$filters = $this->filterRegistry->collection($build);
$output = '';
foreach ($build->files() as $file) {
$content = $file->contents();
$content = $filters->input($file->path(), $content);
$output .= $content . "\n";
}
if (!$this->debug || php_sapi_name() === 'cli') {
$output = $filters->output($build->path(), $output);
}
return trim($output);
} | Generate a compiled asset, with all the configured filters applied.
@param AssetTarget $target The target to build
@return The processed result of $target and it dependencies.
@throws RuntimeException |
public function getThumbnail()
{
try {
$ffmpeg = FFMpeg::create();
$video = $ffmpeg->open($this->file->getPathname());
$frame = $video->frame(TimeCode::fromSeconds(0));
$base64 = $frame->save(tempnam(sys_get_temp_dir(), $this->file->getBasename()), true, true);
return Imagick::readImageBlob($base64);
} catch (Exception $e) {
return;
}
} | Generates a thumbnail for the video from the first frame.
@return Imagick |
public function handle(Request $request, Closure $next)
{
$asset = $request->route()->parameter('asset');
if ($asset && !$this->auth->check()) {
$ip = ip2long($request->ip());
if (!AssetDownload::recentlyLogged($asset->getId(), $ip)->count() > 0) {
AssetDownload::create([
'asset_id' => $asset->getId(),
'ip' => $ip,
'time' => time(),
]);
$asset->incrementDownloads();
}
}
return $next($request);
} | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed |
public function deleting(Model $model)
{
$model->deleted_by = $this->guard->check() ? $this->guard->user()->getId() : null;
} | Set deleted_by on the model prior to deletion.
@param Model $model
@return void |
public function getParam($key)
{
return isset($this->params[$key]) ? $this->params[$key] : null;
} | Returns a search parameter by key.
@param string $key
@return mixed |
public function hasFilters()
{
$params = array_except($this->params, ['order', 'limit']);
return !empty($params) && !empty(array_values($params));
} | Returns whether the parameters array contains any filters.
@return bool |
public function files()
{
$files = [];
foreach (call_user_func($this->callable) as $file) {
$path = $this->scanner->find($file);
if ($path === false) {
throw new RuntimeException("Could not locate {$file} for {$this->callable} in any configured path.");
}
$files[] = new Local($path);
}
return $files;
} | Get the list of files from the callback.
@return array |
public function input($filename, $input)
{
if (substr($filename, strlen($this->_settings['ext']) * -1) !== $this->_settings['ext']) {
return $input;
}
$filename = preg_replace('/ /', '\\ ', $filename);
$bin = $this->_settings['sass'] . ' ' . $filename;
$return = $this->_runCmd($bin, '', array('PATH' => $this->_settings['path']));
return $return;
} | Runs SCSS compiler 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 input($filename, $input)
{
if (substr($filename, strlen($this->_settings['ext']) * -1) !== $this->_settings['ext']) {
return $input;
}
$cmd = $this->_settings['node'] . ' ' . $this->_settings['coffee'] . ' -c -p -s ';
$env = array('NODE_PATH' => $this->_settings['node_path']);
return $this->_runCmd($cmd, $input, $env);
} | Runs `coffee` against files that match the configured extension.
@param string $filename Filename being processed.
@param string $content Content of the file being processed.
@return string |
public static function factory($link, array $attrs = [])
{
if (URL::getAssetId($link) > 0) {
return new AssetLink($link, $attrs);
}
if (is_numeric($link) || URL::isInternal($link)) {
return new PageLink($link, $attrs);
}
return new External($link, $attrs);
} | @param int|string $link
@param array $attrs
@return Link |
public function getAssetId(): int
{
return (isset($this->attrs['asset_id']) && !empty($this->attrs['asset_id'])) ?
$this->attrs['asset_id'] : 0;
} | Alias of getFeatureImageId(), for backwards compatibility.
@return int |
public function getParameter($key)
{
$query = $this->getQuery();
return isset($query[$key]) ? $query[$key] : null;
} | Returns a query string parameter for a given key.
@param string $key
@return mixed |
public function getQuery()
{
if ($this->query === null) {
$string = parse_url($this->link, PHP_URL_QUERY);
parse_str($string, $this->query);
}
return $this->query;
} | Returns an array of query string parameters in the URL.
@return array |
public static function assetURL(array $params)
{
if (isset($params['asset']) && is_object($params['asset'])) {
$asset = $params['asset'];
$params['asset'] = $params['asset']->getId();
}
if (!isset($params['action'])) {
$params['action'] = 'view';
}
if (isset($params['height']) && !isset($params['width'])) {
$params['width'] = 0;
}
$url = route('asset', $params);
if (isset($asset)) {
$url .= '?'.$asset->getLastModified()->getTimestamp();
}
return $url;
} | Generate a URL to link to an asset.
@param array $params
@return string |
public static function chunk($type, $slotname, $page = null)
{
return ChunkFacade::insert($type, $slotname, $page);
} | Interest a chunk into a page.
@param string $type
@param string $slotname
@param PageInterface|null $page
@return Chunk |
public static function description(PageInterface $page = null)
{
$page = $page ?: Router::getActivePage();
$description = $page->getDescription() ?:
ChunkFacade::get('text', 'standfirst', $page)->text();
return strip_tags($description);
} | Reutrn the meta description for a page.
If no page is given then the active page is used.
The page description property will be used, if that isn't set then the page standfirst is used.
@param null|Page $page
@return string |
public static function getTags()
{
$finder = new Tag\Finder\Finder();
foreach (func_get_args() as $arg) {
if (is_string($arg)) {
$finder->addFilter(new Tag\Finder\Group($arg));
} elseif ($arg instanceof PageInterface) {
$finder->addFilter(new Tag\Finder\AppliedToPage($arg));
} elseif ($arg instanceof TagInterface) {
$finder->addFilter(new Tag\Finder\AppliedWith($arg));
}
}
return $finder
->setOrderBy('group', 'asc')
->setOrderBy('name', 'asc')
->findAll();
} | Get tags matching given parameters.
Accepts a page, group name, or tag as arguments in any order to search by.
@return array |
public static function getTagsInSection(PageInterface $page = null, $group = null)
{
$page = $page ?: Router::getActivePage();
$finder = new Tag\Finder\Finder();
$finder->addFilter(new Tag\Finder\AppliedToPageDescendants($page));
$finder->addFilter(new Tag\Finder\Group($group));
return $finder->setOrderBy('name', 'asc')->findAll();
} | Get the pages applied to the children of a page.
@param Page\Page $page
@param string $group
@return array |
public static function pub($file, $theme = null)
{
$theme = $theme ?: static::activeThemeName();
return "/vendor/boomcms/themes/$theme/".ltrim(trim($file), '/');
} | Get a relative path to a file in a theme's public directory.
@param string $file
@param string $theme
@return string |
public function getValue(array $keys, $default = null)
{
$config = $this->config;
$pointer = &$config;
foreach ($keys as $key) {
if (!array_key_exists($key, $pointer)) {
if ($default === null) {
throw new InvalidArgumentException(sprintf(
'Key "%s" does not exist',
implode('.', $keys)
));
}
return $default;
}
$pointer = &$pointer[$key];
}
return $pointer;
} | Returns value by key. You can supply default value for when the key is missing.
Without default value exception is thrown for nonexistent keys.
@param string[] $keys
@param mixed $default
@return mixed |
public function up()
{
Schema::create('pages_relations', function (Blueprint $table) {
$table->integer('page_id')
->unsigned()
->references('id')
->on('pages')
->onUpdate('CASCADE')
->onDelete('CASCADE');
$table->integer('related_page_id')
->unsigned()
->references('id')
->on('pages')
->onUpdate('CASCADE')
->onDelete('CASCADE');
$table
->integer('created_by')
->unsigned()
->references('id')
->on('people')
->onUpdate('CASCADE')
->onDelete('CASCADE');
$table
->integer('created_at')
->unsigned()
->nullable();
$table->primary(['page_id', 'related_page_id']);
});
} | Run the migrations.
@return void |
public function handle($request, Closure $next)
{
$activePage = Router::getActivePage();
if ($activePage === null || Gate::denies('toolbar', $activePage)) {
return $next($request);
}
$response = $next($request);
$originalHtml = ($response instanceof Response)
? $response->getOriginalContent()
: (string) $response;
preg_match('|(.*)(</head>)(.*<body[^>]*>)|imsU', $originalHtml, $matches);
if (!empty($matches)) {
$head = view('boomcms::editor.iframe', [
'before_closing_head' => $matches[1],
'body_tag' => $matches[3],
'editor' => $this->editor,
'page_id' => $activePage->getId(),
]);
$newHtml = str_replace($matches[0], (string) $head, $originalHtml);
if ($response instanceof Response) {
$response->setContent($newHtml);
} else {
return $newHtml;
}
}
return $response;
} | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed |
public function hasLink()
{
return isset($this->attrs['url'])
&& trim($this->attrs['url'])
&& $this->attrs['url'] !== '#'
&& $this->attrs['url'] !== 'http://';
} | Whether the current slide has a link associated with it.
@return bool |
public function output($filename, $content)
{
if (!class_exists('JShrink\Minifier')) {
throw new \Exception(sprintf('Cannot not load filter class "%s".', 'JShrink\Minifier'));
}
return Minifier::minify($content, array('flaggedComments' => $this->_settings['flaggedComments']));
} | Apply JShrink to $content.
@param string $filename target filename
@param string $content Content to filter.
@throws \Exception
@return string |
public function assetsUpdated(): AlbumInterface
{
$assets = $this->assets();
$feature = $assets->orderBy(Asset::ATTR_UPLOADED_AT, 'desc')->first();
$this->update([
self::ATTR_FEATURE_IMAGE => $feature ? $feature->getId() : null,
self::ATTR_ASSET_COUNT => $assets->count(),
]);
return $this;
} | {@inheritdoc}
@return AlbumInterface $this |
public function render($request, Exception $e)
{
if ($this->isHttpException($e)) {
$code = $e->getStatusCode();
if ($code !== 500 || App::environment('production') || App::environment('staging')) {
$page = Page::findByInternalName($code);
if ($page) {
$request = Request::create($page->url()->getLocation(), 'GET');
return response(Route::dispatch($request)->getContent(), $code);
}
}
}
return parent::render($request, $e);
} | Render an exception into an HTTP response.
@param \Illuminate\Http\Request $request
@param \Exception $e
@return \Illuminate\Http\Response |
public function isFresh(AssetTarget $target)
{
$buildName = $this->buildFileName($target);
$buildFile = $this->outputDir($target) . DIRECTORY_SEPARATOR . $buildName;
if (!file_exists($buildFile)) {
return false;
}
$buildTime = filemtime($buildFile);
if ($this->configTime && $this->configTime >= $buildTime) {
return false;
}
foreach ($target->files() as $file) {
$time = $file->modifiedTime();
if ($time === false || $time >= $buildTime) {
return false;
}
}
$filters = $this->filterRegistry->collection($target);
foreach ($filters->filters() as $filter) {
foreach ($filter->getDependencies($target) as $child) {
$time = $child->modifiedTime();
if ($time >= $buildTime) {
return false;
}
}
}
return true;
} | Check to see if a cached build file is 'fresh'.
Fresh cached files have timestamps newer than all of the component
files.
@param AssetTarget $target The target file being built.
@return boolean |
public function buildFileName(AssetTarget $target)
{
$file = $target->name();
if ($target->isThemed() && $this->theme) {
$file = $this->theme . '-' . $file;
}
return $file;
} | Get the final build file name for a target.
@param AssetTarget $target The target to get a name for.
@return string |
public function read(AssetTarget $target)
{
$buildName = $this->buildFileName($target);
return file_get_contents($this->path . $buildName);
} | Get the cached result for a build target.
@param AssetTarget $target The target to get content for.
@return string |
public function settings(array $settings = null)
{
if ($settings) {
$this->_settings = array_merge($this->_settings, $settings);
}
return $this->_settings;
} | Gets settings for this filter. Will always include 'paths'
key which points at paths available for the type of asset being generated.
@param array $settings Array of settings.
@return array Array of updated settings. |
protected function _runCmd($cmd, $content, $environment = null)
{
$Process = new AssetProcess();
$Process->environment($environment);
$Process->command($cmd)->run($content);
if ($Process->error()) {
throw new RuntimeException($Process->error());
}
return $Process->output();
} | Run the compressor command and get the output
@param string $cmd The command to run.
@param string $content The content to run through the command.
@return The result of the command.
@throws RuntimeException |
protected function _findExecutable($search, $file)
{
$file = str_replace('/', DIRECTORY_SEPARATOR, $file);
if (file_exists($file)) {
return $file;
}
foreach ($search as $path) {
$path = rtrim($path, DIRECTORY_SEPARATOR);
if (file_exists($path . DIRECTORY_SEPARATOR . $file)) {
return $path . DIRECTORY_SEPARATOR . $file;
}
}
return null;
} | Find the command executable. If $file is an absolute path
to a file that exists $search will not be looked at.
@param array $search Paths to search.
@param string $file The executable to find. |
public function output($filename, $content)
{
$defaults = array('compilation_level' => $this->_settings['level']);
$errors = $this->_query($content, array('output_info' => 'errors'));
if (!empty($errors)) {
throw new \Exception(sprintf("%s:\n%s\n", 'Errors', $errors));
}
$output = $this->_query($content, array('output_info' => 'compiled_code'));
if (!Configure::read('debug')) {
return $output;
}
foreach ($this->_settings as $setting => $value) {
if (!in_array($setting, array('warnings', 'statistics')) || true != $value) {
continue;
}
$args = array('output_info' => $setting);
if ('warnings' == $setting && in_array($value, array('QUIET', 'DEFAULT', 'VERBOSE'))) {
$args['warning_level'] = $value;
}
$$setting = $this->_query($content, $args);
printf("%s:\n%s\n", ucfirst($setting), $$setting);
}
return $output;
} | {@inheritdoc} |
protected function _query($content, $args = array())
{
if (!extension_loaded('curl')) {
throw new \Exception('Missing the `curl` extension.');
}
$args = array_merge($this->_defaults, $args);
if (!empty($this->_settings['level'])) {
$args['compilation_level'] = $this->_settings['level'];
}
foreach ($this->_settings as $key => $val) {
if (in_array($key, $this->_params)) {
$args[$key] = $val;
}
}
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://closure-compiler.appspot.com/compile',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => 'js_code=' . urlencode($content) . '&' . http_build_query($args),
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HEADER => 0,
CURLOPT_FOLLOWLOCATION => 0
));
$output = curl_exec($ch);
if (false === $output) {
throw new \Exception('Curl error: ' . curl_error($ch));
}
curl_close($ch);
return $output;
} | Query the Closure compiler API.
@param string $content Javascript to compile.
@param array $args API parameters.
@throws \Exception If curl extension is missing.
@throws \Exception If curl triggers an error.
@return string |
public function boot(Guard $guard, Store $session, Router $router)
{
$activePage = $router->getActivePage();
$this->app->singleton(Editor::class, function () use ($guard, $session, $activePage) {
$default = ($guard->check() && $activePage && $guard->user()->can('toolbar', $activePage)) ? Editor::EDIT : Editor::DISABLED;
return new Editor($session, $default);
});
} | Bootstrap any application services.
@return void |
public function cachedCompiler($outputDir = '', $debug = false)
{
return new CachedCompiler(
$this->cacher($outputDir),
$this->compiler($debug)
);
} | Create a Caching Compiler
@param string $outputDir The directory to output cached files to.
@param bool $debug Whether or not to enable debugging mode for the compiler.
@return \MiniAsset\Output\CachedCompiler |
public function writer($tmpPath = '')
{
$tmpPath = $tmpPath ?: $this->config->get('general.timestampPath');
if (!$tmpPath) {
$tmpPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR;
}
$timestamp = [
'js' => $this->config->get('js.timestamp'),
'css' => $this->config->get('css.timestamp'),
];
$writer = new AssetWriter($timestamp, $tmpPath, $this->config->theme());
$writer->configTimestamp($this->config->modifiedTime());
$writer->filterRegistry($this->filterRegistry());
return $writer;
} | Create an AssetWriter
@param string $tmpPath The path where the build timestamp lookup should be stored.
@return \MiniAsset\AssetWriter |
public function cacher($path = '')
{
if (!$path) {
$path = sys_get_temp_dir() . DIRECTORY_SEPARATOR;
}
$cache = new AssetCacher($path, $this->config->theme());
$cache->configTimestamp($this->config->modifiedTime());
$cache->filterRegistry($this->filterRegistry());
return $cache;
} | Create an AssetCacher
@param string $path The path to cache assets into.
@return \MiniAsset\AssetCacher |
public function target($name)
{
if (!$this->config->hasTarget($name)) {
throw new RuntimeException("The target named '$name' does not exist.");
}
$ext = $this->config->getExt($name);
$themed = $this->config->isThemed($name);
$filters = $this->config->targetFilters($name);
$target = $this->config->cachePath($ext) . $name;
$files = [];
$scanner = $this->scanner($this->config->paths($ext, $name));
$paths = $scanner->paths();
$required = $this->config->requires($name);
if ($required) {
$compiler = $this->cachedCompiler();
foreach ($required as $dependency) {
$files[] = new Target($this->target($dependency), $compiler);
}
}
foreach ($this->config->files($name) as $file) {
if (preg_match('#^https?://#', $file)) {
$files[] = new Remote($file);
} else {
if (preg_match('/(.*\/)(\*.*?)$/U', $file, $matches)) {
$path = $scanner->find($matches[1]);
if ($path === false) {
throw new RuntimeException("Could not locate folder $file for $name in any configured path.");
}
$glob = new Glob($path, $matches[2]);
$files = array_merge($files, $glob->files());
} elseif (preg_match(static::CALLBACK_PATTERN, $file, $matches)) {
$callback = new Callback($matches[1], $matches[2], $scanner);
$files = array_merge($files, $callback->files());
} else {
$path = $scanner->find($file);
if ($path === false) {
throw new RuntimeException("Could not locate $file for $name in any configured path.");
}
$files[] = new Local($path);
}
}
}
return new AssetTarget($target, $files, $filters, $paths, $themed);
} | Create a single build target
@param string $name The name of the target to build
@return \MiniAsset\AssetTarget
@throws \RuntimeException |
public function filterRegistry()
{
$filters = [];
foreach ($this->config->allFilters() as $name) {
$filters[$name] = $this->buildFilter($name, $this->config->filterConfig($name));
}
return new FilterRegistry($filters);
} | Create a filter registry containing all the configured filters.
@return \MiniAsset\Filter\FilterRegistry |
protected function buildFilter($name, $config)
{
$className = $name;
if (!class_exists($className)) {
$className = 'MiniAsset\Filter\\' . $name;
}
if (!class_exists($className)) {
throw new RuntimeException(sprintf('Cannot load filter "%s".', $name));
}
$filter = new $className();
$filter->settings($config);
return $filter;
} | Create a single filter
@param string $name The name of the filter to build.
@param array $config The configuration for the filter.
@return \MiniAsset\Filter\AssetFilterInterface |
public function down()
{
Schema::drop('sites');
Schema::drop('asset_site');
Schema::drop('person_site');
Schema::table('pages', function (Blueprint $table) {
$table->dropColumn(Page::ATTR_SITE);
});
Schema::table('groups', function (Blueprint $table) {
$table->dropColumn(Group::ATTR_SITE);
});
Schema::table('tags', function (Blueprint $table) {
$table->dropColumn(Group::ATTR_SITE);
});
Schema::table('page_urls', function (Blueprint $table) {
$table->dropColumn(Page::ATTR_SITE);
$table->dropUnique('page_urls_site_id_location');
});
} | Reverse the migrations.
@return void |
public function getNext()
{
return $this
->where(self::ATTR_PAGE, $this->getPageId())
->where(self::ATTR_CREATED_AT, '>', $this->getEditedTime()->getTimestamp())
->orderBy(self::ATTR_CREATED_AT, 'asc')
->first();
} | Returns the next version.
@return PageVersion |
public function isPublished(DateTime $time = null)
{
$timestamp = $time ? $time->getTimestamp() : time();
return $this->{self::ATTR_EMBARGOED_UNTIL} && $this->{self::ATTR_EMBARGOED_UNTIL} <= $timestamp;
} | Whether the version is published.
If a time is given then the embargo time is compared with the given time.
Otherwise it is compared with the current time.
@param null|DateTime $time
@return bool |
public function status(DateTime $time = null)
{
if ($this->isPendingApproval()) {
return 'pending approval';
} elseif ($this->isDraft()) {
return 'draft';
} elseif ($this->isPublished($time)) {
return 'published';
} elseif ($this->isEmbargoed($time)) {
return 'embargoed';
}
} | Returns the status of the current page version.
If a time parameter is given then the status of the page at that time will be returned.
@param null|DateTime $time
@return string |
public function addRole($roleId, $allowed, $pageId = 0)
{
if (!$this->hasRole($roleId, $pageId)) {
$this->roles()
->attach($roleId, [
self::PIVOT_ATTR_ALLOWED => $allowed,
self::PIVOT_ATTR_PAGE_ID => $pageId,
]);
}
return $this;
} | Adds a role to the current group.
This will also add the role to all members of the group.
@param int $roleId ID of the role to add
@param int $allowed Whether the group is allowed or prevented from the role.
@param int $pageId Make the role active at a particular point in the page tree.
@return $this |
public function hasRole($roleId, $pageId = 0)
{
return $this->roles()
->wherePivot(self::PIVOT_ATTR_PAGE_ID, '=', $pageId)
->wherePivot(self::PIVOT_ATTR_ROLE_ID, '=', $roleId)
->exists();
} | Determines whether the current group has a specified role allowed / denied.
@param int $roleId
@param int $pageId
@return bool |
public function removeRole($roleId, $pageId = 0)
{
$this->roles()
->wherePivot(self::PIVOT_ATTR_ROLE_ID, '=', $roleId)
->wherePivot(self::PIVOT_ATTR_PAGE_ID, '=', $pageId)
->detach();
return $this;
} | Remove a role from a group.
After removing the role from the group the permissions for the people the group are updated.
@param int $roleId
@return $this |
public function getLinks(int $limit = 0): array
{
if ($this->links === null) {
$links = $this->attrs['links'] ?? [];
$this->links = $this->removeInvalidOrHiddenLinks($links);
}
return $limit > 0 ? array_slice($this->links, 0, $limit) : $this->links;
} | Returns an array of links in the linkset.
Or an empty array if the linkset doesn't contain any (valid, visible) links
@param int $limit
@return array |
protected function removeInvalidOrHiddenLinks(array $links): array
{
foreach ($links as $i => &$link) {
if (!isset($link['target_page_id']) && !isset($link['url'])) {
unset($links[$i]);
continue;
}
$target = empty($link['target_page_id']) ? $link['url'] : $link['target_page_id'];
$link = Link::factory($target, $link);
if (!$link->isValid() || (!$this->editable && !$link->isVisible())) {
unset($links[$i]);
}
}
return array_values($links);
} | Removes links which are:.
* Invalid because they don't have a target page ID or a URL to link to
* Hidden because they're an internal link but the page isn't visible to the current user
@param array $links
@return array |
public function input($filename, $content)
{
$this->_filename = $filename;
$content = preg_replace_callback($this->_backgroundPattern, array($this, '_replace'), $content);
$content = preg_replace_callback($this->_backgroundImagePattern, array($this, '_replace'), $content);
return $content;
} | Input filter. Locates CSS background images relative to the
filename and gets the filemtime for the images.
@param string $filename The file being processed
@param string $content The file content
@return The content with images timestamped. |
protected function _replace($matches)
{
$webroot = null;
if (defined('WWW_ROOT')) {
$webroot = WWW_ROOT;
}
if (!empty($this->_settings['webroot'])) {
$webroot = $this->_settings['webroot'];
}
$path = $matches['path'];
if ($path[0] === '/') {
$imagePath = $webroot . rtrim($path, '/');
} else {
$imagePath = realpath(dirname($this->_filename) . DIRECTORY_SEPARATOR . $path);
}
if (file_exists($imagePath)) {
$path = $this->_timestamp($imagePath, $path);
}
return $matches['prop'] . $path . $matches['trail'];
} | Do replacements.
- $matches[0] -> whole background line.
- $matches[path] -> the url with any wrapping '/'
If the image path starts with / its assumed to be an absolute path
which will be prepended with settings[webroot] or WWW_ROOT
@param array $matches Array of matches
@return string Replaced code. |
protected function _timestamp($filepath, $path)
{
if (strpos($path, '?') === false) {
$path .= '?t=' . filemtime($filepath);
}
return $path;
} | Add timestamps to the given path. Will not change paths with
querystrings, as they could have anything in them or be customized
already.
@param string $filepath The absolute path to the file for timestamping
@param string $path The path to append a timestamp to.
@return string Path with a timestamp. |
public function getMetadata(): array
{
if ($this->metadata === null) {
$this->metadata = $this->readMetadata();
ksort($this->metadata);
}
return $this->metadata;
} | {@inheritdoc}
@return array |
protected function oneOf(array $keys, $default = null)
{
$metadata = $this->getMetadata();
foreach ($keys as $key) {
if (isset($metadata[$key])) {
return $metadata[$key];
}
}
return $default;
} | Loop through an array of metadata keys and return the first one that exists.
@param array $keys
@param mixed $default
@return mixed |
public function handle(Request $request, Closure $next)
{
View::share('button', function ($type, $text, $attrs = []) {
return new UI\Button($type, $text, $attrs);
});
View::share('menu', function () {
return view('boomcms::menu')->render();
});
View::share('menuButton', function () {
return new UI\MenuButton();
});
$jsFile = $this->app->environment('local') ? 'cms.js' : 'cms.min.js';
View::share('boomJS', "<script type='text/javascript' src='/vendor/boomcms/boom-core/js/$jsFile?".BoomCMS::getVersion()."'></script>");
View::share('editor', $this->editor);
return $next($request);
} | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed |
public function WriteXY($x, $y, $line, $txt, $link = '')
{
$this->SetXY($x, $y);
$this->Write($line, $txt, $link);
} | Write to position
@param string $x
@param string $y
@param string $line
@param string $txt
@param string|identifier $link URL or identifier returned by AddLink().
@return void |
public function arc($x1, $y1, $x2, $y2, $x3, $y3)
{
$h = $this->h;
$this->out(
sprintf(
'%.2F %.2F %.2F %.2F %.2F %.2F c ',
$x1 * $this->k,
($h - $y1) * $this->k,
$x2 * $this->k,
($h - $y2) * $this->k,
$x3 * $this->k,
($h - $y3) * $this->k
)
);
} | Create an Arc.
@param int $x1
@param int $y1
@param int $x2
@param int $y2
@param int $x3
@param int $y3 |
public function circle($x, $y, $r, $style = 'D')
{
$this->Ellipse($x, $y, $r, $r, $style);
} | create a circle.
@param int $x
@param int $y
@param int $r
@param string $style |
public function getCode128CheckNum($val)
{
$sum = 103;
for ($i = 0; $i < strlen($val); $i++) {
$sum += ($i + 1) * $this->ChrToC128(ord(substr($val, $i, 1)));
}
$ch_num = $sum % 103;
return $ch_num;
} | helper method get Code 128.
@param string $val
@return int |
public function rotate($angle, $x = -1, $y = -1)
{
if ($x == -1) {
$x = $this->x;
}
if ($y == -1) {
$y = $this->y;
}
if ($this->angle!=0) {
$this->_out('Q');
}
$this->angle = $angle;
if ($angle != 0) {
$angle*=M_PI/180;
$c=cos($angle);
$s=sin($angle);
$cx=$x*$this->k;
$cy=($this->h-$y)*$this->k;
$this->_out(sprintf(
'q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm',
$c,
$s,
-$s,
$c,
$cx,
$cy,
-$cx,
-$cy
));
}
} | Rotate object
based on:
@link http://www.fpdf.org/en/script/script2.php
@param int $angle degrees
@param int $x x position
@param int $y y position |
public function rotatedText($x, $y, $txt, $angle)
{
//Text rotated around its origin
$this->rotate($angle, $x, $y);
$this->Text($x, $y, $txt);
$this->rotate(0);
} | Rotate text
@link http://www.fpdf.org/en/script/script2.php
@param int $x
@param int $y
@param string $txt
@param int $angle
@return void |
public function up()
{
$features = DB::table('chunk_features')
->get()
->toArray();
foreach ($features as $feature) {
$feature = (array) $feature;
$slotname = $feature['slotname'];
$exists = Linkset::where('slotname', $slotname)
->where('page_id', $feature['page_id'])
->exists();
if ($exists === true) {
$slotname = 'feature-'.$slotname;
}
Linkset::create([
'slotname' => $slotname,
'page_vid' => $feature['page_vid'],
'page_id' => $feature['page_id'],
'links' => [
['target_page_id' => $feature['target_page_id']],
],
]);
}
Schema::drop('chunk_features');
DB::table('page_versions')
->whereIn('chunk_type', ['feature', 'link'])
->update([
'chunk_type' => 'linkset',
]);
} | Run the migrations.
@return void |
public function compare(PageVersion $new, PageVersion $old)
{
if ($new->getRestoredVersionId()) {
return new Diff\RestoredVersion($new, $old);
}
if ($new->isContentChange()) {
return new Diff\ChunkChange($new, $old);
}
if ($new->getTemplateId() !== $old->getTemplateId()) {
return new Diff\TemplateChange($new, $old);
}
if (strcmp($new->getTitle(), $old->getTitle()) !== 0) {
return new Diff\TitleChange($new, $old);
}
if ($new->isPendingApproval() && !$old->isPendingApproval()) {
return new Diff\ApprovalRequest($new, $old);
}
if ($new->isEmbargoed($new->getEditedTime())) {
if (!$old->isEmbargoed($old->getEditedTime())) {
return new Diff\Embargoed($new, $old);
}
if ($new->getEmbargoedUntil()->getTimestamp() !== $old->getEmbargoedUntil()->getTimestamp()) {
return new Diff\EmbargoChanged($new, $old);
}
}
if ($new->isPublished($new->getEditedTime())) {
if (!$old->isPublished($old->getEditedTime())) {
return new Diff\Published($new, $old);
}
}
} | Compare two versions.
@param PageVersion $new
@param PageVersion $old
@return Diff\BaseChange |
public function allowedToEdit(Page $page = null)
{
if ($page === null) {
return true;
}
return Editor::isEnabled() && $this->gate->allows('edit', $page);
} | Returns whether the logged in user is allowed to edit a page.
@return bool |
public function edit($type, $slotname, $page = null)
{
$className = $this->getClassName($type);
if ($page === null) {
$page = Router::getActivePage();
}
$model = $this->find($type, $slotname, $page->getCurrentVersion());
$attrs = $model ? $model->toArray() : [];
$chunk = new $className($page, $attrs, $slotname);
return $chunk->editable($this->allowedToEdit($page));
} | Returns a chunk object of the required type.
@param string $type Chunk type, e.g. text, feature, etc.
@param string $slotname The name of the slot to retrieve a chunk from.
@param mixed $page The page the chunk belongs to. If not given then the page from the current request will be used.
@return BaseChunk |
public function find($type, $slotname, PageVersion $version)
{
$cached = $this->getFromCache($type, $slotname, $version);
if ($cached !== false) {
return $cached;
}
$class = $this->getModelName($type);
$chunk = $version->getId() ?
$class::getSingleChunk($version, $slotname)->first()
: null;
$this->saveToCache($type, $slotname, $version, $chunk);
return $chunk;
} | Find a chunk by page version, type, and slotname.
@param string $type
@param string $slotname
@param PageVersion $version
@return null|BaseChunk |
public function findById($type, $chunkId)
{
$model = $this->getModelName($type);
return $model::find($chunkId);
} | Find a chunk by it's ID.
@param string $type
@param int $chunkId
@return ChunkModel |
public function getFromCache($type, $slotname, PageVersion $version)
{
$key = $this->getCacheKey($type, $slotname, $version);
return $this->cache->get($key, false);
} | Get a chunk from the cache.
@param type $type
@param type $slotname
@param PageVersion $version
@return mixed |
public function insert($type, $slotname, $page = null)
{
if ($page === null || $page === Router::getActivePage()) {
return $this->edit($type, $slotname, $page);
}
return $this->get($type, $slotname, $page);
} | Insert a chunk into a page.
@param string $type
@param string $slotname
@param null|Page $page
@return mixed |
public function saveToCache($type, $slotname, $version, ChunkModel $chunk = null)
{
$key = $this->getCacheKey($type, $slotname, $version);
$this->cache->forever($key, $chunk);
} | Save a chunk to the cache.
@param type $type
@param type $slotname
@param type $version
@param null|ChunkModel $chunk |
public function since(PageVersion $version)
{
$chunks = [];
foreach ($this->types as $type) {
$className = $this->getModelName($type);
$chunks[$type] = $className::getSince($version)->get();
}
return $chunks;
} | Returns an array of chunks which have changed since a version.
@param PageVersion $version
@return array |
public function up()
{
Schema::create('page_versions', function (Blueprint $table) {
$table->increments('id');
$table->integer('page_id')->unsigned()->nullable()->index('page_v_rid');
$table->smallInteger('template_id')->nullable()->index('page_versions_template_id');
$table->string('title', 100)->nullable()->default('Untitled');
$table->smallInteger('edited_by')->unsigned()->nullable()->index('edited_by');
$table->integer('edited_time')->unsigned()->nullable();
$table->integer('embargoed_until')->unsigned()->nullable();
$table->boolean('pending_approval')->nullable()->default(0)->index('page_versions_pending_approval');
$table->index('title');
$table->index(['page_id', 'edited_time', 'embargoed_until']);
$table->string(PageVersion::ATTR_CHUNK_TYPE, 15);
$table->integer(PageVersion::ATTR_CHUNK_ID)->unsigned();
$table
->integer('restored_from')
->unsigned()
->references('id')
->on('page_versions')
->onUpdate('CASCADE')
->onDelete('SET NULL');
});
} | Run the migrations.
@return void |
public function input($filename, $input)
{
if (substr($filename, strlen($this->_settings['ext']) * -1) !== $this->_settings['ext']) {
return $input;
}
$tmpFile = tempnam(TMP, 'TYPESCRIPT');
$cmd = $this->_settings['typescript'] . " " . escapeshellarg($filename) . " --out " . $tmpFile;
$this->_runCmd($cmd, null);
$output = file_get_contents($tmpFile);
unlink($tmpFile);
return $output;
} | Runs `tsc` against files that match the configured extension.
@param string $filename Filename being processed.
@param string $content Content of the file being processed.
@return string |
public function getCreatedAt()
{
$timestamp = $this->oneOf(['exif:DateTimeOriginal', 'exif:DateTimeDigitized', 'exif:DateTime', 'date:create']);
try {
return !empty($timestamp) ? Carbon::parse($timestamp) : null;
} catch (Exception $e) {
return;
}
} | {@inheritdoc}
@return null|Carbon |
public function getDimensions(): array
{
if ($this->dimensions === null) {
$this->dimensions = getimagesize($this->file->getPathname());
}
return $this->dimensions;
} | Get the dimensions (width and height) of an image as an array.
@return array |