public function manageRecordUpdate($tableName, $recordData, $activityEntryMode = self::ACTIVITY_ENTRY_MODE_PARENT, &$childLogEntries = null, &$parentCollectionRelationshipsChanged = false, $parentData = array()) { $log = $this->logger(); $schemaArray = TableSchema::getSchemaArray($tableName); $currentUser = AuthProvider::getUserRecord(); $TableGateway = $this; if ($tableName !== $this->table) { $TableGateway = new RelationalTableGateway($this->acl, $tableName, $this->adapter); } // Upload file if necessary $TableGateway->copyFiles($tableName, $recordData); $recordIsNew = !array_key_exists($TableGateway->primaryKeyFieldName, $recordData); //Dont do for directus users since id is pk if ($recordIsNew && $tableName != 'directus_users') { $cmsOwnerColumnName = $this->acl->getCmsOwnerColumnByTable($tableName); if ($cmsOwnerColumnName) { $recordData[$cmsOwnerColumnName] = $currentUser['id']; } } //Dont let non-admins make admins if ($tableName == 'directus_users' && $currentUser['group'] != 1) { if (isset($recordData['group']) && $recordData['group']['id'] == 1) { unset($recordData['group']); } } $thisIsNested = $activityEntryMode == self::ACTIVITY_ENTRY_MODE_CHILD; // Recursive functions will change this value (by reference) as necessary // $nestedCollectionRelationshipsChanged = $thisIsNested ? $parentCollectionRelationshipsChanged : false; $nestedCollectionRelationshipsChanged = false; if ($thisIsNested) { $nestedCollectionRelationshipsChanged =& $parentCollectionRelationshipsChanged; } // Recursive functions will append to this array by reference // $nestedLogEntries = $thisIsNested ? $childLogEntries : array(); $nestedLogEntries = array(); if ($thisIsNested) { $nestedLogEntries =& $childLogEntries; } // Update and/or Add Many-to-One Associations $parentRecordWithForeignKeys = $TableGateway->addOrUpdateManyToOneRelationships($schemaArray, $recordData, $nestedLogEntries, $nestedCollectionRelationshipsChanged); // Merge the M21 foreign keys into the recordData array $recordData = array_merge($recordData, $parentRecordWithForeignKeys); // If more than the record ID is present. $newRecordObject = null; $parentRecordChanged = $this->recordDataContainsNonPrimaryKeyData($parentRecordWithForeignKeys); // || $recordIsNew; if ($parentRecordChanged) { // Update the parent row, w/ any new association fields replaced by their IDs $newRecordObject = $TableGateway->addOrUpdateRecordByArray($parentRecordWithForeignKeys)->toArray(); } // Do it this way, because & byref for outcome of ternary operator spells trouble $draftRecord =& $parentRecordWithForeignKeys; if ($recordIsNew) { $draftRecord =& $newRecordObject; } // Restore X2M relationship / alias fields to the record representation & process these relationships. $collectionColumns = TableSchema::getAllAliasTableColumns($tableName); foreach ($collectionColumns as $collectionColumn) { $colName = $collectionColumn['id']; if (isset($recordData[$colName])) { $draftRecord[$colName] = $recordData[$colName]; } } // parent if ($activityEntryMode === self::ACTIVITY_ENTRY_MODE_PARENT) { $parentData = array('id' => array_key_exists($this->primaryKeyFieldName, $recordData) ? $recordData[$this->primaryKeyFieldName] : null, 'table_name' => $tableName); } $draftRecord = $TableGateway->addOrUpdateToManyRelationships($schemaArray, $draftRecord, $nestedLogEntries, $nestedCollectionRelationshipsChanged, $parentData); $rowId = $draftRecord[$this->primaryKeyFieldName]; $columnNames = TableSchema::getAllNonAliasTableColumnNames($tableName); $TemporaryTableGateway = new TableGateway($tableName, $this->adapter); $fullRecordData = $TemporaryTableGateway->select(function ($select) use($rowId, $columnNames) { $select->where->equalTo($this->primaryKeyFieldName, $rowId); $select->limit(1)->columns($columnNames); })->current(); if (!$fullRecordData) { $recordType = $recordIsNew ? "new" : "pre-existing"; throw new \RuntimeException("Attempted to load {$recordType} record post-insert with empty result. Lookup via row id: " . print_r($rowId, true)); } $fullRecordData = (array) $fullRecordData; $deltaRecordData = $recordIsNew ? array() : array_intersect_key((array) $parentRecordWithForeignKeys, (array) $fullRecordData); switch ($activityEntryMode) { // Activity logging is enabled, and I am a nested action case self::ACTIVITY_ENTRY_MODE_CHILD: $logEntryAction = $recordIsNew ? DirectusActivityTableGateway::ACTION_ADD : DirectusActivityTableGateway::ACTION_UPDATE; $childLogEntries[] = array('type' => DirectusActivityTableGateway::makeLogTypeFromTableName($this->table), 'table_name' => $tableName, 'action' => $logEntryAction, 'user' => $currentUser['id'], 'datetime' => gmdate('Y-m-d H:i:s'), 'parent_id' => isset($parentData['id']) ? $parentData['id'] : null, 'parent_table' => isset($parentData['table_name']) ? $parentData['table_name'] : null, 'data' => json_encode($fullRecordData), 'delta' => json_encode($deltaRecordData), 'row_id' => $rowId, 'identifier' => $this->findRecordIdentifier($schemaArray, $fullRecordData), 'logged_ip' => $_SERVER['REMOTE_ADDR'], 'user_agent' => $_SERVER['HTTP_USER_AGENT']); if ($recordIsNew) { /** * This is a nested call, creating a new record w/in a foreign collection. * Indicate by reference that the top-level record's relationships have changed. */ $parentCollectionRelationshipsChanged = true; } break; case self::ACTIVITY_ENTRY_MODE_PARENT: // Does this act deserve a log? $parentRecordNeedsLog = $nestedCollectionRelationshipsChanged || $parentRecordChanged; /** * NESTED QUESTIONS! * @todo what do we do if the foreign record OF a foreign record changes? * is that activity entry also directed towards this parent activity entry? * @todo how should nested activity entries relate to the revision histories of foreign items? * @todo one day: treat children as parents if this top-level record was not modified. */ $recordIdentifier = $this->findRecordIdentifier($schemaArray, $fullRecordData); // Produce log if something changed. if ($parentRecordChanged || $nestedCollectionRelationshipsChanged) { $logEntryAction = $recordIsNew ? DirectusActivityTableGateway::ACTION_ADD : DirectusActivityTableGateway::ACTION_UPDATE; //If we are updating and active is being set to 0 then we are deleting if (!$recordIsNew && array_key_exists(STATUS_COLUMN_NAME, $deltaRecordData)) { if ($deltaRecordData[STATUS_COLUMN_NAME] == STATUS_DELETED_NUM) { $logEntryAction = DirectusActivityTableGateway::ACTION_DELETE; } } // Save parent log entry $parentLogEntry = AclAwareRowGateway::makeRowGatewayFromTableName($this->acl, "directus_activity", $this->adapter); $logData = array('type' => DirectusActivityTableGateway::makeLogTypeFromTableName($this->table), 'table_name' => $tableName, 'action' => $logEntryAction, 'user' => $currentUser['id'], 'datetime' => gmdate('Y-m-d H:i:s'), 'parent_id' => null, 'data' => json_encode($fullRecordData), 'delta' => json_encode($deltaRecordData), 'parent_changed' => (int) $parentRecordChanged, 'identifier' => $recordIdentifier, 'row_id' => $rowId, 'logged_ip' => $_SERVER['REMOTE_ADDR'], 'user_agent' => $_SERVER['HTTP_USER_AGENT']); $parentLogEntry->populate($logData, false); $parentLogEntry->save(); // Update & insert nested activity entries $ActivityGateway = new DirectusActivityTableGateway($this->acl, $this->adapter); foreach ($nestedLogEntries as $entry) { $entry['parent_id'] = $rowId; // @todo ought to insert these in one batch $ActivityGateway->insert($entry); } } break; } // Yield record object $recordGateway = new AclAwareRowGateway($this->acl, $TableGateway->primaryKeyFieldName, $tableName, $this->adapter); $recordGateway->populate($fullRecordData, true); return $recordGateway; }
return JsonView::render(array('message' => 'Invalid table name')); } unset($requestPayload['addTable']); try { $statusColumnName = STATUS_COLUMN_NAME; $createTableQuery = "CREATE TABLE `{$requestPayload['table_name']}` (\n id int(11) unsigned NOT NULL AUTO_INCREMENT,\n `{$statusColumnName}` tinyint(1) unsigned DEFAULT NULL,\n PRIMARY KEY(id)\n );"; $ZendDb->query($createTableQuery, $ZendDb::QUERY_MODE_EXECUTE); } catch (\Exception $e) { } } $privileges = new DirectusPrivilegesTableGateway($acl, $ZendDb); $response = $privileges->insertPrivilege($requestPayload); return JsonView::render($response); })->via('POST'); $app->map("/{$v}/privileges/:groupId/:privilegeId", function ($groupId, $privilegeId) use($acl, $ZendDb, $params, $requestPayload, $app) { $currentUser = Auth::getUserRecord(); $myGroupId = $currentUser['group']; if ($myGroupId != 1) { throw new Exception('Permission denied'); } $privileges = new DirectusPrivilegesTableGateway($acl, $ZendDb); if (isset($requestPayload['activeState'])) { if ($requestPayload['activeState'] !== 'all') { $priv = $privileges->findByStatus($requestPayload['table_name'], $requestPayload['group_id'], $requestPayload['activeState']); if ($priv) { $requestPayload['id'] = $priv['id']; $requestPayload['status_id'] = $priv['status_id']; } else { unset($requestPayload['id']); $requestPayload['status_id'] = $requestPayload['activeState']; $response = $privileges->insertPrivilege($requestPayload);
private function isCurrentUserAdmin() { $currentUser = Auth::getUserRecord(); //Dont let non-admins have alter privilege return $currentUser['group'] == 1 ? true : false; }
$ZendDb = Bootstrap::get('ZendDb'); $acl = Bootstrap::get('acl'); /** * Authentication */ $DirectusUsersTableGateway = new DirectusUsersTableGateway($acl, $ZendDb); Auth::setUserCacheRefreshProvider(function ($userId) use($DirectusUsersTableGateway) { $cacheFn = function () use($userId, $DirectusUsersTableGateway) { return $DirectusUsersTableGateway->find($userId); }; $cacheKey = MemcacheProvider::getKeyDirectusUserFind($userId); $user = $DirectusUsersTableGateway->memcache->getOrCache($cacheKey, $cacheFn, 10800); return $user; }); if (Auth::loggedIn()) { $user = Auth::getUserRecord(); $acl->setUserId($user['id']); $acl->setGroupId($user['group']); } $app->hook('slim.before.dispatch', function () use($app) { if (!Auth::loggedIn()) { http_response_code(403); echo "<h1>403 Forbidden</h1>"; // $app->halt(403); // Never works very well exit; } }); $app->get("/:id/:format(/:filename)", function ($id, $format, $filename) use($app, $acl, $ZendDb) { $notFound = function () { http_response_code(404); echo "<h1>404 Not found</h1>";
function get_auth_info($attribute) { // if there's not config files created if (!defined('BASE_PATH') || !defined('APPLICATION_PATH')) { return null; } if (!Directus\Auth\Provider::loggedIn()) { return null; } $userInfo = \Directus\Auth\Provider::getUserRecord(); return isset($userInfo[$attribute]) ? $userInfo[$attribute] : null; }