code
stringlengths 17
296k
| docstring
stringlengths 30
30.3k
| func_name
stringlengths 1
89
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
153
| url
stringlengths 51
209
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
public function __construct($name = null, $showPagination = null, $showAdd = null)
{
$this->setName($name ?: 'DetailForm');
$this->setShowPagination($showPagination);
$this->setShowAdd($showAdd);
} | Create a popup component. The two arguments will specify how the popup form's HTML and
behaviour is created. The given controller will be customised, putting the edit form into the
template with the given name.
The arguments are experimental API's to support partial content to be passed back to whatever
controller who wants to display the getCMSFields
@param string $name The name of the edit form to place into the pop-up form
@param bool $showPagination Whether the `Previous` and `Next` buttons should display or not, leave as null to use default
@param bool $showAdd Whether the `Add` button should display or not, leave as null to use default | __construct | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldDetailForm.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDetailForm.php | BSD-3-Clause |
protected function getItemRequestHandler($gridField, $record, $requestHandler)
{
$class = $this->getItemRequestClass();
$assignedClass = $this->itemRequestClass;
$this->extend('updateItemRequestClass', $class, $gridField, $record, $requestHandler, $assignedClass);
/** @var GridFieldDetailForm_ItemRequest $handler */
$handler = Injector::inst()->createWithArgs(
$class,
[$gridField, $this, $record, $requestHandler, $this->name]
);
if ($template = $this->getTemplate()) {
$handler->setTemplate($template);
}
$this->extend('updateItemRequestHandler', $handler);
return $handler;
} | Build a request handler for the given record
@param GridField $gridField
@param ViewableData $record
@param RequestHandler $requestHandler
@return GridFieldDetailForm_ItemRequest | getItemRequestHandler | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldDetailForm.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDetailForm.php | BSD-3-Clause |
public function setThrowExceptionOnBadDataType($throwExceptionOnBadDataType)
{
Deprecation::notice('5.2.0', 'Will be removed without equivalent functionality');
$this->throwExceptionOnBadDataType = $throwExceptionOnBadDataType;
return $this;
} | Determine what happens when this component is used with a list that isn't {@link SS_Filterable}.
- true: An exception is thrown
- false: This component will be ignored - it won't make any changes to the GridField.
By default, this is set to true so that it's clearer what's happening, but the predefined
{@link GridFieldConfig} subclasses set this to false for flexibility.
@param bool $throwExceptionOnBadDataType
@return $this
@deprecated 5.2.0 Will be removed without equivalent functionality | setThrowExceptionOnBadDataType | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldPaginator.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldPaginator.php | BSD-3-Clause |
protected function checkDataType($dataList)
{
if ($dataList instanceof Limitable) {
return true;
} else {
// This will be changed to always throw an exception in a future major release.
if ($this->throwExceptionOnBadDataType) {
throw new LogicException(
static::class . " expects an SS_Limitable list to be passed to the GridField."
);
}
return false;
}
} | Check that this dataList is of the right data type.
Returns false if it's a bad data type, and if appropriate, throws an exception.
@param SS_List $dataList
@return bool | checkDataType | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldPaginator.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldPaginator.php | BSD-3-Clause |
protected function getGridPagerState(GridField $gridField)
{
return $gridField->State->GridFieldPaginator;
} | Retrieves/Sets up the state object used to store and retrieve information
about the current paging details of this GridField
@param GridField $gridField
@return GridState_Data | getGridPagerState | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldPaginator.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldPaginator.php | BSD-3-Clause |
public function getTemplateParameters(GridField $gridField)
{
if (!$this->checkDataType($gridField->getList())) {
return null;
}
$state = $this->getGridPagerState($gridField);
// Figure out which page and record range we're on
$totalRows = $this->totalItems;
if (!$totalRows) {
return null;
}
$totalPages = 1;
$firstShownRecord = 1;
$lastShownRecord = $totalRows;
if ($itemsPerPage = $this->getItemsPerPage()) {
$totalPages = (int)ceil($totalRows / $itemsPerPage);
if ($totalPages == 0) {
$totalPages = 1;
}
$firstShownRecord = ($state->currentPage - 1) * $itemsPerPage + 1;
if ($firstShownRecord > $totalRows) {
$firstShownRecord = $totalRows;
}
$lastShownRecord = $state->currentPage * $itemsPerPage;
if ($lastShownRecord > $totalRows) {
$lastShownRecord = $totalRows;
}
}
// If there is only 1 page for all the records in list, we don't need to go further
// to sort out those first page, last page, pre and next pages, etc
// we are not render those in to the paginator.
if ($totalPages === 1) {
return new ArrayData([
'OnlyOnePage' => true,
'FirstShownRecord' => $firstShownRecord,
'LastShownRecord' => $lastShownRecord,
'NumRecords' => $totalRows,
'NumPages' => $totalPages
]);
} else {
// First page button
$firstPage = new GridField_FormAction($gridField, 'pagination_first', 'First', 'paginate', 1);
$firstPage->addExtraClass('btn btn-secondary btn--hide-text btn-sm font-icon-angle-double-left ss-gridfield-pagination-action ss-gridfield-firstpage');
if ($state->currentPage == 1) {
$firstPage = $firstPage->performDisabledTransformation();
}
// Previous page button
$previousPageNum = $state->currentPage <= 1 ? 1 : $state->currentPage - 1;
$previousPage = new GridField_FormAction(
$gridField,
'pagination_prev',
'Previous',
'paginate',
$previousPageNum
);
$previousPage->addExtraClass('btn btn-secondary btn--hide-text btn-sm font-icon-angle-left ss-gridfield-pagination-action ss-gridfield-previouspage');
if ($state->currentPage == 1) {
$previousPage = $previousPage->performDisabledTransformation();
}
// Next page button
$nextPageNum = $state->currentPage >= $totalPages ? $totalPages : $state->currentPage + 1;
$nextPage = new GridField_FormAction(
$gridField,
'pagination_next',
'Next',
'paginate',
$nextPageNum
);
$nextPage->addExtraClass('btn btn-secondary btn--hide-text btn-sm font-icon-angle-right ss-gridfield-pagination-action ss-gridfield-nextpage');
if ($state->currentPage == $totalPages) {
$nextPage = $nextPage->performDisabledTransformation();
}
// Last page button
$lastPage = new GridField_FormAction($gridField, 'pagination_last', 'Last', 'paginate', $totalPages);
$lastPage->addExtraClass('btn btn-secondary btn--hide-text btn-sm font-icon-angle-double-right ss-gridfield-pagination-action ss-gridfield-lastpage');
if ($state->currentPage == $totalPages) {
$lastPage = $lastPage->performDisabledTransformation();
}
// Render in template
return new ArrayData([
'OnlyOnePage' => false,
'FirstPage' => $firstPage,
'PreviousPage' => $previousPage,
'CurrentPageNum' => $state->currentPage,
'NumPages' => $totalPages,
'NextPage' => $nextPage,
'LastPage' => $lastPage,
'FirstShownRecord' => $firstShownRecord,
'LastShownRecord' => $lastShownRecord,
'NumRecords' => $totalRows
]);
}
} | Determines arguments to be passed to the template for building this field
@param GridField $gridField
@return ArrayData If paging is available this will be an ArrayData
object of paging details with these parameters:
<ul>
<li>OnlyOnePage: boolean - Is there only one page?</li>
<li>FirstShownRecord: integer - Number of the first record displayed</li>
<li>LastShownRecord: integer - Number of the last record displayed</li>
<li>NumRecords: integer - Total number of records</li>
<li>NumPages: integer - The number of pages</li>
<li>CurrentPageNum (optional): integer - If OnlyOnePage is false, the number of the current page</li>
<li>FirstPage (optional): GridField_FormAction - Button to go to the first page</li>
<li>PreviousPage (optional): GridField_FormAction - Button to go to the previous page</li>
<li>NextPage (optional): GridField_FormAction - Button to go to the next page</li>
<li>LastPage (optional): GridField_FormAction - Button to go to last page</li>
</ul> | getTemplateParameters | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldPaginator.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldPaginator.php | BSD-3-Clause |
public function getGroup($gridField, $record, $columnName)
{
if (!$this->canUnlink($record)) {
return null;
}
return parent::getGroup($gridField, $record, $columnName);
} | Get the ActionMenu group (not related to Member group)
@param GridField $gridField
@param DataObject $record
@param $columnName
@return null|string | getGroup | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldGroupDeleteAction.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldGroupDeleteAction.php | BSD-3-Clause |
public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
$record = $gridField->getList()->find('ID', $arguments['RecordID']);
if (!$record || !$actionName == 'unlinkrelation' || $this->canUnlink($record)) {
parent::handleAction($gridField, $actionName, $arguments, $data);
return;
}
throw new ValidationException(
_t(__CLASS__ . '.UnlinkSelfFailure', 'Cannot remove yourself from this group, you will lose admin rights')
);
} | Handle the actions and apply any changes to the GridField
@param GridField $gridField
@param string $actionName
@param array $arguments
@param array $data Form data
@throws ValidationException | handleAction | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldGroupDeleteAction.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldGroupDeleteAction.php | BSD-3-Clause |
public function getColumnAttributes($gridField, $record, $columnName)
{
return ['class' => 'grid-field__col-compact'];
} | Return any special attributes that will be used for FormField::create_tag()
@param GridField $gridField
@param DataObjectInterface&ViewableData $record
@param string $columnName
@return array | getColumnAttributes | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldDeleteAction.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDeleteAction.php | BSD-3-Clause |
public function getColumnsHandled($gridField)
{
return ['Actions'];
} | Which columns are handled by this component
@param GridField $gridField
@return array | getColumnsHandled | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldDeleteAction.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDeleteAction.php | BSD-3-Clause |
public function getActions($gridField)
{
return ['deleterecord', 'unlinkrelation'];
} | Which GridField actions are this component handling
@param GridField $gridField
@return array | getActions | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldDeleteAction.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDeleteAction.php | BSD-3-Clause |
public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
$list = $gridField->getList();
if ($actionName == 'deleterecord' || $actionName == 'unlinkrelation') {
/** @var DataObjectInterface&ViewableData $item */
$item = $list->byID($arguments['RecordID']);
if (!$item) {
return;
}
if ($actionName == 'deleterecord') {
$this->checkForRequiredMethod($item, 'canDelete');
if (!$item->canDelete()) {
throw new ValidationException(
_t(__CLASS__ . '.DeletePermissionsFailure', "No delete permissions")
);
}
if (!($list instanceof DataList)) {
// We need to make sure to exclude the item since the list items have already been determined.
// This must happen before deletion while the item still has its ID set.
$gridField->setList($list->exclude(['ID' => $item->ID]));
}
$item->delete();
} else {
$this->checkForRequiredMethod($item, 'canEdit');
if (!$item->canEdit()) {
throw new ValidationException(
_t(__CLASS__ . '.EditPermissionsFailure', "No permission to unlink record")
);
}
$list->remove($item);
}
}
} | Handle the actions and apply any changes to the GridField
@param GridField $gridField
@param string $actionName
@param array $arguments
@param array $data Form data
@throws ValidationException | handleAction | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldDeleteAction.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDeleteAction.php | BSD-3-Clause |
public function getRemoveRelation()
{
return $this->removeRelation;
} | Get whether to remove or delete the relation
@return bool | getRemoveRelation | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldDeleteAction.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDeleteAction.php | BSD-3-Clause |
public function setRemoveRelation($removeRelation)
{
$this->removeRelation = (bool) $removeRelation;
return $this;
} | Set whether to remove or delete the relation
@param bool $removeRelation
@return $this | setRemoveRelation | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldDeleteAction.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDeleteAction.php | BSD-3-Clause |
public function setThrowExceptionOnBadDataType($throwExceptionOnBadDataType)
{
Deprecation::notice('5.2.0', 'Will be removed without equivalent functionality');
$this->throwExceptionOnBadDataType = $throwExceptionOnBadDataType;
} | Determine what happens when this component is used with a list that isn't {@link SS_Filterable}.
- true: An exception is thrown
- false: This component will be ignored - it won't make any changes to the GridField.
By default, this is set to true so that it's clearer what's happening, but the predefined
{@link GridFieldConfig} subclasses set this to false for flexibility.
@param bool $throwExceptionOnBadDataType
@deprecated 5.2.0 Will be removed without equivalent functionality | setThrowExceptionOnBadDataType | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldFilterHeader.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldFilterHeader.php | BSD-3-Clause |
protected function checkDataType($dataList)
{
if ($dataList instanceof Filterable) {
return true;
} else {
// This will be changed to always throw an exception in a future major release.
if ($this->throwExceptionOnBadDataType) {
throw new LogicException(
static::class . " expects an SS_Filterable list to be passed to the GridField."
);
}
return false;
}
} | Check that this dataList is of the right data type.
Returns false if it's a bad data type, and if appropriate, throws an exception.
@param SS_List $dataList
@return bool | checkDataType | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldFilterHeader.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldFilterHeader.php | BSD-3-Clause |
public function getActions($gridField)
{
if (!$this->checkDataType($gridField->getList())) {
return [];
}
return ['filter', 'reset'];
} | If the GridField has a filterable datalist, return an array of actions
@param GridField $gridField
@return array | getActions | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldFilterHeader.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldFilterHeader.php | BSD-3-Clause |
public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
if (!$this->checkDataType($gridField->getList())) {
return;
}
$state = $this->getState($gridField);
$state->Columns = [];
if ($actionName === 'filter') {
if (isset($data['filter'][$gridField->getName()])) {
foreach ($data['filter'][$gridField->getName()] as $key => $filter) {
$state->Columns->$key = $filter;
}
}
}
} | If the GridField has a filterable datalist, return an array of actions
@param GridField $gridField
@param string $actionName
@param array $data
@return void | handleAction | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldFilterHeader.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldFilterHeader.php | BSD-3-Clause |
public function getSearchContext(GridField $gridField)
{
if (!$this->searchContext) {
$modelClass = $gridField->getModelClass();
$singleton = singleton($modelClass);
if (!$singleton->hasMethod('getDefaultSearchContext')) {
throw new LogicException(
'Cannot dynamically instantiate SearchContext. Pass the SearchContext to setSearchContext()'
. " or implement a getDefaultSearchContext() method on $modelClass"
);
}
$list = $gridField->getList();
$searchContext = $singleton->getDefaultSearchContext();
// In case we are working with a list not backed by the database we need to convert the search context into a BasicSearchContext
// This is because the scaffolded filters use the ORM for data searching
if (!$list instanceof DataList) {
$searchContext = $this->getBasicSearchContext($gridField, $searchContext);
}
$this->searchContext = $searchContext;
}
return $this->searchContext;
} | Generate a search context based on the model class of the of the GridField
@param GridField $gridfield
@return SearchContext | getSearchContext | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldFilterHeader.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldFilterHeader.php | BSD-3-Clause |
public function getSearchFieldSchema(GridField $gridField)
{
Deprecation::noticeWithNoReplacment(
'5.4.0',
'Will be replaced with SilverStripe\ORM\Search\SearchContextForm::getSchemaData()'
);
$schemaUrl = Controller::join_links($gridField->Link(), 'schema/SearchForm');
$inst = singleton($gridField->getModelClass());
$context = $this->getSearchContext($gridField);
$params = $gridField->getRequest()->postVar('filter') ?: [];
if (array_key_exists($gridField->getName(), $params ?? [])) {
$params = $params[$gridField->getName()];
}
if ($context->getSearchParams()) {
$params = array_merge($context->getSearchParams(), $params);
}
$context->setSearchParams($params);
$searchField = $this->getSearchField() ?: $inst->config()->get('general_search_field');
if (!$searchField) {
$searchField = $context->getSearchFields()->first();
$searchField = $searchField && property_exists($searchField, 'name') ? $searchField->name : null;
}
// Prefix "Search__" onto the filters to match the field names in the actual form
$filters = $context->getSearchParams();
if (!empty($filters)) {
$filters = array_combine(array_map(function ($key) {
return 'Search__' . $key;
}, array_keys($filters ?? [])), $filters ?? []);
}
$searchAction = GridField_FormAction::create($gridField, 'filter', false, 'filter', null);
$clearAction = GridField_FormAction::create($gridField, 'reset', false, 'reset', null);
$schema = [
'formSchemaUrl' => $schemaUrl,
'name' => $searchField,
'placeholder' => $this->getPlaceHolder($inst),
'filters' => $filters ?: new \stdClass, // stdClass maps to empty json object '{}'
'gridfield' => $gridField->getName(),
'searchAction' => $searchAction->getAttribute('name'),
'searchActionState' => $searchAction->getAttribute('data-action-state'),
'clearAction' => $clearAction->getAttribute('name'),
'clearActionState' => $clearAction->getAttribute('data-action-state'),
];
return json_encode($schema);
} | Returns the search field schema for the component
@param GridField $gridfield
@return string
@deprecated 5.4.0 Will be replaced with SilverStripe\ORM\Search\SearchContextForm::getSchemaData() | getSearchFieldSchema | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldFilterHeader.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldFilterHeader.php | BSD-3-Clause |
public function getSearchFormSchema(GridField $gridField)
{
Deprecation::noticeWithNoReplacment(
'5.4.0',
'Will be replaced with SilverStripe\Forms\FormRequestHandler::getSchema()'
);
$form = $this->getSearchForm($gridField);
// If there are no filterable fields, return a 400 response
if (!$form) {
return new HTTPResponse(_t(__CLASS__ . '.SearchFormFaliure', 'No search form could be generated'), 400);
}
$parts = $gridField->getRequest()->getHeader(FormSchema::SCHEMA_HEADER);
$schemaID = $gridField->getRequest()->getURL();
$data = FormSchema::singleton()
->getMultipartSchema($parts, $schemaID, $form);
$response = new HTTPResponse(json_encode($data));
$response->addHeader('Content-Type', 'application/json');
return $response;
} | Returns the search form schema for the component
@param GridField $gridfield
@return HTTPResponse
@deprecated 5.4.0 Will be replaced with SilverStripe\Forms\FormRequestHandler::getSchema() | getSearchFormSchema | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldFilterHeader.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldFilterHeader.php | BSD-3-Clause |
public function getHTMLFragments($gridField)
{
$forTemplate = new ArrayData([]);
if (!$this->canFilterAnyColumns($gridField)) {
return null;
}
$fieldSchema = $this->getSearchFieldSchema($gridField);
$forTemplate->SearchFieldSchema = $fieldSchema;
$searchTemplates = SSViewer::get_templates_by_class($this, '_Search', __CLASS__);
return [
'before' => $forTemplate->renderWith($searchTemplates),
'buttons-before-right' => sprintf(
'<button type="button" name="showFilter" aria-label="%s" title="%s"' .
' class="btn btn-secondary font-icon-search btn--no-text btn--icon-large grid-field__filter-open"></button>',
_t('SilverStripe\\Forms\\GridField\\GridField.OpenFilter', "Open search and filter"),
_t('SilverStripe\\Forms\\GridField\\GridField.OpenFilter', "Open search and filter")
)
];
} | Either returns the legacy filter header or the search button and field
@param GridField $gridField
@return array|null | getHTMLFragments | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldFilterHeader.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldFilterHeader.php | BSD-3-Clause |
public function Value()
{
$data = $this->data ? $this->data->getChangesArray() : [];
return json_encode($data, JSON_FORCE_OBJECT);
} | Returns a json encoded string representation of this state.
@return string | Value | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridState.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridState.php | BSD-3-Clause |
public function dataValue()
{
return $this->Value();
} | Returns a json encoded string representation of this state.
@return string | dataValue | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridState.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridState.php | BSD-3-Clause |
public function getData($name, $default = null)
{
if (!array_key_exists($name, $this->data ?? [])) {
$this->data[$name] = $default;
} else {
if (is_array($this->data[$name])) {
$this->data[$name] = new GridState_Data($this->data[$name]);
}
}
return $this->data[$name];
} | Retrieve the value for the given key
@param string $name The name of the value to retrieve
@param mixed $default Default value to assign if not set. Note that this *will* be included in getChangesArray()
@return mixed The value associated with this key, or the value specified by $default if not set | getData | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridState_Data.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridState_Data.php | BSD-3-Clause |
public function getHTMLFragments($gridField)
{
$button = new GridField_FormAction(
$gridField,
'export',
_t('SilverStripe\\Forms\\GridField\\GridField.CSVEXPORT', 'Export to CSV'),
'export',
null
);
$button->addExtraClass('btn btn-secondary no-ajax font-icon-down-circled action_export');
$button->setForm($gridField->getForm());
return [
$this->targetFragment => $button->Field(),
];
} | Place the export button in a <p> tag below the field
@param GridField $gridField
@return array | getHTMLFragments | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldExportButton.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldExportButton.php | BSD-3-Clause |
public function handleExport($gridField, $request = null)
{
$now = date("d-m-Y-H-i");
$fileName = "export-$now.csv";
if ($fileData = $this->generateExportFileData($gridField)) {
return HTTPRequest::send_file($fileData, $fileName, 'text/csv');
}
return null;
} | Handle the export, for both the action button and the URL
@param GridField $gridField
@param HTTPRequest $request
@return HTTPResponse | handleExport | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldExportButton.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldExportButton.php | BSD-3-Clause |
public function getHTMLFragments($gridField)
{
$modalID = $gridField->ID() . '_ImportModal';
// Check for form message prior to rendering form (which clears session messages)
$form = $this->getImportForm();
$hasMessage = $form && $form->getMessage();
// Render modal
$template = SSViewer::get_templates_by_class(static::class, '_Modal');
$viewer = new ArrayData([
'ImportModalTitle' => $this->getModalTitle(),
'ImportModalID' => $modalID,
'ImportIframe' => $this->getImportIframe(),
'ImportForm' => $this->getImportForm(),
]);
$modal = $viewer->renderWith($template)->forTemplate();
// Build action button
$button = new GridField_FormAction(
$gridField,
'import',
_t('SilverStripe\\Forms\\GridField\\GridField.CSVIMPORT', 'Import CSV'),
'import',
null
);
$button
->addExtraClass('btn btn-secondary font-icon-upload btn--icon-large action_import')
->setForm($gridField->getForm())
->setAttribute('data-toggle', 'modal')
->setAttribute('aria-controls', $modalID)
->setAttribute('data-target', "#{$modalID}")
->setAttribute('data-modal', $modal);
// If form has a message, trigger it to automatically open
if ($hasMessage) {
$button->setAttribute('data-state', 'open');
}
return [
$this->targetFragment => $button->Field()
];
} | Place the export button in a <p> tag below the field
@param GridField $gridField
@return array | getHTMLFragments | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldImportButton.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldImportButton.php | BSD-3-Clause |
protected function getPaginator($gridField)
{
$paginator = $gridField->getConfig()->getComponentByType(GridFieldPaginator::class);
if (!$paginator && GridFieldPageCount::config()->uninherited('require_paginator')) {
throw new LogicException(
static::class . " relies on a GridFieldPaginator to be added " . "to the same GridField, but none are present."
);
}
return $paginator;
} | Retrieves an instance of a GridFieldPaginator attached to the same control
@param GridField $gridField The parent gridfield
@return GridFieldPaginator The attached GridFieldPaginator, if found.
@throws LogicException | getPaginator | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldPageCount.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldPageCount.php | BSD-3-Clause |
public function getColumnAttributes($gridField, $record, $columnName)
{
return ['class' => 'grid-field__col-compact'];
} | Return any special attributes that will be used for FormField::create_tag()
@param GridField $gridField
@param ViewableData $record
@param string $columnName
@return array | getColumnAttributes | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldEditButton.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldEditButton.php | BSD-3-Clause |
public function getColumnsHandled($gridField)
{
return ['Actions'];
} | Which columns are handled by this component
@param GridField $gridField
@return array | getColumnsHandled | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldEditButton.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldEditButton.php | BSD-3-Clause |
public function getActions($gridField)
{
return [];
} | Which GridField actions are this component handling.
@param GridField $gridField
@return array | getActions | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldEditButton.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldEditButton.php | BSD-3-Clause |
public function getExtraClass()
{
return implode(' ', array_keys($this->extraClass ?? []));
} | Get the extra HTML classes to add for edit buttons
@return string | getExtraClass | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldEditButton.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldEditButton.php | BSD-3-Clause |
public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
} | Handle the actions and apply any changes to the GridField.
@param GridField $gridField
@param string $actionName
@param mixed $arguments
@param array $data - form data
@return void | handleAction | php | silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldEditButton.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldEditButton.php | BSD-3-Clause |
public function save($id, array $state)
{
$this->getRequest()->getSession()->set($id, $state);
// This adapter does not require any additional attributes...
return [];
} | Save the given state against the given ID returning an associative array to be added as attributes on the form
action
@param string $id
@param array $state
@return array | save | php | silverstripe/silverstripe-framework | src/Forms/GridField/FormAction/SessionStore.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/FormAction/SessionStore.php | BSD-3-Clause |
public function save($id, array $state)
{
// Just save the state in the attributes of the action
return [
'data-action-state' => json_encode($state),
];
} | Save the given state against the given ID returning an associative array to be added as attributes on the form
action
@param string $id
@param array $state
@return array | save | php | silverstripe/silverstripe-framework | src/Forms/GridField/FormAction/AttributeStore.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/FormAction/AttributeStore.php | BSD-3-Clause |
public function getState(Form $form)
{
$state = [
'id' => $form->FormName(),
'fields' => [],
'messages' => [],
'notifyUnsavedChanges' => $form->getNotifyUnsavedChanges(),
];
// flattened nested fields are returned, rather than only top level fields.
$state['fields'] = array_merge(
$this->getFieldStates($form->Fields()),
$this->getFieldStates($form->Actions())
);
if ($message = $form->getSchemaMessage()) {
$state['messages'][] = $message;
}
return $state;
} | Gets the current state of this form as a nested array.
@param Form $form
@return array | getState | php | silverstripe/silverstripe-framework | src/Forms/Schema/FormSchema.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/Schema/FormSchema.php | BSD-3-Clause |
public static function filename2url($filename)
{
$filename = realpath($filename ?? '');
if (!$filename) {
return null;
}
// Filter files outside of the webroot
$base = realpath(BASE_PATH);
$baseLength = strlen($base ?? '');
if (substr($filename ?? '', 0, $baseLength) !== $base) {
return null;
}
$relativePath = ltrim(substr($filename ?? '', $baseLength ?? 0), '/\\');
return Director::absoluteURL($relativePath);
} | Turns a local system filename into a URL by comparing it to the script filename.
@param string $filename
@return string | filename2url | php | silverstripe/silverstripe-framework | src/Control/HTTP.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTP.php | BSD-3-Clause |
public static function absoluteURLs($html)
{
$html = str_replace('$CurrentPageURL', Controller::curr()->getRequest()->getURL() ?? '', $html ?? '');
return HTTP::urlRewriter($html, function ($url) {
//no need to rewrite, if uri has a protocol (determined here by existence of reserved URI character ":")
if (preg_match('/^\w+:/', $url ?? '')) {
return $url;
}
return Director::absoluteURL((string) $url);
});
} | Turn all relative URLs in the content to absolute URLs.
@param string $html
@return string | absoluteURLs | php | silverstripe/silverstripe-framework | src/Control/HTTP.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTP.php | BSD-3-Clause |
public static function setGetVar($varname, $varvalue, $currentURL = null, $separator = '&')
{
if (!isset($currentURL)) {
$request = Controller::curr()->getRequest();
$currentURL = $request->getURL(true);
}
$uri = $currentURL;
$isRelative = false;
// We need absolute URLs for parse_url()
if (Director::is_relative_url($uri)) {
$uri = Controller::join_links(Director::absoluteBaseURL(), $uri);
$isRelative = true;
}
// try to parse uri
$parts = parse_url($uri ?? '');
if (!$parts) {
throw new InvalidArgumentException("Can't parse URL: " . $uri);
}
// Parse params and add new variable
$params = [];
if (isset($parts['query'])) {
parse_str($parts['query'] ?? '', $params);
}
$params[$varname] = $varvalue;
// Generate URI segments and formatting
$scheme = (isset($parts['scheme'])) ? $parts['scheme'] : 'http';
$user = (isset($parts['user']) && $parts['user'] != '') ? $parts['user'] : '';
if ($user != '') {
// format in either user:[email protected] or [email protected]
$user .= (isset($parts['pass']) && $parts['pass'] != '') ? ':' . $parts['pass'] . '@' : '@';
}
$host = (isset($parts['host'])) ? $parts['host'] : '';
$port = (isset($parts['port']) && $parts['port'] != '') ? ':' . $parts['port'] : '';
$path = (isset($parts['path']) && $parts['path'] != '') ? $parts['path'] : '';
// handle URL params which are existing / new
$params = ($params) ? '?' . http_build_query($params, '', $separator) : '';
// keep fragments (anchors) intact.
$fragment = (isset($parts['fragment']) && $parts['fragment'] != '') ? '#' . $parts['fragment'] : '';
// Recompile URI segments
$newUri = $scheme . '://' . $user . $host . $port . $path . $params . $fragment;
if ($isRelative) {
return Controller::join_links(Director::baseURL(), Director::makeRelative($newUri));
}
return $newUri;
} | Will try to include a GET parameter for an existing URL, preserving existing parameters and
fragments. If no URL is given, falls back to $_SERVER['REQUEST_URI']. Uses parse_url() to
dissect the URL, and http_build_query() to reconstruct it with the additional parameter.
Converts any '&' (ampersand) URL parameter separators to the more XHTML compliant '&'.
CAUTION: If the URL is determined to be relative, it is prepended with Director::absoluteBaseURL().
This method will always return an absolute URL because Director::makeRelative() can lead to
inconsistent results.
@param string $varname
@param string $varvalue
@param string|null $currentURL Relative or absolute URL, or HTTPRequest to get url from
@param string $separator Separator for http_build_query().
@return string | setGetVar | php | silverstripe/silverstripe-framework | src/Control/HTTP.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTP.php | BSD-3-Clause |
public static function findByTagAndAttribute($content, $attributes)
{
$regexes = [];
foreach ($attributes as $tag => $attribute) {
$regexes[] = "/<{$tag} [^>]*$attribute *= *([\"'])(.*?)\\1[^>]*>/i";
$regexes[] = "/<{$tag} [^>]*$attribute *= *([^ \"'>]+)/i";
}
$result = [];
if ($regexes) {
foreach ($regexes as $regex) {
if (preg_match_all($regex ?? '', $content ?? '', $matches)) {
$result = array_merge_recursive($result, (isset($matches[2]) ? $matches[2] : $matches[1]));
}
}
}
return count($result ?? []) ? $result : null;
} | Search for all tags with a specific attribute, then return the value of that attribute in a
flat array.
@param string $content
@param array $attributes An array of tags to attributes, for example "[a] => 'href', [div] => 'id'"
@return array | findByTagAndAttribute | php | silverstripe/silverstripe-framework | src/Control/HTTP.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTP.php | BSD-3-Clause |
public static function get_mime_type($filename)
{
// If the finfo module is compiled into PHP, use it.
$path = BASE_PATH . DIRECTORY_SEPARATOR . $filename;
if (class_exists('finfo') && file_exists($path ?? '')) {
$finfo = new finfo(FILEINFO_MIME_TYPE);
return $finfo->file($path);
}
// Fallback to use the list from the HTTP.yml configuration and rely on the file extension
// to get the file mime-type
$ext = strtolower(File::get_file_extension($filename) ?? '');
// Get the mime-types
$mimeTypes = HTTP::config()->uninherited('MimeTypes');
// The mime type doesn't exist
if (!isset($mimeTypes[$ext])) {
return 'application/unknown';
}
return $mimeTypes[$ext];
} | Get the MIME type based on a file's extension. If the finfo class exists in PHP, and the file
exists relative to the project root, then use that extension, otherwise fallback to a list of
commonly known MIME types.
@param string $filename
@return string | get_mime_type | php | silverstripe/silverstripe-framework | src/Control/HTTP.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTP.php | BSD-3-Clause |
public static function test(
$url,
$postVars = [],
$session = [],
$httpMethod = null,
$body = null,
$headers = [],
$cookies = [],
&$request = null
) {
return static::mockRequest(
function (HTTPRequest $request) {
return Director::singleton()->handleRequest($request);
},
$url,
$postVars,
$session,
$httpMethod,
$body,
$headers,
$cookies,
$request
);
} | Test a URL request, returning a response object. This method is a wrapper around
Director::handleRequest() to assist with functional testing. It will execute the URL given, and
return the result as an HTTPResponse object.
@param string $url The URL to visit.
@param array $postVars The $_POST & $_FILES variables.
@param array|Session $session The {@link Session} object representing the current session.
By passing the same object to multiple calls of Director::test(), you can simulate a persisted
session.
@param string $httpMethod The HTTP method, such as GET or POST. It will default to POST if
postVars is set, GET otherwise. Overwritten by $postVars['_method'] if present.
@param string $body The HTTP body.
@param array $headers HTTP headers with key-value pairs.
@param array|Cookie_Backend $cookies to populate $_COOKIE.
@param HTTPRequest $request The {@see SS_HTTP_Request} object generated as a part of this request.
@return HTTPResponse
@throws HTTPResponse_Exception | test | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function get_current_page()
{
return Director::$current_page ? Director::$current_page : Controller::curr();
} | Return the {@link SiteTree} object that is currently being viewed. If there is no SiteTree
object to return, then this will return the current controller.
@return SiteTree|Controller | get_current_page | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
protected static function parseHost($url)
{
// Get base hostname
$host = parse_url($url ?? '', PHP_URL_HOST);
if (!$host) {
return null;
}
// Include port
$port = parse_url($url ?? '', PHP_URL_PORT);
if ($port) {
$host .= ':' . $port;
}
return $host;
} | Return only host (and optional port) part of a url
@param string $url
@return string|null Hostname, and optional port, or null if not a valid host | parseHost | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
protected static function validateUserAndPass($url)
{
$parsedURL = parse_url($url ?? '');
// Validate user (disallow slashes)
if (!empty($parsedURL['user']) && strstr($parsedURL['user'] ?? '', '\\')) {
return false;
}
if (!empty($parsedURL['pass']) && strstr($parsedURL['pass'] ?? '', '\\')) {
return false;
}
return true;
} | Validate user and password in URL, disallowing slashes
@param string $url
@return bool | validateUserAndPass | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function host(HTTPRequest $request = null)
{
// Check if overridden by alternate_base_url
if ($baseURL = static::config()->get('alternate_base_url')) {
$baseURL = Injector::inst()->convertServiceProperty($baseURL);
$host = static::parseHost($baseURL);
if ($host) {
return $host;
}
}
$request = static::currentRequest($request);
if ($request && ($host = $request->getHeader('Host'))) {
return $host;
}
// Check given header
if (isset($_SERVER['HTTP_HOST'])) {
return $_SERVER['HTTP_HOST'];
}
// Check base url
if ($baseURL = static::config()->uninherited('default_base_url')) {
$baseURL = Injector::inst()->convertServiceProperty($baseURL);
$host = static::parseHost($baseURL);
if ($host) {
return $host;
}
}
// Fail over to server_name (least reliable)
return isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : gethostname();
} | A helper to determine the current hostname used to access the site.
The following are used to determine the host (in order)
- Director.alternate_base_url (if it contains a domain name)
- Trusted proxy headers
- HTTP Host header
- SS_BASE_URL env var
- SERVER_NAME
- gethostname()
@param HTTPRequest $request
@return string Host name, including port (if present) | host | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function port(HTTPRequest $request = null)
{
$host = static::host($request);
return (int)parse_url($host ?? '', PHP_URL_PORT) ?: null;
} | Return port used for the base URL.
Note, this will be null if not specified, in which case you should assume the default
port for the current protocol.
@param HTTPRequest $request
@return int|null | port | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function protocolAndHost(HTTPRequest $request = null)
{
return static::protocol($request) . static::host($request);
} | Returns the domain part of the URL 'http://www.mysite.com'. Returns FALSE is this environment
variable isn't set.
@param HTTPRequest $request
@return bool|string | protocolAndHost | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function protocol(HTTPRequest $request = null)
{
return (Director::is_https($request)) ? 'https://' : 'http://';
} | Return the current protocol that the site is running under.
@param HTTPRequest $request
@return string | protocol | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function is_https(HTTPRequest $request = null)
{
// Check override from alternate_base_url
if ($baseURL = static::config()->uninherited('alternate_base_url')) {
$baseURL = Injector::inst()->convertServiceProperty($baseURL);
$protocol = parse_url($baseURL ?? '', PHP_URL_SCHEME);
if ($protocol) {
return $protocol === 'https';
}
}
// Check the current request
$request = static::currentRequest($request);
if ($request && ($scheme = $request->getScheme())) {
return $scheme === 'https';
}
// Check default_base_url
if ($baseURL = static::config()->uninherited('default_base_url')) {
$baseURL = Injector::inst()->convertServiceProperty($baseURL);
$protocol = parse_url($baseURL ?? '', PHP_URL_SCHEME);
if ($protocol) {
return $protocol === 'https';
}
}
return false;
} | Return whether the site is running as under HTTPS.
@param HTTPRequest $request
@return bool | is_https | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function baseURL()
{
// Check override base_url
$alternate = static::config()->get('alternate_base_url');
if ($alternate) {
$alternate = Injector::inst()->convertServiceProperty($alternate);
return rtrim(parse_url($alternate ?? '', PHP_URL_PATH) ?? '', '/') . '/';
}
// Get env base url
$baseURL = rtrim(BASE_URL, '/') . '/';
// Check if BASE_SCRIPT_URL is defined
// e.g. `index.php/`
if (defined('BASE_SCRIPT_URL')) {
return $baseURL . BASE_SCRIPT_URL;
}
return $baseURL;
} | Return the root-relative url for the baseurl
@return string Root-relative url with trailing slash. | baseURL | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function baseFolder()
{
$alternate = Director::config()->uninherited('alternate_base_folder');
return $alternate ?: BASE_PATH;
} | Returns the root filesystem folder for the site. It will be automatically calculated unless
it is overridden with {@link setBaseFolder()}.
@return string | baseFolder | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function publicDir()
{
return PUBLIC_DIR;
} | The name of the public directory
@return string | publicDir | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function is_absolute($path)
{
if (empty($path)) {
return false;
}
if ($path[0] == '/' || $path[0] == '\\') {
return true;
}
return preg_match('/^[a-zA-Z]:[\\\\\/]/', $path ?? '') == 1;
} | Returns true if a given path is absolute. Works under both *nix and windows systems.
@param string $path
@return bool | is_absolute | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function is_root_relative_url($url)
{
return strpos($url ?? '', '/') === 0 && strpos($url ?? '', '//') !== 0;
} | Determine if the url is root relative (i.e. starts with /, but not with //) SilverStripe
considers root relative urls as a subset of relative urls.
@param string $url
@return bool | is_root_relative_url | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function is_absolute_url($url)
{
// Strip off the query and fragment parts of the URL before checking
if (($queryPosition = strpos($url ?? '', '?')) !== false) {
$url = substr($url ?? '', 0, $queryPosition - 1);
}
if (($hashPosition = strpos($url ?? '', '#')) !== false) {
$url = substr($url ?? '', 0, $hashPosition - 1);
}
$colonPosition = strpos($url ?? '', ':');
$slashPosition = strpos($url ?? '', '/');
return (
// Base check for existence of a host on a compliant URL
parse_url($url ?? '', PHP_URL_HOST)
// Check for more than one leading slash (forward or backward) without a protocol.
// While not a RFC compliant absolute URL, it is completed to a valid URL by some browsers,
// and hence a potential security risk. Single leading slashes are not an issue though.
// Note: Need 4 backslashes to have a single non-escaped backslash for regex.
|| preg_match('%^\s*(\\\\|/){2,}%', $url ?? '')
|| (
// If a colon is found, check if it's part of a valid scheme definition
// (meaning its not preceded by a slash).
$colonPosition !== false
&& ($slashPosition === false || $colonPosition < $slashPosition)
)
);
} | Checks if a given URL is absolute (e.g. starts with 'http://' etc.). URLs beginning with "//"
are treated as absolute, as browsers take this to mean the same protocol as currently being used.
Useful to check before redirecting based on a URL from user submissions through $_GET or $_POST,
and avoid phishing attacks by redirecting to an attackers server.
Note: Can't solely rely on PHP's parse_url() , since it is not intended to work with relative URLs
or for security purposes. filter_var($url, FILTER_VALIDATE_URL) has similar problems.
@param string $url
@return bool | is_absolute_url | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function is_site_url($url)
{
// Validate user and password
if (!static::validateUserAndPass($url)) {
return false;
}
// Validate host[:port]
$urlHost = static::parseHost($url);
if ($urlHost && $urlHost === static::host()) {
return true;
}
// Allow extensions to weigh in
$isSiteUrl = false;
// Not using static::singleton() here because it can break
// functional tests such as those in HTTPCacheControlIntegrationTest
// This happens because a singleton of Director is instantiating prior to tests being run,
// because Controller::normaliseTrailingSlash() is called during SapphireTest::setUp(),
// which in turn calls Director::is_site_url()
// For this specific use case we don't need to use dependency injection because the
// chance of the extend() method being customised in projects is low.
// Any extension hooks implementing updateIsSiteUrl() will still be called as expected
$director = new static();
$director->extend('updateIsSiteUrl', $isSiteUrl, $url);
if ($isSiteUrl) {
return true;
}
// Relative urls always are site urls
return Director::is_relative_url($url);
} | Checks if the given URL is belonging to this "site" (not an external link). That's the case if
the URL is relative, as defined by {@link is_relative_url()}, or if the host matches
{@link protocolAndHost()}.
Useful to check before redirecting based on a URL from user submissions through $_GET or $_POST,
and avoid phishing attacks by redirecting to an attackers server.
Provides an extension point to allow extra checks on the URL to allow some external URLs,
e.g. links on secondary domains that point to the same CMS, or subsite domains.
@param string $url
@return bool | is_site_url | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function getAbsFile($file)
{
// If already absolute
if (Director::is_absolute($file)) {
return $file;
}
// If path is relative to public folder search there first
if (Director::publicDir()) {
$path = Path::join(Director::publicFolder(), $file);
if (file_exists($path ?? '')) {
return $path;
}
}
// Default to base folder
return Path::join(Director::baseFolder(), $file);
} | Given a filesystem reference relative to the site root, return the full file-system path.
@param string $file
@return string | getAbsFile | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function fileExists($file)
{
// replace any appended query-strings, e.g. /path/to/foo.php?bar=1 to /path/to/foo.php
$file = preg_replace('/([^\?]*)?.*/', '$1', $file ?? '');
return file_exists(Director::getAbsFile($file) ?? '');
} | Returns true if the given file exists. Filename should be relative to the site root.
@param $file
@return bool | fileExists | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function absoluteBaseURL()
{
$baseURL = Director::absoluteURL(
Director::baseURL(),
Director::ROOT
);
return Controller::normaliseTrailingSlash($baseURL);
} | Returns the Absolute URL of the site root.
@return string | absoluteBaseURL | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function absoluteBaseURLWithAuth(HTTPRequest $request = null)
{
// Detect basic auth
$login = '';
if ($request) {
$user = $request->getHeader('PHP_AUTH_USER');
if ($user) {
$password = $request->getHeader('PHP_AUTH_PW');
$login = sprintf("%s:%s@", $user, $password);
}
}
return Director::protocol($request) . $login . static::host($request) . Director::baseURL();
} | Returns the Absolute URL of the site root, embedding the current basic-auth credentials into
the URL.
@param HTTPRequest|null $request
@return string | absoluteBaseURLWithAuth | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
protected static function force_redirect($destURL)
{
// Redirect to installer
$response = new HTTPResponse();
$response->redirect($destURL, 301);
throw new HTTPResponse_Exception($response);
} | Skip any further processing and immediately respond with a redirect to the passed URL.
@param string $destURL
@throws HTTPResponse_Exception | force_redirect | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function forceWWW(HTTPRequest $request = null)
{
$handler = CanonicalURLMiddleware::singleton()->setForceWWW(true);
$handler->throwRedirectIfNeeded($request);
} | Force a redirect to a domain starting with "www."
@param HTTPRequest $request | forceWWW | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function is_ajax(HTTPRequest $request = null)
{
$request = Director::currentRequest($request);
if ($request) {
return $request->isAjax();
}
return (
isset($_REQUEST['ajax']) ||
(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest")
);
} | Checks if the current HTTP-Request is an "Ajax-Request" by checking for a custom header set by
jQuery or whether a manually set request-parameter 'ajax' is present.
Note that if you plan to use this to alter your HTTP response on a cached page,
you should add X-Requested-With to the Vary header.
@param HTTPRequest $request
@return bool | is_ajax | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function is_cli()
{
return Environment::isCli();
} | Returns true if this script is being run from the command line rather than the web server.
@return bool | is_cli | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function get_session_environment_type(HTTPRequest $request = null)
{
Deprecation::notice('5.4.0', 'Use get_environment_type() instead.');
$request = static::currentRequest($request);
if (!$request) {
return null;
}
$session = $request->getSession();
if (!empty($session->get('isDev'))) {
return Kernel::DEV;
} elseif (!empty($session->get('isTest'))) {
return Kernel::TEST;
}
} | Returns the session environment override
@internal This method is not a part of public API and will be deleted without a deprecation warning
@param HTTPRequest $request
@return string|null null if not overridden, otherwise the actual value
@deprecated 5.4.0 Use get_environment_type() instead. | get_session_environment_type | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function isLive()
{
return Director::get_environment_type() === 'live';
} | This function will return true if the site is in a live environment. For information about
environment types, see {@link Director::set_environment_type()}.
@return bool | isLive | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function isDev()
{
return Director::get_environment_type() === 'dev';
} | This function will return true if the site is in a development environment. For information about
environment types, see {@link Director::set_environment_type()}.
@return bool | isDev | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function isTest()
{
return Director::get_environment_type() === 'test';
} | This function will return true if the site is in a test environment. For information about
environment types, see {@link Director::set_environment_type()}.
@return bool | isTest | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function get_template_global_variables()
{
return [
'absoluteBaseURL',
'baseURL',
'isDev',
'isTest',
'isLive',
'is_ajax',
'isAjax' => 'is_ajax',
'BaseHref' => 'absoluteBaseURL',
];
} | Returns an array of strings of the method names of methods on the call that should be exposed
as global variables in the templates.
@return array | get_template_global_variables | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
protected static function currentRequest(HTTPRequest $request = null)
{
// Ensure we only use a registered HTTPRequest and don't
// incidentally construct a singleton
if (!$request && Injector::inst()->has(HTTPRequest::class)) {
$request = Injector::inst()->get(HTTPRequest::class);
}
return $request;
} | Helper to validate or check the current request object
@param HTTPRequest $request
@return HTTPRequest Request object if one is both current and valid | currentRequest | php | silverstripe/silverstripe-framework | src/Control/Director.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Director.php | BSD-3-Clause |
public static function enabled_for($response)
{
$contentType = $response->getHeader("Content-Type");
// Disable content negotiation for other content types
if ($contentType
&& substr($contentType ?? '', 0, 9) != 'text/html'
&& substr($contentType ?? '', 0, 21) != 'application/xhtml+xml'
) {
return false;
}
if (ContentNegotiator::getEnabled()) {
return true;
} else {
return (substr($response->getBody() ?? '', 0, 5) == '<' . '?xml');
}
} | Returns true if negotiation is enabled for the given response. By default, negotiation is only
enabled for pages that have the xml header.
@param HTTPResponse $response
@return bool | enabled_for | php | silverstripe/silverstripe-framework | src/Control/ContentNegotiator.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/ContentNegotiator.php | BSD-3-Clause |
public static function getEnabled()
{
if (isset(static::$current_enabled)) {
return static::$current_enabled;
}
return Config::inst()->get(static::class, 'enabled');
} | Gets the current enabled status, if it is not set this will fallback to config
@return bool | getEnabled | php | silverstripe/silverstripe-framework | src/Control/ContentNegotiator.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/ContentNegotiator.php | BSD-3-Clause |
public static function setEnabled($enabled)
{
static::$current_enabled = $enabled;
} | Sets the current enabled status
@param bool $enabled | setEnabled | php | silverstripe/silverstripe-framework | src/Control/ContentNegotiator.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/ContentNegotiator.php | BSD-3-Clause |
public function setFragmentOverride($fragments)
{
if (!is_array($fragments)) {
throw new InvalidArgumentException("fragments must be an array");
}
$this->fragmentOverride = $fragments;
return $this;
} | Set up fragment overriding - will completely replace the incoming fragments.
@param array $fragments Fragments to insert.
@return $this | setFragmentOverride | php | silverstripe/silverstripe-framework | src/Control/PjaxResponseNegotiator.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/PjaxResponseNegotiator.php | BSD-3-Clause |
public function process()
{
} | Overload this method to contain the task logic. | process | php | silverstripe/silverstripe-framework | src/Control/CliController.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/CliController.php | BSD-3-Clause |
public function __construct(Kernel $kernel)
{
$this->kernel = $kernel;
} | Initialize the application with a kernel instance
@param Kernel $kernel | __construct | php | silverstripe/silverstripe-framework | src/Control/HTTPApplication.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPApplication.php | BSD-3-Clause |
public function setFlushDiscoverer(FlushDiscoverer $discoverer)
{
$this->flushDiscoverer = $discoverer;
return $this;
} | Override the default flush discovery
@param FlushDiscoverer $discoverer
@return $this | setFlushDiscoverer | php | silverstripe/silverstripe-framework | src/Control/HTTPApplication.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPApplication.php | BSD-3-Clause |
public function getFlushDiscoverer(HTTPRequest $request)
{
if ($this->flushDiscoverer) {
return $this->flushDiscoverer;
}
return new CompositeFlushDiscoverer([
new ScheduledFlushDiscoverer($this->kernel),
new DeployFlushDiscoverer($this->kernel),
new RequestFlushDiscoverer($request, $this->getEnvironmentType())
]);
} | Returns the current flush discoverer
@param HTTPRequest $request a request to probe for flush parameters
@return FlushDiscoverer | getFlushDiscoverer | php | silverstripe/silverstripe-framework | src/Control/HTTPApplication.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPApplication.php | BSD-3-Clause |
protected function getEnvironmentType()
{
$kernel_env = $this->kernel->getEnvironment();
$server_env = Environment::getEnv('SS_ENVIRONMENT_TYPE');
$env = !is_null($kernel_env) ? $kernel_env : $server_env;
return $env;
} | Return the current environment type (dev, test or live)
Only checks Kernel and Server ENV as we
don't have sessions initialized yet
@return string | getEnvironmentType | php | silverstripe/silverstripe-framework | src/Control/HTTPApplication.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPApplication.php | BSD-3-Clause |
public function getKernel()
{
return $this->kernel;
} | Get the kernel for this application
@return Kernel | getKernel | php | silverstripe/silverstripe-framework | src/Control/HTTPApplication.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPApplication.php | BSD-3-Clause |
protected function handleAction($request, $action)
{
$classMessage = Director::isLive() ? 'on this handler' : 'on class ' . static::class;
if (!$this->hasMethod($action)) {
return new HTTPResponse("Action '$action' isn't available $classMessage.", 404);
}
$res = $this->extend('beforeCallActionHandler', $request, $action);
if ($res) {
return reset($res);
}
$actionRes = $this->$action($request);
$res = $this->extend('afterCallActionHandler', $request, $action, $actionRes);
if ($res) {
return reset($res);
}
return $actionRes;
} | Given a request, and an action name, call that action name on this RequestHandler
Must not raise HTTPResponse_Exceptions - instead it should return
@param $request
@param $action
@return HTTPResponse | handleAction | php | silverstripe/silverstripe-framework | src/Control/RequestHandler.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/RequestHandler.php | BSD-3-Clause |
public function allowedActions($limitToClass = null)
{
if ($limitToClass) {
$actions = Config::forClass($limitToClass)->get('allowed_actions', true);
} else {
$actions = $this->config()->get('allowed_actions');
}
if (is_array($actions)) {
if (array_key_exists('*', $actions ?? [])) {
throw new InvalidArgumentException("Invalid allowed_action '*'");
}
// convert all keys and values to lowercase to
// allow for easier comparison, unless it is a permission code
$actions = array_change_key_case($actions ?? [], CASE_LOWER);
foreach ($actions as $key => $value) {
if (is_numeric($key)) {
$actions[$key] = strtolower($value ?? '');
}
}
return $actions;
} else {
return null;
}
} | Get a array of allowed actions defined on this controller,
any parent classes or extensions.
Caution: Since 3.1, allowed_actions definitions only apply
to methods on the controller they're defined on,
so it is recommended to use the $class argument
when invoking this method.
@param string $limitToClass
@return array|null | allowedActions | php | silverstripe/silverstripe-framework | src/Control/RequestHandler.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/RequestHandler.php | BSD-3-Clause |
public function getRequest()
{
return $this->request;
} | Returns the HTTPRequest object that this controller is using.
Returns a placeholder {@link NullHTTPRequest} object unless
{@link handleAction()} or {@link handleRequest()} have been called,
which adds a reference to an actual {@link HTTPRequest} object.
@return HTTPRequest | getRequest | php | silverstripe/silverstripe-framework | src/Control/RequestHandler.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/RequestHandler.php | BSD-3-Clause |
public function Link($action = null)
{
// Check configured url_segment
$url = $this->config()->get('url_segment');
if ($url) {
$link = Controller::join_links($url, $action);
// Give extensions the chance to modify by reference
$this->extend('updateLink', $link, $action);
return $link;
}
// no link defined by default
trigger_error(
'Request handler ' . static::class . ' does not have a url_segment defined. ' . 'Relying on this link may be an application error',
E_USER_WARNING
);
return null;
} | Returns a link to this controller.
Returns null if no link could be generated.
Overload with your own Link rules if they exist.
@param string $action Optional action
@return ?string | Link | php | silverstripe/silverstripe-framework | src/Control/RequestHandler.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/RequestHandler.php | BSD-3-Clause |
public function getBackURL()
{
$request = $this->getRequest();
if (!$request) {
return null;
}
$backURL = $request->requestVar('BackURL');
// Fall back to X-Backurl header
if (!$backURL && $request->isAjax() && $request->getHeader('X-Backurl')) {
$backURL = $request->getHeader('X-Backurl');
}
if (!$backURL) {
return null;
}
if (Director::is_site_url($backURL)) {
return $backURL;
}
return null;
} | Safely get the value of the BackURL param, if provided via querystring / posted var
@return string | getBackURL | php | silverstripe/silverstripe-framework | src/Control/RequestHandler.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/RequestHandler.php | BSD-3-Clause |
protected function init()
{
// This is used to test that subordinate controllers are actually calling parent::init() - a common bug
$this->baseInitCalled = true;
} | Initialisation function that is run before any action on the controller is called.
@uses BasicAuth::requireLogin() | init | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
public function doInit()
{
//extension hook
$this->extend('onBeforeInit');
// Safety call
$this->baseInitCalled = false;
$this->init();
if (!$this->baseInitCalled) {
$class = static::class;
user_error(
"init() method on class '{$class}' doesn't call Controller::init()."
. "Make sure that you have parent::init() included.",
E_USER_WARNING
);
}
$this->extend('onAfterInit');
} | A stand in function to protect the init function from failing to be called as well as providing before and
after hooks for the init function itself
This should be called on all controllers before handling requests | doInit | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
protected function beforeHandleRequest(HTTPRequest $request)
{
//Set up the internal dependencies (request, response)
$this->setRequest($request);
//Push the current controller to protect against weird session issues
$this->pushCurrent();
$this->setResponse(new HTTPResponse());
//kick off the init functionality
$this->doInit();
} | A bootstrap for the handleRequest method
@param HTTPRequest $request | beforeHandleRequest | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
protected function afterHandleRequest()
{
//Pop the current controller from the stack
$this->popCurrent();
} | Cleanup for the handleRequest method | afterHandleRequest | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
protected function handleAction($request, $action)
{
foreach ($request->latestParams() as $k => $v) {
if ($v || !isset($this->urlParams[$k])) {
$this->urlParams[$k] = $v;
}
}
$this->action = $action;
$this->requestParams = $request->requestVars();
if ($this->hasMethod($action)) {
$result = parent::handleAction($request, $action);
// If the action returns an array, customise with it before rendering the template.
if (is_array($result)) {
return $this->getViewer($action)->process($this->customise($result));
} else {
return $result;
}
}
// Fall back to index action with before/after handlers
$beforeResult = $this->extend('beforeCallActionHandler', $request, $action);
if ($beforeResult) {
return reset($beforeResult);
}
$result = $this->getViewer($action)->process($this);
$afterResult = $this->extend('afterCallActionHandler', $request, $action, $result);
if ($afterResult) {
return reset($afterResult);
}
return $result;
} | Controller's default action handler. It will call the method named in "$Action", if that method
exists. If "$Action" isn't given, it will use "index" as a default.
@param HTTPRequest $request
@param string $action
@return DBHTMLText|HTTPResponse | handleAction | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
public function setResponse(HTTPResponse $response)
{
$this->response = $response;
return $this;
} | Sets the HTTPResponse object that this controller is building up.
@param HTTPResponse $response
@return $this | setResponse | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
public function defaultAction($action)
{
return $this->getViewer($action)->process($this);
} | This is the default action handler used if a method doesn't exist. It will process the
controller object with the template returned by {@link getViewer()}.
@param string $action
@return DBHTMLText | defaultAction | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
public function getAction()
{
return $this->action;
} | Returns the action that is being executed on this controller.
@return string | getAction | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
public function getViewer($action)
{
// Hard-coded templates
if (isset($this->templates[$action]) && $this->templates[$action]) {
$templates = $this->templates[$action];
} elseif (isset($this->templates['index']) && $this->templates['index']) {
$templates = $this->templates['index'];
} elseif ($this->template) {
$templates = $this->template;
} else {
// Build templates based on class hierarchy
$actionTemplates = [];
$classTemplates = [];
$parentClass = static::class;
while ($parentClass !== parent::class) {
// _action templates have higher priority
if ($action && $action != 'index') {
$actionTemplates[] = strtok($parentClass ?? '', '_') . '_' . $action;
}
// class templates have lower priority
$classTemplates[] = strtok($parentClass ?? '', '_');
$parentClass = get_parent_class($parentClass ?? '');
}
// Add controller templates for inheritance chain
$templates = array_unique(array_merge($actionTemplates, $classTemplates));
}
return SSViewer::create($templates);
} | Return the viewer identified being the default handler for this Controller/Action combination.
@param string $action
@return SSViewer | getViewer | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
public function removeAction($fullURL, $action = null)
{
if (!$action) {
$action = $this->getAction(); //default to current action
}
$returnURL = $fullURL;
if (($pos = strpos($fullURL ?? '', $action ?? '')) !== false) {
$returnURL = substr($fullURL ?? '', 0, $pos);
}
return $returnURL;
} | Removes all the "action" part of the current URL and returns the result. If no action parameter
is present, returns the full URL.
@param string $fullURL
@param null|string $action
@return string | removeAction | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
protected function definingClassForAction($action)
{
$definingClass = parent::definingClassForAction($action);
if ($definingClass) {
return $definingClass;
}
$class = static::class;
while ($class != 'SilverStripe\\Control\\RequestHandler') {
$templateName = strtok($class ?? '', '_') . '_' . $action;
if (SSViewer::hasTemplate($templateName)) {
return $class;
}
$class = get_parent_class($class ?? '');
}
return null;
} | Return the class that defines the given action, so that we know where to check allowed_actions.
Overrides RequestHandler to also look at defined templates.
@param string $action
@return string | definingClassForAction | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
public function hasActionTemplate($action)
{
if (isset($this->templates[$action])) {
return true;
}
$parentClass = static::class;
$templates = [];
while ($parentClass != __CLASS__) {
$templates[] = strtok($parentClass ?? '', '_') . '_' . $action;
$parentClass = get_parent_class($parentClass ?? '');
}
return SSViewer::hasTemplate($templates);
} | Returns TRUE if this controller has a template that is specifically designed to handle a
specific action.
@param string $action
@return bool | hasActionTemplate | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
public static function curr()
{
if (Controller::$controller_stack) {
return Controller::$controller_stack[0];
}
// This user_error() will be removed in the next major version of Silverstripe CMS
user_error("No current controller available", E_USER_WARNING);
return null;
} | Returns the current controller.
@return Controller | curr | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.