_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q258800 | HierarchicalTrait.children | test | public function children()
{
if ($this->children !== null) {
return $this->children;
}
$this->children = $this->loadChildren();
return $this->children;
} | php | {
"resource": ""
} |
q258801 | HierarchicalTrait.siblings | test | public function siblings()
{
if ($this->siblings !== null) {
return $this->siblings;
}
$master = $this->master();
if ($master === null) {
// Todo: return all top-level objects.
$siblings = [];
} else {
// Todo: Remove "current" object from siblings
$siblings = $master->children();
}
$this->siblings = $siblings;
return $this->siblings;
} | php | {
"resource": ""
} |
q258802 | HierarchicalTrait.loadObjectFromSource | test | private function loadObjectFromSource($id)
{
$obj = $this->modelFactory()->create($this->objType());
$obj->load($id);
if ($obj->id()) {
return $obj;
} else {
return null;
}
} | php | {
"resource": ""
} |
q258803 | HierarchicalTrait.loadObjectFromCache | test | private function loadObjectFromCache($id)
{
$objType = $this->objType();
if (isset(static::$objectCache[$objType][$id])) {
return static::$objectCache[$objType][$id];
} else {
return null;
}
} | php | {
"resource": ""
} |
q258804 | HierarchicalTrait.addObjectToCache | test | private function addObjectToCache(ModelInterface $obj)
{
static::$objectCache[$this->objType()][$obj->id()] = $obj;
return $this;
} | php | {
"resource": ""
} |
q258805 | CategoryTrait.categoryItems | test | public function categoryItems()
{
if ($this->categoryItems === null) {
$this->categoryItems = $this->loadCategoryItems();
}
return $this->categoryItems;
} | php | {
"resource": ""
} |
q258806 | RoutableTrait.slugPattern | test | public function slugPattern()
{
if (!$this->slugPattern) {
$metadata = $this->metadata();
if (isset($metadata['routable']['pattern'])) {
$this->setSlugPattern($metadata['routable']['pattern']);
} elseif (isset($metadata['slug_pattern'])) {
$this->setSlugPattern($metadata['slug_pattern']);
} else {
throw new Exception(sprintf(
'Undefined route pattern (slug) for %s',
get_called_class()
));
}
}
return $this->slugPattern;
} | php | {
"resource": ""
} |
q258807 | RoutableTrait.slugPrefix | test | public function slugPrefix()
{
if (!$this->slugPrefix) {
$metadata = $this->metadata();
if (isset($metadata['routable']['prefix'])) {
$this->slugPrefix = $this->translator()->translation($metadata['routable']['prefix']);
}
}
return $this->slugPrefix;
} | php | {
"resource": ""
} |
q258808 | RoutableTrait.slugSuffix | test | public function slugSuffix()
{
if (!$this->slugSuffix) {
$metadata = $this->metadata();
if (isset($metadata['routable']['suffix'])) {
$this->slugSuffix = $this->translator()->translation($metadata['routable']['suffix']);
}
}
return $this->slugSuffix;
} | php | {
"resource": ""
} |
q258809 | RoutableTrait.isSlugEditable | test | public function isSlugEditable()
{
if ($this->isSlugEditable === null) {
$metadata = $this->metadata();
if (isset($metadata['routable']['editable'])) {
$this->isSlugEditable = !!$metadata['routable']['editable'];
} else {
$this->isSlugEditable = false;
}
}
return $this->isSlugEditable;
} | php | {
"resource": ""
} |
q258810 | RoutableTrait.setSlug | test | public function setSlug($slug)
{
$slug = $this->translator()->translation($slug);
if ($slug !== null) {
$this->slug = $slug;
$values = $this->slug->data();
foreach ($values as $lang => $val) {
$this->slug[$lang] = $this->slugify($val);
}
} else {
/** @todo Hack used for regenerating route */
if (isset($_POST['slug'])) {
$this->slug = [];
} else {
$this->slug = null;
}
}
return $this;
} | php | {
"resource": ""
} |
q258811 | RoutableTrait.generateSlug | test | public function generateSlug()
{
$languages = $this->translator()->availableLocales();
$patterns = $this->slugPattern();
$curSlug = $this->slug();
$newSlug = [];
$origLang = $this->translator()->getLocale();
foreach ($languages as $lang) {
$pattern = $patterns[$lang];
$this->translator()->setLocale($lang);
if ($this->isSlugEditable() && isset($curSlug[$lang]) && strlen($curSlug[$lang])) {
$newSlug[$lang] = $curSlug[$lang];
} else {
$newSlug[$lang] = $this->generateRoutePattern($pattern);
if (!strlen($newSlug[$lang])) {
throw new UnexpectedValueException(sprintf(
'The slug is empty. The pattern is "%s"',
$pattern
));
}
}
$newSlug[$lang] = $this->finalizeSlug($newSlug[$lang]);
$newRoute = $this->createRouteObject();
$newRoute->setData([
'lang' => $lang,
'slug' => $newSlug[$lang],
'route_obj_type' => $this->objType(),
'route_obj_id' => $this->id(),
]);
if (!$newRoute->isSlugUnique()) {
$newRoute->generateUniqueSlug();
$newSlug[$lang] = $newRoute->slug();
}
}
$this->translator()->setLocale($origLang);
return $this->translator()->translation($newSlug);
} | php | {
"resource": ""
} |
q258812 | RoutableTrait.generateRoutePattern | test | protected function generateRoutePattern($pattern)
{
if ($this instanceof ViewableInterface && $this->view() !== null) {
$route = $this->view()->render($pattern, $this->viewController());
} else {
$route = preg_replace_callback('~\{\{\s*(.*?)\s*\}\}~i', [ $this, 'parseRouteToken' ], $pattern);
}
return $this->slugify($route);
} | php | {
"resource": ""
} |
q258813 | RoutableTrait.filterRouteToken | test | protected function filterRouteToken($value, $token = null)
{
unset($token);
if ($value instanceof \Closure) {
$value = $value();
}
if ($value instanceof \DateTime) {
$value = $value->format('Y-m-d-H:i');
}
if (method_exists($value, '__toString')) {
$value = strval($value);
}
return $value;
} | php | {
"resource": ""
} |
q258814 | RoutableTrait.generateObjectRoute | test | protected function generateObjectRoute($slug = null, array $data = [])
{
if (!$slug) {
$slug = $this->generateSlug();
}
if ($slug instanceof Translation) {
$slugs = $slug->data();
} else {
throw new InvalidArgumentException(sprintf(
'[%s] slug parameter must be an instance of %s, received %s',
get_called_class().'::'.__FUNCTION__,
Translation::class,
is_object($slug) ? get_class($slug) : gettype($slug)
));
}
if (!is_array($data)) {
$data = [];
}
$origLang = $this->translator()->getLocale();
foreach ($slugs as $lang => $slug) {
if (!in_array($lang, $this->translator()->availableLocales())) {
continue;
}
$this->translator()->setLocale($lang);
$newRoute = $this->createRouteObject();
$oldRoute = $this->getLatestObjectRoute();
$defaultData = [
// Not used, might be too much.
'route_template' => $this->templateIdent(),
'route_options' => $this->routeOptions(),
'route_options_ident' => $this->routeOptionsIdent(),
];
$immutableData = [
'lang' => $lang,
'slug' => $slug,
'route_obj_type' => $this->objType(),
'route_obj_id' => $this->id(),
'active' => true,
];
$newData = array_merge($defaultData, $data, $immutableData);
// Unchanged but sync extra properties
if ($slug === $oldRoute->slug()) {
$oldRoute->setData([
'route_template' => $newData['route_template'],
'route_options' => $newData['route_options'],
'route_options_ident' => $newData['route_options_ident'],
]);
$oldRoute->update([ 'route_template', 'route_options' ]);
continue;
}
$newRoute->setData($newData);
if (!$newRoute->isSlugUnique()) {
$newRoute->generateUniqueSlug();
}
if ($newRoute->id()) {
$newRoute->update();
} else {
$newRoute->save();
}
}
$this->translator()->setLocale($origLang);
} | php | {
"resource": ""
} |
q258815 | RoutableTrait.url | test | public function url($lang = null)
{
$slug = $this->slug();
if ($slug instanceof Translation && $lang) {
return $slug[$lang];
}
if ($slug) {
return $slug;
}
$url = (string)$this->getLatestObjectRoute($lang)->slug();
return $url;
} | php | {
"resource": ""
} |
q258816 | RoutableTrait.slugify | test | public function slugify($str)
{
static $sluggedArray;
if (isset($sluggedArray[$str])) {
return $sluggedArray[$str];
}
$metadata = $this->metadata();
$separator = isset($metadata['routable']['separator']) ? $metadata['routable']['separator'] : '-';
$delimiters = '-_|';
$pregDelim = preg_quote($delimiters);
$directories = '\\/';
$pregDir = preg_quote($directories);
// Do NOT remove forward slashes.
$slug = preg_replace('![^(\p{L}|\p{N})(\s|\/)]!u', $separator, $str);
if (!isset($metadata['routable']['lowercase']) || $metadata['routable']['lowercase'] === false) {
$slug = mb_strtolower($slug, 'UTF-8');
}
// Strip HTML
$slug = strip_tags($slug);
// Remove diacritics
$slug = htmlentities($slug, ENT_COMPAT, 'UTF-8');
$slug = preg_replace('!&([a-zA-Z])(uml|acute|grave|circ|tilde|cedil|ring);!', '$1', $slug);
// Simplify ligatures
$slug = preg_replace('!&([a-zA-Z]{2})(lig);!', '$1', $slug);
// Remove unescaped HTML characters
$unescaped = '!&(raquo|laquo|rsaquo|lsaquo|rdquo|ldquo|rsquo|lsquo|hellip|amp|nbsp|quot|ordf|ordm);!';
$slug = preg_replace($unescaped, '', $slug);
// Unify all dashes/underscores as one separator character
$flip = ($separator === '-') ? '_' : '-';
$slug = preg_replace('!['.preg_quote($flip).']+!u', $separator, $slug);
// Remove all whitespace and normalize delimiters
$slug = preg_replace('![_\|\s|\(\)]+!', $separator, $slug);
// Squeeze multiple delimiters and whitespace with a single separator
$slug = preg_replace('!['.$pregDelim.'\s]{2,}!', $separator, $slug);
// Squeeze multiple URI path delimiters
$slug = preg_replace('!['.$pregDir.']{2,}!', $separator, $slug);
// Remove delimiters surrouding URI path delimiters
$slug = preg_replace('!(?<=['.$pregDir.'])['.$pregDelim.']|['.$pregDelim.'](?=['.$pregDir.'])!', '', $slug);
// Strip leading and trailing dashes or underscores
$slug = trim($slug, $delimiters);
// Cache the slugified string
$sluggedArray[$str] = $slug;
return $slug;
} | php | {
"resource": ""
} |
q258817 | RoutableTrait.finalizeSlug | test | protected function finalizeSlug($slug)
{
$prefix = $this->slugPrefix();
if ($prefix) {
$prefix = $this->generateRoutePattern((string)$prefix);
if ($slug === $prefix) {
throw new UnexpectedValueException('The slug is the same as the prefix.');
}
$slug = $prefix.preg_replace('!^'.preg_quote($prefix).'\b!', '', $slug);
}
$suffix = $this->slugSuffix();
if ($suffix) {
$suffix = $this->generateRoutePattern((string)$suffix);
if ($slug === $suffix) {
throw new UnexpectedValueException('The slug is the same as the suffix.');
}
$slug = preg_replace('!\b'.preg_quote($suffix).'$!', '', $slug).$suffix;
}
$slug = rtrim($slug, '/');
return $slug;
} | php | {
"resource": ""
} |
q258818 | RoutableTrait.deleteObjectRoutes | test | protected function deleteObjectRoutes()
{
if (!$this->objType()) {
return false;
}
if (!$this->id()) {
return false;
}
$loader = $this->createRouteObjectCollectionLoader();
$loader
->addFilters([
[
'property' => 'route_obj_type',
'value' => $this->objType(),
],
[
'property' => 'route_obj_id',
'value' => $this->id(),
],
]);
$collection = $loader->load();
foreach ($collection as $route) {
$route->delete();
}
return true;
} | php | {
"resource": ""
} |
q258819 | RoutableTrait.createRouteObjectCollectionLoader | test | public function createRouteObjectCollectionLoader()
{
$loader = new CollectionLoader([
'logger' => $this->logger,
'factory' => $this->modelFactory(),
'model' => $this->getRouteObjectPrototype(),
]);
return $loader;
} | php | {
"resource": ""
} |
q258820 | RevisionableTrait.allRevisions | test | public function allRevisions(callable $callback = null)
{
$loader = new CollectionLoader([
'logger' => $this->logger,
'factory' => $this->modelFactory()
]);
$loader->setModel($this->createRevisionObject());
$loader->addFilter('target_type', $this->objType());
$loader->addFilter('target_id', $this->id());
$loader->addOrder('rev_ts', 'desc');
if ($callback !== null) {
$loader->setCallback($callback);
}
$revisions = $loader->load();
return $revisions->objects();
} | php | {
"resource": ""
} |
q258821 | PublishableTrait.setPublishDate | test | public function setPublishDate($time)
{
if ($time === null || $time === '') {
$this->publishDate = null;
return $this;
}
if (is_string($time)) {
try {
$time = new DateTime($time);
} catch (Exception $e) {
throw new UnexpectedValueException(sprintf(
'Invalid Publication Date: %s',
$e->getMessage()
), $e->getCode(), $e);
}
}
if (!$time instanceof DateTimeInterface) {
throw new InvalidArgumentException(
'Publication Date must be a date/time string or an instance of DateTimeInterface'
);
}
$this->publishDate = $time;
return $this;
} | php | {
"resource": ""
} |
q258822 | PublishableTrait.setExpiryDate | test | public function setExpiryDate($time)
{
if ($time === null || $time === '') {
$this->expiryDate = null;
return $this;
}
if (is_string($time)) {
try {
$time = new DateTime($time);
} catch (Exception $e) {
throw new UnexpectedValueException(sprintf(
'Invalid Expiration Date: %s',
$e->getMessage()
), $e->getCode(), $e);
}
}
if (!$time instanceof DateTimeInterface) {
throw new InvalidArgumentException(
'Expiration Date must be a date/time string or an instance of DateTimeInterface'
);
}
$this->expiryDate = $time;
return $this;
} | php | {
"resource": ""
} |
q258823 | PublishableTrait.setPublishStatus | test | public function setPublishStatus($status)
{
if ($status === null || $status === '') {
$this->publishStatus = null;
return $this;
}
$specialStatus = [
static::STATUS_EXPIRED => static::STATUS_PUBLISHED,
static::STATUS_UPCOMING => static::STATUS_PUBLISHED
];
/** Resolve any special statuses */
if (isset($specialStatus[$status])) {
$status = $specialStatus[$status];
}
$validStatus = [
static::STATUS_DRAFT,
static::STATUS_PENDING,
static::STATUS_PUBLISHED
];
if (!in_array($status, $validStatus)) {
throw new InvalidArgumentException(sprintf(
'Status "%s" is not a valid publish status.',
$status
));
}
$this->publishStatus = $status;
return $this;
} | php | {
"resource": ""
} |
q258824 | PublishableTrait.publishDateStatus | test | public function publishDateStatus()
{
$now = new DateTime();
$publish = $this->publishDate();
$expiry = $this->expiryDate();
$status = $this->publishStatus();
if ($status !== static::STATUS_PUBLISHED) {
return $status;
}
if (!$publish) {
if (!$expiry || $now < $expiry) {
return static::STATUS_PUBLISHED;
} else {
return static::STATUS_EXPIRED;
}
} else {
if ($now < $publish) {
return static::STATUS_UPCOMING;
} else {
if (!$expiry || $now < $expiry) {
return static::STATUS_PUBLISHED;
} else {
return static::STATUS_EXPIRED;
}
}
}
} | php | {
"resource": ""
} |
q258825 | Help.index | test | public function index()
{
if (!userHasPermission('admin:admin:help:view')) {
unauthorised();
}
// --------------------------------------------------------------------------
// Page Title
$this->data['page']->title = 'Help Videos';
// --------------------------------------------------------------------------
// Get data
$oInput = Factory::service('Input');
$oHelpModel = Factory::model('Help', 'nails/module-admin');
$sTableAlias = $oHelpModel->getTableAlias();
// Get pagination and search/sort variables
$iPage = (int) $oInput->get('page') ?: 0;
$iPerPage = (int) $oInput->get('perPage') ?: 50;
$sSortOn = $oInput->get('sortOn') ?: $sTableAlias . '.label';
$sSortOrder = $oInput->get('sortOrder') ?: 'asc';
$sKeywords = $oInput->get('keywords') ?: '';
// --------------------------------------------------------------------------
// Define the sortable columns
$aSortColumns = [
$sTableAlias . '.label' => 'Label',
$sTableAlias . '.duration' => 'Duration',
$sTableAlias . '.created' => 'Added',
$sTableAlias . '.modified' => 'Modified',
];
// --------------------------------------------------------------------------
// Define the $aData variable for the queries
$aData = [
'sort' => [
[$sSortOn, $sSortOrder],
],
'keywords' => $sKeywords,
];
// Get the items for the page
$iTotalRows = $oHelpModel->countAll($aData);
$this->data['videos'] = $oHelpModel->getAll($iPage, $iPerPage, $aData);
// Set Search and Pagination objects for the view
$this->data['search'] = Helper::searchObject(true, $aSortColumns, $sSortOn, $sSortOrder, $iPerPage, $sKeywords);
$this->data['pagination'] = Helper::paginationObject($iPage, $iPerPage, $iTotalRows);
// --------------------------------------------------------------------------
$oAsset = Factory::service('Asset');
$oAsset->inline('$(\'a.video-button\').fancybox({ type : \'iframe\' });', 'JS');
// --------------------------------------------------------------------------
// Load views
Helper::loadView('index');
} | php | {
"resource": ""
} |
q258826 | Utilities.rewrite_routes | test | public function rewrite_routes()
{
if (!userHasPermission('admin:admin:utilities:rewriteRoutes')) {
unauthorised();
}
// --------------------------------------------------------------------------
$oInput = Factory::service('Input');
if ($oInput->post('go')) {
$oRoutesService = Factory::service('Routes');
if ($oRoutesService->update()) {
$this->data['success'] = 'Routes rewritten successfully.';
} else {
$this->data['error'] = 'There was a problem writing the routes. ';
$this->data['error'] .= $oRoutesService->lastError();
}
}
// --------------------------------------------------------------------------
// Load views
Helper::loadView('rewriteRoutes');
} | php | {
"resource": ""
} |
q258827 | SourceResponse.reset | test | public function reset()
{
if (!empty($this->aData)) {
reset($this->aData);
} elseif ($this->oSource instanceof \PDOStatement) {
// unsupported
} elseif ($this->oSource instanceof \CI_DB_mysqli_result) {
$this->oSource->data_seek(0);
}
} | php | {
"resource": ""
} |
q258828 | SourceResponse.getNextItem | test | public function getNextItem()
{
$oRow = null;
if (!empty($this->aData)) {
$oRow = current($this->aData);
next($this->aData);
} elseif ($this->oSource instanceof \PDOStatement) {
$oRow = $this->oSource->fetch(\PDO::FETCH_ASSOC);
} elseif ($this->oSource instanceof \CI_DB_mysqli_result) {
$oRow = $this->oSource->unbuffered_row();
}
return is_callable($this->cFormatter) ? call_user_func($this->cFormatter, $oRow) : $oRow;
} | php | {
"resource": ""
} |
q258829 | Logs.site | test | public function site()
{
if (!userHasPermission('admin:admin:logs:site:browse')) {
unauthorised();
}
// --------------------------------------------------------------------------
Factory::helper('string');
$oUri = Factory::service('Uri');
$sMethod = $oUri->segment(5) ? $oUri->segment(5) : 'index';
$sMethod = 'site' . underscoreToCamelcase(strtolower($sMethod), false);
if (method_exists($this, $sMethod)) {
$this->{$sMethod}();
} else {
show404('', true);
}
} | php | {
"resource": ""
} |
q258830 | Logs.siteIndex | test | protected function siteIndex()
{
if (!userHasPermission('admin:admin:logs:site:browse')) {
unauthorised();
}
// --------------------------------------------------------------------------
$this->data['page']->title = 'Browse Logs';
$oAsset = Factory::service('Asset');
$oAsset->library('MUSTACHE');
$oAsset->load('nails.admin.logs.site.min.js', 'NAILS');
$oAsset->inline('logsSite = new NAILS_Admin_Logs_Site();', 'JS');
Helper::loadView('site/index');
} | php | {
"resource": ""
} |
q258831 | Logs.siteView | test | protected function siteView()
{
if (!userHasPermission('admin:admin:logs:site:browse')) {
unauthorised();
}
// --------------------------------------------------------------------------
$oUri = Factory::service('Uri');
$sFile = $oUri->segment(6);
$this->data['page']->title = 'Browse Logs › ' . $sFile;
$oSiteLogModel = Factory::model('SiteLog', 'nails/module-admin');
$this->data['logs'] = $oSiteLogModel->readLog($sFile);
if (!$this->data['logs']) {
show404();
}
Helper::loadView('site/view');
} | php | {
"resource": ""
} |
q258832 | Logs.event | test | public function event()
{
if (!userHasPermission('admin:admin:logs:event:browse')) {
unauthorised();
}
// --------------------------------------------------------------------------
// Set method info
$this->data['page']->title = 'Browse Events';
// --------------------------------------------------------------------------
$sTableAlias = $this->event->getTableAlias();
// --------------------------------------------------------------------------
// Get pagination and search/sort variables
$oInput = Factory::service('Input');
$iPage = (int) $oInput->get('page') ?: 0;
$iPerPage = (int) $oInput->get('perPage') ?: 50;
$sSortOn = $oInput->get('sortOn') ?: $sTableAlias . '.created';
$sSortOrder = $oInput->get('sortOrder') ?: 'desc';
$sKeywords = $oInput->get('keywords') ?: '';
// --------------------------------------------------------------------------
// Define the sortable columns
$aSortColumns = [
$sTableAlias . '.created' => 'Created',
$sTableAlias . '.type' => 'Type',
];
// --------------------------------------------------------------------------
// Define the $aData variable for the queries
$aData = [
'sort' => [
[$sSortOn, $sSortOrder],
],
'keywords' => $sKeywords,
];
// Are we downloading? Or viewing?
if ($oInput->get('dl') && userHasPermission('admin:admin:logs:event:download')) {
// Get all items for the search, the view will iterate over the resultset
$oEvents = $this->event->getAllRawQuery(null, null, $aData);
Helper::loadCsv($oEvents, 'export-events-' . toUserDatetime(null, 'Y-m-d_h-i-s') . '.csv');
} else {
// Get the items for the page
$iTotalRows = $this->event->countAll($aData);
$this->data['events'] = $this->event->getAll($iPage, $iPerPage, $aData);
// Set Search and Pagination objects for the view
$this->data['search'] = Helper::searchObject(true, $aSortColumns, $sSortOn, $sSortOrder, $iPerPage, $sKeywords);
$this->data['pagination'] = Helper::paginationObject($iPage, $iPerPage, $iTotalRows);
// Add the header button for downloading
if (userHasPermission('admin:admin:logs:event:download')) {
// Build the query string, so that the same search is applies
$oInput = Factory::service('Input');
$aParams = [];
$aParams['dl'] = true;
$aParams['sortOn'] = $oInput->get('sortOn');
$aParams['sortOrder'] = $oInput->get('sortOrder');
$aParams['keywords'] = $oInput->get('keywords');
$aParams = array_filter($aParams);
$aParams = http_build_query($aParams);
Helper::addHeaderButton('admin/admin/logs/event?' . $aParams, 'Download As CSV');
}
Helper::loadView('event/index');
}
} | php | {
"resource": ""
} |
q258833 | DefaultController.permissions | test | public static function permissions(): array
{
$aPermissions = parent::permissions();
if (!empty(static::CONFIG_PERMISSION)) {
$aPermissions['browse'] = 'Can browse items';
$aPermissions['create'] = 'Can create items';
$aPermissions['edit'] = 'Can edit items';
$aPermissions['delete'] = 'Can delete items';
$aPermissions['restore'] = 'Can restore items';
}
return $aPermissions;
} | php | {
"resource": ""
} |
q258834 | DefaultController.index | test | public function index(): void
{
if (!static::userCan('browse')) {
unauthorised();
}
$oInput = Factory::service('Input');
$oModel = $this->getModel();
$aConfig = $this->getConfig();
$sAlias = $oModel->getTableAlias();
$aSortConfig = $aConfig['SORT_OPTIONS'];
if (classUses($oModel, Nestable::class)) {
$aSortConfig = array_merge(['Hierarchy' => 'order'], $aSortConfig);
}
// Get the first key (i.e the default sort)
$sFirstKey = reset($aSortConfig);
// Prepare the sort options so they have the appropriate table alias
$aSortCol = [];
foreach ($aSortConfig as $sLabel => $sColumn) {
if (strpos($sColumn, '.') === false) {
$aSortCol[$sAlias . '.' . $sColumn] = $sLabel;
} else {
$aSortCol[$sColumn] = $sLabel;
}
}
// Other parameters
$iPage = $oInput->get('page') ? $oInput->get('page') : 0;
$iPerPage = $oInput->get('perPage') ? $oInput->get('perPage') : 50;
$sSortOn = $oInput->get('sortOn') ? $oInput->get('sortOn') : $sAlias . '.' . $sFirstKey;
$sSortOrder = $oInput->get('sortOrder') ? $oInput->get('sortOrder') : $aConfig['SORT_DIRECTION'];
$sKeywords = $oInput->get('keywords');
$aCbFilters = $this->indexCheckboxFilters();
$aDdFilters = $this->indexDropdownFilters();
$aData = [
'cbFilters' => $aCbFilters,
'ddFilters' => $aDdFilters,
'keywords' => $sKeywords,
'sort' => [
[$sSortOn, $sSortOrder],
],
] + $aConfig['INDEX_DATA'];
// --------------------------------------------------------------------------
if (classUses($oModel, Localised::class)) {
$aData['NO_LOCALISE_FILTER'] = true;
}
// --------------------------------------------------------------------------
$iTotalRows = $oModel->countAll($aData);
$this->data['items'] = $oModel->getAll($iPage, $iPerPage, $aData);
$this->data['pagination'] = Helper::paginationObject($iPage, $iPerPage, $iTotalRows);
$this->data['search'] = Helper::searchObject(
true,
$aSortCol,
$sSortOn,
$sSortOrder,
$iPerPage,
$sKeywords,
$aCbFilters,
$aDdFilters
);
// --------------------------------------------------------------------------
static::addHeaderButtons($aConfig['INDEX_HEADER_BUTTONS']);
// --------------------------------------------------------------------------
$this->data['page']->title = $aConfig['TITLE_PLURAL'] . ' › Manage';
Helper::loadView('index');
} | php | {
"resource": ""
} |
q258835 | DefaultController.delete | test | public function delete(): void
{
$aConfig = $this->getConfig();
if (!$aConfig['CAN_DELETE']) {
show404();
} elseif (!static::userCan('delete')) {
unauthorised();
}
$oDb = Factory::service('Database');
$oModel = $this->getModel();
$oItem = $this->getItem();
if (empty($oItem)) {
show404();
}
try {
$oDb->trans_begin();
$this->beforeDelete($oItem);
if (classUses($oModel, Localised::class)) {
$oModel->delete($oItem->id, $oItem->locale);
} elseif (!$oModel->delete($oItem->id)) {
throw new NailsException(static::DELETE_ERROR_MESSAGE . ' ' . $oModel->lastError());
}
$this->afterDelete($oItem);
$oDb->trans_commit();
if ($aConfig['CAN_RESTORE'] && static::userCan('restore')) {
if (classUses($oModel, Localised::class)) {
$sRestoreLink = anchor(
$aConfig['BASE_URL'] . '/restore/' . $oItem->id . '/' . $oItem->locale,
'Restore?'
);
} else {
$sRestoreLink = anchor(
$aConfig['BASE_URL'] . '/restore/' . $oItem->id,
'Restore?'
);
}
} else {
$sRestoreLink = '';
}
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->setFlashData('success', static::DELETE_SUCCESS_MESSAGE . ' ' . $sRestoreLink);
$this->returnToIndex();
} catch (\Exception $e) {
$oDb->trans_rollback();
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->setFlashData('error', static::DELETE_ERROR_MESSAGE . ' ' . $e->getMessage());
$this->returnToIndex();
}
} | php | {
"resource": ""
} |
q258836 | DefaultController.restore | test | public function restore(): void
{
$aConfig = $this->getConfig();
if (!$aConfig['CAN_RESTORE']) {
show404();
} elseif (!static::userCan('restore')) {
unauthorised();
}
$oUri = Factory::service('Uri');
$oDb = Factory::service('Database');
$oSession = Factory::service('Session', 'nails/module-auth');
$oModel = $this->getModel();
$oItem = $this->getItem([], null, true);
try {
$oDb->trans_begin();
if (classUses($oModel, Localised::class)) {
$bResult = $oModel->restore($oItem->id, $oItem->locale);
} else {
$bResult = $oModel->restore($oItem->id);
}
if (!$bResult) {
throw new NailsException(static::RESTORE_ERROR_MESSAGE . ' ' . $oModel->lastError());
}
$oDb->trans_commit();
$oSession->setFlashData('success', static::RESTORE_SUCCESS_MESSAGE);
$this->returnToIndex();
} catch (\Exception $e) {
$oDb->trans_rollback();
$oSession->setFlashData('error', static::RESTORE_ERROR_MESSAGE . ' ' . $e->getMessage());
$this->returnToIndex();
}
} | php | {
"resource": ""
} |
q258837 | DefaultController.sort | test | public function sort(): void
{
$aConfig = $this->getConfig();
if (!$aConfig['CAN_EDIT']) {
show404();
} elseif (!static::userCan('edit')) {
unauthorised();
}
$oModel = $this->getModel();
$oInput = Factory::service('Input');
$oDb = Factory::service('Database');
if ($oInput->post()) {
try {
$oDb->trans_begin();
$aItems = array_values((array) $oInput->post('order'));
foreach ($aItems as $iOrder => $iId) {
if (classUses($oModel, Localised::class)) {
$aItems = $oModel->getAll([
'NO_LOCALISE_FILTER' => true,
'where' => [
['id', $iId],
],
]);
foreach ($aItems as $oItem) {
if (!$oModel->update($iId, ['order' => $iOrder], $oItem->locale)) {
throw new NailsException(
static::ORDER_ERROR_MESSAGE . ' ' . $oModel->lastError()
);
}
}
} elseif (!$oModel->update($iId, ['order' => $iOrder])) {
throw new NailsException(
static::ORDER_ERROR_MESSAGE . ' ' . $oModel->lastError()
);
}
}
$oDb->trans_commit();
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->setFlashData('success', static::ORDER_SUCCESS_MESSAGE);
redirect($aConfig['BASE_URL'] . '/sort');
} catch (\Exception $e) {
$oDb->trans_rollback();
$this->data['error'] = $e->getMessage();
}
}
$aItems = $oModel->getAll($aConfig['SORT_DATA']);
$this->data['items'] = $aItems;
$this->data['page']->title = $aConfig['TITLE_PLURAL'] . ' › Sort';
Helper::loadView('order');
} | php | {
"resource": ""
} |
q258838 | DefaultController.localisedItemCanBeDeleted | test | protected static function localisedItemCanBeDeleted(Resource $oItem)
{
/** @var Locale $oLocale */
$oLocale = Factory::service('Locale');
$sDefaultLocale = (string) $oLocale->getDefautLocale();
$sItemLocale = (string) $oItem->locale;
if ($sDefaultLocale !== $sItemLocale) {
return true;
} elseif ($sDefaultLocale === $sItemLocale && count($oItem->available_locales) === 1) {
return true;
} else {
return false;
}
} | php | {
"resource": ""
} |
q258839 | DefaultController.getTitleSingle | test | protected static function getTitleSingle(): string
{
if (!empty(static::CONFIG_TITLE_SINGLE)) {
return static::CONFIG_TITLE_SINGLE;
}
$sTitle = preg_replace('/([a-z])([A-Z])/', '$1 $2', static::CONFIG_MODEL_NAME);
$sTitle = strtolower($sTitle);
$sTitle = ucwords($sTitle);
return $sTitle;
} | php | {
"resource": ""
} |
q258840 | DefaultController.indexDropdownFilters | test | protected function indexDropdownFilters(): array
{
$aFilters = [];
if (classUses(static::getModel(), Localised::class)) {
/** @var Locale $oLocale */
$oLocale = Factory::service('Locale');
$aOptions = [];
$aOptions[] = Factory::factory('IndexFilterOption', 'nails/module-admin')
->setLabel('All Locales');
foreach ($oLocale->getSupportedLocales() as $oSupportedLocale) {
$aOptions[] = Factory::factory('IndexFilterOption', 'nails/module-admin')
->setLabel($oSupportedLocale->getDisplayLanguage())
->setValue($oSupportedLocale->getLanguage() . '_' . $oSupportedLocale->getRegion());
}
$aFilters[] = Factory::factory('IndexFilter', 'nails/module-admin')
->setLabel('Locale')
->setColumn('CONCAT(`language`, \'_\', `region`)')
->addOptions($aOptions);
}
return $aFilters;
} | php | {
"resource": ""
} |
q258841 | DefaultController.getPostObject | test | protected function getPostObject(): array
{
$aConfig = $this->getConfig();
$oModel = static::getModel();
$oInput = Factory::service('Input');
$oUri = Factory::service('Uri');
$aOut = [];
foreach ($aConfig['FIELDS'] as $oField) {
if (in_array($oField->key, $aConfig['EDIT_IGNORE_FIELDS'])) {
continue;
}
$aOut[$oField->key] = $oInput->post($oField->key);
if ($oField->allow_null && empty($aOut[$oField->key])) {
$aOut[$oField->key] = null;
}
// Type casting
switch ($oField->type) {
case 'boolean':
$aOut[$oField->key] = (bool) $aOut[$oField->key];
break;
}
}
if (classUses($oModel, Localised::class)) {
$iExistingId = $oUri->segment(5);
if ($oUri->segment(5)) {
$aOut['id'] = $oUri->segment(5);
}
}
return $aOut;
} | php | {
"resource": ""
} |
q258842 | DefaultController.getItem | test | protected function getItem(array $aData = [], int $iSegment = null, bool $bIncludeDeleted = false, bool $b404 = true)
{
$iSegment = $iSegment ?? 5;
$oUri = Factory::service('Uri');
$oModel = $this->getModel();
$iItemId = (int) $oUri->segment($iSegment);
if (classUses($oModel, Localised::class) && $oUri->segment($iSegment + 1)) {
$aData['USE_LOCALE'] = $oUri->segment($iSegment + 1);
}
if (!array_key_exists('where', $aData)) {
$aData['where'] = [];
}
$aData['where'][] = ['id', $iItemId];
$aItems = $oModel->getAll(
null,
null,
$aData,
$bIncludeDeleted
);
$oItem = reset($aItems);
if ($b404 && empty($oItem)) {
show404();
}
return $oItem;
} | php | {
"resource": ""
} |
q258843 | DefaultController.returnToIndex | test | protected function returnToIndex(): void
{
$oInput = Factory::service('Input');
$sReferrer = $oInput->server('HTTP_REFERER');
if (!empty($sReferrer)) {
redirect($sReferrer);
} else {
redirect($this->getConfig()['BASE_URL']);
}
} | php | {
"resource": ""
} |
q258844 | IndexFilter.addOption | test | public function addOption($sLabel, $mValue = null, $bIsSelected = false, $bIsQuery = null)
{
if ($sLabel instanceof Option) {
$this->aOptions[] = $sLabel;
} else {
$this->aOptions[] = Factory::factory('IndexFilterOption', 'nails/module-admin')
->setLabel($sLabel)
->setValue($mValue)
->setIsSelected($bIsSelected)
->setIsQuery($bIsQuery);
}
return $this;
} | php | {
"resource": ""
} |
q258845 | IndexFilter.addOptions | test | public function addOptions($aOptions)
{
foreach ($aOptions as $aOption) {
if ($aOption instanceof Option) {
$this->aOptions[] = $aOption;
} else {
$sLabel = getFromArray('label', $aOption, getFromArray(0, $aOption));
$mValue = getFromArray('value', $aOption, getFromArray(1, $aOption));
$bIsSelected = (bool) getFromArray('selected', $aOption, getFromArray(2, $aOption));
$bIsQuery = (bool) getFromArray('query', $aOption, getFromArray(3, $aOption));
$this->addOption($sLabel, $mValue, $bIsSelected, $bIsQuery);
}
}
return $this;
} | php | {
"resource": ""
} |
q258846 | IndexFilter.getOption | test | public function getOption($iOptionIndex)
{
return array_key_exists($iOptionIndex, $this->aOptions) ? $this->aOptions[$iOptionIndex] : null;
} | php | {
"resource": ""
} |
q258847 | Option.handleMethodCall | test | private function handleMethodCall($aMethods, $sMethod, $mValue)
{
if (substr($sMethod, 0, 3) !== 'set') {
return $this->{$aMethods[$sMethod]};
}
$this->{$aMethods[$sMethod]} = $mValue;
return $this;
} | php | {
"resource": ""
} |
q258848 | Export.setBatchStatus | test | public function setBatchStatus(array $aIds, $sStatus, $sError = '')
{
if (is_object(reset($aIds))) {
$aIds = arrayExtractProperty($aIds, 'id');
}
if (!empty($aIds)) {
$oDb = Factory::service('Database');
$oDb->set('status', $sStatus);
$oDb->set('modified', 'NOW()', false);
if ($sError) {
$oDb->set('error', $sError);
}
$oDb->where_in('id', $aIds);
$oDb->update($this->getTableName());
}
} | php | {
"resource": ""
} |
q258849 | Export.setBatchDownloadId | test | public function setBatchDownloadId(array $aIds, $iDownloadId)
{
if (is_object(reset($aIds))) {
$aIds = arrayExtractProperty($aIds, 'id');
}
if (!empty($aIds)) {
$oDb = Factory::service('Database');
$oDb->set('download_id', $iDownloadId);
$oDb->set('modified', 'NOW()', false);
$oDb->where_in('id', $aIds);
$oDb->update($this->getTableName());
}
} | php | {
"resource": ""
} |
q258850 | AdminRouter.index | test | public function index()
{
// When executing on the CLI we don't need to perform a few bit's of sense checking
$oInput = Factory::service('Input');
if (!$oInput::isCli()) {
// Is there an AdminIP whitelist?
$whitelistIp = (array) appSetting('whitelist', 'admin');
if ($whitelistIp) {
if (!isIpInRange($oInput->ipAddress(), $whitelistIp)) {
show404();
}
}
// Before we do anything, is the user an admin?
if (!isAdmin()) {
unauthorised();
}
}
// Determine which admin controllers are available to the system
$this->findAdminControllers();
// --------------------------------------------------------------------------
/**
* Sort the controllers into a view friendly array, taking into
* consideration the user's order and state preferences.
*/
$this->prepAdminControllersNav();
// Save adminControllers to controller data so everyone can use it
$this->data['adminControllers'] = $this->adminControllers;
$this->data['adminControllersNav'] = $this->adminControllersNav;
// --------------------------------------------------------------------------
// Route the user's request
$this->routeRequest();
} | php | {
"resource": ""
} |
q258851 | AdminRouter.findAdminControllers | test | protected function findAdminControllers()
{
// Look in the admin module
$this->loadAdminControllers(
'admin',
NAILS_PATH . 'module-admin/admin/controllers/',
NAILS_APP_PATH . 'application/modules/admin/controllers/',
['adminRouter.php']
);
// Look in all enabled modules
foreach (Components::modules() as $module) {
/**
* Skip the admin module. We use the moduleName rather than the component name
* so that we don't inadvertently load up the admin module (or any module identifying
* itself as admin) and listing all the files contained therein; we only want
* admin/controllers.
*/
if ($module->moduleName == 'admin') {
continue;
}
$this->loadAdminControllers(
$module->moduleName,
$module->path . 'admin/controllers/',
NAILS_APP_PATH . 'application/modules/' . $module->moduleName . '/admin/controllers/'
);
}
// Finally, look for app admin controllers
$this->loadAppAdminControllers();
} | php | {
"resource": ""
} |
q258852 | AdminRouter.loadAdminControllers | test | protected function loadAdminControllers($moduleName, $controllerPath, $appPath, $ignore = [])
{
// Does a path exist? Don't pollute the array with empty modules
if (is_dir($controllerPath)) {
// Look for controllers
$files = directory_map($controllerPath, 1);
foreach ($files as $file) {
if (in_array($file, $ignore)) {
continue;
}
$this->loadAdminController($file, $moduleName, $controllerPath, $appPath);
}
}
} | php | {
"resource": ""
} |
q258853 | AdminRouter.loadAdminController | test | protected function loadAdminController($file, $moduleName, $controllerPath, $appPath)
{
$fileName = substr($file, 0, strpos($file, '.php'));
// PHP file, no leading underscore
if (!$this->isValidAdminFile($file)) {
return;
}
// Valid file, load it up and define the full class path and name
require_once $controllerPath . $file;
$classPath = $controllerPath . $file;
$className = 'Nails\Admin\\' . ucfirst($moduleName) . '\\' . ucfirst($fileName);
// If there's an app version of this controller than we'll use that one instead.
if (is_file($appPath . $file)) {
require_once $appPath . $file;
$classPath = $appPath . $file;
$className = 'App\Admin\\' . ucfirst($moduleName) . '\\' . ucfirst($fileName);
// Does the expected class exist? If it doesn't fall back to the previous one
if (!class_exists($className)) {
$classPath = $controllerPath . $file;
$className = 'Nails\Admin\\' . ucfirst($moduleName) . '\\' . ucfirst($fileName);
}
}
// Load and process the class
$this->loadAdminClass($fileName, $className, $classPath, $moduleName);
} | php | {
"resource": ""
} |
q258854 | AdminRouter.loadAdminClass | test | protected function loadAdminClass($fileName, $className, $classPath, $moduleName)
{
// Does the expected class exist?
if (!class_exists($className)) {
return false;
}
// Does it have an announce method?
if (!method_exists($className, 'announce')) {
return false;
}
// Cool! We have a controller which is valid, Add it to the stack!
if (!isset($this->adminControllers[$moduleName])) {
$this->adminControllers[$moduleName] = new \stdClass();
$this->adminControllers[$moduleName]->controllers = [];
}
$aNavGroupings = $className::announce();
if (!empty($aNavGroupings) && !is_array($aNavGroupings) && !($aNavGroupings instanceof \Nails\Admin\Factory\Nav)) {
/**
* @todo Use an admin specific exception class, and autoload it.
*/
throw new RouterException('Admin Nav groupings returned by ' . $className . '::announce() were invalid', 1);
} elseif (!is_array($aNavGroupings)) {
$aNavGroupings = array_filter([$aNavGroupings]);
}
$this->adminControllers[$moduleName]->controllers[$fileName] = [
'className' => (string) $className,
'path' => (string) $classPath,
'groupings' => $aNavGroupings,
];
return true;
} | php | {
"resource": ""
} |
q258855 | AdminRouter.routeRequest | test | protected function routeRequest()
{
// What are we trying to access?
$oUri = Factory::service('Uri');
$sModule = $oUri->rsegment(3) ? $oUri->rsegment(3) : '';
$sController = ucfirst($oUri->rsegment(4) ? $oUri->rsegment(4) : $sModule);
$sMethod = $oUri->rsegment(5) ? $oUri->rsegment(5) : 'index';
if (empty($sModule)) {
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->keepFlashData();
redirect('admin/admin/dashboard');
} elseif (isset($this->adminControllers[$sModule]->controllers[$sController])) {
$aRequestController = $this->adminControllers[$sModule]->controllers[$sController];
$this->data['currentRequest'] = $aRequestController;
$sControllerName = $aRequestController['className'];
if (is_callable([$sControllerName, $sMethod])) {
$oController = new $sControllerName();
$oController->$sMethod();
} else {
show404();
}
} else {
show404();
}
} | php | {
"resource": ""
} |
q258856 | Helper.loadView | test | public static function loadView($sViewFile, $bLoadStructure = true, $bReturnView = false)
{
$aData =& getControllerData();
$oInput = Factory::service('Input');
$oView = Factory::service('View');
// Are we in a modal?
if ($oInput->get('isModal')) {
if (!isset($aData['headerOverride']) && !isset($aData['isModal'])) {
$aData['isModal'] = true;
}
if (empty($aData['headerOverride'])) {
$aData['headerOverride'] = '_components/structure/headerBlank';
}
if (empty($aData['footerOverride'])) {
$aData['footerOverride'] = '_components/structure/footerBlank';
}
}
$aHeaderViews = array_filter([
$bLoadStructure && !empty($aData['headerOverride']) ? $aData['headerOverride'] : '',
$bLoadStructure && empty($aData['headerOverride']) ? '_components/structure/header' : '',
]);
$sHeaderView = reset($aHeaderViews);
$aFooterViews = array_filter([
$bLoadStructure && !empty($aData['footerOverride']) ? $aData['footerOverride'] : '',
$bLoadStructure && empty($aData['footerOverride']) ? '_components/structure/footer' : '',
]);
$sFooterView = reset($aFooterViews);
if ($bReturnView) {
$sOut = $oView->load($sHeaderView, $aData, true);
$sOut .= static::loadInlineView($sViewFile, $aData, true);
$sOut .= $oView->load($sFooterView, $aData, true);
return $sOut;
} else {
$oView->load($sHeaderView, $aData);
static::loadInlineView($sViewFile, $aData);
$oView->load($sFooterView, $aData);
}
} | php | {
"resource": ""
} |
q258857 | Helper.loadCsv | test | public static function loadCsv($mData, $sFilename = '', $bHeaderRow = true)
{
// Determine what type of data has been supplied
if (is_array($mData) || get_class($mData) == 'CI_DB_mysqli_result') {
// If filename has been specified then set some additional headers
if (!empty($sFilename)) {
$oInput = Factory::service('Input');
$oOutput = Factory::service('Output');
// Common headers
$oOutput->set_content_type('text/csv');
$oOutput->set_header('Content-Disposition: attachment; filename="' . $sFilename . '"');
$oOutput->set_header('Expires: 0');
$oOutput->set_header("Content-Transfer-Encoding: binary");
// Handle IE, classic.
$userAgent = $oInput->server('HTTP_USER_AGENT');
if (strpos($userAgent, "MSIE") !== false) {
$oOutput->set_header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
$oOutput->set_header('Pragma: public');
} else {
$oOutput->set_header('Pragma: no-cache');
}
}
// Not using self::loadInlineView() as this may be called from many contexts
$oView = Factory::service('View');
if (is_array($mData)) {
$oView->load('admin/_components/csv/array', ['data' => $mData, 'header' => $bHeaderRow]);
} elseif (get_class($mData) == 'CI_DB_mysqli_result') {
$oView->load('admin/_components/csv/dbResult', ['data' => $mData, 'header' => $bHeaderRow]);
}
} else {
throw new NailsException('Unsupported object type passed to ' . get_class() . '::loadCSV');
}
} | php | {
"resource": ""
} |
q258858 | Helper.loadInlineView | test | public static function loadInlineView($sViewFile, $aViewData = [], $bReturnView = false)
{
$aCtrlData =& getControllerData();
$sCtrlPath = !empty($aCtrlData['currentRequest']['path']) ? $aCtrlData['currentRequest']['path'] : '';
$sCtrlName = basename($sCtrlPath, '.php');
$aCtrlPath = explode(DIRECTORY_SEPARATOR, $sCtrlPath);
$aCtrlPath = array_splice($aCtrlPath, 0, count($aCtrlPath) - 2);
$aCtrlPath[] = 'views';
$aCtrlPath[] = $sCtrlName;
$aCtrlPath[] = $sViewFile;
$sViewPath = implode(DIRECTORY_SEPARATOR, $aCtrlPath) . '.php';
$oView = Factory::service('View');
// Load the view
try {
return $oView->load($sViewPath, $aViewData, $bReturnView);
} catch (ViewNotFoundException $e) {
// If it fails, and the controller is a default admin controller then load up that view
$sClassName = $aCtrlData['currentRequest']['className'];
if (!classExtends($sClassName, 'Nails\\Admin\\Controller\\DefaultController')) {
throw new ViewNotFoundException(
$e->getMessage(),
$e->getCode()
);
}
// Step through the class hierarchy and look there
$aParents = class_parents($sClassName);
foreach ($aParents as $sParent) {
try {
if ($sParent !== 'Nails\\Admin\\Controller\\DefaultController') {
$oReflection = new \ReflectionClass('\\' . $sParent);
$sViewPath = realpath(dirname($oReflection->getFileName()) . '/../views') . '/';
$aClassBits = explode('\\', $oReflection->getName());
$sViewPath .= end($aClassBits) . '/';
} else {
$sViewPath = 'admin/DefaultController/';
$bTriedDefault = true;
};
return $oView->load(
$sViewPath . $sViewFile,
$aViewData,
$bReturnView
);
} catch (ViewNotFoundException $e) {
// Allow the loop to continue, unless we've already tried the default views
if (!empty($bTriedDefault)) {
throw $e;
}
}
}
}
} | php | {
"resource": ""
} |
q258859 | Helper.loadSearch | test | public static function loadSearch($oSearchObj, $bReturnView = true)
{
$aData = [
'searchable' => isset($oSearchObj->searchable) ? $oSearchObj->searchable : true,
'sortColumns' => isset($oSearchObj->sortColumns) ? $oSearchObj->sortColumns : [],
'sortOn' => isset($oSearchObj->sortOn) ? $oSearchObj->sortOn : null,
'sortOrder' => isset($oSearchObj->sortOrder) ? $oSearchObj->sortOrder : null,
'perPage' => isset($oSearchObj->perPage) ? $oSearchObj->perPage : 50,
'keywords' => isset($oSearchObj->keywords) ? $oSearchObj->keywords : '',
'checkboxFilter' => isset($oSearchObj->checkboxFilter) ? $oSearchObj->checkboxFilter : [],
'dropdownFilter' => isset($oSearchObj->dropdownFilter) ? $oSearchObj->dropdownFilter : [],
];
// Not using self::loadInlineView() as this may be called from many contexts
$oView = Factory::service('View');
return $oView->load('admin/_components/search', $aData, $bReturnView);
} | php | {
"resource": ""
} |
q258860 | Helper.searchFilterGetValueAtKey | test | public static function searchFilterGetValueAtKey($oFilterObj, $iKey)
{
return isset($oFilterObj->options[$iKey]->value) ? $oFilterObj->options[$iKey]->value : null;
} | php | {
"resource": ""
} |
q258861 | Helper.loadPagination | test | public static function loadPagination($oPaginationObject, $bReturnView = true)
{
$aData = [
'page' => isset($oPaginationObject->page) ? $oPaginationObject->page : null,
'perPage' => isset($oPaginationObject->perPage) ? $oPaginationObject->perPage : null,
'totalRows' => isset($oPaginationObject->totalRows) ? $oPaginationObject->totalRows : null,
];
// Not using self::loadInlineView() as this may be called from many contexts
$oView = Factory::service('View');
return $oView->load('admin/_components/pagination', $aData, $bReturnView);
} | php | {
"resource": ""
} |
q258862 | Helper.loadCellAuto | test | public static function loadCellAuto($mValue, $sCellClass = '', $sCellAdditional = '')
{
// @todo - handle more field types
if (is_bool($mValue)) {
return Helper::loadBoolCell($mValue);
} elseif (preg_match('/\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d/', $mValue)) {
return Helper::loadDateTimeCell($mValue);
} elseif (preg_match('/\d\d\d\d-\d\d-\d\d/', $mValue)) {
return Helper::loadDateCell($mValue);
} else {
return '<td class="' . $sCellClass . '">' . $mValue . $sCellAdditional . '</td>';
}
} | php | {
"resource": ""
} |
q258863 | Helper.loadUserCell | test | public static function loadUserCell($mUser)
{
if (is_numeric($mUser)) {
$oUserModel = Factory::model('User', 'nails/module-auth');
$oUser = $oUserModel->getById($mUser);
} elseif (is_string($mUser)) {
$oUserModel = Factory::model('User', 'nails/module-auth');
$oUser = $oUserModel->getByEmail($mUser);
if (empty($oUser)) {
$oUser = $oUserModel->getByUsername($mUser);
}
} else {
$oUser = $mUser;
}
$aUser = [
'id' => !empty($oUser->id) ? $oUser->id : null,
'profile_img' => !empty($oUser->profile_img) ? $oUser->profile_img : null,
'gender' => !empty($oUser->gender) ? $oUser->gender : null,
'first_name' => !empty($oUser->first_name) ? $oUser->first_name : null,
'last_name' => !empty($oUser->last_name) ? $oUser->last_name : null,
'email' => !empty($oUser->email) ? $oUser->email : null,
];
$oView = Factory::service('View');
return $oView->load('admin/_components/table-cell-user', $aUser, true);
} | php | {
"resource": ""
} |
q258864 | Helper.loadDateCell | test | public static function loadDateCell($sDate, $sNoData = '—')
{
$aData = [
'date' => $sDate,
'noData' => $sNoData,
];
$oView = Factory::service('View');
return $oView->load('admin/_components/table-cell-date', $aData, true);
} | php | {
"resource": ""
} |
q258865 | Helper.loadDateTimeCell | test | public static function loadDateTimeCell($sDateTime, $sNoData = '—')
{
$aData = [
'dateTime' => $sDateTime,
'noData' => $sNoData,
];
$oView = Factory::service('View');
return $oView->load('admin/_components/table-cell-datetime', $aData, true);
} | php | {
"resource": ""
} |
q258866 | Helper.loadBoolCell | test | public static function loadBoolCell($value, $sDateTime = null)
{
$aData = [
'value' => $value,
'dateTime' => $sDateTime,
];
$oView = Factory::service('View');
return $oView->load('admin/_components/table-cell-boolean', $aData, true);
} | php | {
"resource": ""
} |
q258867 | Helper.loadSettingsComponentTable | test | public static function loadSettingsComponentTable($sComponentService, $sProvider, $sComponentType = 'component')
{
$oModel = Factory::service($sComponentService, $sProvider);
$sKey = $oModel->getSettingKey();
$aComponents = $oModel->getAll();
$aEnabled = (array) $oModel->getEnabledSlug();
$bEnableMultiple = $oModel->isMultiple();
$aData = [
'key' => $sKey,
'components' => $aComponents,
'enabled' => $aEnabled,
'canSelectMultiple' => $bEnableMultiple,
'componentType' => $sComponentType,
];
$oView = Factory::service('View');
return $oView->load('admin/_components/settings-component-table', $aData, true);
} | php | {
"resource": ""
} |
q258868 | Helper.addHeaderButton | test | public static function addHeaderButton(
$sUrl,
$sLabel,
$sContext = null,
$sConfirmTitle = null,
$sConfirmBody = null
) {
$sContext = empty($sContext) ? 'primary' : $sContext;
self::$aHeaderButtons[] = [
'url' => $sUrl,
'label' => $sLabel,
'context' => $sContext,
'confirmTitle' => $sConfirmTitle,
'confirmBody' => $sConfirmBody,
];
} | php | {
"resource": ""
} |
q258869 | Helper.dynamicTable | test | public static function dynamicTable($sKey, array $aFields, array $aData = [])
{
return Factory::service('View')
->load(
'admin/_components/dynamic-table',
[
'sKey' => $sKey,
'aFields' => $aFields,
'aData' => $aData,
],
true
);
} | php | {
"resource": ""
} |
q258870 | Nav.postSave | test | public function postSave()
{
$oInput = Factory::service('Input');
$aPrefRaw = array_filter((array) $oInput->post('preferences'));
$oPref = new \stdClass();
foreach ($aPrefRaw as $sModule => $aOptions) {
$oPref->{$sModule} = new \stdClass();
$oPref->{$sModule}->open = stringToBoolean($aOptions['open']);
}
$oAdminModel = Factory::model('Admin', 'nails/module-admin');
$oAdminModel->setAdminData('nav_state', $oPref);
return Factory::factory('ApiResponse', 'nails/module-api');
} | php | {
"resource": ""
} |
q258871 | Create.execute | test | protected function execute(InputInterface $oInput, OutputInterface $oOutput): int
{
parent::execute($oInput, $oOutput);
// --------------------------------------------------------------------------
try {
// Ensure the paths exist
$this->createPath(self::EXPORT_PATH);
// Create the DataExport source
$this->createSource();
} catch (\Exception $e) {
return $this->abort(
self::EXIT_CODE_FAILURE,
[$e->getMessage()]
);
}
// --------------------------------------------------------------------------
// Cleaning up
$oOutput->writeln('');
$oOutput->writeln('<comment>Cleaning up...</comment>');
// --------------------------------------------------------------------------
// And we're done
$oOutput->writeln('');
$oOutput->writeln('Complete!');
return self::EXIT_CODE_SUCCESS;
} | php | {
"resource": ""
} |
q258872 | Create.createSource | test | private function createSource(): void
{
$aFields = $this->getArguments();
$aFields['CLASS_NAME'] = str_replace(' ', '', ucwords(preg_replace('/[^a-zA-Z ]/', '', $aFields['NAME'])));
$aFields['FILENAME'] = strtolower(url_title($aFields['NAME']));
try {
$this->oOutput->write('Creating DataExport Source <comment>' . $aFields['CLASS_NAME'] . '</comment>... ');
// Check for existing DataExport source
$sPath = static::EXPORT_PATH . $aFields['CLASS_NAME'] . '.php';
if (file_exists($sPath)) {
throw new ControllerExistsException(
'DataExport Source "' . $aFields['CLASS_NAME'] . '" exists already at path "' . $sPath . '"'
);
}
$this->createFile($sPath, $this->getResource('template/data_export_source.php', $aFields));
$aCreated[] = $sPath;
$this->oOutput->writeln('<info>done!</info>');
} catch (\Exception $e) {
$this->oOutput->writeln('<error>failed!</error>');
throw new NailsException($e->getMessage());
}
} | php | {
"resource": ""
} |
q258873 | Csv.formatRow | test | protected function formatRow($oRow)
{
$aItems = array_map(
function ($sItem) {
return str_replace('"', '""', trim($sItem));
},
(array) $oRow
);
return '"' . implode('","', $aItems) . '"' . "\n";
} | php | {
"resource": ""
} |
q258874 | Nav.addAction | test | public function addAction($label, $url = 'index', $alerts = [], $order = null)
{
$this->actions[$url] = new \stdClass();
$this->actions[$url]->label = $label;
$this->actions[$url]->alerts = !is_array($alerts) ? [$alerts] : $alerts;
if (is_null($order)) {
$this->actions[$url]->order = count($this->actions);
} else {
$this->actions[$url]->order = $order;
}
return $this;
} | php | {
"resource": ""
} |
q258875 | Admin.setAdminData | test | public function setAdminData($key, $value, $userId = null)
{
return $this->setUnsetAdminData($key, $value, $userId, true);
} | php | {
"resource": ""
} |
q258876 | Admin.unsetAdminData | test | public function unsetAdminData($key, $userId = null)
{
return $this->setUnsetAdminData($key, null, $userId, false);
} | php | {
"resource": ""
} |
q258877 | Admin.setUnsetAdminData | test | protected function setUnsetAdminData($key, $value, $userId, $set)
{
// Get the user ID
$userId = $this->adminDataGetUserId($userId);
// Get the existing data for this user
$existing = $this->getAdminData(null, $userId);
if ($set) {
// Set the new key
if (in_array($key, $this->aJsonFields)) {
$value = json_encode($value);
}
$existing[$key] = $value;
} else {
// Unset the existing key
$existing[$key] = null;
}
// Save to the DB
$bResult = $this->oUserMetaService->update(
NAILS_DB_PREFIX . 'user_meta_admin',
$userId,
$existing
);
} | php | {
"resource": ""
} |
q258878 | Admin.clearAdminData | test | public function clearAdminData($userId)
{
// Get the user ID
$userId = $this->adminDataGetUserId($userId);
$bResult = $this->oUserMetaService->update(
NAILS_DB_PREFIX . 'user_meta_admin',
$userId,
[
'nav_state' => null,
]
);
if ($bResult) {
$this->unsetCache('admin-data-' . $userId);
}
return $bResult;
} | php | {
"resource": ""
} |
q258879 | SiteLog.getAll | test | public function getAll($iPage = null, $iPerPage = null, array $aData = [], $bIncludeDeleted = false): array
{
$dirMap = directory_map($this->logPath, 0);
$logFiles = [];
$filenameRegex = '/^log\-(\d{4}\-\d{2}\-\d{2})\.php$/';
foreach ($dirMap as $logFile) {
if (preg_match($filenameRegex, $logFile)) {
$logFiles[] = $logFile;
}
}
arsort($logFiles);
$logFiles = array_values($logFiles);
$out = [];
foreach ($logFiles as $file) {
$temp = new \stdClass();
$temp->date = preg_replace($filenameRegex, '$1', $file);
$temp->file = $file;
$temp->lines = $this->countLines($this->logPath . $file);
$out[] = $temp;
}
return $out;
} | php | {
"resource": ""
} |
q258880 | Ckeditor.findConfig | test | protected function findConfig($sFile)
{
// @todo (Pablo - 2018-07-13) - The paths and URLs should probably be determined by the Asset service
if (file_exists(NAILS_APP_PATH . 'assets/build/js/' . $sFile)) {
return site_url('assets/build/js/' . $sFile);
} elseif (file_exists(NAILS_APP_PATH . 'assets/js/' . $sFile)) {
return site_url('assets/js/' . $sFile);
} else {
return NAILS_ASSETS_URL . 'js/' . $sFile;
}
} | php | {
"resource": ""
} |
q258881 | Base.loadJs | test | protected function loadJs()
{
\Nails\Common\Controller\Base::setNailsJs();
$oAsset = Factory::service('Asset');
// Module assets
$oAsset->load('admin.min.js', 'nails/module-admin');
$oAsset->load('nails.default.min.js', 'NAILS');
$oAsset->load('nails.admin.js', 'NAILS');
$oAsset->load('nails.forms.min.js', 'NAILS');
$oAsset->load('nails.api.min.js', 'NAILS');
// Component assets
foreach (Components::available() as $oComponent) {
if (!empty($oComponent->data->{'nails/module-admin'}->autoload)) {
$oAutoLoad = $oComponent->data->{'nails/module-admin'}->autoload;
if (!empty($oAutoLoad->assets->js)) {
foreach ($oAutoLoad->assets->js as $mAsset) {
if (is_string($mAsset)) {
$sAsset = $mAsset;
$sLocation = $oComponent->slug;
} else {
$sAsset = !empty($mAsset[0]) ? $mAsset[0] : null;
$sLocation = !empty($mAsset[1]) ? $mAsset[1] : null;
}
$oAsset->load($sAsset, $sLocation, 'JS');
}
}
// JS Inline
if (!empty($oAutoLoad->assets->jsInline)) {
foreach ($oAutoLoad->assets->jsInline as $sAsset) {
$oAsset->inline($sAsset, 'JS');
}
}
}
}
// Global JS
$sAdminJsPath = defined('APP_ADMIN_JS_PATH') ? APP_ADMIN_JS_PATH : NAILS_APP_PATH . 'assets/build/js/admin.min.js';
$sAdminJsUrl = defined('APP_ADMIN_JS_URL') ? APP_ADMIN_JS_URL : 'admin.min.js';
if (file_exists($sAdminJsPath)) {
$oAsset->load($sAdminJsUrl);
}
// Inline assets
$sJs = 'var _nails,_nails_admin,_nails_api, _nails_forms;';
$sJs .= 'if (typeof(NAILS_JS) === \'function\'){';
$sJs .= '_nails = new NAILS_JS();';
$sJs .= '}';
$sJs .= 'if (typeof(NAILS_API) === \'function\'){';
$sJs .= '_nails_api = new NAILS_API();';
$sJs .= '}';
$sJs .= 'if (typeof(NAILS_Admin) === \'function\'){';
$sJs .= '_nails_admin = new NAILS_Admin();';
$sJs .= '}';
$sJs .= 'if (typeof(NAILS_Forms) === \'function\'){';
$sJs .= '_nails_forms = new NAILS_Forms();';
$sJs .= '}';
$oAsset->inline($sJs, 'JS');
} | php | {
"resource": ""
} |
q258882 | Base.loadCss | test | protected function loadCss()
{
$oAsset = Factory::service('Asset');
// Module assets
$oAsset->load('nails.admin.css', 'NAILS');
$oAsset->load('admin.css', 'nails/module-admin');
// Component assets
foreach (Components::available() as $oComponent) {
if (!empty($oComponent->data->{'nails/module-admin'}->autoload)) {
$oAutoLoad = $oComponent->data->{'nails/module-admin'}->autoload;
if (!empty($oAutoLoad->assets->css)) {
foreach ($oAutoLoad->assets->css as $mAsset) {
if (is_string($mAsset)) {
$sAsset = $mAsset;
$sLocation = $oComponent->slug;
} else {
$sAsset = !empty($mAsset[0]) ? $mAsset[0] : null;
$sLocation = !empty($mAsset[1]) ? $mAsset[1] : null;
}
$oAsset->load($sAsset, $sLocation, 'CSS');
}
}
// CSS Inline
if (!empty($oAutoLoad->assets->cssInline)) {
foreach ($oAutoLoad->assets->cssInline as $sAsset) {
$oAsset->inline($sAsset, 'CSS');
}
}
}
}
// Global CSS
$sAdminCssPath = defined('APP_ADMIN_CSS_PATH') ? APP_ADMIN_CSS_PATH : NAILS_APP_PATH . 'assets/build/css/admin.min.css';
$sAdminCssUrl = defined('APP_ADMIN_CSS_URL') ? APP_ADMIN_CSS_URL : 'admin.min.css';
if (file_exists($sAdminCssPath)) {
$oAsset->load($sAdminCssUrl);
}
} | php | {
"resource": ""
} |
q258883 | Base.loadLibraries | test | protected function loadLibraries()
{
$oAsset = Factory::service('Asset');
// jQuery
$oAsset->load('jquery/dist/jquery.min.js', 'NAILS-BOWER');
// Fancybox
$oAsset->load('fancybox/source/jquery.fancybox.pack.js', 'NAILS-BOWER');
$oAsset->load('fancybox/source/jquery.fancybox.css', 'NAILS-BOWER');
// jQuery Toggles
$oAsset->load('jquery-toggles/toggles.min.js', 'NAILS-BOWER');
$oAsset->load('jquery-toggles/css/toggles.css', 'NAILS-BOWER');
$oAsset->load('jquery-toggles/css/themes/toggles-modern.css', 'NAILS-BOWER');
// Tipsy
$oAsset->load('tipsy/src/javascripts/jquery.tipsy.js', 'NAILS-BOWER');
$oAsset->load('tipsy/src/stylesheets/tipsy.css', 'NAILS-BOWER');
// scrollTo
$oAsset->load('jquery.scrollTo/jquery.scrollTo.min.js', 'NAILS-BOWER');
// jQuery Cookies
$oAsset->load('jquery-cookie/jquery.cookie.js', 'NAILS-BOWER');
// Retina.js
$oAsset->load('retina.js/dist/retina.min.js', 'NAILS-BOWER');
// Bootstrap
$oAsset->load('bootstrap/js/dropdown.js', 'NAILS-BOWER');
// Fontawesome
$oAsset->load('fontawesome/css/font-awesome.min.css', 'NAILS-BOWER');
// Asset libraries
$oAsset->library('jqueryui');
$oAsset->library('select2');
$oAsset->library('ckeditor');
$oAsset->library('uploadify');
$oAsset->library('knockout');
$oAsset->library('moment');
$oAsset->library('mustache');
} | php | {
"resource": ""
} |
q258884 | Base.autoLoad | test | protected function autoLoad()
{
foreach (Components::available() as $oComponent) {
if (!empty($oComponent->data->{'nails/module-admin'}->autoload)) {
$oAutoLoad = $oComponent->data->{'nails/module-admin'}->autoload;
// Libraries
if (!empty($oAutoLoad->services)) {
foreach ($oAutoLoad->services as $sService) {
Factory::service($sService, $oComponent->slug);
}
}
// Models
if (!empty($oAutoLoad->models)) {
foreach ($oAutoLoad->models as $sModel) {
Factory::model($sModel, $oComponent->slug);
}
}
// Helpers
if (!empty($oAutoLoad->helpers)) {
foreach ($oAutoLoad->helpers as $sHelper) {
Factory::helper($sHelper, $oComponent->slug);
}
}
}
}
} | php | {
"resource": ""
} |
q258885 | Base.backwardsCompatibility | test | public static function backwardsCompatibility(&$oBindTo)
{
// @todo (Pablo - 2017-06-08) - Try and remove these dependencies
$oBindTo->load =& get_instance()->load;
$oBindTo->lang =& get_instance()->lang;
} | php | {
"resource": ""
} |
q258886 | Settings.site | test | public function site()
{
if (!userHasPermission('admin:admin:settings:site:.*')) {
unauthorised();
}
// --------------------------------------------------------------------------
$oInput = Factory::service('Input');
if ($oInput->post()) {
$aSettings = [];
if (userHasPermission('admin:admin:settings:site:customjscss')) {
$aSettings['site_custom_js'] = $oInput->post('site_custom_js');
$aSettings['site_custom_css'] = $oInput->post('site_custom_css');
$aSettings['site_custom_markup'] = $oInput->post('site_custom_markup');
}
if (userHasPermission('admin:admin:settings:site:analytics')) {
$aSettings['google_analytics_account'] = $oInput->post('google_analytics_account');
}
if (userHasPermission('admin:admin:settings:site:maintenance')) {
$sRawIPs = $oInput->post('maintenance_mode_whitelist');
$aSettings['maintenance_mode_enabled'] = (bool) $oInput->post('maintenance_mode_enabled');
$aSettings['maintenance_mode_whitelist'] = $this->prepareWhitelist($sRawIPs);
$aSettings['maintenance_mode_title'] = $oInput->post('maintenance_mode_title');
$aSettings['maintenance_mode_body'] = $oInput->post('maintenance_mode_body');
}
if (!empty($aSettings)) {
$oAppSettingService = Factory::service('AppSetting');
if ($oAppSettingService->set($aSettings, 'site')) {
$this->data['success'] = 'Site settings have been saved.';
} else {
$this->data['error'] = 'There was a problem saving site settings.';
}
} else {
$this->data['message'] = 'No settings to save.';
}
}
// --------------------------------------------------------------------------
// Get data
$this->data['settings'] = appSetting(null, 'app', true);
// --------------------------------------------------------------------------
// Set page title
$this->data['page']->title = 'Settings › Site';
// --------------------------------------------------------------------------
// Load assets
$oAsset = Factory::service('Asset');
$oAsset->load('nails.admin.settings.min.js', 'NAILS');
$oAsset->load('nails.admin.admin.settings.min.js', 'NAILS');
// --------------------------------------------------------------------------
// Load views
Helper::loadView('site');
} | php | {
"resource": ""
} |
q258887 | Settings.prepareWhitelist | test | protected function prepareWhitelist($sInput)
{
$sWhitelistRaw = $sInput;
$sWhitelistRaw = str_replace("\n\r", "\n", $sWhitelistRaw);
$aWhitelistRaw = explode("\n", $sWhitelistRaw);
$aWhitelist = [];
foreach ($aWhitelistRaw as $sLine) {
$aWhitelist = array_merge(explode(',', $sLine), $aWhitelist);
}
$aWhitelist = array_unique($aWhitelist);
$aWhitelist = array_filter($aWhitelist);
$aWhitelist = array_map('trim', $aWhitelist);
$aWhitelist = array_values($aWhitelist);
return $aWhitelist;
} | php | {
"resource": ""
} |
q258888 | Settings.extractFieldsets | test | protected function extractFieldsets($sComponentSlug, $aSettings, $fieldSetIndex = 0)
{
foreach ($aSettings as $oSetting) {
// If the object contains a `fields` property then consider this a fieldset and inception
if (isset($oSetting->fields)) {
$fieldSetIndex++;
if (!isset($this->data['fieldsets'][$fieldSetIndex])) {
$this->data['fieldsets'][$fieldSetIndex] = [
'legend' => $oSetting->legend,
'fields' => [],
];
}
$this->extractFieldsets($sComponentSlug, $oSetting->fields, $fieldSetIndex);
} else {
$sValue = appSetting($oSetting->key, $sComponentSlug);
if (!is_null($sValue)) {
$oSetting->default = $sValue;
}
if (!isset($this->data['fieldsets'][$fieldSetIndex])) {
$this->data['fieldsets'][$fieldSetIndex] = [
'legend' => '',
'fields' => [],
];
}
$this->data['fieldsets'][$fieldSetIndex]['fields'][] = $oSetting;
$this->aFields[] = $oSetting;
}
}
} | php | {
"resource": ""
} |
q258889 | DataExport.getSourceBySlug | test | public function getSourceBySlug($sSlug)
{
foreach ($this->aSources as $oSource) {
if ($sSlug === $oSource->slug) {
return $oSource;
}
}
return null;
} | php | {
"resource": ""
} |
q258890 | DataExport.getFormatBySlug | test | public function getFormatBySlug($sSlug)
{
foreach ($this->aFormats as $oFormat) {
if ($sSlug === $oFormat->slug) {
return $oFormat;
}
}
return null;
} | php | {
"resource": ""
} |
q258891 | DataExport.export | test | public function export($sSourceSlug, $sFormatSlug, $aOptions = [])
{
$oSource = $this->getSourceBySlug($sSourceSlug);
if (empty($oSource)) {
throw new NailsException('Invalid data source "' . $sSourceSlug . '"');
}
$oFormat = $this->getFormatBySlug($sFormatSlug);
if (empty($oFormat)) {
throw new NailsException('Invalid data format "' . $sFormatSlug . '"');
}
$oSourceResponse = $oSource->instance->execute($aOptions);
if (!is_array($oSourceResponse)) {
$aSourceResponses = [$oSourceResponse];
} else {
$aSourceResponses = $oSourceResponse;
}
// Create temporary working directory
$sTempDir = CACHE_PATH . 'data-export-' . md5(microtime(true)) . mt_rand() . '/';
mkdir($sTempDir);
// Process each file
$aFiles = [];
try {
foreach ($aSourceResponses as $oSourceResponse) {
if (!($oSourceResponse instanceof SourceResponse)) {
throw new NailsException('Source must return an instance of SourceResponse');
}
// Create a new file
$sFile = $sTempDir . $oSourceResponse->getFilename() . '.' . $oFormat->instance->getFileExtension();
$aFiles[] = $sFile;
$rFile = fopen($sFile, 'w+');
// Write to the file
$oSourceResponse->reset();
$oFormat->instance->execute($oSourceResponse, $rFile);
// Close the file
fclose($rFile);
}
// Compress if > 1
if (count($aFiles) > 1) {
$sArchiveFile = $sTempDir . 'export.zip';
$oZip = Factory::service('Zip');
foreach ($aFiles as $sFile) {
$oZip->read_file($sFile);
}
$oZip->archive($sArchiveFile);
$aFiles[] = $sArchiveFile;
}
$sFile = end($aFiles);
// Save to CDN
$oCdn = Factory::service('Cdn', 'nails/module-cdn');
$oObject = $oCdn->objectCreate($sFile, 'data-export');
if (empty($oObject)) {
throw new NailsException('Failed to upload exported file. ' . $oCdn->lastError());
}
} finally {
// Tidy up
foreach ($aFiles as $sFile) {
if (file_exists($sFile)) {
unlink($sFile);
}
}
rmdir($sTempDir);
}
return $oObject->id;
} | php | {
"resource": ""
} |
q258892 | Export.executionFailed | test | protected function executionFailed(
\Exception $oException,
\stdClass $oRequest,
\Nails\Admin\Model\Export $oModel,
\Nails\Admin\Factory\Email\DataExport $oEmail
) {
$this->writeLog('Exception: ' . $oException->getMessage());
$oModel->setBatchStatus($oRequest->ids, $oModel::STATUS_FAILED, $oException->getMessage());
$oEmail
->data([
'status' => $oModel::STATUS_FAILED,
'error' => $oException->getMessage(),
]);
foreach ($oRequest->recipients as $iRecipient) {
$oEmail->to($iRecipient)->send();
}
} | php | {
"resource": ""
} |
q258893 | ChangeLog.add | test | public function add(
$sVerb,
$sArticle,
$sItem,
$iItemId,
$sTitle,
$sUrl = null,
$sField = null,
$mOldValue = null,
$mNewValue = null,
$bStrict = true
) {
/**
* if the old_value and the new_value are the same then why are you logging
* a change!? Lazy [read: efficient] dev.
*/
if (!is_null($sField)) {
if (!is_string($mNewValue)) {
$mNewValue = print_r($mNewValue, true);
}
if (!is_string($mOldValue)) {
$mOldValue = print_r($mOldValue, true);
}
$mNewValue = trim($mNewValue);
$mOldValue = trim($mOldValue);
if ($bStrict && $mNewValue === $mOldValue) {
return false;
} elseif ($mNewValue == $mOldValue) {
return false;
}
}
// --------------------------------------------------------------------------
/**
* Define the key for this change; keys should be common across identical
* items so we can group changes of the same item together.
*/
$key = md5(activeUser('id') . '|' . $sVerb . '|' . $sArticle . '|' . $sItem . '|' . $iItemId . '|' . $sTitle . '|' . $sUrl);
if (empty($this->aChanges[$key])) {
$this->aChanges[$key] = [
'user_id' => activeUser('id') ? activeUser('id') : null,
'verb' => $sVerb,
'article' => $sArticle,
'item' => $sItem,
'item_id' => $iItemId,
'title' => $sTitle,
'url' => $sUrl,
'changes' => [],
];
}
// --------------------------------------------------------------------------
/**
* Generate a subkey, so that multiple calls to the same field overwrite
* each other
*/
if ($sField) {
$this->aChanges[$key]['changes'][md5($sField)] = (object) [
'field' => $sField,
'old_value' => $mOldValue,
'new_value' => $mNewValue,
];
}
// --------------------------------------------------------------------------
// If we're not saving in batches then save now
if (!$this->bBatchSave) {
$this->save();
}
return true;
} | php | {
"resource": ""
} |
q258894 | ChangeLog.save | test | public function save()
{
// Process all the items and save to the DB, then clean up
if ($this->aChanges) {
$this->aChanges = array_values($this->aChanges);
$oDate = Factory::factory('DateTime');
for ($i = 0; $i < count($this->aChanges); $i++) {
$this->aChanges[$i]['changes'] = array_values($this->aChanges[$i]['changes']);
$this->aChanges[$i]['changes'] = json_encode($this->aChanges[$i]['changes']);
$this->aChanges[$i]['created'] = $oDate->format('Y-m-d H:i:s');
$this->aChanges[$i]['created_by'] = activeUser('id');
$this->aChanges[$i]['modified'] = $oDate->format('Y-m-d H:i:s');
$this->aChanges[$i]['modified_by'] = activeUser('id');
}
$oDb = Factory::service('Database');
$oDb->insert_batch($this->getTableName(), $this->aChanges);
}
$this->clear();
} | php | {
"resource": ""
} |
q258895 | ChangeLog.getAll | test | public function getAll($iPage = null, $iPerPage = null, array $aData = [], $bIncludeDeleted = false): array
{
// If the first value is an array then treat as if called with getAll(null, null, $aData);
// @todo (Pablo - 2017-06-29) - Refactor how this join works (use expandable field)
if (is_array($iPage)) {
$aData = $iPage;
$iPage = null;
}
if (empty($aData['select'])) {
$aData['select'] = [
$this->getTableAlias() . '.*',
'u.first_name',
'u.last_name',
'u.gender',
'u.profile_img',
'ue.email',
];
}
return parent::getAll($iPage, $iPerPage, $aData, $bIncludeDeleted);
} | php | {
"resource": ""
} |
q258896 | ChangeLog.getCountCommon | test | protected function getCountCommon(array $aData = [])
{
// Join user tables
$oDb = Factory::service('Database');
$oDb->join(NAILS_DB_PREFIX . 'user u', 'u.id = ' . $this->getTableAlias() . '.user_id', 'LEFT');
$oDb->join(NAILS_DB_PREFIX . 'user_email ue', 'ue.user_id = ' . $this->getTableAlias() . '.user_id AND ue.is_primary = 1', 'LEFT');
// Searching?
if (!empty($aData['keywords'])) {
if (empty($aData['or_like'])) {
$aData['or_like'] = [];
}
$toSlug = strtolower(str_replace(' ', '_', $aData['keywords']));
$aData['or_like'][] = [
'column' => $this->getTableAlias() . '.type',
'value' => $toSlug,
];
$aData['or_like'][] = [
'column' => 'ue.email',
'value' => $aData['keywords'],
];
}
parent::getCountCommon($aData);
} | php | {
"resource": ""
} |
q258897 | ChangeLog.formatObject | test | protected function formatObject(
&$oObj,
array $aData = [],
array $aIntegers = [],
array $aBools = [],
array $aFloats = []
) {
parent::formatObject($oObj, $aData, $aIntegers, $aBools, $aFloats);
if (!empty($oObj->item_id)) {
$oObj->item_id = (int) $oObj->item_id;
}
$oObj->changes = @json_decode($oObj->changes);
$oObj->user = (object) [
'id' => $oObj->user_id,
'first_name' => isset($oObj->first_name) ? $oObj->first_name : '',
'last_name' => isset($oObj->last_name) ? $oObj->last_name : '',
'gender' => isset($oObj->gender) ? $oObj->gender : '',
'profile_img' => isset($oObj->profile_img) ? $oObj->profile_img : '',
'email' => isset($oObj->email) ? $oObj->email : '',
];
unset($oObj->user_id);
unset($oObj->first_name);
unset($oObj->last_name);
unset($oObj->gender);
unset($oObj->profile_img);
unset($oObj->email);
} | php | {
"resource": ""
} |
q258898 | Note.getRemap | test | public function getRemap($sMethod, array $aData = [])
{
list($sModel, $iItemId) = $this->getModelClassAndId();
$aData['where'] = [
['model', $sModel],
['item_id', $iItemId],
];
return parent::getRemap($sMethod, $aData);
} | php | {
"resource": ""
} |
q258899 | Note.validateUserInput | test | protected function validateUserInput($aData, $oItem = null)
{
$aData = parent::validateUserInput($aData, $oItem);
list($sModel) = $this->getModelClassAndId();
$aData['model'] = $sModel;
return $aData;
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.