_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q247000 | PermissionsEntityMapper.buildPermission | validation | public function buildPermission(int $id, string $title, ?string $description, bool $active, \DateTimeImmutable $created, array $roles): Permission
{
return new Permission($id, $title, $description, $active, $created, $roles);
} | php | {
"resource": ""
} |
q247001 | PermissionsEntityMapper.getObjects | validation | public function getObjects(array $whereColumnsInfo = null, string $orderBy = null): array
{
$permissions = [];
foreach ($this->selectArray(null, $whereColumnsInfo, $orderBy) as $permissionArray) {
$permissions[] = $this->buildPermission($permissionArray['id'], $permissionArray['title'], $permissionArray['description'], $permissionArray['active'], $permissionArray['created'], $permissionArray['roles']);
}
return $permissions;
} | php | {
"resource": ""
} |
q247002 | PermissionsEntityMapper.delete | validation | public function delete(int $id): string
{
// make sure there is a permission for the primary key
if (null === $permission = $this->getObjectById($id)) {
throw new Exceptions\QueryResultsNotFoundException();
}
$this->doDeleteTransaction($id);
$title = $permission->getTitle();
unset($permission);
return $title;
} | php | {
"resource": ""
} |
q247003 | AdminListView.indexView | validation | public function indexView(Response $response, ?array $displayItems = null)
{
/** if display items have not been passed in, get them from the mapper */
if ($displayItems === null) {
$displayItems = $this->getDisplayItems();
}
/** save error in var prior to unsetting */
$filterErrorMessage = FormHelper::getFieldError($this->sessionFilterFieldKey);
FormHelper::unsetSessionFormErrors();
return $this->view->render(
$response,
$this->template,
[
'title' => $this->mapper->getListViewTitle(),
'insertLinkInfo' => $this->insertLinkInfo,
'filterOpsList' => QueryBuilder::getWhereOperatorsText(),
'filterValue' => $this->getFilterFieldValue(),
'filterErrorMessage' => $filterErrorMessage,
'filterFormActionRoute' => $this->indexRoute,
'filterFieldName' => $this->sessionFilterFieldKey,
'isFiltered' => $this->getFilterFieldValue() != '',
'resetFilterRoute' => $this->filterResetRoute,
'updatesPermitted' => $this->updatesPermitted,
'updateColumn' => $this->updateColumn,
'updateRoute' => $this->updateRoute,
'deletesPermitted' => $this->deletesPermitted,
'deleteRoute' => $this->deleteRoute,
'displayItems' => $displayItems,
'columnCount' => $this->mapper->getCountSelectColumns(),
'sortColumn' => $this->mapper->getListViewSortColumn(),
'sortAscending' => $this->mapper->getListViewSortAscending(),
'navigationItems' => $this->navigationItems
]
);
} | php | {
"resource": ""
} |
q247004 | AdminListView.getFilterFieldValue | validation | protected function getFilterFieldValue(): string
{
if (isset($_SESSION[SlimPostgres::SESSION_KEY_ADMIN_LIST_VIEW_FILTER][$this->getFilterKey()][self::SESSION_FILTER_VALUE_KEY])) {
return $_SESSION[SlimPostgres::SESSION_KEY_ADMIN_LIST_VIEW_FILTER][$this->getFilterKey()][self::SESSION_FILTER_VALUE_KEY];
} else {
return '';
}
} | php | {
"resource": ""
} |
q247005 | AdministratorsView.routeIndexResetFilter | validation | public function routeIndexResetFilter(Request $request, Response $response, $args)
{
// redirect to the clean url
return $this->indexViewObjects($response, true);
} | php | {
"resource": ""
} |
q247006 | AdministratorsView.indexViewObjects | validation | public function indexViewObjects(Response $response, bool $resetFilter = false)
{
if ($resetFilter) {
return $this->resetFilter($response, $this->indexRoute);
}
try {
$administrators = $this->administratorsEntityMapper->getObjects($this->getFilterColumnsInfo(), null, $this->authentication, $this->authorization);
} catch (QueryFailureException $e) {
$administrators = [];
// warning event is inserted when query fails
SlimPostgres::setAdminNotice('Query Failed', 'failure');
}
return $this->indexView($response, $administrators);
} | php | {
"resource": ""
} |
q247007 | PhpMailerService.clear | validation | private function clear() {
if (!isset($this->phpMailer)) {
return;
}
$this->phpMailer->clearAddresses();
$this->phpMailer->clearCCs();
$this->phpMailer->clearBCCs();
$this->phpMailer->clearReplyTos();
$this->phpMailer->clearAllRecipients();
$this->phpMailer->clearAttachments();
$this->phpMailer->clearCustomHeaders();
} | php | {
"resource": ""
} |
q247008 | PhpMailerService.create | validation | private function create() {
$m = new \PHPMailer();
switch ($this->protocol) {
case 'sendmail':
$m->isSendmail();
break;
case 'smtp':
$m->isSMTP();
$m->Host = $this->smtpHost;
$m->SMTPAuth = false;
$m->SMTPAutoTLS = false;
$m->Port = $this->smtpPort;
break;
case 'mail':
$m->isMail();
break;
case 'qmail':
$m->isQmail();
break;
default:
throw new \Exception('bad phpmailerType: '.$this->protocol);
}
return $m;
} | php | {
"resource": ""
} |
q247009 | UpdateBuilder.addColumn | validation | public function addColumn(string $name, $value)
{
$this->args[] = $value;
if (count($this->args) > 1) {
$this->setColumnsValues .= ", ";
}
$argNum = count($this->args);
$this->setColumnsValues .= "$name = \$".$argNum;
} | php | {
"resource": ""
} |
q247010 | UpdateBuilder.setSql | validation | public function setSql()
{
$this->args[] = $this->updateOnColumnValue;
$lastArgNum = count($this->args);
$this->sql = "UPDATE $this->dbTable SET $this->setColumnsValues WHERE $this->updateOnColumnName = $".$lastArgNum;
} | php | {
"resource": ""
} |
q247011 | AuthorizationService.getLoggedInAdministrator | validation | public function getLoggedInAdministrator(): Administrator
{
if (!isset($_SESSION[SlimPostgres::SESSION_KEY_ADMINISTRATOR_ID])) {
throw new \Exception("No one is logged in");
}
if (null === $administrator = (AdministratorsEntityMapper::getInstance())->getObjectById($_SESSION[SlimPostgres::SESSION_KEY_ADMINISTRATOR_ID])) {
unset($_SESSION[SlimPostgres::SESSION_KEY_ADMINISTRATOR_ID]); /** remove for security */
throw new \Exception("Invalid administrator id ".$_SESSION[SlimPostgres::SESSION_KEY_ADMINISTRATOR_ID]." in session");
}
return $administrator;
} | php | {
"resource": ""
} |
q247012 | Administrator.hasOneRole | validation | public function hasOneRole(array $roleIds): bool
{
foreach ($roleIds as $roleId) {
if ($this->hasRole((int) $roleId)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q247013 | Administrator.getRolesString | validation | public function getRolesString(): string
{
$rolesString = "";
foreach ($this->roleNames as $role) {
$rolesString .= "$role, ";
}
return Functions::removeLastCharsFromString($rolesString, 2);
} | php | {
"resource": ""
} |
q247014 | Administrator.isUpdatable | validation | public function isUpdatable(): bool
{
if (is_null($this->authorization)) {
throw new \Exception("Authorization must be set");
}
// top dogs can update
if ($this->authorization->hasTopRole()) {
return true;
}
// non-top dogs can be updated
if (!$this->hasTopRole()) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q247015 | Administrator.isDeletable | validation | public function isDeletable(): bool
{
if (is_null($this->authorization)) {
throw new \Exception("Authorization must be set");
}
$id = $this->getId();
// make sure the current administrator is not deleting her/himself
if ($this->isLoggedIn()) {
$this->notDeletableReason = "Administrator cannot delete own account: id $id";
return false;
}
// non-top dogs cannot delete top dogs
if (!$this->getAuthorization()->hasTopRole() && $this->hasTopRole()) {
$this->notDeletableReason = "Not authorized to delete administrator: id $id";
return false;
}
// make sure there are no events for administrator being deleted
if ((EventsTableMapper::getInstance())->existForAdministrator($id)) {
$this->notDeletableReason = "Events exist for administrator: id $id";
return false;
}
return true;
} | php | {
"resource": ""
} |
q247016 | RolesView.indexViewObjects | validation | public function indexViewObjects(Response $response, bool $resetFilter = false)
{
if ($resetFilter) {
return $this->resetFilter($response, $this->indexRoute);
}
try {
$roles = $this->mapper->getObjects($this->getFilterColumnsInfo());
} catch (QueryFailureException $e) {
$roles = [];
// warning is inserted when query fails
SlimPostgres::setAdminNotice('Query Failed', 'failure');
}
return $this->indexView($response, $roles);
} | php | {
"resource": ""
} |
q247017 | QueryBuilder.add | validation | public function add(string $sql)
{
$args = func_get_args();
array_shift($args); // drop the first one (the sql string)
$this->sql .= $sql;
$this->args = array_merge($this->args, $args);
return $this;
} | php | {
"resource": ""
} |
q247018 | QueryBuilder.null_eq | validation | public function null_eq(string $name, $arg)
{
if ($arg === null) {
$this->sql .= "$name is null";
}
else {
$this->args[] = $arg;
$argNum = count($this->args);
$this->sql .= "$name = \$$argNum";
}
return $this;
} | php | {
"resource": ""
} |
q247019 | QueryBuilder.set | validation | public function set(string $sql, array $args)
{
$this->sql = $sql;
$this->args = $args;
} | php | {
"resource": ""
} |
q247020 | QueryBuilder.getOne | validation | public function getOne(): ?string
{
$result = $this->execute();
if (pg_num_rows($result) == 1) {
// make sure only 1 field in query
if (pg_num_fields($result) == 1) {
return pg_fetch_array($result)[0];
}
else {
throw new \Exception("Too many result fields");
}
}
else {
// either 0 or multiple records in result
// if 0
if (pg_num_rows($result) == 0) {
// no error here. client can error if appropriate
return null;
}
else {
throw new \Exception("Multiple results");
}
}
} | php | {
"resource": ""
} |
q247021 | AdminNavigation.setNav | validation | private function setNav()
{
$this->nav = [
'System' => [
'subSections' => [
'Administrators' => [
'route' => ROUTE_ADMINISTRATORS,
'authorization' => ADMINISTRATORS_VIEW_RESOURCE,
'subSections' => [
'Insert' => [
'route' => ROUTE_ADMINISTRATORS_INSERT,
'authorization' => ADMINISTRATORS_INSERT_RESOURCE,
],
]
],
'Roles' => [
'route' => ROUTE_ADMINISTRATORS_ROLES,
'authorization' => ROLES_VIEW_RESOURCE,
'subSections' => [
'Insert' => [
'route' => ROUTE_ADMINISTRATORS_ROLES_INSERT,
'authorization' => ROLES_INSERT_RESOURCE,
],
],
],
'Permissions' => [
'route' => ROUTE_ADMINISTRATORS_PERMISSIONS,
'authorization' => PERMISSIONS_VIEW_RESOURCE,
'subSections' => [
'Insert' => [
'route' => ROUTE_ADMINISTRATORS_PERMISSIONS_INSERT,
'authorization' => PERMISSIONS_INSERT_RESOURCE,
],
]
],
'Events' => [
'route' => ROUTE_EVENTS,
'authorization' => EVENTS_VIEW_RESOURCE,
'subSections' => [
'Types' => [
'route' => ROUTE_DATABASE_TABLES,
'args' => [ROUTEARG_DATABASE_TABLE_NAME => 'event_types'],
'authorization' => EVENTS_VIEW_RESOURCE,
],
]
],
'Database' => [
'authorization' => DATABASE_TABLES_VIEW_RESOURCE,
'subSections' => $this->getDatabaseTablesSection()
],
]
],
'Logout' => [
'route' => ROUTE_LOGOUT,
],
];
if (isset($this->container['settings']['adminNav'])) {
if (!is_array($this->container['settings']['adminNav'])) {
throw new \Exception("adminNav config must be array");
}
$this->nav = array_merge($this->container['settings']['adminNav'], $this->nav);
}
} | php | {
"resource": ""
} |
q247022 | AdminNavigation.getSectionForAdministrator | validation | private function getSectionForAdministrator(array $section, string $sectionName): array
{
if (isset($section['authorization']) && !$this->container->authorization->isAuthorized($section['authorization'])) {
return [];
}
// rebuild based on permissions
$updatedSection = [];
foreach ($section as $key => $value) {
if ($key != 'subSections') {
$updatedSection[$key] = $value;
}
}
$updatedSubSections = [];
if (isset($section['subSections'])) {
foreach ($section['subSections'] as $subSectionName => $subSection) {
$updatedSubSection = $this->getSectionForAdministrator($subSection, $subSectionName);
if (count($updatedSubSection) > 0) {
$updatedSubSections[$subSectionName] = $updatedSubSection;
}
}
}
if (count($updatedSubSections) > 0) {
$updatedSection['subSections'] = $updatedSubSections;
}
return $updatedSection;
} | php | {
"resource": ""
} |
q247023 | RolesController.routeGetDelete | validation | public function routeGetDelete(Request $request, Response $response, $args)
{
if (!$this->authorization->isAuthorized(ROLES_DELETE_RESOURCE)) {
throw new \Exception('No permission.');
}
$primaryKey = $args[ROUTEARG_PRIMARY_KEY];
$tableName = $this->tableMapper->getFormalTableName(false);
$primaryKeyColumnName = $this->tableMapper->getPrimaryKeyColumnName();
try {
$this->tableMapper->deleteByPrimaryKey($primaryKey);
$this->events->insertInfo(EVENT_ROLE_DELETE, [$primaryKeyColumnName => $primaryKey]);
SlimPostgres::setAdminNotice("Deleted $tableName $primaryKey");
} catch (Exceptions\UnallowedActionException $e) {
$this->events->insertWarning(EVENT_UNALLOWED_ACTION, ['error' => $e->getMessage()]);
SlimPostgres::setAdminNotice($e->getMessage(), 'failure');
} catch (Exceptions\QueryResultsNotFoundException $e) {
define('EVENT_QUERY_NO_RESULTS', 'Query Results Not Found');
$this->events->insertWarning(EVENT_QUERY_NO_RESULTS, $e->getMessage());
SlimPostgres::setAdminNotice($e->getMessage(), 'failure');
} catch (Exceptions\QueryFailureException $e) {
$this->events->insertError(EVENT_QUERY_FAIL, ['error' => $e->getMessage()]);
SlimPostgres::setAdminNotice('Delete Failed', 'failure');
}
return $response->withRedirect($this->router->pathFor(SlimPostgres::getRouteName(true, $this->routePrefix, 'index')));
} | php | {
"resource": ""
} |
q247024 | DatabaseTableController.enterEventAndNotice | validation | private function enterEventAndNotice(string $action, $primaryKeyValue = null)
{
if ($action != 'insert' && $action != 'update') {
throw new \InvalidArgumentException("Action must be either insert or update");
}
$actionPastTense = ($action == 'insert') ? 'inserted' : 'updated';
$tableNameSingular = $this->tableMapper->getFormalTableName(false);
$noteStart = "$actionPastTense $tableNameSingular";
/** use event constant if defined, squelch warning */
$eventTitle = @constant("EVENT_".strtoupper($tableNameSingular)."_".strtoupper($action)) ?? $noteStart;
$adminNotification = $noteStart;
$eventPayload = [];
if (null !== $primaryKeyColumnName = $this->tableMapper->getPrimaryKeyColumnName()) {
$adminNotification .= " $primaryKeyValue"; // if primary key is set the new id is returned by mapper insert method
$eventPayload = [$primaryKeyColumnName => $primaryKeyValue];
}
$eventPayload = array_merge($eventPayload, $this->requestInput);
$this->events->insertInfo($eventTitle, $eventPayload);
SlimPostgres::setAdminNotice($adminNotification);
} | php | {
"resource": ""
} |
q247025 | DatabaseTableController.routePutUpdate | validation | public function routePutUpdate(Request $request, Response $response, $args)
{
if (!$this->authorization->isAuthorized(constant(strtoupper($this->routePrefix)."_UPDATE_RESOURCE"))) {
throw new \Exception('No permission.');
}
$primaryKeyValue = $args[ROUTEARG_PRIMARY_KEY];
/** note that boolean columns that don't exist in request input are added as false */
$this->setRequestInput($request, DatabaseTableForm::getFieldNames($this->tableMapper), $this->tableMapper->getBooleanColumnNames());
$redirectRoute = SlimPostgres::getRouteName(true, $this->routePrefix, 'index');
// make sure there is a record for the primary key
if (null === $record = $this->tableMapper->selectForPrimaryKey($primaryKeyValue)) {
return $this->databaseRecordNotFound($response, $primaryKeyValue, $this->tableMapper, 'update');
}
// if no changes made stay on page with error
$changedColumnsValues = $this->getMapper()->getChangedColumnsValues($this->requestInput, $record);
if (count($changedColumnsValues) == 0) {
SlimPostgres::setAdminNotice("No changes made", 'failure');
return $this->view->updateView($request, $response, $args);
}
$validator = new DatabaseTableUpdateFormValidator($this->requestInput, $this->tableMapper, $record);
if (!$validator->validate()) {
// redisplay the form with input values and error(s)
FormHelper::setFieldErrors($validator->getFirstErrors());
$args[SlimPostgres::USER_INPUT_KEY] = $this->requestInput;
return $this->view->updateView($request, $response, $args);
}
$this->tableMapper->updateByPrimaryKey($changedColumnsValues, $primaryKeyValue);
$this->enterEventAndNotice('update', $primaryKeyValue);
return $response->withRedirect($this->router->pathFor($redirectRoute));
} | php | {
"resource": ""
} |
q247026 | InsertBuilder.addColumn | validation | public function addColumn(string $name, $value)
{
$this->args[] = $value;
if (mb_strlen($this->columns) > 0) {
$this->columns .= ", ";
}
$this->columns .= $name;
if (mb_strlen($this->values) > 0) {
$this->values .= ", ";
}
$argNum = count($this->args);
$this->values .= "$".$argNum;
} | php | {
"resource": ""
} |
q247027 | ResponseUtilities.databaseRecordNotFound | validation | private function databaseRecordNotFound(Response $response, $primaryKey, TableMapper $tableMapper, string $routeAction, ?string $title = null)
{
// $routeAction must be 'update' or 'delete'
if ($routeAction != 'update' && $routeAction != 'delete') {
throw new \Exception("routeAction $routeAction must be update or delete");
}
// enter event
$this->events->insertWarning(EVENT_QUERY_NO_RESULTS, [$tableMapper->getPrimaryKeyColumnName() => $primaryKey, 'table' => $tableMapper->getTableName()]);
$noticeTitle = ($title != null) ? $title: 'Record';
SlimPostgres::setAdminNotice("$noticeTitle $primaryKey Not Found", 'failure');
return $response->withRedirect($this->router->pathFor(SlimPostgres::getRouteName(true, $this->routePrefix, 'index')));
} | php | {
"resource": ""
} |
q247028 | AuthenticationController.routeGetLogout | validation | public function routeGetLogout(Request $request, Response $response)
{
$this->events->setAdministratorId($this->authentication->getAdministratorId());
if (null === $username = $this->authentication->getAdministratorUsername()) {
$this->events->insertWarning(EVENT_LOGOUT_FAULT);
} else {
$this->events->insertInfo(EVENT_LOGOUT);
$this->authentication->logout();
}
return $response->withRedirect($this->router->pathFor(ROUTE_HOME));
} | php | {
"resource": ""
} |
q247029 | InsertUpdateBuilder.runExecute | validation | public function runExecute(bool $alterBooleanArgs = false)
{
if (!isset($this->sql)) {
$this->setSql();
}
if (isset($this->primaryKeyName)) {
return parent::executeWithReturnField($this->primaryKeyName, $alterBooleanArgs);
} else {
return parent::execute($alterBooleanArgs);
}
} | php | {
"resource": ""
} |
q247030 | DatabaseTableFormValidator.setRules | validation | protected function setRules(bool $skipUniqueForUnchanged = false, array $record = null)
{
$this->mapFieldsRules($this->databaseTableValidation->getValidationRules());
$uniqueColumns = $this->mapper->getUniqueColumns();
if (count($uniqueColumns) > 0) {
$this->addUniqueRule();
foreach ($uniqueColumns as $databaseColumnMapper) {
$field = $databaseColumnMapper->getName();
// only set rule for changed columns if $skipUniqueForUnchanged is set true
if ( !($skipUniqueForUnchanged && $this->inputData[$field] == $record[$field]) ) {
$this->rule('unique', $field, $databaseColumnMapper, $this);
}
}
}
} | php | {
"resource": ""
} |
q247031 | ColumnMapper.setDefaultValue | validation | private function setDefaultValue($columnDefault)
{
if (is_null($columnDefault)) {
$this->defaultValue = '';
} else {
switch ($this->type) {
case 'character':
case 'character varying':
case 'text':
// formatted like 'default'::text
case 'USER-DEFINED':
// formatted like 'default'::tableName_columnName
// parse out default
$parseColumnDefault = explode("'", $columnDefault);
$this->defaultValue = $parseColumnDefault[1];
break;
case 'boolean':
// overwrite to be congruous with a postgres value returned from select
if ($columnDefault == 'true') {
$this->defaultValue = Postgres::BOOLEAN_TRUE;
}
break;
default:
$this->defaultValue = $columnDefault;
}
}
} | php | {
"resource": ""
} |
q247032 | Permission.isDeletable | validation | public function isDeletable(): bool
{
if (in_array($this->title, self::UNDELETABLE)) {
return false;
}
return (PermissionsTableMapper::getInstance())->isDeletable();
} | php | {
"resource": ""
} |
q247033 | TableMapper.setConstraints | validation | private function setConstraints()
{
$q = new QueryBuilder("SELECT ccu.column_name, tc.constraint_type FROM INFORMATION_SCHEMA.constraint_column_usage ccu JOIN information_schema.table_constraints tc ON ccu.constraint_name = tc.constraint_name WHERE tc.table_name = ccu.table_name AND ccu.table_name = $1", $this->tableName);
$qResult = $q->execute();
while ($qRow = pg_fetch_assoc($qResult)) {
switch($qRow['constraint_type']) {
case 'PRIMARY KEY':
$this->primaryKeyColumnName = $qRow['column_name'];
break;
case 'UNIQUE':
$this->uniqueColumnNames[] = $qRow['column_name'];
}
}
} | php | {
"resource": ""
} |
q247034 | TableMapper.addColumnConstraint | validation | protected function addColumnConstraint(ColumnMapper $column, string $constraint, $context = true)
{
$column->addConstraint($constraint, $context);
} | php | {
"resource": ""
} |
q247035 | TableMapper.addBooleanColumnFalse | validation | private function addBooleanColumnFalse(array $columnValues): array
{
foreach ($this->getBooleanColumnNames() as $booleanColumnName) {
if (!isset($columnValues[$booleanColumnName])) {
$columnValues[$booleanColumnName] = Postgres::BOOLEAN_FALSE;
}
}
return $columnValues;
} | php | {
"resource": ""
} |
q247036 | TableMapper.insert | validation | public function insert(array $columnValues, bool $addBooleanColumnFalse = false)
{
if ($addBooleanColumnFalse) {
$columnValues = $this->addBooleanColumnFalse($columnValues);
}
$ib = new InsertBuilder($this->tableName);
if ($this->getPrimaryKeyColumnName() !== null) {
$ib->setPrimaryKeyName($this->getPrimaryKeyColumnName());
}
$this->addColumnsToBuilder($ib, $columnValues);
return $ib->runExecute();
} | php | {
"resource": ""
} |
q247037 | SlimPostgres.setSlimMiddleware | validation | private function setSlimMiddleware(\Slim\App $slim, $slimContainer)
{
/** handle CSRF check failures and allow template to access and insert CSRF fields to forms */
$slim->add(new CsrfMiddleware($slimContainer));
/** Insert System Event for every resource request */
if (isset($this->config['trackAll']) && $this->config['trackAll']) {
$slim->add(new TrackerMiddleware($slimContainer));
}
/** slim CSRF check middleware */
$slim->add($slimContainer->csrf);
} | php | {
"resource": ""
} |
q247038 | SlimPostgres.getRouteName | validation | public static function getRouteName(bool $isAdmin = true, string $routePrefix = null, string $routeType = null, string $requestMethod = null): string
{
$routeName = '';
if ($isAdmin) {
$routeName .= ROUTEPREFIX_ADMIN;
}
if ($routePrefix !== null) {
$routeName .= '.' . $routePrefix;
}
if ($requestMethod !== null) {
$validActionMethods = ['put', 'post'];
if (!in_array($requestMethod, $validActionMethods)) {
throw new \Exception("Invalid request method $requestMethod. Only post and put accepted in route names.");
}
$routeName .= '.' . $requestMethod;
}
if ($routeType !== null) {
if (!in_array($routeType, self::VALID_ROUTE_TYPES)) {
throw new \Exception("Invalid route type $routeType");
}
$routeName .= '.' . $routeType;
}
return $routeName;
} | php | {
"resource": ""
} |
q247039 | DatabaseTableViewChild.routeIndex | validation | public function routeIndex(Request $request, Response $response, $args)
{
$this->tableName = $args[ROUTEARG_DATABASE_TABLE_NAME];
$this->tableMapper = new TableMapper($this->tableName);
parent::__construct($this->container, $this->tableMapper, ROUTEPREFIX_ROLES);
return $this->indexView($response);
} | php | {
"resource": ""
} |
q247040 | AdministratorsEntityMapper.selectArrayWithRolesString | validation | public function selectArrayWithRolesString(string $columns = "*", array $whereColumnsInfo = null): array
{
$administrators = [];
$results = $this->selectArray($columns, $whereColumnsInfo);
foreach ($results as $index => $administrator) {
$administrators[$index] = $administrator;
$administrators[$index]['roles'] = implode(", ", $administrators[$index]['roles']);
}
return $administrators;
} | php | {
"resource": ""
} |
q247041 | AdministratorsEntityMapper.delete | validation | public function delete(int $id, AuthenticationService $authentication, AuthorizationService $authorization): string
{
// make sure there is an administrator for the primary key
if (null === $administrator = $this->getObjectById($id)) {
throw new Exceptions\QueryResultsNotFoundException();
}
$administrator->setAuth($authentication, $authorization);
if (!$administrator->isDeletable()) {
throw new Exceptions\UnallowedActionException($administrator->getNotDeletableReason());
}
$this->doDeleteTransaction($id);
$username = $administrator->getUsername();
unset($administrator);
return $username;
} | php | {
"resource": ""
} |
q247042 | ListTemplate.getDeleteCell | validation | protected function getDeleteCell(bool $showDeleteLink, ?string $primaryKeyValue): string
{
if ($showDeleteLink && $this->deleteRoute == null) {
throw new \Exception("Must have deleteRoute");
}
if ($showDeleteLink && $primaryKeyValue === null) {
throw new \Exception("Must have primaryKeyValue to delete");
}
$cellValue = ($showDeleteLink) ? '<a href="'.$this->router->pathFor($this->deleteRoute, ["primaryKey" => $primaryKeyValue]).'" title="delete" onclick="return confirm(\'Are you sure you want to delete '.$primaryKeyValue.'?\');">X</a>' : ' ';
return '<td>'.$cellValue.'</td>';
} | php | {
"resource": ""
} |
q247043 | PermissionsView.indexViewObjects | validation | public function indexViewObjects(Response $response, bool $resetFilter = false)
{
if ($resetFilter) {
return $this->resetFilter($response, $this->indexRoute);
}
try {
$permissions = $this->permissionsEntityMapper->getObjects($this->getFilterColumnsInfo());
} catch (QueryFailureException $e) {
$permissions = [];
// warning event is inserted when query fails
SlimPostgres::setAdminNotice('Query Failed', 'failure');
}
return $this->indexView($response, $permissions);
} | php | {
"resource": ""
} |
q247044 | Check.whitelist | validation | public function whitelist(array $whitelist)
{
$this->_definitions = array();
foreach ($whitelist as $definition)
{
// Pre-configured object
if (is_object($definition))
{
if ($definition instanceof Definition\IDefinition)
$definitionObject = $definition;
else
throw new \InvalidArgumentException('Definition objects must implement IDefinition');
}
// IPv4 address
elseif (preg_match('/[a-z:\/]/', $definition) === 0)
$definitionObject = new Definition\IPv4Address($definition);
// IPv4 CIDR notation
elseif (preg_match('/[a-z:]/', $definition) === 0)
$definitionObject = new Definition\IPv4CIDR($definition);
// IPv6 address
elseif (preg_match('/^[0-9a-f:]+$/', $definition))
$definitionObject = new Definition\IPv6Address($definition);
// IPv6 CIDR notation
elseif (preg_match('/^[0-9a-f:\/]+$/', $definition))
$definitionObject = new Definition\IPv6CIDR($definition);
// Wildcard domain
elseif (preg_match('/^\*\.[\w\.\-]+$/', $definition))
$definitionObject = new Definition\WildcardDomain($definition);
// Domain
elseif (preg_match('/^[\w\.\-]+$/', $definition))
$definitionObject = new Definition\Domain($definition);
else
throw new \InvalidArgumentException('Unable to parse definition "'.$definition.'"');
$this->_definitions[] = $definitionObject;
}
} | php | {
"resource": ""
} |
q247045 | Check.check | validation | public function check($value)
{
foreach ($this->_definitions as $definition)
if ($definition->match($value))
return true;
return false;
} | php | {
"resource": ""
} |
q247046 | Counter.increment | validation | public function increment()
{
$this->counter++;
if (1 === $this->counter) {
$this->expiresAt = $this->now() + $this->expiresIn;
}
} | php | {
"resource": ""
} |
q247047 | FusionExtension.validate | validation | public function validate(ValidationResult $result) {
// Determine the field to use, based on the configuration defined tag types.
$validate = 'Title';
$class = $this->owner->ClassName;
foreach(Config::inst()->get('FusionService', 'custom_tag_types') as $type => $field) {
if($type === $class) {
$validate = $field;
}
}
// Confirm that the tag has been given a title and doesn't already exist.
if($result->valid() && !$this->owner->$validate) {
$result->error("\"{$validate}\" required!");
}
// Allow extension.
$this->owner->extend('validateFusionExtension', $result);
return $result;
} | php | {
"resource": ""
} |
q247048 | FusionExtension.onAfterWrite | validation | public function onAfterWrite() {
parent::onAfterWrite();
// Determine the field to use, based on the configuration defined tag types.
$write = 'Title';
$class = $this->owner->ClassName;
foreach(Config::inst()->get('FusionService', 'custom_tag_types') as $type => $field) {
if($type === $class) {
$write = $field;
}
}
// Determine whether there's an existing fusion tag.
$changed = $this->owner->getChangedFields();
$existing = FusionTag::get()->filter('Title', $this->owner->$write)->first();
if(is_null($this->owner->FusionTagID) && !$existing) {
// There is no fusion tag, therefore instantiate one using this tag.
$fusion = FusionTag::create();
$fusion->Title = $this->owner->$write;
$fusion->TagTypes = serialize(array(
$class => $class
));
$fusion->write();
// Update this tag to point to the fusion tag.
$this->owner->FusionTagID = $fusion->ID;
$this->owner->write();
}
else if(is_null($this->owner->FusionTagID) && $existing) {
// There is a fusion tag, therefore append this tag type.
$types = unserialize($existing->TagTypes);
$types[$class] = $class;
$existing->TagTypes = serialize($types);
$existing->write();
// Update this tag to point to the fusion tag.
$this->owner->FusionTagID = $existing->ID;
$this->owner->write();
}
else if(isset($changed[$write]) && !isset($changed['FusionTagID']) && $existing && ($existing->ID != $this->owner->FusionTagID)) {
// Update the fusion tag to remove this tag type.
$fusion = FusionTag::get()->byID($this->owner->FusionTagID);
$types = unserialize($fusion->TagTypes);
unset($types[$this->owner->ClassName]);
$fusion->TagTypes = !empty($types) ? serialize($types) : null;
$fusion->write();
// There is an existing fusion tag, therefore append this tag type.
$types = unserialize($existing->TagTypes);
$types[$class] = $class;
$existing->TagTypes = serialize($types);
$existing->write();
// Update this tag to point to the new fusion tag.
$this->owner->FusionTagID = $existing->ID;
$this->owner->write();
}
// Determine whether this tag has been updated.
else if(isset($changed[$write]) && !isset($changed['FusionTagID']) && ($existing = FusionTag::get()->byID($this->owner->FusionTagID))) {
// There is an update, therefore update the existing fusion tag to reflect the change.
$existing->Title = $changed[$write]['after'];
$existing->write();
}
} | php | {
"resource": ""
} |
q247049 | FusionExtension.onAfterDelete | validation | public function onAfterDelete() {
parent::onAfterDelete();
$fusion = FusionTag::get()->byID($this->owner->FusionTagID);
$types = unserialize($fusion->TagTypes);
unset($types[$this->owner->ClassName]);
$fusion->TagTypes = !empty($types) ? serialize($types) : null;
$fusion->write();
} | php | {
"resource": ""
} |
q247050 | CMSMainTaggingExtension.updateSearchForm | validation | public function updateSearchForm($form) {
// Update the page filtering, allowing multiple tags.
Requirements::javascript(FUSION_PATH . '/javascript/fusion.js');
// Instantiate a field containing the existing tags.
$form->Fields()->insertBefore(ListboxField::create(
'q[Tagging]',
'Tags',
FusionTag::get()->map('Title', 'Title')->toArray(),
(($filtering = $this->owner->getRequest()->getVar('q')) && isset($filtering['Tagging'])) ? $filtering['Tagging'] : array(),
null,
true
), 'q[Term]');
// Allow extension.
$this->owner->extend('updateCMSMainTaggingExtensionSearchForm', $form);
} | php | {
"resource": ""
} |
q247051 | TaggingExtension.updateSearchableFields | validation | public function updateSearchableFields(&$fields) {
// Instantiate a field containing the existing tags.
$fields = array_merge(array(
'Tagging' => array(
'title' => 'Tags',
'field' => ListboxField::create(
'Tagging',
'Tags',
FusionTag::get()->map('Title', 'Title')->toArray(),
(Controller::has_curr() && ($filtering = Controller::curr()->getRequest()->getVar('q')) && isset($filtering['Tagging'])) ? $filtering['Tagging'] : array(),
null,
true
),
'filter' => $this->owner->dbObject('Tagging')->stat('default_search_filter_class')
)
), $fields);
// Allow extension.
$this->owner->extend('updateTaggingExtensionSearchableFields', $fields);
} | php | {
"resource": ""
} |
q247052 | TaggingExtension.updateCMSFields | validation | public function updateCMSFields(FieldList $fields) {
$fields->removeByName('FusionTags');
// Determine whether consolidated tags are found in the existing relationships.
$types = array();
foreach(singleton('FusionService')->getFusionTagTypes() as $type => $field) {
$types[$type] = $type;
}
$types = array_intersect($this->owner->many_many(), $types);
if(empty($types)) {
// There are no consolidated tags found, therefore instantiate a tagging field.
$fields->addFieldToTab('Root.Tagging', ListboxField::create(
'FusionTags',
'Tags',
FusionTag::get()->map()->toArray()
)->setMultiple(true));
}
// Allow extension.
$this->owner->extend('updateTaggingExtensionCMSFields', $fields);
} | php | {
"resource": ""
} |
q247053 | TaggingExtension.onBeforeWrite | validation | public function onBeforeWrite() {
parent::onBeforeWrite();
// Determine whether consolidated tags are found in the existing relationships.
$types = array();
foreach(singleton('FusionService')->getFusionTagTypes() as $type => $field) {
$types[$type] = $type;
}
$types = array_intersect($this->owner->many_many(), $types);
if(empty($types)) {
// There are no consolidated tags found, therefore update the tagging based on the fusion tags.
$tagging = array();
foreach($this->owner->FusionTags() as $tag) {
$tagging[] = $tag->Title;
}
}
else {
// Empty the fusion tags to begin.
$this->owner->FusionTags()->removeAll();
// There are consolidated tags found, therefore update the tagging based on these.
$tagging = array();
foreach($types as $relationship => $type) {
foreach($this->owner->$relationship() as $tag) {
// Update both the fusion tags and tagging (using the relationship causes caching issues).
$fusion = FusionTag::get()->byID($tag->FusionTagID);
$this->owner->FusionTags()->add($fusion);
$tagging[] = $fusion->Title;
}
}
}
$this->owner->Tagging = implode(' ', $tagging);
} | php | {
"resource": ""
} |
q247054 | FusionTag.getCMSFields | validation | public function getCMSFields() {
$fields = parent::getCMSFields();
// Determine whether the tag types should be displayed.
$types = array();
foreach($this->service->getFusionTagTypes() as $type => $field) {
$types[$type] = $type;
}
if(count($types)) {
// The serialised representation will require a custom field to display correctly.
$fields->replaceField('TagTypes', $list = ListboxField::create(
'Types',
'Tag Types',
$types
)->setMultiple(true));
// Disable existing tag types to prevent deletion.
$items = is_string($this->TagTypes) ? array_keys(unserialize($this->TagTypes)) : array();
$list->setValue($items);
$list->setDisabledItems($items);
}
else {
// There are no existing or configuration defined tag types.
$fields->removeByName('TagTypes');
}
// Allow extension.
$this->extend('updateFusionTagCMSFields', $fields);
return $fields;
} | php | {
"resource": ""
} |
q247055 | FusionTag.validate | validation | public function validate() {
$result = parent::validate();
$this->Title = strtolower($this->Title);
if($result->valid() && !$this->Title) {
$result->error('"Title" required!');
}
else if($result->valid() && FusionTag::get_one('FusionTag', array(
'ID != ?' => $this->ID,
'Title = ?' => $this->Title
))) {
$result->error('Tag already exists!');
}
// Allow extension.
$this->extend('validateFusionTag', $result);
return $result;
} | php | {
"resource": ""
} |
q247056 | FusionTag.onBeforeWrite | validation | public function onBeforeWrite() {
parent::onBeforeWrite();
// Determine whether new tag types exist.
$types = $this->Types ? explode(',', $this->Types) : array();
// Merge the new and existing tag types.
if(is_string($this->TagTypes)) {
$types = array_merge($types, array_keys(unserialize($this->TagTypes)));
}
if(!empty($types)) {
sort($types);
// Update the tag types with a serialised representation.
$formatted = array();
$existing = $this->service->getFusionTagTypes();
foreach($types as $type) {
// The tag type exclusions need checking.
if(isset($existing[$type])) {
$formatted[$type] = $type;
}
}
$this->TagTypes = !empty($formatted) ? serialize($formatted) : null;
// Update the custom field to reflect the change correctly.
$this->Types = implode(',', $formatted);
}
} | php | {
"resource": ""
} |
q247057 | FusionTag.onAfterWrite | validation | public function onAfterWrite() {
parent::onAfterWrite();
// Determine the tag types to update.
$types = unserialize($this->TagTypes);
$changed = $this->getChangedFields();
foreach($this->service->getFusionTagTypes() as $type => $field) {
if(isset($types[$type])) {
// Determine whether new tag types exist.
$newTypes = array();
if(isset($changed['TagTypes'])) {
$before = unserialize($changed['TagTypes']['before']);
$after = unserialize($changed['TagTypes']['after']);
$newTypes = is_array($before) ? array_diff($after, $before) : $after;
}
// Determine whether there's an existing tag.
if((isset($changed['ID']) || isset($newTypes[$type])) && !($type::get()->filter($field, $this->Title)->first())) {
// There is no tag, therefore instantiate one using this fusion tag.
$tag = $type::create();
$tag->$field = $this->Title;
$tag->FusionTagID = $this->ID;
$tag->write();
}
// Determine whether this fusion tag has been updated.
else if(!isset($changed['ID']) && isset($changed['Title']) && ($existing = $type::get()->filter($field, $changed['Title']['before']))) {
// There is an update, therefore update the existing tag/s to reflect the change.
foreach($existing as $tag) {
$tag->$field = $changed['Title']['after'];
$tag->write();
}
}
}
}
// Update the searchable content tagging for this fusion tag.
if(!isset($changed['ID']) && isset($changed['Title'])) {
$this->service->updateTagging($this->ID);
}
} | php | {
"resource": ""
} |
q247058 | FusionService.getFusionTagTypes | validation | public function getFusionTagTypes() {
// Determine existing tag types.
$types = array();
$configuration = Config::inst();
// The tag type exclusions need checking.
$exclusions = $configuration->get('FusionService', 'tag_type_exclusions');
$classes = ClassInfo::subclassesFor('DataObject');
unset($classes['FusionTag']);
foreach($classes as $class) {
// Determine the tag types to consolidate, based on data objects ending with "Tag".
if((strpos(strrev($class), strrev('Tag')) === 0) && !in_array($class, $exclusions) && !ClassInfo::classImplements($class, 'TestOnly')) {
// Use the title field as a default.
$types[$class] = 'Title';
}
}
// Determine configuration defined tag types.
foreach($configuration->get('FusionService', 'custom_tag_types') as $type => $field) {
if(in_array($type, $classes) && !in_array($type, $exclusions)) {
// Use the configuration defined field.
$types[$type] = $field;
}
}
return $types;
} | php | {
"resource": ""
} |
q247059 | FusionService.updateTagging | validation | public function updateTagging($fusionID) {
// Determine any data objects with the tagging extension.
$configuration = Config::inst();
$classes = ClassInfo::subclassesFor('DataObject');
unset($classes['DataObject']);
foreach($classes as $class) {
// Determine the specific data object extensions.
$extensions = $configuration->get($class, 'extensions', Config::UNINHERITED);
if(is_array($extensions) && in_array('TaggingExtension', $extensions)) {
// Determine whether this fusion tag is being used.
$mode = Versioned::get_reading_mode();
Versioned::reading_stage('Stage');
$objects = $class::get()->filter('FusionTags.ID', $fusionID);
// Update the searchable content tagging for these data objects.
if($class::has_extension($class, 'Versioned')) {
// These data objects are versioned.
foreach($objects as $object) {
// Update the staging version.
$object->writeWithoutVersion();
}
Versioned::reading_stage('Live');
$objects = $class::get()->filter('FusionTags.ID', $fusionID);
foreach($objects as $object) {
// Update the live version.
$object->writeWithoutVersion();
}
}
else {
// These data objects are not versioned.
foreach($objects as $object) {
$object->write();
}
}
Versioned::set_reading_mode($mode);
}
}
} | php | {
"resource": ""
} |
q247060 | AlertManager.createAlertsForType | validation | private function createAlertsForType($type, array $messages)
{
$alerts = array();
foreach ($messages as $msg) {
$alerts[] = new Alert($type, $msg);
}
return $alerts;
} | php | {
"resource": ""
} |
q247061 | SelectelAdapter.transformFiles | validation | protected function transformFiles($files)
{
$result = [];
foreach ($files as $file) {
$result[] = [
'type' => $file['content_type'] === 'application/directory' ? 'dir' : 'file',
'path' => $file['name'],
'size' => intval($file['bytes']),
'timestamp' => strtotime($file['last_modified']),
'mimetype' => $file['content_type'],
];
}
return $result;
} | php | {
"resource": ""
} |
q247062 | SelectelAdapter.writeToContainer | validation | protected function writeToContainer($type, $path, $payload)
{
try {
$this->container->{'uploadFrom'.$type}($path, $payload);
} catch (UploadFailedException $e) {
return false;
}
return $this->getMetadata($path);
} | php | {
"resource": ""
} |
q247063 | FlashAlertsHelper.renderFlashAlerts | validation | public function renderFlashAlerts(array $options = array())
{
$options = $this->resolveOptions($options);
return $this->templating->render(
$options['template'],
$options
);
} | php | {
"resource": ""
} |
q247064 | FlashAlertsHelper.resolveOptions | validation | private function resolveOptions(array $options = array())
{
$this->options['alertPublisher'] = $this->alertPublisher;
return array_merge($this->options, $options);
} | php | {
"resource": ""
} |
q247065 | Request.setMethod | validation | public function setMethod($method)
{
$method = strtolower($method);
if (!array_key_exists($method, $this->curl->getAllowedMethods())) {
throw new \InvalidArgumentException("Method [$method] not a valid HTTP method.");
}
$this->method = $method;
return $this;
} | php | {
"resource": ""
} |
q247066 | Request.encodeData | validation | public function encodeData()
{
switch ($this->encoding) {
case Request::ENCODING_JSON:
return json_encode($this->data);
break;
case Request::ENCODING_RAW:
return (string) $this->data;
break;
case Request::ENCODING_QUERY:
return http_build_query($this->data);
break;
default:
throw new \UnexpectedValueException("Encoding [$encoding] not a known Request::ENCODING_* constant");
}
} | php | {
"resource": ""
} |
q247067 | Request.setJson | validation | public function setJson($toggle)
{
$this->setEncoding($toggle ? Request::ENCODING_JSON : Request::ENCODING_QUERY);
return $this;
} | php | {
"resource": ""
} |
q247068 | Laracurl.buildUrl | validation | public function buildUrl($url, array $query)
{
// append the query string
if (!empty($query)) {
$queryString = http_build_query($query);
$url .= '?' . $queryString;
}
return $url;
} | php | {
"resource": ""
} |
q247069 | Laracurl.newRequest | validation | public function newRequest($method, $url, $data = array(), $encoding = Request::ENCODING_QUERY)
{
$class = $this->requestClass;
$request = new $class($this);
$request->setMethod($method);
$request->setUrl($url);
$request->setData($data);
$request->setEncoding($encoding);
return $request;
} | php | {
"resource": ""
} |
q247070 | Laracurl.newRawRequest | validation | public function newRawRequest($method, $url, $data = '')
{
return $this->newRequest($method, $url, $data, Request::ENCODING_RAW);
} | php | {
"resource": ""
} |
q247071 | Laracurl.prepareRequest | validation | public function prepareRequest(Request $request)
{
$this->ch = curl_init();
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_HEADER, true);
curl_setopt($this->ch, CURLOPT_URL, $request->getUrl());
$options = $request->getOptions();
if (!empty($options)) {
curl_setopt_array($this->ch, $options);
}
$method = $request->getMethod();
if ($method === 'post') {
curl_setopt($this->ch, CURLOPT_POST, 1);
} elseif ($method !== 'get') {
curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
}
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $request->formatHeaders());
if ($this->methods[$method] === true) {
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $request->encodeData());
}
} | php | {
"resource": ""
} |
q247072 | Laracurl.sendRequest | validation | public function sendRequest(Request $request)
{
$this->prepareRequest($request);
$result = curl_exec($this->ch);
if ($result === false) {
throw new \RuntimeException("cURL request failed with error: " . curl_error($this->ch));
}
$response = $this->createResponseObject($result);
curl_close($this->ch);
return $response;
} | php | {
"resource": ""
} |
q247073 | Laracurl.createResponseObject | validation | protected function createResponseObject($response)
{
$info = curl_getinfo($this->ch);
$headerSize = curl_getinfo($this->ch, CURLINFO_HEADER_SIZE);
$headerText = substr($response, 0, $headerSize);
$headers = $this->headerToArray($headerText);
$body = substr($response, $headerSize);
$class = $this->responseClass;
$obj = new $class($body, $headers, $info);
return $obj;
} | php | {
"resource": ""
} |
q247074 | Laracurl.headerToArray | validation | protected function headerToArray($header)
{
$tmp = explode("\r\n", $header);
$headers = array();
foreach ($tmp as $singleHeader) {
$delimiter = strpos($singleHeader, ': ');
if ($delimiter !== false) {
$key = substr($singleHeader, 0, $delimiter);
$val = substr($singleHeader, $delimiter + 2);
$headers[$key] = $val;
} else {
$delimiter = strpos($singleHeader, ' ');
if ($delimiter !== false) {
$key = substr($singleHeader, 0, $delimiter);
$val = substr($singleHeader, $delimiter + 1);
$headers[$key] = $val;
}
}
}
return $headers;
} | php | {
"resource": ""
} |
q247075 | Response.setCode | validation | protected function setCode($code)
{
$this->code = $code;
$this->statusText = $code;
list($this->statusCode, ) = explode(' ', $code);
} | php | {
"resource": ""
} |
q247076 | DocumentRoot.clearExpiredCacheEntries | validation | private function clearExpiredCacheEntries(int $now)
{
$this->now = $now;
foreach ($this->cacheTimeouts as $path => $timeout) {
if ($now <= $timeout) {
break;
}
$fileInfo = $this->cache[$path];
unset(
$this->cache[$path],
$this->cacheTimeouts[$path]
);
$this->bufferedFileCount -= isset($fileInfo->buffer);
$this->cacheEntryCount--;
}
} | php | {
"resource": ""
} |
q247077 | DocumentRoot.handleRequest | validation | public function handleRequest(Request $request): Promise
{
$path = removeDotPathSegments($request->getUri()->getPath());
return new Coroutine(
($fileInfo = $this->fetchCachedStat($path, $request))
? $this->respondFromFileInfo($fileInfo, $request)
: $this->respondWithLookup($this->root . $path, $path, $request)
);
} | php | {
"resource": ""
} |
q247078 | PhumborExtension.transform | validation | public function transform($orig, $transformation = null, $overrides = array())
{
return $this->transformer->transform($orig, $transformation, $overrides);
} | php | {
"resource": ""
} |
q247079 | BaseTransformer.transform | validation | public function transform($orig, $transformation = null, $overrides = array())
{
$url = $this->factory->url($orig);
if (is_null($transformation) && count($overrides) == 0) {
return $url;
}
// Check if a transformation is given without overrides
if (!isset($this->transformations[$transformation]) && count($overrides) == 0) {
throw new Exception\UnknownTransformationException(
"Unknown transformation $transformation. Use on of "
. "the following ".implode(', ', array_keys($this->transformations))
);
}
// Override transformation configuration with custom values
$configuration = array();
if (isset($this->transformations[$transformation])) {
$configuration = $this->transformations[$transformation];
}
$configuration = array_merge($configuration, $overrides);
// Build url from transformation configuration
foreach ($configuration as $filter => $arguments) {
$method = self::$filterMethod[$filter];
$this->$method($url, $arguments);
}
return $url;
} | php | {
"resource": ""
} |
q247080 | BaseTransformer.trim | validation | protected function trim(Builder $url, $args)
{
$args = (is_string($args)) ? $args : null;
$url->trim($args);
} | php | {
"resource": ""
} |
q247081 | BaseTransformer.crop | validation | protected function crop(Builder $url, $args)
{
$url->crop($args['top_left_x'], $args['top_left_y'], $args['bottom_right_x'], $args['bottom_right_y']);
} | php | {
"resource": ""
} |
q247082 | SamlUser.addRole | validation | public function addRole($role)
{
if (is_string($role)) {
$role = new Role($role);
} elseif (!$role instanceof RoleInterface) {
throw new \InvalidArgumentException(sprintf('Role must be a string or RoleInterface instance, but got %s.', gettype($role)));
}
if(!\in_array($role, $this->roles)) {
$this->roles[] = $role;
}
} | php | {
"resource": ""
} |
q247083 | BatchResizeAdditionalFieldProvider.getAdditionalFields | validation | public function getAdditionalFields(array &$taskInfo, $task, \TYPO3\CMS\Scheduler\Controller\SchedulerModuleController $parentObject)
{
$editCommand = version_compare(TYPO3_branch, '9.5', '>=')
? $parentObject->getCurrentAction() === Action::EDIT
: $parentObject->CMD === 'edit';
// Initialize selected fields
if (!isset($taskInfo['scheduler_batchResize_directories'])) {
$taskInfo['scheduler_batchResize_directories'] = $this->defaultDirectories;
if ($editCommand) {
/** @var $task \Causal\ImageAutoresize\Task\BatchResizeTask */
$taskInfo['scheduler_batchResize_directories'] = $task->directories;
}
}
if (!isset($taskInfo['scheduler_batchResize_excludeDirectories'])) {
$taskInfo['scheduler_batchResize_excludeDirectories'] = $this->defaultExcludeDirectories;
if ($editCommand) {
/** @var $task \Causal\ImageAutoresize\Task\BatchResizeTask */
$taskInfo['scheduler_batchResize_excludeDirectories'] = $task->excludeDirectories;
}
}
// Create HTML form fields
$additionalFields = [];
// Directories to be processed
$fieldName = 'tx_scheduler[scheduler_batchResize_directories]';
$fieldId = 'scheduler_batchResize_directories';
$fieldValue = trim($taskInfo['scheduler_batchResize_directories']);
$fieldHtml = '<textarea class="form-control" rows="4" name="' . $fieldName . '" id="' . $fieldId . '">' . htmlspecialchars($fieldValue) . '</textarea>';
$additionalFields[$fieldId] = [
'code' => $fieldHtml,
'label' => 'LLL:EXT:image_autoresize/Resources/Private/Language/locallang_mod.xlf:label.batchResize.directories',
];
// Directories to be excluded
$fieldName = 'tx_scheduler[scheduler_batchResize_excludeDirectories]';
$fieldId = 'scheduler_batchResize_excludeDirectories';
$fieldValue = trim($taskInfo['scheduler_batchResize_excludeDirectories']);
$fieldHtml = '<textarea class="form-control" rows="4" name="' . $fieldName . '" id="' . $fieldId . '">' . htmlspecialchars($fieldValue) . '</textarea>';
$additionalFields[$fieldId] = [
'code' => $fieldHtml,
'label' => 'LLL:EXT:image_autoresize/Resources/Private/Language/locallang_mod.xlf:label.batchResize.excludeDirectories',
];
return $additionalFields;
} | php | {
"resource": ""
} |
q247084 | BatchResizeAdditionalFieldProvider.validateAdditionalFields | validation | public function validateAdditionalFields(array &$submittedData, \TYPO3\CMS\Scheduler\Controller\SchedulerModuleController $parentObject)
{
$result = true;
// Check for valid directories
$directories = GeneralUtility::trimExplode(LF, $submittedData['scheduler_batchResize_directories'], true);
foreach ($directories as $directory) {
$absoluteDirectory = GeneralUtility::getFileAbsFileName($directory);
if (!@is_dir($absoluteDirectory)) {
$result = false;
$parentObject->addMessage(
sprintf(
$GLOBALS['LANG']->sL('LLL:EXT:image_autoresize/Resources/Private/Language/locallang_mod.xlf:msg.invalidDirectories'),
$directory
),
\TYPO3\CMS\Core\Messaging\FlashMessage::ERROR
);
}
}
$directories = GeneralUtility::trimExplode(LF, $submittedData['scheduler_batchResize_excludeDirectories'], true);
foreach ($directories as $directory) {
$absoluteDirectory = GeneralUtility::getFileAbsFileName($directory);
if (!@is_dir($absoluteDirectory)) {
$result = false;
$parentObject->addMessage(
sprintf(
$GLOBALS['LANG']->sL('LLL:EXT:image_autoresize/Resources/Private/Language/locallang_mod.xlf:msg.invalidExcludeDirectories'),
$directory
),
\TYPO3\CMS\Core\Messaging\FlashMessage::ERROR);
}
}
return $result;
} | php | {
"resource": ""
} |
q247085 | BatchResizeAdditionalFieldProvider.saveAdditionalFields | validation | public function saveAdditionalFields(array $submittedData, \TYPO3\CMS\Scheduler\Task\AbstractTask $task)
{
/** @var $task \Causal\ImageAutoresize\Task\BatchResizeTask */
$task->directories = trim($submittedData['scheduler_batchResize_directories']);
$task->excludeDirectories = trim($submittedData['scheduler_batchResize_excludeDirectories']);
} | php | {
"resource": ""
} |
q247086 | BatchResizeTask.execute | validation | public function execute()
{
$configuration = ConfigurationController::readConfiguration();
$this->imageResizer = GeneralUtility::makeInstance(\Causal\ImageAutoresize\Service\ImageResizer::class);
$this->imageResizer->initializeRulesets($configuration);
if (empty($this->directories)) {
// Process watched directories
$directories = $this->imageResizer->getAllDirectories();
} else {
$directories = GeneralUtility::trimExplode(LF, $this->directories, true);
}
$processedDirectories = [];
// Expand watched directories if they contain wildcard characters
$expandedDirectories = [];
foreach ($directories as $directory) {
if (($pos = strpos($directory, '/*')) !== false) {
$pattern = $this->imageResizer->getDirectoryPattern($directory);
$basePath = substr($directory, 0, $pos + 1);
$objects = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator(PATH_site . $basePath),
\RecursiveIteratorIterator::SELF_FIRST
);
foreach ($objects as $name => $object) {
$relativePath = substr($name, strlen(PATH_site));
if (substr($relativePath, -2) === DIRECTORY_SEPARATOR . '.') {
if (preg_match($pattern, $relativePath)) {
$expandedDirectories[] = substr($relativePath, 0, -1);
}
}
}
} else {
$expandedDirectories[] = $directory;
}
}
$directories = $expandedDirectories;
$success = true;
foreach ($directories as $directory) {
$skip = false;
foreach ($processedDirectories as $processedDirectory) {
if (GeneralUtility::isFirstPartOfStr($directory, $processedDirectory)) {
continue 2;
}
}
// Execute bach resize
$success |= $this->batchResizePictures($directory);
$processedDirectories[] = $directory;
}
return $success;
} | php | {
"resource": ""
} |
q247087 | BatchResizeTask.syslog | validation | public function syslog($message, $severity = \TYPO3\CMS\Core\Messaging\FlashMessage::OK)
{
switch ($severity) {
case \TYPO3\CMS\Core\Messaging\FlashMessage::NOTICE:
$severity = GeneralUtility::SYSLOG_SEVERITY_NOTICE;
break;
case \TYPO3\CMS\Core\Messaging\FlashMessage::INFO:
$severity = GeneralUtility::SYSLOG_SEVERITY_INFO;
break;
case \TYPO3\CMS\Core\Messaging\FlashMessage::OK:
$severity = GeneralUtility::SYSLOG_SEVERITY_INFO;
break;
case \TYPO3\CMS\Core\Messaging\FlashMessage::WARNING:
$severity = GeneralUtility::SYSLOG_SEVERITY_WARNING;
break;
case \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR:
$severity = GeneralUtility::SYSLOG_SEVERITY_ERROR;
break;
}
GeneralUtility::sysLog($message, 'image_autoresize', $severity);
} | php | {
"resource": ""
} |
q247088 | FileUpload.sanitizeFileName | validation | public function sanitizeFileName($fileName, \TYPO3\CMS\Core\Resource\Folder $folder)
{
$slotArguments = func_get_args();
// Last parameter is the signal name itself and is not actually part of the arguments
array_pop($slotArguments);
$storageConfiguration = $folder->getStorage()->getConfiguration();
$storageRecord = $folder->getStorage()->getStorageRecord();
if ($storageRecord['driver'] !== 'Local') {
// Unfortunately unsupported yet
return;
}
$targetDirectory = $storageConfiguration['pathType'] === 'relative' ? PATH_site : '';
$targetDirectory .= rtrim(rtrim($storageConfiguration['basePath'], '/') . $folder->getIdentifier(), '/');
$processedFileName = static::$imageResizer->getProcessedFileName(
$targetDirectory . '/' . $fileName,
$GLOBALS['BE_USER']
);
if ($processedFileName !== null) {
static::$originalFileName = $fileName;
$slotArguments[0] = PathUtility::basename($processedFileName);
return $slotArguments;
}
} | php | {
"resource": ""
} |
q247089 | FileUpload.populateMetadata | validation | public function populateMetadata(\TYPO3\CMS\Core\Resource\FileInterface $file, \TYPO3\CMS\Core\Resource\Folder $folder)
{
if (is_array(static::$metadata) && count(static::$metadata)) {
\Causal\ImageAutoresize\Utility\FAL::indexFile(
$file,
'', '',
static::$metadata['COMPUTED']['Width'],
static::$metadata['COMPUTED']['Height'],
static::$metadata
);
}
} | php | {
"resource": ""
} |
q247090 | ConfigurationController.moduleContent | validation | protected function moduleContent(array $row)
{
$this->formResultCompiler = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Form\FormResultCompiler::class);
$wizard = $this->formResultCompiler->addCssFiles();
$wizard .= $this->buildForm($row);
$wizard .= $this->formResultCompiler->printNeededJSFunctions();
$this->content .= $wizard;
} | php | {
"resource": ""
} |
q247091 | ConfigurationController.buildForm | validation | protected function buildForm(array $row)
{
$record = [
'uid' => static::virtualRecordId,
'pid' => 0,
];
$record = array_merge($record, $row);
// Trick to use a virtual record
$dataProviders =& $GLOBALS['TYPO3_CONF_VARS']['SYS']['formEngine']['formDataGroup']['tcaDatabaseRecord'];
$dataProviders[\Causal\ImageAutoresize\Backend\Form\FormDataProvider\VirtualDatabaseEditRow::class] = [
'before' => [
\TYPO3\CMS\Backend\Form\FormDataProvider\DatabaseEditRow::class,
]
];
// Initialize record in our virtual provider
\Causal\ImageAutoresize\Backend\Form\FormDataProvider\VirtualDatabaseEditRow::initialize($record);
/** @var \TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord $formDataGroup */
$formDataGroup = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord::class);
/** @var \TYPO3\CMS\Backend\Form\FormDataCompiler $formDataCompiler */
$formDataCompiler = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Form\FormDataCompiler::class, $formDataGroup);
/** @var \TYPO3\CMS\Backend\Form\NodeFactory $nodeFactory */
$nodeFactory = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Form\NodeFactory::class);
$formDataCompilerInput = [
'tableName' => static::virtualTable,
'vanillaUid' => $record['uid'],
'command' => 'edit',
'returnUrl' => '',
];
// Load the configuration of virtual table 'tx_imageautoresize'
$this->loadVirtualTca();
$formData = $formDataCompiler->compile($formDataCompilerInput);
$formData['renderType'] = 'outerWrapContainer';
$formResult = $nodeFactory->create($formData)->render();
// Remove header and footer
$html = preg_replace('/<h1>.*<\/h1>/', '', $formResult['html']);
$startFooter = strrpos($html, '<div class="help-block text-right">');
$endTag = '</div>';
if ($startFooter !== false) {
$endFooter = strpos($html, $endTag, $startFooter);
$html = substr($html, 0, $startFooter) . substr($html, $endFooter + strlen($endTag));
}
$formResult['html'] = '';
$formResult['doSaveFieldName'] = 'doSave';
// @todo: Put all the stuff into FormEngine as final "compiler" class
// @todo: This is done here for now to not rewrite JStop()
// @todo: and printNeededJSFunctions() now
$this->formResultCompiler->mergeResult($formResult);
// Combine it all
$formContent = '
<!-- EDITING FORM -->
' . $html . '
<input type="hidden" name="returnUrl" value="' . htmlspecialchars($this->retUrl) . '" />
<input type="hidden" name="closeDoc" value="0" />
<input type="hidden" name="doSave" value="0" />
<input type="hidden" name="_serialNumber" value="' . md5(microtime()) . '" />
<input type="hidden" name="_scrollPosition" value="" />';
$overriddenAjaxUrl = GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('TxImageAutoresize::record_flex_container_add'));
$formContent .= <<<HTML
<script type="text/javascript">
TYPO3.settings.ajaxUrls['record_flex_container_add'] = $overriddenAjaxUrl;
</script>
HTML;
return $formContent;
} | php | {
"resource": ""
} |
q247092 | ConfigurationController.addToolbarButtons | validation | protected function addToolbarButtons()
{
// Render SAVE type buttons:
// The action of each button is decided by its name attribute. (See doProcessData())
$buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
$saveSplitButton = $buttonBar->makeSplitButton();
// SAVE button:
$saveButton = $buttonBar->makeInputButton()
->setTitle(htmlspecialchars($this->languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:rm.saveDoc')))
->setName('_savedok')
->setValue('1')
->setForm('EditDocumentController')
->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
'actions-document-save',
\TYPO3\CMS\Core\Imaging\Icon::SIZE_SMALL
));
$saveSplitButton->addItem($saveButton, true);
// SAVE & CLOSE button:
$saveAndCloseButton = $buttonBar->makeInputButton()
->setTitle(htmlspecialchars($this->languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:rm.saveCloseDoc')))
->setName('_saveandclosedok')
->setValue('1')
->setForm('EditDocumentController')
->setClasses('t3js-editform-submitButton')
->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
'actions-document-save-close',
\TYPO3\CMS\Core\Imaging\Icon::SIZE_SMALL
));
$saveSplitButton->addItem($saveAndCloseButton);
$buttonBar->addButton($saveSplitButton, \TYPO3\CMS\Backend\Template\Components\ButtonBar::BUTTON_POSITION_LEFT, 2);
// CLOSE button:
$closeButton = $buttonBar->makeLinkButton()
->setTitle(htmlspecialchars($this->languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:rm.closeDoc')))
->setHref('#')
->setClasses('t3js-editform-close')
->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
'actions-view-go-back',
\TYPO3\CMS\Core\Imaging\Icon::SIZE_SMALL
));
$buttonBar->addButton($closeButton);
} | php | {
"resource": ""
} |
q247093 | ConfigurationController.processData | validation | protected function processData()
{
$close = GeneralUtility::_GP('closeDoc');
$save = GeneralUtility::_GP('_savedok');
$saveAndClose = GeneralUtility::_GP('_saveandclosedok');
if ($save || $saveAndClose) {
$table = static::virtualTable;
$id = static::virtualRecordId;
$field = 'rulesets';
$inputData_tmp = GeneralUtility::_GP('data');
$data = $inputData_tmp[$table][$id];
if (count($inputData_tmp[$table]) > 1) {
foreach ($inputData_tmp[$table] as $key => $values) {
if ($key === $id) continue;
ArrayUtility::mergeRecursiveWithOverrule($data, $values);
}
}
$newConfig = $this->config;
ArrayUtility::mergeRecursiveWithOverrule($newConfig, $data);
// Action commands (sorting order and removals of FlexForm elements)
$ffValue = &$data[$field];
if ($ffValue) {
$actionCMDs = GeneralUtility::_GP('_ACTION_FLEX_FORMdata');
if (is_array($actionCMDs[$table][$id][$field]['data'])) {
$dataHandler = new CustomDataHandler();
$dataHandler->_ACTION_FLEX_FORMdata($ffValue['data'], $actionCMDs[$table][$id][$field]['data']);
}
// Renumber all FlexForm temporary ids
$this->persistFlexForm($ffValue['data']);
// Keep order of FlexForm elements
$newConfig[$field] = $ffValue;
}
// Persist configuration
$localconfConfig = $newConfig;
$localconfConfig['conversion_mapping'] = implode(',', GeneralUtility::trimExplode(LF, $localconfConfig['conversion_mapping'], true));
if ($this->persistConfiguration($localconfConfig)) {
$this->config = $newConfig;
}
}
if ($close || $saveAndClose) {
$closeUrl = BackendUtility::getModuleUrl('tools_ExtensionmanagerExtensionmanager');
\TYPO3\CMS\Core\Utility\HttpUtility::redirect($closeUrl);
}
} | php | {
"resource": ""
} |
q247094 | ConfigurationController.loadVirtualTca | validation | protected function loadVirtualTca()
{
$GLOBALS['TCA'][static::virtualTable] = include(ExtensionManagementUtility::extPath($this->extKey) . 'Configuration/TCA/Module/Options.php');
ExtensionManagementUtility::addLLrefForTCAdescr(static::virtualTable, 'EXT:' . $this->extKey . '/Resource/Private/Language/locallang_csh_' . static::virtualTable . '.xlf');
} | php | {
"resource": ""
} |
q247095 | ConfigurationController.persistFlexForm | validation | protected function persistFlexForm(array &$valueArray)
{
foreach ($valueArray as $key => $value) {
if ($key === 'el') {
foreach ($value as $idx => $v) {
if ($v && substr($idx, 0, 3) === 'ID-') {
$valueArray[$key][substr($idx, 3)] = $v;
unset($valueArray[$key][$idx]);
}
}
} elseif (isset($valueArray[$key])) {
$this->persistFlexForm($valueArray[$key]);
}
}
} | php | {
"resource": ""
} |
q247096 | ConfigurationController.addStatisticsAndSocialLink | validation | protected function addStatisticsAndSocialLink()
{
$fileName = PATH_site . 'typo3temp/.tx_imageautoresize';
if (!is_file($fileName)) {
return;
}
$data = json_decode(file_get_contents($fileName), true);
if (!is_array($data) || !(isset($data['images']) && isset($data['bytes']))) {
return;
}
$resourcesPath = '../' . ExtensionManagementUtility::siteRelPath($this->extKey) . 'Resources/Public/';
$pageRenderer = $this->moduleTemplate->getPageRenderer();
$pageRenderer->addCssFile($resourcesPath . 'Css/twitter.css');
$pageRenderer->addJsFile($resourcesPath . 'JavaScript/popup.js');
$totalSpaceClaimed = GeneralUtility::formatSize((int)$data['bytes']);
$messagePattern = $this->languageService->getLL('storage.claimed');
$message = sprintf($messagePattern, $totalSpaceClaimed, (int)$data['images']);
$flashMessage = htmlspecialchars($message);
$twitterMessagePattern = $this->languageService->getLL('social.twitter');
$message = sprintf($twitterMessagePattern, $totalSpaceClaimed);
$url = 'https://extensions.typo3.org/extension/image_autoresize/';
$twitterLink = 'https://twitter.com/intent/tweet?text=' . urlencode($message) . '&url=' . urlencode($url);
$twitterLink = GeneralUtility::quoteJSvalue($twitterLink);
$flashMessage .= '
<div class="custom-tweet-button">
<a href="#" onclick="popitup(' . $twitterLink . ',\'twitter\')" title="' . htmlspecialchars($this->languageService->getLL('social.share')) . '">
<i class="btn-icon"></i>
<span class="btn-text">Tweet</span>
</a>
</div>';
$this->content .= '
<div class="alert alert-info">
<div class="media">
<div class="media-left">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-info fa-stack-1x"></i>
</span>
</div>
<div class="media-body">
' . $flashMessage . '
</div>
</div>
</div>
';
} | php | {
"resource": ""
} |
q247097 | ImageResizer.initializeRulesets | validation | public function initializeRulesets(array $configuration)
{
$general = $configuration;
$general['usergroup'] = '';
unset($general['rulesets']);
$general = $this->expandValuesInRuleset($general);
if ($general['conversion_mapping'] === '') {
$general['conversion_mapping'] = [];
}
if (isset($configuration['rulesets'])) {
$rulesets = $this->compileRuleSets($configuration['rulesets']);
} else {
$rulesets = [];
}
// Inherit values from general configuration in rule sets if needed
foreach ($rulesets as $k => &$ruleset) {
foreach ($general as $key => $value) {
if (!isset($ruleset[$key])) {
$ruleset[$key] = $value;
} elseif ($ruleset[$key] === '') {
$ruleset[$key] = $value;
}
}
if (count($ruleset['usergroup']) == 0) {
// Make sure not to try to override general configuration
// => only keep directories not present in general configuration
$ruleset['directories'] = array_diff($ruleset['directories'], $general['directories']);
if (count($ruleset['directories']) == 0) {
unset($rulesets[$k]);
}
}
}
// Use general configuration as very last rule set
$rulesets[] = $general;
$this->rulesets = $rulesets;
} | php | {
"resource": ""
} |
q247098 | ImageResizer.localize | validation | protected function localize($input)
{
if (TYPO3_MODE === 'FE') {
$output = is_object($GLOBALS['TSFE']) ? $GLOBALS['TSFE']->sL($input) : $input;
} else {
$output = $GLOBALS['LANG']->sL($input);
}
return $output;
} | php | {
"resource": ""
} |
q247099 | ImageResizer.notify | validation | protected function notify($callbackNotification, $message, $severity)
{
$callableName = '';
if (is_callable($callbackNotification, false, $callableName)) {
call_user_func($callbackNotification, $message, $severity);
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.