code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
protected function generateSlug(string $sLabel, int $iIgnoreId = null) { $iCounter = 0; $oDb = Factory::service('Database'); $sSlug = Transliterator::transliterate($sLabel); do { if ($iCounter) { $sSlugTest = $sSlug . '-' . $iCounter; } else { $sSlugTest = $sSlug; } if ($iIgnoreId) { $oDb->where($this->tableIdColumn . ' !=', $iIgnoreId); } $oDb->where($this->tableSlugColumn, $sSlugTest); $iCounter++; } while ($oDb->count_all_results($this->getTableName())); return $sSlugTest; }
Generates a unique slug @param string $sLabel The label from which to generate a slug @param int $iIgnoreId The ID of an item to ignore @return string @throws ModelException
protected function generateToken($sMask = null, $sTable = null, $sColumn = null) { if (is_null($sMask)) { $sMask = $this->sTokenMask; } if (is_null($sTable)) { $sTable = $this->getTableName(); } if (is_null($sColumn)) { if (!$this->tableTokenColumn) { throw new ModelException(static::class . '::generateToken() Token variable not set', 1); } $sColumn = $this->tableTokenColumn; } $oDb = Factory::service('Database'); do { $sToken = generateToken($sMask); $oDb->where($sColumn, $sToken); } while ($oDb->count_all_results($sTable)); return $sToken; }
Generates a unique token for a record @param string|null $sMask The token mask, defaults to $this->sTokenMask @param string|null $sTable The table to use defaults to $this->table @param string|null $sColumn The column to use, defaults to $this->tableTokenColumn @return string @throws ModelException
public function getTableName($bIncludeAlias = false) { // @todo (Pablo - 2019-03-14) - Phase out support for $this->table if (empty($this->table) && empty(static::TABLE)) { throw new ModelException(static::class . '::TABLE not set', 1); } $sTable = static::TABLE ?? $this->table; return $bIncludeAlias ? trim($sTable . ' as `' . $this->getTableAlias() . '`') : $sTable; }
Returns protected property $table @param bool $bIncludeAlias Whether to include the table's alias @throws ModelException @return string
public function getTableAlias($bIncludeSeparator = false) { // @todo (Pablo - 2019-04-15) - Deprecate $this->>tableAlias $sOut = static::TABLE_ALIAS ?? $this->tableAlias ?? ''; if (empty($sOut)) { // work it out $sTable = strtolower($this->getTableName()); $sTable = preg_replace('/[^a-z_]/', '', $sTable); $sTable = preg_replace('/_/', ' ', $sTable); $aTable = explode(' ', $sTable); foreach ($aTable as $sWord) { $sOut .= $sWord[0]; } } if (!empty($sOut) && $bIncludeSeparator) { $sOut .= '.'; } return $sOut; }
Returns protected property $tableAlias @param bool $bIncludeSeparator Whether to include the prefix separator @return string
protected function autoSaveExpandableFieldsExtract(array &$aData) { $aFields = []; $aOut = []; $aExpandableFields = $this->getExpandableFields(); foreach ($aExpandableFields as $oField) { if ($oField->auto_save) { $aFields[$oField->trigger] = $oField; } } foreach ($aData as $sKey => $mValue) { if (array_key_exists($sKey, $aFields)) { $aOut[$sKey] = $aFields[$sKey]; $aOut[$sKey]->data = $mValue; unset($aData[$sKey]); } } return $aOut; }
Extracts any autosaveable expandable fields and unsets them from the main array @param array $aData The data passed to create() or update() @return array
protected function autoSaveExpandableFieldsSave($iId, array $aExpandableFields) { foreach ($aExpandableFields as $oField) { $aData = array_filter((array) $oField->data); $this->saveAssociatedItems( $iId, $aData, $oField->id_column, $oField->model, $oField->provider ); } }
Saves extracted expandable fields @param int $iId @param array $aExpandableFields
public function getColumn($sColumn, $sDefault = null) { $sColumn = ucfirst(trim($sColumn)); if (property_exists($this, 'table' . $sColumn . 'Column')) { return $this->{'table' . $sColumn . 'Column'}; } return $sDefault; }
Returns the column name for specific columns of interest @param string $sColumn The column to query @param string|null $sDefault The default value if not defined @return string
protected function describeFieldsPrepareLabel($sLabel) { $aPatterns = [ // Common words '/\bid\b/i' => 'ID', '/\burl\b/i' => 'URL', '/\bhtml\b/i' => 'HTML', // Common file extensions '/\bpdf\b/i' => 'PDF', ]; $sLabel = ucwords(preg_replace('/[\-_]/', ' ', $sLabel)); $sLabel = preg_replace(array_keys($aPatterns), array_values($aPatterns), $sLabel); return $sLabel; }
Generates a human friendly label from the field's key @param string $sLabel The label to format @return string
protected function describeFieldsGuessValidation(&$oField, $sType) { preg_match('/^(.*?)(\((.+?)\)(.*))?$/', $sType, $aMatches); $sType = ArrayHelper::getFromArray(1, $aMatches, 'text'); $iLength = ArrayHelper::getFromArray(3, $aMatches); $sExtra = trim(strtolower(ArrayHelper::getFromArray(4, $aMatches))); switch ($sType) { /** * Numeric */ case 'int': if ($sExtra === 'unsigned') { $oField->validation[] = 'greater_than[-1]'; } else { $oField->validation[] = 'integer'; } break; case 'tinyint': if ($oField->type === 'boolean') { $oField->validation[] = 'is_bool'; } else { $oField->validation[] = 'integer'; } break; /** * String */ case 'varchar': if ($iLength) { $oField->validation[] = 'max_length[' . $iLength . ']'; } break; /** * Date and time */ case 'date': $oField->validation[] = 'valid_date'; break; case 'datetime': $oField->validation[] = 'valid_datetime'; break; /** * ENUM */ case 'enum': $oField->validation[] = 'in_list[' . implode(',', array_keys($oField->options)) . ']'; break; /** * Default to basic string */ default: if ($iLength) { $oField->validation[] = 'max_length[' . $iLength . ']'; } break; } }
Guesses the field's validation rules based on it's type @param \stdClass $oField The field object @param string $sType The database type
protected function triggerEvent($sEvent, array $aData) { if ($sEvent) { Factory::service('Event') ->trigger( $sEvent, static::getEventNamespace(), $aData ); } }
Triggers an event @param string $sEvent The event to trigger @param array $aData Data to pass to listeners @throws ModelException
public static function backwardsCompatibility(&$oBindTo) { // @todo (Pablo - 2017-06-07) - Remove these $oBindTo->db = Factory::service('Database'); $oBindTo->encrypt = Factory::service('Encrypt'); }
Various older modules expect to be able to access a few services/models via magic methods. These will be deprecated soon. @param object $oBindTo The class to bind to
private function getSections(Options $options): array { $allSections = []; /** @var \eZ\Publish\API\Repository\Values\Content\Section[] $sections */ $sections = $this->sectionService->loadSections(); $configuredSections = $options['sections']; foreach ($sections as $section) { if (count($configuredSections) > 0 && !in_array($section->identifier, $configuredSections, true)) { continue; } $allSections[$section->name] = $section->identifier; } return $allSections; }
Returns the allowed sections from eZ Platform.
public function addRaw($aAttr) { if (!empty($aAttr)) { $sHash = md5(json_encode($aAttr)); $this->aEntries[$sHash] = $aAttr; } return $this; }
Adds a meta tag, setting all the element keys as tag attributes. @param array $aAttr An array of attributes which make up the entry
public function removeRaw($aAttr) { if (!empty($aAttr)) { $sHash = md5(json_encode($aAttr)); unset($this->aEntries[$sHash]); } return $this; }
Adds a meta tag @param array $aAttr An array of attributes which make up the entry
public function add($sName, $sContent, $sTag = '') { $aMeta = [ 'name' => $sName, 'content' => $sContent, 'tag' => $sTag, ]; return $this->addRaw($aMeta); }
Adds a basic meta tag, setting the name and the content attributes @param string $sName The element's name attribute @param string $sContent The element's content attribute @param string $sTag The elements's type
public function remove($sName, $sContent, $sTag = '') { $aMeta = [ 'name' => $sName, 'content' => $sContent, 'tag' => $sTag, ]; return $this->removeRaw($aMeta); }
Removes a basic meta tag @param string $sName The elements's name attribute @param string $sContent The elements's content attribute @param string $sTag The elements's type
public function removeByPropertyPattern($aProperties) { foreach ($this->aEntries as $sHash => $aEntry) { foreach ($aProperties as $aPatterns) { foreach ($aPatterns as $sProperty => $sPattern) { if (!array_key_exists($sProperty, $aEntry)) { continue 2; } elseif (!preg_match('/^' . $sPattern . '$/i', $aEntry[$sProperty])) { continue 2; } } unset($this->aEntries[$sHash]); } } return $this; }
Removes items whose propeerties match a defined pattern @param array $aProperties A key/value array of properties and matching patterns @return $this
public function outputAr() { $aOut = []; foreach ($this->aEntries as $aEntry) { $sTemp = !empty($aEntry['tag']) ? '<' . $aEntry['tag'] . ' ' : '<meta '; unset($aEntry['tag']); foreach ($aEntry as $sKey => $sValue) { $sTemp .= $sKey . '="' . $sValue . '" '; } $sTemp = trim($sTemp) . '>'; $aOut[] = $sTemp; } return $aOut; }
Compiles the elements into an array of strings @return array
public function getAllNested(array $aData = [], $bIncludeDeleted = false, $sProperty = 'children') { $aAll = parent::getAll(null, null, $aData, $bIncludeDeleted); return $this->nestItems($aAll, $sProperty); }
Similar to getAll, but returns the items in a nested array @param array $aData Customise the result set @param bool $bIncludeDeleted Whether to include deleted results @param string $sProperty The property to which to assign children @return array
protected function nestItems(array $aAll, $sProperty, $iParentId = null) { $aOut = []; $sIdCol = $this->tableIdColumn; $sParentCol = $this->tableParentColumn; foreach ($aAll as $oItem) { // Check the parent ID column exists if (!property_exists($oItem, $sParentCol)) { throw new NailsException('Parent column "' . $sParentCol . '" is not defined on result set.'); } $iThisParentId = $oItem->{$sParentCol}; if ($iThisParentId == $iParentId) { $oItem->{$sProperty} = $this->nestItems($aAll, $sProperty, $oItem->{$sIdCol}); $aOut[] = $oItem; } else if (!property_exists($oItem, $sProperty)) { $oItem->{$sProperty} = []; } } return $aOut; }
Nests items @param array $aAll The items to nest @param string $sProperty The property to which to assign children @param null $iParentId The parent ID to check against @return array @throws NailsException
public function getAllNestedFlat(array $aData = [], $sSeparator = ' &rsaquo; ', $bIncludeDeleted = false) { $aAllNested = $this->getAllNested($aData, $bIncludeDeleted, 'children'); $aFlattened = $this->flattenItems($aAllNested); foreach ($aFlattened as &$aLabels) { $aLabels = implode($sSeparator, $aLabels); } return $aFlattened; }
Returns nested items, but as a flat array. The item's parent's labels will be prepended to the string @param array $aData Customise the result set @param string $sSeparator The separator to use between labels @param bool $bIncludeDeleted Whether to include deleted results @return array
private function loadStateIdentifiers(): array { if ($this->stateIdentifiers === null) { $this->stateIdentifiers = $this->repository->sudo( static function (Repository $repository): array { $stateIdentifiers = []; $stateGroups = $repository->getObjectStateService()->loadObjectStateGroups(); foreach ($stateGroups as $stateGroup) { $stateIdentifiers[$stateGroup->identifier] = []; $states = $repository->getObjectStateService()->loadObjectStates($stateGroup); foreach ($states as $state) { $stateIdentifiers[$stateGroup->identifier][] = $state->identifier; } } return $stateIdentifiers; } ); } return $this->stateIdentifiers; }
Returns the list of object state identifiers separated by group. @return string[][]
private function buildObjectStateFilterParameters(ParameterBuilderInterface $builder, array $groups = []): void { $builder->add( 'filter_by_object_state', ParameterType\Compound\BooleanType::class, [ 'groups' => $groups, ] ); $builder->get('filter_by_object_state')->add( 'object_states', EzParameterType\ObjectStateType::class, [ 'multiple' => true, 'groups' => $groups, ] ); }
Builds the parameters for filtering by object states.
private function getObjectStateFilterCriteria(ParameterCollectionInterface $parameterCollection): ?Criterion { if ($parameterCollection->getParameter('filter_by_object_state')->getValue() !== true) { return null; } $objectStates = $parameterCollection->getParameter('object_states')->getValue() ?? []; if (count($objectStates) === 0) { return null; } $criteria = []; foreach ($this->getObjectStateIds($objectStates) as $stateIds) { $criteria[] = new Criterion\ObjectStateId($stateIds); } return new Criterion\LogicalAnd($criteria); }
Returns the criteria used to filter content by object state.
private function getObjectStateIds(array $stateIdentifiers): array { $idList = []; foreach ($stateIdentifiers as $identifier) { $identifier = explode('|', $identifier); if (count($identifier) !== 2) { continue; } try { $stateGroup = $this->objectStateHandler->loadGroupByIdentifier($identifier[0]); $objectState = $this->objectStateHandler->loadByIdentifier($identifier[1], $stateGroup->id); $idList[$stateGroup->id][] = $objectState->id; } catch (NotFoundException $e) { continue; } } return $idList; }
Returns object state IDs for all provided object state identifiers. State identifiers are in format "<group_identifier>|<state_identifier>"
private function loadLanguages(): iterable { if (method_exists($this->languageService, 'loadLanguageListByCode')) { return $this->languageService->loadLanguageListByCode($this->languageCodes); } // Deprecated: Remove when support for eZ kernel < 7.5 ends $languages = []; foreach ($this->languageCodes as $languageCode) { try { $language = $this->languageService->loadLanguage($languageCode); } catch (NotFoundException $e) { continue; } $languages[] = $language; } return $languages; }
Loads the list of eZ Platform languages from language codes available in the object. @deprecated Acts as a BC layer for eZ kernel <7.5 @return \eZ\Publish\API\Repository\Values\Content\Language[]
private function getPosixLocale(Language $language): ?array { if (!$language->enabled) { return null; } $posixLocale = $this->localeConverter->convertToPOSIX($language->languageCode); if ($posixLocale === null) { return null; } if (!Locales::exists($posixLocale)) { return null; } return [$posixLocale, Locales::getName($posixLocale)]; }
Returns the array with POSIX locale code and name for provided eZ Platform language. If POSIX locale does not exist or if language is not enabled, null will be returned.
public static function init() { if (static::$bIsReady) { return; } $aErrorHandlers = Components::drivers('nails/common', 'ErrorHandler'); $oDefaultDriver = null; $aCustomDrivers = []; foreach ($aErrorHandlers as $oErrorHandler) { if ($oErrorHandler->slug == static::DEFAULT_ERROR_HANDLER) { $oDefaultDriver = $oErrorHandler; } else { $aCustomDrivers[] = $oErrorHandler; } } if (count($aCustomDrivers) > 1) { $aNames = []; foreach ($aCustomDrivers as $oErrorHandler) { $aNames[] = $oErrorHandler->slug; } static::halt(implode(', ', $aNames), 'More than one error handler installed'); return; } elseif (count($aCustomDrivers) === 1) { $oErrorHandler = reset($aCustomDrivers); } else { $oErrorHandler = $oDefaultDriver; } $sDriverNamespace = ArrayHelper::getFromArray('namespace', (array) $oErrorHandler->data); $sDriverClass = ArrayHelper::getFromArray('class', (array) $oErrorHandler->data); $sClassName = '\\' . $sDriverNamespace . $sDriverClass; if (!class_exists($sClassName)) { static::halt('Expected: ' . $sClassName, 'Driver class not available'); } elseif (!in_array(static::INTERFACE_NAME, class_implements($sClassName))) { static::halt('Error Handler "' . $sClassName . '" must implement "' . static::INTERFACE_NAME . '"'); } $sClassName::init(); static::$sDriverClass = $sClassName; static::$oDefaultDriver = $oDefaultDriver; static::setHandlers(); static::$bIsReady = true; }
Sets up the appropriate error handling driver
public function getDefaultDriverClass() { $oDriver = $this->getDefaultDriver(); $sDriverNamespace = ArrayHelper::getFromArray('namespace', (array) $oDriver->data); $sDriverClass = ArrayHelper::getFromArray('class', (array) $oDriver->data); return '\\' . $sDriverNamespace . $sDriverClass; }
Returns the default error driver class name @return string
public function triggerError($iErrorNumber = 0, $sErrorString = '', $sErrorFile = '', $iErrorLine = 0) { // PHP5.6 doesn't like $this->sDriverClass::error() $sDriverClass = static::$sDriverClass; $sDriverClass::error($iErrorNumber, $sErrorString, $sErrorFile, $iErrorLine); }
Manually trigger an error @param int $iErrorNumber @param string $sErrorString @param string $sErrorFile @param int $iErrorLine
public function showFatalErrorScreen($sSubject = '', $sMessage = '', $oDetails = null) { if (is_array($sMessage)) { $sMessage = implode("\n", $sMessage); } if (is_null($oDetails)) { $oDetails = (object) [ 'type' => null, 'code' => null, 'msg' => null, 'file' => null, 'line' => null, 'backtrace' => null, ]; } // Get the backtrace if (function_exists('debug_backtrace')) { $oDetails->backtrace = debug_backtrace(); } else { $oDetails->backtrace = []; } set_status_header(HttpCodes::STATUS_INTERNAL_SERVER_ERROR); $this->renderErrorView( '500', [ 'sSubject' => $sSubject, 'sMessage' => $sMessage, 'oDetails' => $oDetails, ] ); exit(HttpCodes::STATUS_INTERNAL_SERVER_ERROR); }
Shows the fatal error screen. A diagnostic screen is shown on non-production environments @param string $sSubject The error subject @param string $sMessage The error message @param \stdClass $oDetails Breakdown of the error which occurred @return void
public function show401($bLogError = true) { if (function_exists('isLoggedIn') && isLoggedIn()) { if ($bLogError) { $sPage = ArrayHelper::getFromArray('REQUEST_URI', $_SERVER); log_message('error', '401 Unauthorised --> ' . $sPage); } $sMessage = 'The page you are trying to view is restricted. Sadly you do not have enough '; $sMessage .= 'permissions to see its content.'; if (function_exists('wasAdmin') && wasAdmin()) { $oUserModel = Factory::model('User', 'nails/module-auth'); $oRecovery = $oUserModel->getAdminRecoveryData(); $sMessage .= '<br /><br />'; $sMessage .= '<small>'; $sMessage .= 'However, it looks like you are logged in as someone else.'; $sMessage .= '<br />' . anchor($oRecovery->loginUrl, 'Log back in as ' . $oRecovery->name); $sMessage .= ' and try again.'; $sMessage .= '</small>'; } set_status_header(401); $this->renderErrorView( '401', [ 'sSubject' => '401 Unauthorized', 'sMessage' => $sMessage, ] ); exit(401); } else { $oSession = Factory::service('Session', 'nails/module-auth'); $oInput = Factory::service('Input'); $sMessage = 'Sorry, you need to be logged in to see that page.'; $oSession->setFlashData('message', $sMessage); if ($oInput->server('REQUEST_URI')) { $sReturn = $oInput->server('REQUEST_URI'); } elseif (uri_string()) { $sReturn = uri_string(); } else { $sReturn = ''; } $sReturn = $sReturn ? '?return_to=' . urlencode($sReturn) : ''; redirect('auth/login' . $sReturn); } }
Renders the 401 page and halts script execution @param bool $bLogError Whether to log the error
public static function halt($sError, $sSubject = '', int $iCode = HttpCodes::STATUS_INTERNAL_SERVER_ERROR) { if (php_sapi_name() === 'cli' || defined('STDIN')) { $sSubject = trim(strip_tags($sSubject)); $sError = trim(strip_tags($sError)); echo "\n"; echo $sSubject ? 'ERROR: ' . $sSubject . ":\n" : ''; echo $sSubject ? $sError : 'ERROR: ' . $sError; echo "\n\n"; } else { set_status_header($iCode); ?> <style type="text/css"> p { font-family: monospace; margin: 20px 10px; } strong { color: red; } code { padding: 5px; border: 1px solid #CCC; background: #EEE } </style> <p> <strong>ERROR:</strong> <?=$sSubject ? '<em>' . $sSubject . '</em> - ' : ''?> <?=$sError?> </p> <?php } exit(1); }
A very low-level error function, used before the main error handling stack kicks in @param string $sError The error to show @param string $sSubject An optional subject line @param int $iCode The status code to send
public function run($module = '', $group = '') { if (is_object($module)) { $this->CI = &$module; } return parent::run($group); }
Quick mod of run() to allow for HMVC. @param string $module @param string $group @return bool
public function unique_if_diff($new, $params) { list($table, $column, $old) = explode(".", $params, 3); if ($new == $old) { return true; } if (!array_key_exists('unique_if_diff', $this->_error_messages)) { $this->set_message('unique_if_diff', lang('fv_unique_if_diff_field')); } $oDb = Factory::service('Database'); $oDb->where($column . ' !=', $old); $oDb->where($column, $new); $oDb->limit(1); $q = $oDb->get($table); if ($q->row()) { return false; } return true; }
Checks if a certain value is unique in a specified table if different from current value. @param string $new The form value @param string $params Parameters passed from set_rules() method @return boolean
public function valid_postcode($str) { if (!array_key_exists('valid_postcode', $this->_error_messages)) { $this->set_message('valid_postcode', lang('fv_valid_postcode')); } $pattern = '/^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$/'; return preg_match($pattern, strtoupper($str)) ? true : false; }
Checks if a string is in a valid UK post code format. @param string $str The form value @return boolean
public function item_count(array $aArray, $sParam) { $aParams = preg_replace('/[^0-9]/', '', explode(',', $sParam)); $mFloor = ArrayHelper::getFromArray(0, $aParams, 0); $mCeiling = ArrayHelper::getFromArray(1, $aParams, INF); if (substr($sParam, 0, 1) === '(' && substr($sParam, -1, 1) === ')') { $mFloor++; $mCeiling--; } if (($bAboveFloor = $mFloor <= count($aArray)) === false) { $this->set_message('item_count', lang('fv_count_floor')); } if (($bBeneathCeiling = $mCeiling >= count($aArray)) === false) { $this->set_message('item_count', lang('fv_count_ceiling')); } return $bAboveFloor && $bBeneathCeiling; }
Checks if an array satisfies specified count restrictions. @param array $aArray The value to check @param string $sParam The parameter to check against @return boolean
public function valid_date($sDate, $sFormat) { // If blank, then assume the date is not required if (empty($sDate)) { return true; } if (empty($sFormat)) { $sFormat = 'Y-m-d'; } if (!array_key_exists('valid_date', $this->_error_messages)) { $this->set_message('valid_date', lang('fv_valid_date_field')); } try { $oDate = \DateTime::createFromFormat($sFormat, $sDate); if (empty($oDate)) { return false; } return $oDate->format($sFormat) == $sDate; } catch (\Exception $e) { return false; } }
Check if a date is valid @param string $sDate The date string to check @param string $sFormat The format the string is in @return boolean
public function date_future($sDate, $sFormat) { // If blank, then assume the date is not required if (empty($sDate)) { return true; } if (empty($sFormat)) { $sFormat = 'Y-m-d'; } if (!array_key_exists('date_future', $this->_error_messages)) { $this->set_message('date_future', lang('fv_valid_date_future_field')); } try { $oNow = Factory::factory('DateTime'); $oDate = \DateTime::createFromFormat($sFormat, $sDate); if (empty($oDate)) { return false; } $oNow->setTime(0, 0, 0); $oDate->setTime(0, 0, 0); return $oDate > $oNow; } catch (\Exception $e) { return false; } }
Checks if a date is in the future @param string $sDate The date string to check @param string $sFormat The format the string is in @return boolean
public function date_before($sDate, $sParams) { // If blank, then assume the date is not required if (empty($sDate)) { return true; } if (empty($sParams)) { return false; } $aParams = explode('.', $sParams); $sField = !empty($aParams[0]) ? $aParams[0] : null; $sFormat = !empty($aParams[1]) ? $aParams[1] : 'Y-m-d'; if (empty($sField)) { return false; } if (!array_key_exists('date_before', $this->_error_messages)) { $this->set_message('date_before', lang('fv_valid_date_before_field')); } // If the other field is blank then bail out $oInput = Factory::service('Input'); $sOther = $oInput->post($sField); if (empty($sOther)) { return false; } try { $oDate = \DateTime::createFromFormat($sFormat, $sDate); $oOther = \DateTime::createFromFormat($sFormat, $sOther); if (empty($oDate) || $oOther) { return false; } $oDate->setTime(0, 0, 0); $oOther->setTime(0, 0, 0); return $oDate < $oOther; } catch (\Exception $e) { return false; } }
Checks if a date is before another date field @param string $sDate The date string to check @param string $sParams The other field name, and the date format (optional), separated with a period. @return boolean
public function valid_datetime($sDateTime, $sFormat) { // If blank, then assume the date is not required if (empty($sDateTime)) { return true; } if (empty($sFormat)) { $sFormat = 'Y-m-d H:i:s'; } if (!array_key_exists('valid_datetime', $this->_error_messages)) { $this->set_message('valid_datetime', lang('fv_valid_datetime_field')); } try { $oDate = \DateTime::createFromFormat($sFormat, $sDateTime); if (empty($oDate)) { return false; } return $oDate->format($sFormat) == $sDateTime; } catch (\Exception $e) { return false; } }
Checks if a datetime string is valid @param string $sDateTime The datetime string to check @param string $sFormat The format the string is in @return boolean
public function datetime_future($sDateTime, $sFormat) { // If blank, then assume the date is not required if (empty($sDateTime)) { return true; } if (empty($sFormat)) { $sFormat = 'Y-m-d H:i:s'; } if (!array_key_exists('datetime_future', $this->_error_messages)) { $this->set_message('datetime_future', lang('fv_valid_datetime_future_field')); } try { $oNow = Factory::factory('DateTime'); $oDate = \DateTime::createFromFormat($sFormat, $sDateTime); if (empty($oDate)) { return false; } return $oDate > $oNow; } catch (\Exception $e) { return false; } }
Checks if a datetime string is in the future @param string $sDateTime The datetime string to check @param string $sFormat The format the string is in @return boolean
public function valid_time($sTime, $sFormat) { // If blank, then assume the date is not required if (empty($sTime)) { return true; } if (empty($sFormat)) { $sFormat = 'H:i:s'; } if (!array_key_exists('valid_time', $this->_error_messages)) { $this->set_message('valid_time', lang('fv_valid_time_field')); } try { $oDate = \DateTime::createFromFormat($sFormat, $sTime); if (empty($oDate)) { return false; } return $oDate->format($sFormat) == $sTime; } catch (\Exception $e) { return false; } }
Checks if a time string is valid @param string $sTime The time string to check @param string $sFormat The format the string is in @return boolean
public function in_range($str, $field) { $_range = explode('-', $field); $_low = isset($_range[0]) ? (float) $_range[0] : null; $_high = isset($_range[1]) ? (float) $_range[1] : null; if (is_null($_low) || is_null($_high)) { return true; } if ((float) $str >= $_low && (float) $str <= $_high) { return true; } else { if (!array_key_exists('in_range', $this->_error_messages)) { $this->set_message('in_range', lang('fv_in_range_field')); } return false; } }
Checks if a value is within a range as defined in $field @param string $str The form value @param string $field The range, e.g., 0-10 @return boolean
public function valid_email($str) { if (function_exists('filter_var')) { return (bool) filter_var($str, FILTER_VALIDATE_EMAIL); } else { return parent::valid_email($str); } }
Valid Email, using filter_var if possible falling back to CI's regex @access public @param string @return bool
public function cdnObjectPickerMultiObjectRequired($aValues) { $this->set_message( 'cdnObjectPickerMultiObjectRequired', 'All items must have a file set.' ); foreach ($aValues as $aValue) { if (empty($aValue['object_id'])) { return false; } } return true; }
Validates that all items within a CDN Object Multi Picker have a label set @param array $aValues The values from the picker @return boolean @todo provide this from within the CDN module
public function is_unique($sString, $sParameters) { $aParameters = explode('.', $sParameters); $sTable = ArrayHelper::getFromArray(0, $aParameters); $sColumn = ArrayHelper::getFromArray(1, $aParameters); $sIgnoreId = ArrayHelper::getFromArray(2, $aParameters); $sIgnoreColumn = ArrayHelper::getFromArray(3, $aParameters, 'id'); $oDb = Factory::service('Database'); $oDb->where($sColumn, $sString); if ($sIgnoreId) { $oDb->where($sIgnoreColumn . ' !=', $sIgnoreId); } return $oDb->count_all_results($sTable) === 0; }
Checks a value is uniqe in a given table @param string $sString The string to check @param string $sParameters Period separated parameters; table.column.ignore_id.ignore_id_column @return bool
public function is_bool($bValue) { $this->set_message('is_bool', lang('fv_is_bool_field')); return is_bool($bValue) || $bValue === '1' || $bValue === '0' || $bValue === 1 || $bValue === 0; }
Checks whether a value is a boolean value @param string $bValue The value to check @return bool
public function supportedLocale($sValue) { /** @var Locale $oLocale */ $oLocale = Factory::service('Locale'); $aSupportedLocales = $oLocale->getSupportedLocales(); if (!in_array($sValue, $aSupportedLocales)) { $this->set_message('supportedLocale', 'This is not a supported locale'); return false; } return true; }
Determines whether the vlaue is a supported locale @param string $sValue The vaue to check @return bool @throws \Nails\Common\Exception\FactoryException
public function is($sValue, $sExpected) { if ($sValue !== $sExpected) { $this->set_message('is', 'This field must be exactly "' . $sExpected . '"'); return false; } return true; }
Determines whether a value is specifically something @param string $sValue The value to check @param string $sExpected The expected value @return bool
public static function filter($sType): array { if (!isset(static::$aCache[$sType])) { $aComponents = static::available(); static::$aCache[$sType] = []; foreach ($aComponents as $oComponent) { if ($oComponent->type === $sType) { static::$aCache[$sType][] = $oComponent; } } } return static::$aCache[$sType]; }
Returns a filtered array of components @param string $sType The type of component to return @return Component[]
public static function getBySlug($sSlug): ?Component { $aComponents = static::available(); foreach ($aComponents as $oComponent) { if ($oComponent->slug === $sSlug) { return $oComponent; } } return null; }
Returns a component by its slug @param string $sSlug The component's slug @return Component
public static function getApp($bUseCache = true): Component { // If we have already fetched this data then don't get it again if ($bUseCache && isset(static::$aCache['APP'])) { return static::$aCache['APP']; } // -------------------------------------------------------------------------- $sComposer = @file_get_contents(NAILS_APP_PATH . 'composer.json'); if (empty($sComposer)) { ErrorHandler::halt('Failed to get app configuration; could not load composer.json'); } $oComposer = @json_decode($sComposer); if (empty($oComposer)) { ErrorHandler::halt('Failed to get app configuration; could not decode composer.json'); } $aComposer = (array) $oComposer; $aNails = !empty($oComposer->extra->nails) ? (array) $oComposer->extra->nails : []; $oOut = new Component( (object) [ 'slug' => 'app', 'name' => 'app', 'description' => ArrayHelper::getFromArray('description', $aNails, ArrayHelper::getFromArray('description', $aComposer)), 'homepage' => ArrayHelper::getFromArray('homepage', $aNails, ArrayHelper::getFromArray('homepage', $aComposer)), 'authors' => ArrayHelper::getFromArray('authors', $aNails, ArrayHelper::getFromArray('authors', $aComposer)), 'extra' => (object) [ 'nails' => (object) [ 'namespace' => '\\App\\', 'moduleName' => ArrayHelper::getFromArray('moduleName', $aNails, ''), 'data' => ArrayHelper::getFromArray('data', $aNails, null), 'autoload' => ArrayHelper::getFromArray('autoload', $aNails, null), ], ], ], NAILS_APP_PATH, './', true ); // -------------------------------------------------------------------------- if ($bUseCache) { static::$aCache['APP'] = $oOut; } return $oOut; }
Returns an instance of the app as a component @param bool $bUseCache Whether to use the cache or not @return Component
public static function exists($sSlug): bool { $aModules = static::modules(); foreach ($aModules as $oModule) { if ($sSlug === $oModule->slug) { return true; } } return false; }
Test whether a component is installed @param string $sSlug The component's slug @return bool
public static function skins($sModule, $sSubType = ''): array { $aSkins = static::filter('skin'); $aOut = []; foreach ($aSkins as $oSkin) { // Provide a url field for the skin if (Functions::isPageSecure()) { $oSkin->url = SECURE_BASE_URL . $oSkin->relativePath; } else { $oSkin->url = BASE_URL . $oSkin->relativePath; } if ($oSkin->forModule == $sModule) { if (!empty($sSubType) && $sSubType == $oSkin->subType) { $aOut[] = $oSkin; } elseif (empty($sSubType)) { $aOut[] = $oSkin; } } } return $aOut; }
Returns registered skins, optionally filtered @param string $sModule The module to filter for @param string $sSubTyp The sub-type to filter by @return Component[]
public static function drivers($sModule, $sSubType = ''): array { $aDrivers = static::filter('driver'); $aOut = []; foreach ($aDrivers as $oDriver) { if ($oDriver->forModule == $sModule) { if (!empty($sSubType) && $sSubType == $oDriver->subType) { $aOut[] = $oDriver; } elseif (empty($sSubType)) { $aOut[] = $oDriver; } } } return $aOut; }
Returns registered drivers, optionally filtered @param string $sModule The module to filter for @param string $sSubTyp The sub-type to filter by @return Component[]
public static function getDriverInstance($oDriver): Base { // Allow for driver requesting as a string if (is_string($oDriver)) { $oDriver = \Nails\Components::getBySlug($oDriver); } if (isset(static::$aCache['DRIVER_INSTANCE'][$oDriver->slug])) { return static::$aCache['DRIVER_INSTANCE'][$oDriver->slug]; } // Test driver if (!empty($oDriver->data->namespace)) { $sNamespace = $oDriver->data->namespace; } else { throw new NailsException('Driver Namespace missing from driver "' . $oDriver->slug . '"', 1); } if (!empty($oDriver->data->class)) { $sClassName = $oDriver->data->class; } else { throw new NailsException('Driver ClassName missing from driver "' . $oDriver->slug . '"', 2); } // Load the driver file $sDriverPath = $oDriver->path . 'src/' . $oDriver->data->class . '.php'; if (!file_exists($sDriverPath)) { throw new NailsException( 'Driver file for "' . $oDriver->slug . '" does not exist at "' . $sDriverPath . '"', 3 ); } require_once $sDriverPath; // Check if the class exists $sDriverClass = $sNamespace . $sClassName; if (!class_exists($sDriverClass)) { throw new NailsException('Driver class does not exist "' . $sDriverClass . '"', 4); } // Save for later static::$aCache['DRIVER_INSTANCE'][$oDriver->slug] = new $sDriverClass(); return static::$aCache['DRIVER_INSTANCE'][$oDriver->slug]; }
Returns an instance of a single driver @param object $oDriver The Driver definition @throws NailsException @return Base
public static function detectClassComponent($mClass): ?Component { $oReflect = new \ReflectionClass($mClass); $sPath = $oReflect->getFileName(); $bIsVendor = (bool) preg_match('/^' . preg_quote(NAILS_APP_PATH . 'vendor', '/') . '/', $sPath); if (!$bIsVendor) { return static::getApp(); } foreach (static::available() as $oComponent) { if ($oComponent->slug === 'app') { continue; } elseif (preg_match('/^' . preg_quote($oComponent->path, '/') . '/', $sPath)) { return $oComponent; } } return null; }
Attempt to detect which component a class belongs to @param mixed $mClass A class as a string or an object @return Component|null @throws \ReflectionException
protected function setDefinitions() { // Define where we should look $aDefinitionLocations = []; $aDefinitionLocations[] = NAILS_COMMON_PATH . 'config/app_notifications.php'; foreach (Components::modules() as $oModule) { $aDefinitionLocations[] = $oModule->path . $oModule->moduleName . '/config/app_notifications.php'; } $aDefinitionLocations[] = NAILS_APP_PATH . 'application/config/app_notifications.php'; // Find definitions foreach ($aDefinitionLocations as $sPath) { $this->loadDefinitions($sPath); } // Put into a vague order ksort($this->notifications); }
Defines the notifications
protected function loadDefinitions($path) { if (file_exists($path)) { include $path; if (!empty($config['notification_definitions'])) { $this->notifications = array_merge($this->notifications, $config['notification_definitions']); } } }
Loads definitions located at $path @param string $path The path to load @return void
public function getDefinitions($grouping = null) { if (is_null($grouping)) { return $this->notifications; } elseif (isset($this->notifications[$grouping])) { return $this->notifications[$grouping]; } else { return []; } }
Returns the notification defnintions, optionally limited per group @param string $grouping The group to limit to @return array
public function get($key = null, $grouping = 'app', $force_refresh = false) { // Check that it's a valid key/grouping pair if (!isset($this->notifications[$grouping]->options[$key])) { $this->setError($grouping . '/' . $key . ' is not a valid group/key pair.'); return false; } // -------------------------------------------------------------------------- if (empty($this->emails[$grouping]) || $force_refresh) { $oDb = Factory::service('Database'); $oDb->where('grouping', $grouping); $notifications = $oDb->get($this->table)->result(); $this->emails[$grouping] = []; foreach ($notifications as $setting) { $this->emails[$grouping][$setting->key] = json_decode($setting->value); } } // -------------------------------------------------------------------------- if (empty($key)) { return $this->emails[$grouping]; } else { return isset($this->emails[$grouping][$key]) ? $this->emails[$grouping][$key] : []; } }
Gets emails associated with a particular group/key @param string $key The key to retrieve @param string $grouping The group the key belongs to @param boolean $force_refresh Whether to force a group refresh @return array
public function set($key, $grouping = 'app', $value = null) { $oDb = Factory::service('Database'); $oDb->trans_begin(); if (is_array($key)) { foreach ($key as $key => $value) { $this->doSet($key, $grouping, $value); } } else { $this->doSet($key, $grouping, $value); } if ($oDb->trans_status() === false) { $oDb->trans_rollback(); return false; } else { $oDb->trans_commit(); return true; } }
Set a group/key either by passing an array of key=>value pairs as the $key or by passing a string to $key and setting $value @param mixed $key The key to set, or an array of key => value pairs @param string $grouping The grouping to store the keys under @param mixed $value The data to store, only used if $key is a string @return boolean
protected function doSet($key, $grouping, $value) { // Check that it's a valid key/grouping pair if (!isset($this->notifications[$grouping]->options[$key])) { $this->setError($grouping . '/' . $key . ' is not a valid group/key pair.'); return false; } // -------------------------------------------------------------------------- $oDb = Factory::service('Database'); $oDb->where('key', $key); $oDb->where('grouping', $grouping); if ($oDb->count_all_results($this->table)) { $oDb->where('grouping', $grouping); $oDb->where('key', $key); $oDb->set('value', json_encode($value)); $oDb->update($this->table); } else { $oDb->set('grouping', $grouping); $oDb->set('key', $key); $oDb->set('value', json_encode($value)); $oDb->insert($this->table); } }
Inserts/Updates a group/key value @param string $key The key to set @param string $grouping The key's grouping @param mixed $value The value of the group/key @return void
public static function possessive($sString) { // Attempt to match the case $sLastChar = substr($sString, -1); $bIsLowerCase = strtolower($sLastChar) === $sLastChar; $sPossessionChar = $bIsLowerCase ? 's' : 'S'; return substr($sString, -1) == $sPossessionChar ? $sString . '\'' : $sString . '\'' . $sPossessionChar; }
Correctly adds a possessive apostrophe to a word @param string $sString The word to which to add a possessive apostrophe @return string
public static function pluralise($iValue, $sSingular, $sSpecified = null) { $sSingular = trim($sSingular); if ($iValue == 1) { return $sSingular; } else { return $sSpecified ?: plural($sSingular); } }
Pluralises english words if a value is greater than 1 @param integer $iValue The number to compare against @param string $sSingular The word to pluralise @param string $sSpecified A specific word to use for the plural @return string
public function detectFromFile(string $sFile): string { if (!file_exists($sFile)) { return ''; } $rHandle = finfo_open(FILEINFO_MIME_TYPE); $sMime = finfo_file($rHandle, $sFile); if ($sMime === 'application/octet-stream' || empty($sMime)) { $sMime = $this->oDetector->getType($sFile); } return $sMime ?? 'application/octet-stream'; }
Detect a file's mimetype, first using the system, followed by the detector @param string $sFile The path to the file to detect @return string @throws \Exception
public function addMime(string $sMime, array $aExtensions): self { $this->updateMap(static::$aMapMimeToExtensions, $sMime, $aExtensions); foreach ($aExtensions as $sExtension) { $this->updateMap(static::$aMapExtensionToMimes, $sExtension, [$sMime]); } return $this; }
Adds a new mime type to the map and its associated extensions @param string $sMime The mime type to add @param array $aExtensions An array of acceptable extensions @return Mime
public function addExtension(string $sExtension, array $aMimes): self { $this->updateMap(static::$aMapExtensionToMimes, $sExtension, $aMimes); foreach ($aMimes as $sMime) { $this->updateMap(static::$aMapMimeToExtensions, $sMime, [$sExtension]); } return $this; }
Adds a new extension to the map and its associated mime types @param string $sExtension the extension to add @param array $aMimes An array of acceptable mime types @return Mime
protected function updateMap(array &$aMap, string $sKey, array $aValues): self { if (!array_key_exists($sKey, $aMap)) { $aMap[$sKey] = []; } $aMap[$sKey] = array_values( array_unique( array_merge( $aMap[$sKey], $aValues ) ) ); return $this; }
Updates a map array @param array $aMap The array to update @param string $sKey The key to update @param array $aValues The values to add @return Mime
public function getDefault() { $sDefault = $this->oCi->config->item('languages_default'); $oLanguage = $this->getByCode($sDefault); return !empty($oLanguage) ? $oLanguage : false; }
Retursn the default language object @return mixed stdClass on success, false on failure
public function getDefaultCode() { $oDefault = $this->getDefault(); return empty($oDefault->code) ? false : $oDefault->code; }
Returns the default language's code @return mixed stdClass on success, false on failure
public function getDefaultLabel() { $oDefault = $this->getDefault(); return empty($oDefault->label) ? false : $oDefault->label; }
Returns the default language's label @return mixed stdClass on success, false on failure
public function getAllFlat() { $aOut = []; $aLanguages = $this->getAll(); foreach ($aLanguages as $oLanguage) { $aOut[$oLanguage->code] = $oLanguage->label; } return $aOut; }
Returns all defined languages as a flat array @return array
public function getAllEnabled() { $aEnabled = $this->oCi->config->item('languages_enabled'); $aOut = []; foreach ($aEnabled as $sCode) { $aOut[] = $this->getByCode($sCode); } return array_filter($aOut); }
Returns all the enabled languages @return array
public function getAllEnabledFlat() { $aOut = []; $aLanguages = $this->getAllEnabled(); foreach ($aLanguages as $oLanguage) { $aOut[$oLanguage->code] = $oLanguage->label; } return $aOut; }
Returns all the enabled languages as a flat array @return array
public function getByCode($sCode) { $aLanguages = $this->getAll(); return !empty($aLanguages[$sCode]) ? $aLanguages[$sCode] : false; }
Returns a language by it's code @param string $sCode The language code @return mixed stdClass on success, false on failure
public function site_url($sUrl = '', $bForceSecure = false) { // If an explicit URL is passed in, then leave it be if (preg_match('/^(http|https|ftp|mailto)\:/', $sUrl)) { return $sUrl; } $sUrl = parent::site_url($sUrl); // If the URL begins with a slash then attempt to guess the host using $_SERVER if (preg_match('/^\//', $sUrl) && !empty($_SERVER['HTTP_HOST'])) { $sProtocol = !empty($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http'; $sUrl = $sProtocol . '://' . $_SERVER['HTTP_HOST'] . $sUrl; } if ($bForceSecure || Functions::isPageSecure()) { $sUrl = preg_replace('#^' . BASE_URL . '#', SECURE_BASE_URL, $sUrl); } return $sUrl; }
Returns the site's URL, secured if necessary @param string $sUrl @param bool $bForceSecure @return mixed|string
public function get($sKey = null, $sGrouping = 'app', $bForceRefresh = false) { if (!isset($this->aSettings[$sGrouping]) || $bForceRefresh) { $oDb = Factory::service('Database'); $oDb->where('grouping', $sGrouping); $aSettings = $oDb->get($this->sTable)->result(); $this->aSettings[$sGrouping] = []; foreach ($aSettings as $oSetting) { $sValue = $oSetting->value; if (!empty($oSetting->is_encrypted)) { $oEncrypt = Factory::service('Encrypt'); $sValue = $oEncrypt->decode($sValue); } $this->aSettings[$sGrouping][$oSetting->key] = json_decode($sValue); } } // -------------------------------------------------------------------------- if (empty($sKey)) { return $this->aSettings[$sGrouping]; } else { return isset($this->aSettings[$sGrouping][$sKey]) ? $this->aSettings[$sGrouping][$sKey] : null; } }
Gets settings associated with a particular group/key @param string $sKey The key to retrieve @param string $sGrouping The group the key belongs to @param boolean $bForceRefresh Whether to force a group refresh @return array
public function set($mKey, $sGrouping = 'app', $mValue = null, $bEncrypt = false) { $oDb = Factory::service('Database'); $oDb->trans_begin(); if (is_array($mKey)) { foreach ($mKey as $sKey => $mValue) { $this->doSet($sKey, $sGrouping, $mValue, $bEncrypt); } } else { $this->doSet($mKey, $sGrouping, $mValue, $bEncrypt); } if ($oDb->trans_status() === false) { $oDb->trans_rollback(); return false; } else { $oDb->trans_commit(); return true; } }
Set a group/key either by passing an array of key=>value pairs as the $key or by passing a string to $key and setting $value @param mixed $mKey The key to set, or an array of key => value pairs @param string $sGrouping The grouping to store the keys under @param mixed $mValue The data to store, only used if $mKey is a string @param boolean $bEncrypt Whether to encrypt the data or not @return boolean
protected function doSet($sKey, $sGrouping, $mValue, $bEncrypt) { $sValue = json_encode($mValue); $bEncrypt = (bool) $bEncrypt; if ($bEncrypt) { $oEncrypt = Factory::service('Encrypt'); $sValue = $oEncrypt->encode($sValue); } $oDb = Factory::service('Database'); $oDb->where('key', $sKey); $oDb->where('grouping', $sGrouping); if ($oDb->count_all_results($this->sTable)) { $oDb->set('value', $sValue); $oDb->set('is_encrypted', $bEncrypt); $oDb->where('grouping', $sGrouping); $oDb->where('key', $sKey); $oDb->update($this->sTable); } else { $oDb->set('value', $sValue); $oDb->set('grouping', $sGrouping); $oDb->set('key', $sKey); $oDb->set('is_encrypted', $bEncrypt); $oDb->insert($this->sTable); } }
Inserts/Updates a group/key value @param string $sKey The key to set @param string $sGrouping The key's grouping @param mixed $mValue The value of the group/key @param boolean $bEncrypt Whether to encrypt the data or not @return void
public function delete($mKey, $sGrouping) { $oDb = Factory::service('Database'); $oDb->trans_begin(); if (is_array($mKey)) { foreach ($mKey as $sKey) { $this->doDelete($sKey, $sGrouping); } } else { $this->doDelete($mKey, $sGrouping); } if ($oDb->trans_status() === false) { $oDb->trans_rollback(); return false; } else { $oDb->trans_commit(); return true; } }
Deletes a key for a particular group @param mixed $mKey The key to delete @param string $sGrouping The key's grouping @return bool
protected function doDelete($sKey, $sGrouping) { $oDb = Factory::service('Database'); $oDb->where('key', $sKey); $oDb->where('grouping', $sGrouping); return $oDb->delete($this->sTable); }
Actually performs the deletion of the row. @param string $sKey The key to delete @param string $sGrouping They key's grouping @return bool
public function deleteGroup($sGrouping) { $oDb = Factory::service('Database'); $oDb->where('grouping', $sGrouping); return $oDb->delete($this->sTable); }
Deletes all keys for a particular group. @param string $sGrouping The group to delete @return bool
private function getContentTypes(Options $options): array { $allContentTypes = []; $groups = $this->contentTypeService->loadContentTypeGroups(); $configuredGroups = $options['types']; foreach ($groups as $group) { $configuredGroups += [$group->identifier => true]; if ($configuredGroups[$group->identifier] === false) { continue; } $contentTypes = $this->contentTypeService->loadContentTypes($group); foreach ($contentTypes as $contentType) { if ( is_array($configuredGroups[$group->identifier]) && !in_array($contentType->identifier, $configuredGroups[$group->identifier], true) ) { continue; } $contentTypeName = $contentType->getName() ?? $contentType->identifier; $allContentTypes[$group->identifier][$contentTypeName] = $contentType->identifier; } } return $allContentTypes; }
Returns the allowed content types from eZ Platform.
protected function _validate_request($segments) { if (count($segments) == 0) { return $segments; } /* locate module controller */ if ($located = $this->locate($segments)) { return $located; } /* use a default 404_override controller */ if (isset($this->routes['404_override']) && $this->routes['404_override']) { $segments = explode('/', $this->routes['404_override']); if ($located = $this->locate($segments)) { return $located; } } /* no controller found */ show404('', true); }
Extending method purely to change the 404 behaviour and PSR-2 things a little. When show404() is reached it means that a valid controller could not be found. These errors should be logged, however show404() by default doesn't log errors, hence the override. @param array $segments The URI segments @return array
public function load($mAssets, $sAssetLocation = 'APP', $sForceType = null): self { // Cast as an array $aAssets = (array) $mAssets; // -------------------------------------------------------------------------- // Backwards compatibility $sAssetLocation = $sAssetLocation === true ? 'NAILS' : $sAssetLocation; // -------------------------------------------------------------------------- switch (strtoupper($sAssetLocation)) { case 'NAILS-BOWER': $sAssetLocationMethod = 'loadNailsBower'; break; case 'NAILS-PACKAGE': $sAssetLocationMethod = 'loadNailsPackage'; break; case 'NAILS': $sAssetLocationMethod = 'loadNails'; break; case 'APP-BOWER': case 'BOWER': $sAssetLocationMethod = 'loadAppBower'; break; case 'APP-PACKAGE': case 'PACKAGE': $sAssetLocationMethod = 'loadAppPackage'; break; case 'APP': $sAssetLocationMethod = 'loadApp'; break; default: $sAssetLocationMethod = 'loadModule'; break; } // -------------------------------------------------------------------------- foreach ($aAssets as $sAsset) { if (preg_match('#^https?://#', $sAsset)) { $this->loadUrl($sAsset, $sForceType); } elseif (substr($sAsset, 0, 0) == '/') { $this->loadAbsolute(substr($sAsset, 1), $sForceType); } else { $this->{$sAssetLocationMethod}($sAsset, $sForceType, $sAssetLocation); } } // -------------------------------------------------------------------------- return $this; }
Loads an asset @param mixed $mAssets The asset to load, can be an array or a string @param string $sAssetLocation The asset's location @param string $sForceType The asset's file type (e.g., JS or CSS) @return $this
protected function loadUrl($sAsset, $sForceType) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': $this->aCss['URL-' . $sAsset] = $sAsset; break; case 'JS': $this->aJs['URL-' . $sAsset] = $sAsset; break; } }
Loads an asset supplied as a URL @param string $sAsset The asset to load @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
protected function loadNails($sAsset, $sForceType) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': $this->aCss['NAILS-' . $sAsset] = NAILS_ASSETS_URL . $this->sCssDir . $sAsset; break; case 'JS': $this->aJs['NAILS-' . $sAsset] = NAILS_ASSETS_URL . $this->sJsDir . $sAsset; break; } }
Loads an asset from the Nails asset module @param string $sAsset The asset to load @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
protected function loadNailsBower($sAsset, $sForceType) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': $this->aCss['NAILS-BOWER-' . $sAsset] = NAILS_ASSETS_URL . $this->sBowerDir . $sAsset; break; case 'JS': $this->aJs['NAILS-BOWER-' . $sAsset] = NAILS_ASSETS_URL . $this->sBowerDir . $sAsset; break; } }
Loads a Bower asset from the NAils asset module's bower_components directory @param string $sAsset The asset to load @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
protected function loadNailsPackage($sAsset, $sForceType) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': $this->aCss['NAILS-PACKAGE-' . $sAsset] = NAILS_ASSETS_URL . 'packages/' . $sAsset; break; case 'JS': $this->aJs['NAILS-PACKAGE-' . $sAsset] = NAILS_ASSETS_URL . 'packages/' . $sAsset; break; } }
Loads a Nails package asset (as a relative url from NAILS_ASSETS_URL . 'packages/') @param string $sAsset The asset to load @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
protected function loadAppBower($sAsset, $sForceType) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': $this->aCss['APP-BOWER-' . $sAsset] = $this->sBaseUrl . $this->sBowerDir . $sAsset; break; case 'JS': $this->aJs['APP-BOWER-' . $sAsset] = $this->sBaseUrl . $this->sBowerDir . $sAsset; break; } }
Loads a Bower asset from the app's bower_components directory @param string $sAsset The asset to load @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
protected function loadAppPackage($sAsset, $sForceType) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': $this->aCss['APP-PACKAGE-' . $sAsset] = $this->sBaseUrl . 'packages/' . $sAsset; break; case 'JS': $this->aJs['APP-PACKAGE-' . $sAsset] = $this->sBaseUrl . 'packages/' . $sAsset; break; } }
Loads an App package asset (as a relative url from 'packages/') @param string $sAsset The asset to load @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
protected function loadApp($sAsset, $sForceType) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': $this->aCss['APP-' . $sAsset] = $this->sBaseUrl . $this->sCssDir . $sAsset; break; case 'JS': $this->aJs['APP-' . $sAsset] = $this->sBaseUrl . $this->sJsDir . $sAsset; break; } }
Loads an asset from the app's asset directory @param string $sAsset The asset to load @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
protected function loadModule($sAsset, $sForceType, $mModule) { if (is_array($mModule)) { $sModule = !empty($mModule[0]) ? $mModule[0] : null; $sLocation = !empty($mModule[1]) ? $mModule[1] : null; } else { $sModule = $mModule; $sLocation = null; } $sType = $this->determineType($sAsset, $sForceType); $sKey = 'MODULE-' . $sModule . '-' . $sAsset; switch ($sType) { case 'CSS': if ($sLocation == 'BOWER') { $this->aCss[$sKey] = $this->sBaseModuleUrl . $sModule . '/assets/bower_components/' . $sAsset; } else { $this->aCss[$sKey] = $this->sBaseModuleUrl . $sModule . '/assets/css/' . $sAsset; } break; case 'JS': if ($sLocation == 'BOWER') { $this->aJs[$sKey] = $this->sBaseModuleUrl . $sModule . '/assets/bower_components/' . $sAsset; } else { $this->aJs[$sKey] = $this->sBaseModuleUrl . $sModule . '/assets/js/' . $sAsset; } break; } }
Loads an asset from a module's asset directory @param string $sAsset The asset to load @param mixed $mModule The module to load from @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
public function unload($mAssets, $sAssetLocation = 'APP', $sForceType = null) { // Cast as an array $aAssets = (array) $mAssets; // -------------------------------------------------------------------------- // Backwards compatibility $sAssetLocation = $sAssetLocation === true ? 'NAILS' : $sAssetLocation; // -------------------------------------------------------------------------- switch (strtoupper($sAssetLocation)) { case 'NAILS-BOWER': $sAssetLocationMethod = 'unloadNailsBower'; break; case 'NAILS-PACKAGE': $sAssetLocationMethod = 'unloadNailsPackage'; break; case 'NAILS': $sAssetLocationMethod = 'unloadNails'; break; case 'APP-BOWER': case 'BOWER': $sAssetLocationMethod = 'unloadAppBower'; break; case 'APP-PACKAGE': case 'PACKAGE': $sAssetLocationMethod = 'unloadAppPackage'; break; case 'APP': $sAssetLocationMethod = 'unloadApp'; break; default: $sAssetLocationMethod = 'unloadModule'; break; } // -------------------------------------------------------------------------- foreach ($aAssets as $sAsset) { if (preg_match('#^https?://#', $sAsset)) { $this->unloadUrl($sAsset, $sForceType); } elseif (substr($sAsset, 0, 0) == '/') { $this->unloadAbsolute($sAsset, $sForceType); } else { $this->{$sAssetLocationMethod}($sAsset, $sForceType, $sAssetLocation); } } // -------------------------------------------------------------------------- return $this; }
Unloads an asset @param mixed $mAssets The asset to unload, can be an array or a string @param string $sAssetLocation The asset's location @param string $sForceType The asset's file type (e.g., JS or CSS) @return object
protected function unloadUrl($sAsset, $sForceType) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': unset($this->aCss['URL-' . $sAsset]); break; case 'JS': unset($this->aJs['URL-' . $sAsset]); break; } }
Unloads an asset supplied as a URL @param string $sAsset The asset to unload @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
protected function unloadAbsolute($sAsset, $sForceType) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': unset($this->aCss['ABSOLUTE-' . $sAsset]); break; case 'JS': unset($this->aJs['ABSOLUTE-' . $sAsset]); break; } }
Unloads an asset supplied as an absolute URL @param string $sAsset The asset to unload @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
protected function unloadNails($sAsset, $sForceType) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': unset($this->aCss['NAILS-' . $sAsset]); break; case 'JS': unset($this->aJs['NAILS-' . $sAsset]); break; } }
Unloads an asset from the Nails asset module @param string $sAsset The asset to unload @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
protected function unloadNailsBower($sAsset, $sForceType) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': unset($this->aCss['NAILS-BOWER-' . $sAsset]); break; case 'JS': unset($this->aJs['NAILS-BOWER-' . $sAsset]); break; } }
Loads a Bower asset from the Nails asset module's bower_components directory @param string $sAsset The asset to unload @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void