sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function verifyUploadedFile($file) { if (is_array($file['error'])) { throw new BadRequestException("Only a single application package file is allowed for import."); } if (UPLOAD_ERR_OK !== ($error = $file['error'])) { throw new InternalServerErrorException( "Failed to receive upload of '" . $file['name'] . "': " . $error ); } $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); if (static::FILE_EXTENSION != $extension) { throw new BadRequestException("Only package files ending with '" . static::FILE_EXTENSION . "' are allowed for import."); } $this->setZipFile($file['tmp_name']); }
Verifies the uploaed file for importing process. @param $file @throws \DreamFactory\Core\Exceptions\BadRequestException @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
protected function verifyImportFromUrl($url) { $extension = strtolower(pathinfo($url, PATHINFO_EXTENSION)); if (static::FILE_EXTENSION != $extension) { throw new BadRequestException("Only package files ending with '" . static::FILE_EXTENSION . "' are allowed for import."); } try { // need to download and extract zip file and move contents to storage $file = FileUtilities::importUrlFileToTemp($url); } catch (\Exception $ex) { throw new InternalServerErrorException("Failed to import package from $url. {$ex->getMessage()}"); } $this->setZipFile($file); }
Verifies file import from url. @param $url @throws \DreamFactory\Core\Exceptions\BadRequestException @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
private function setZipFile($file) { $zip = new \ZipArchive(); if (true !== $zip->open($file)) { throw new InternalServerErrorException('Error opening zip file.'); } $this->zip = $zip; $this->zipFilePath = $file; }
Opens and sets the zip file for import. @param string $file @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
private function sanitizeAppRecord(& $record) { if (!is_array($record)) { throw new BadRequestException('Invalid App data provided'); } if (!isset($record['name'])) { throw new BadRequestException('No App name provided in description.json'); } if (!isset($record['type'])) { $record['type'] = AppTypes::NONE; } if (isset($record['active']) && !isset($record['is_active'])) { $record['is_active'] = $record['active']; unset($record['active']); } elseif (!isset($record['is_active'])) { $record['is_active'] = true; } if ($record['type'] === AppTypes::STORAGE_SERVICE) { if (!empty($serviceId = array_get($record, 'storage_service_id'))) { $fileServiceNames = ServiceManager::getServiceNamesByGroup(ServiceTypeGroups::FILE); $serviceName = ServiceManager::getServiceNameById($serviceId); if (!in_array($serviceName, $fileServiceNames)) { throw new BadRequestException('Invalid Storage Service provided.'); } } else { $record['storage_service_id'] = $this->getDefaultStorageServiceId(); } if (!empty(array_get($record, 'storage_container'))) { $record['storage_container'] = trim($record['storage_container'], '/'); } else { $record['storage_container'] = camelize($record['name']); } } else { $record['storage_service_id'] = null; $record['storage_container'] = null; } if (!isset($record['url'])) { $record['url'] = static::DEFAULT_URL; } else { $record['url'] = ltrim($record['url'], '/'); } if (isset($record['path'])) { $record['path'] = ltrim($record['path'], '/'); } if ($record['type'] === AppTypes::STORAGE_SERVICE || $record['type'] === AppTypes::PATH) { if (empty(array_get($record, 'path'))) { throw new BadRequestException('No Application Path provided in description.json'); } } elseif ($record['type'] === AppTypes::URL) { if (empty(array_get($record, 'url'))) { throw new BadRequestException('No Application URL provided in description.json'); } } }
Sanitizes the app record description.json @param $record @throws \DreamFactory\Core\Exceptions\BadRequestException
entailment
private function insertAppRecord(& $record, $ssId = null, $sc = null) { $record['storage_service_id'] = $ssId; $record['storage_container'] = $sc; $this->sanitizeAppRecord($record); try { $result = ServiceManager::handleRequest('system', Verbs::POST, 'app', ['fields' => '*'], [], [$record]); if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } } catch (\Exception $ex) { throw new InternalServerErrorException("Could not create the application.\n{$ex->getMessage()}"); } $result = $result->getContent(); return ($this->resourceWrapped) ? $result[$this->resourceWrapper][0] : $result[0]; }
@param $record @param null $ssId @param null $sc @return mixed @throws \DreamFactory\Core\Exceptions\BadRequestException @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
private function storeApplicationFiles($appInfo) { if (array_get($appInfo, 'type', AppTypes::NONE) === AppTypes::STORAGE_SERVICE) { $appName = camelize(array_get($appInfo, 'name')); $storageServiceId = array_get($appInfo, 'storage_service_id', $this->getDefaultStorageServiceId()); $storageFolder = array_get($appInfo, 'storage_container', $appName); /** @var $service FileServiceInterface */ $service = ServiceManager::getServiceById($storageServiceId); if (empty($service)) { throw new InternalServerErrorException( "App record created, but failed to import files due to unknown storage service with id '$storageServiceId'." ); } elseif (!($service instanceof FileServiceInterface)) { throw new InternalServerErrorException( "App record created, but failed to import files due to storage service with id '$storageServiceId' not being a file service." ); } $info = $service->extractZipFile($storageFolder, $this->zip); return $info; } else { return []; } }
@param array $appInfo @return array @throws InternalServerErrorException @throws NotFoundException
entailment
public function importAppFromPackage($storageServiceId = null, $storageContainer = null, $record = null) { $record = (array)$record; $data = $this->getAppInfo(); // merge in overriding parameters from request if given $record = array_merge($data, $record); \DB::beginTransaction(); $appResults = $this->insertAppRecord($record, $storageServiceId, $storageContainer); try { $this->insertServices(); $this->insertSchemas(); $this->insertData(); $this->storeApplicationFiles($record); } catch (\Exception $ex) { //Rollback all db changes; \DB::rollBack(); throw $ex; } \DB::commit(); return $appResults; }
@param null | integer $storageServiceId @param null | string $storageContainer @param null | array $record @return \DreamFactory\Core\Contracts\ServiceResponseInterface|mixed @throws \DreamFactory\Core\Exceptions\BadRequestException @throws \DreamFactory\Core\Exceptions\InternalServerErrorException @throws \Exception
entailment
private function initExportZipFile($appName) { $zip = new \ZipArchive(); $tmpDir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $zipFileName = $tmpDir . $appName . '.' . static::FILE_EXTENSION; $this->zip = $zip; $this->zipFilePath = $zipFileName; if (true !== $this->zip->open($zipFileName, \ZipArchive::CREATE)) { throw new InternalServerErrorException('Can not create package file for this application.'); } return true; }
Initialize export zip file. @param $appName @return bool @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
private function packageAppDescription($app) { $record = [ 'name' => $app->name, 'description' => $app->description, 'is_active' => $app->is_active, 'type' => $app->type, 'path' => $app->path, 'url' => $app->url, 'requires_fullscreen' => $app->requires_fullscreen, 'allow_fullscreen_toggle' => $app->allow_fullscreen_toggle, 'toggle_location' => $app->toggle_location ]; if (!$this->zip->addFromString('description.json', json_encode($record, JSON_UNESCAPED_SLASHES))) { throw new InternalServerErrorException("Can not include description in package file."); } return true; }
Package app info for export. @param $app @return bool @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
private function packageAppFiles($app) { $appName = $app->name; $zipFileName = $this->zipFilePath; $storageServiceId = $app->storage_service_id; $storageFolder = $app->storage_container; if (empty($storageServiceId)) { $storageServiceId = $this->getDefaultStorageServiceId(); } if (empty($storageServiceId)) { throw new InternalServerErrorException("Can not find storage service identifier."); } /** @type FileServiceInterface $storage */ $storage = ServiceManager::getServiceById($storageServiceId); if (!$storage) { throw new InternalServerErrorException("Can not find storage service by identifier '$storageServiceId''."); } if ($storage->folderExists($storageFolder)) { $storage->getFolderAsZip($storageFolder, $this->zip, $zipFileName, true); } return true; }
Package app files for export. @param $app @return bool @throws \DreamFactory\Core\Exceptions\ForbiddenException @throws \DreamFactory\Core\Exceptions\InternalServerErrorException @throws \DreamFactory\Core\Exceptions\NotFoundException
entailment
private function packageServices() { if (!empty($this->exportServices)) { $services = []; foreach ($this->exportServices as $serviceName) { if (is_numeric($serviceName)) { /** @type Service $service */ $service = Service::find($serviceName); } else { /** @type Service $service */ $service = Service::whereName($serviceName)->whereDeletable(1)->first(); } if (!empty($service)) { $services[] = [ 'name' => $service->name, 'label' => $service->label, 'description' => $service->description, 'type' => $service->type, 'is_active' => $service->is_active, 'mutable' => $service->mutable, 'deletable' => $service->deletable, 'config' => $service->config ]; } } if (!empty($services) && !$this->zip->addFromString('services.json', json_encode($services, JSON_UNESCAPED_SLASHES)) ) { throw new InternalServerErrorException("Can not include services in package file."); } return true; } return false; }
Package services for export. @return bool @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
private function packageSchemas() { if (!empty($this->exportSchemas)) { $schemas = []; foreach ($this->exportSchemas as $serviceName => $component) { if (is_array($component)) { $component = implode(',', $component); } if (is_numeric($serviceName)) { /** @type Service $service */ $service = Service::find($serviceName); } else { /** @type Service $service */ $service = Service::whereName($serviceName)->whereDeletable(1)->first(); } if (!empty($service) && !empty($component)) { if ($service->type === 'sql_db') { $result = ServiceManager::handleRequest( $serviceName, Verbs::GET, '_schema', ['ids' => $component] ); if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } $schema = $result->getContent(); $schemas[] = [ 'name' => $serviceName, 'table' => ($this->resourceWrapped) ? $schema[$this->resourceWrapper] : $schema ]; } } } if (!empty($schemas) && !$this->zip->addFromString('schema.json', json_encode(['service' => $schemas], JSON_UNESCAPED_SLASHES)) ) { throw new InternalServerErrorException("Can not include database schema in package file."); } return true; } return false; }
Package schemas for export. @return bool @throws InternalServerErrorException @throws \DreamFactory\Core\Exceptions\RestException
entailment
public function exportAppAsPackage($includeFiles = true, $includeData = false) { /** @type App $app */ $app = App::find($this->exportAppId); if (empty($app)) { throw new NotFoundException('App not found in database with app id - ' . $this->exportAppId); } $appName = $app->name; try { $this->initExportZipFile($appName); $this->packageAppDescription($app); $this->packageServices(); $this->packageSchemas(); if ($includeData) { $this->packageData(); } if ($app->type === AppTypes::STORAGE_SERVICE && $includeFiles) { $this->packageAppFiles($app); } $this->zip->close(); FileUtilities::sendFile($this->zipFilePath, true); return null; } catch (\Exception $e) { //Do necessary things here. throw $e; } }
@param bool|true $includeFiles @param bool|false $includeData @return null @throws \DreamFactory\Core\Exceptions\NotFoundException @throws \Exception
entailment
public function getMethodAttribute($method) { if (is_array($method)) { return $method; } else { if (is_string($method)) { $method = (integer)$method; } } return VerbsMask::maskToArray($method); }
Converts verb masks to array of verbs (string) as needed. @param $method @return string
entailment
public function setMethodAttribute($method) { if (is_array($method)) { $action = 0; foreach ($method as $verb) { $action = $action | VerbsMask::toNumeric($verb); } } else { $action = $method; } $this->attributes['method'] = $action; }
Converts methods array to verb masks @param $method @throws \DreamFactory\Core\Exceptions\NotImplementedException
entailment
public function import() { \DB::beginTransaction(); try { $imported = ($this->insertRole()) ?: false; $imported = ($this->insertService()) ?: $imported; $imported = ($this->insertRoleServiceAccess()) ?: $imported; $imported = ($this->insertApp()) ?: $imported; $imported = ($this->insertUser()) ?: $imported; $imported = ($this->insertUserAppRole()) ?: $imported; $imported = ($this->insertOtherResource()) ?: $imported; $imported = ($this->insertEventScripts()) ?: $imported; $imported = ($this->storeFiles()) ?: $imported; $imported = ($this->overwrote) ?: $imported; } catch (\Exception $e) { \DB::rollBack(); \Log::error('Failed to import package. Rolling back. ' . $e->getMessage()); throw $e; } \DB::commit(); return $imported; }
Imports the packages. @throws \Exception @return bool
entailment
protected function insertRole() { $data = $this->package->getResourceFromZip('system/role.json'); $roles = $this->cleanDuplicates($data, 'system', 'role'); if (!empty($roles)) { try { foreach ($roles as $i => $role) { $this->fixCommonFields($role); unset($role['role_service_access_by_role_id']); $roles[$i] = $role; } $payload = ResourcesWrapper::wrapResources($roles); $result = ServiceManager::handleRequest( 'system', Verbs::POST, 'role', [], [], $payload, null, true, true ); if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } return true; } catch (\Exception $e) { // if ($e->getCode() === HttpStatusCodes::HTTP_FORBIDDEN) { // $this->log('error', 'Failed to insert roles. ' . $this->getErrorDetails($e)); // } else { // throw new InternalServerErrorException('Failed to insert roles. ' . $this->getErrorDetails($e)); // } $this->throwExceptions($e, 'Failed to insert roles'); } } return false; }
Imports system/role @return bool @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
protected function insertUser() { $data = $this->package->getResourceFromZip('system/user.json'); $users = $this->cleanDuplicates($data, 'system', 'user'); if (!empty($users)) { try { foreach ($users as $i => $user) { $this->fixCommonFields($user); unset($user['user_to_app_to_role_by_user_id']); $users[$i] = $user; } $payload = ResourcesWrapper::wrapResources($users); $result = ServiceManager::handleRequest( 'system', Verbs::POST, 'user', [], [], $payload, null, true, true ); if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } static::updateUserPassword($users); return true; } catch (DecryptException $e) { throw new UnauthorizedException('Invalid password.'); } catch (\Exception $e) { // if ($e->getCode() === HttpStatusCodes::HTTP_FORBIDDEN) { // $this->log('error', 'Failed to insert users. ' . $this->getErrorDetails($e)); // } else { // throw new InternalServerErrorException('Failed to insert users. ' . $this->getErrorDetails($e)); // } $this->throwExceptions($e, 'Failed to insert users'); } } return false; }
Imports system/user @return bool @throws \DreamFactory\Core\Exceptions\InternalServerErrorException @throws \DreamFactory\Core\Exceptions\UnauthorizedException
entailment
protected static function updateUserPassword($users) { if (!empty($users)) { foreach ($users as $i => $user) { if (isset($user['password'])) { /** @type User $model */ $model = User::where('email', '=', $user['email'])->first(); $model->updatePasswordHash($user['password']); } } } }
Updates user password when package is secured with a password. @param $users @throws \DreamFactory\Core\Exceptions\BadRequestException
entailment
protected function insertUserAppRole() { $usersInZip = $this->package->getResourceFromZip('system/user.json'); $imported = false; if (!empty($usersInZip)) { try { foreach ($usersInZip as $uiz) { $uar = $uiz['user_to_app_to_role_by_user_id']; $user = User::whereEmail($uiz['email'])->first(); if (!empty($user) && !empty($uar)) { $newUserId = $user->id; $cleanedUar = []; foreach ($uar as $r) { $originId = $r['id']; $this->fixCommonFields($r); $newRoleId = $this->getNewRoleId($r['role_id']); $newAppId = $this->getNewAppId($r['app_id']); if (empty($newRoleId) && !empty($r['role_id'])) { $this->log( 'warning', 'Skipping relation user_to_app_to_role_by_user_id with id ' . $originId . ' for user ' . $uiz['email'] . '. Role not found for id ' . $r['role_id'] ); continue; } if (empty($newAppId) && !empty($r['app_id'])) { $this->log( 'warning', 'Skipping relation user_to_app_to_role_by_user_id with id ' . $originId . ' for user ' . $uiz['email'] . '. App not found for id ' . $r['app_id'] ); continue; } $r['role_id'] = $newRoleId; $r['app_id'] = $newAppId; $r['user_id'] = $newUserId; if ($this->isDuplicateUserAppRole($r)) { $this->log( 'notice', 'Skipping duplicate user_to_app_to_role relation with id ' . $originId . '.' ); continue; } $cleanedUar[] = $r; } if (!empty($cleanedUar)) { $userUpdate = ['user_to_app_to_role_by_user_id' => $cleanedUar]; $result = ServiceManager::handleRequest( 'system', Verbs::PATCH, 'user/' . $newUserId, [], [], $userUpdate, null, true, true ); if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } $imported = true; } } elseif (!empty($uar) && empty($user)) { $this->log( 'warning', 'Skipping all user_to_app_to_role_by_user_id relations for user ' . $uiz['email'] . ' No imported/existing user found.' ); \Log::debug('Skipped user_to_app_to_role_by_user_id.', $uiz); } else { $this->log('notice', 'No user_to_app_to_role_by_user_id relation for user ' . $uiz['email']); } } } catch (\Exception $e) { // if ($e->getCode() === HttpStatusCodes::HTTP_FORBIDDEN) { // $this->log( // 'error', // 'Failed to insert user_to_app_to_role_by_user_id relation for users. ' . // $this->getErrorDetails($e) // ); // } else { // throw new InternalServerErrorException( // 'Failed to insert user_to_app_to_role_by_user_id relation for users. ' . // $this->getErrorDetails($e) // ); // } $this->throwExceptions($e, 'Failed to insert user_to_app_to_role_by_user_id relation for users'); } } return $imported; }
Imports user_to_app_to_role_by_user_id relation. @return bool @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
protected function insertService() { $data = $this->package->getResourceFromZip('system/service.json'); $services = $this->cleanDuplicates($data, 'system', 'service'); if (!empty($services)) { try { foreach ($services as $i => $service) { unset($service['id']); unset($service['last_modified_by_id']); $service['created_by_id'] = Session::getCurrentUserId(); if (!empty($oldRoleId = array_get($service, 'config.default_role'))) { $newRoleId = $this->getNewRoleId($oldRoleId); if (!empty($newRoleId)) { array_set($service, 'config.default_role', $newRoleId); } else { // If no new role found then do not store config. default_role field is not nullable. $this->log( 'warning', 'Skipping config for service ' . $service['name'] . '. Default role not found by role id ' . $oldRoleId ); \Log::debug('Skipped service.', $service); unset($service['config']); } } if (!empty($oldDoc = array_get($service, 'doc'))) { $service['service_doc_by_service_id'] = $oldDoc; unset($service['doc']); } $services[$i] = $service; } $payload = ResourcesWrapper::wrapResources($services); $result = ServiceManager::handleRequest( 'system', Verbs::POST, 'service', [], [], $payload, null, true, true ); if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } return true; } catch (\Exception $e) { // if ($e->getCode() === HttpStatusCodes::HTTP_FORBIDDEN) { // $this->log('error', "Failed to insert services. " . $this->getErrorDetails($e)); // } else { // throw new InternalServerErrorException("Failed to insert services. " . $this->getErrorDetails($e)); // } $this->throwExceptions($e, 'Failed to insert services'); } } return false; }
Imports system/service @return bool @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
protected function insertRoleServiceAccess() { $rolesInZip = $this->package->getResourceFromZip('system/role.json'); $imported = false; if (!empty($rolesInZip)) { try { foreach ($rolesInZip as $riz) { $rsa = $riz['role_service_access_by_role_id']; $role = Role::whereName($riz['name'])->first(); if (!empty($role) && !empty($rsa)) { $newRoleId = $role->id; $cleanedRsa = []; foreach ($rsa as $r) { $originId = $r['id']; $this->fixCommonFields($r); $newServiceId = $this->getNewServiceId($r['service_id']); if (empty($newServiceId) && !empty($r['service_id'])) { $this->log( 'warning', 'Skipping relation role_service_access_by_role_id with id ' . $originId . ' for Role ' . $riz['name'] . '. Service not found for ' . $r['service_id'] ); continue; } $r['service_id'] = $newServiceId; $r['role_id'] = $newRoleId; if ($this->isDuplicateRoleServiceAccess($r)) { $this->log( 'notice', 'Skipping duplicate role_service_access relation with id ' . $originId . '.' ); continue; } $cleanedRsa[] = $r; } if (!empty($cleanedRsa)) { $roleUpdate = ['role_service_access_by_role_id' => $cleanedRsa]; $result = ServiceManager::handleRequest( 'system', Verbs::PATCH, 'role/' . $newRoleId, [], [], $roleUpdate, null, true, true ); if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } $imported = true; } } elseif (!empty($rsa) && empty($role)) { $this->log( 'warning', 'Skipping all Role Service Access for ' . $riz['name'] . ' No imported role found.' ); \Log::debug('Skipped Role Service Access.', $riz); } else { $this->log('notice', 'No Role Service Access for role ' . $riz['name']); } } } catch (\Exception $e) { // if ($e->getCode() === HttpStatusCodes::HTTP_FORBIDDEN) { // $this->log( // 'error', // 'Failed to insert role service access records for roles. ' . // $this->getErrorDetails($e) // ); // } // throw new InternalServerErrorException( // 'Failed to insert role service access records for roles. ' . // $this->getErrorDetails($e) // ); $this->throwExceptions($e, 'Failed to insert role service access records for roles'); } } return $imported; }
Imports Role Service Access relations for role. @return bool @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
protected function getErrorDetails(\Exception $e, $trace = false) { $msg = $e->getMessage(); if ($e instanceof DfException) { $context = $e->getContext(); if (is_array($context)) { $context = print_r($context, true); } if (!empty($context)) { $msg .= "\nContext: " . $context; } } if ($trace === true) { $msg .= "\nTrace:\n" . $e->getTraceAsString(); } return $msg; }
Returns details from exception. @param \Exception $e @param bool $trace @return string
entailment
protected function isDuplicateRoleServiceAccess($rsa) { $roleId = array_get($rsa, 'role_id'); $serviceId = array_get($rsa, 'service_id'); $component = array_get($rsa, 'component'); $verbMask = array_get($rsa, 'verb_mask'); $requestorMask = array_get($rsa, 'requestor_mask'); if (is_null($serviceId)) { $servicePhrase = "service_id is NULL"; } else { $servicePhrase = "service_id = '$serviceId'"; } if (is_null($component)) { $componentPhrase = "component is NULL"; } else { $componentPhrase = "component = '$component'"; } return RoleServiceAccess::whereRaw( "role_id = '$roleId' AND $servicePhrase AND $componentPhrase AND verb_mask = '$verbMask' AND requestor_mask = '$requestorMask'" )->exists(); }
Checks for duplicate role_service_access relation. @param $rsa @return bool
entailment
protected function isDuplicateUserAppRole($uar) { $userId = $uar['user_id']; $appId = $uar['app_id']; $roleId = $uar['role_id']; return UserAppRole::whereRaw( "user_id = '$userId' AND role_id = '$roleId' AND app_id = '$appId'" )->exists(); }
Checks for duplicate user_to_app_to_role relation. @param $uar @return bool
entailment
protected function insertApp() { $data = $this->package->getResourceFromZip('system/app.json'); $apps = $this->cleanDuplicates($data, 'system', 'app'); if (!empty($apps)) { try { foreach ($apps as $i => $app) { $this->fixCommonFields($app); $this->unsetImportedRelations($app); $newStorageId = $this->getNewServiceId($app['storage_service_id']); $newRoleId = $this->getNewRoleId($app['role_id']); if (empty($newStorageId) && !empty($app['storage_service_id'])) { $this->log( 'warning', 'Skipping storage_service_id for app ' . $app['name'] . '. Service not found for ' . $app['storage_service_id'] ); } if (empty($newRoleId) && !empty($app['role_id'])) { $this->log( 'warning', 'Skipping role_id for app ' . $app['name'] . '. Role not found for ' . $app['role_id'] ); } $apiKey = $app['api_key']; if (!empty($apiKey) && !App::isApiKeyUnique($apiKey)) { $this->log( 'notice', 'Duplicate API Key found for app ' . $app['name'] . '. Regenerating API Key.' ); } $app['storage_service_id'] = $newStorageId; $app['role_id'] = $newRoleId; $apps[$i] = $app; } $payload = ResourcesWrapper::wrapResources($apps); $result = ServiceManager::handleRequest( 'system', Verbs::POST, 'app', [], [], $payload, null, true, true ); if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } return true; } catch (\Exception $e) { // if ($e->getCode() === HttpStatusCodes::HTTP_FORBIDDEN) { // $this->log('error', 'Failed to insert apps. ' . $this->getErrorDetails($e)); // } else { // throw new InternalServerErrorException('Failed to insert apps. ' . $this->getErrorDetails($e)); // } $this->throwExceptions($e, 'Failed to insert apps'); } } return false; }
Imports system/app @return bool @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
protected function insertOtherResource() { $items = $this->package->getNonStorageServices(); $imported = false; foreach ($items as $service => $resources) { foreach ($resources as $resourceName => $details) { try { $api = $service . '/' . $resourceName; switch ($api) { case 'system/app': case 'system/role': case 'system/service': case 'system/event_script': case 'system/user': // Skip; already imported at this point. break; case $service . '/_table': $imported = $this->insertDbTableResources($service); break; case $service . '/_proc': case $service . '/_func': // Not supported at this time. $this->log('warning', 'Skipping resource ' . $resourceName . '. Not supported.'); break; default: $imported = $this->insertGenericResources($service, $resourceName); break; } } catch (UnauthorizedException $e) { $this->log( 'error', 'Failed to insert resources for ' . $service . '/' . $resourceName . '. ' . $e->getMessage() ); } } } return $imported; }
Imports resources that does not need to inserted in a specific order. @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
protected function insertDbTableResources($service) { $data = $this->package->getResourceFromZip($service . '/_table' . '.json'); if (!empty($data)) { foreach ($data as $table) { $tableName = array_get($table, 'name'); $resource = '_table/' . $tableName; $records = array_get($table, 'record'); $records = $this->cleanDuplicates($records, $service, $resource); if (!empty($records)) { try { foreach ($records as $i => $record) { $this->fixCommonFields($record, false); $this->unsetImportedRelations($record); $records[$i] = $record; } $payload = ResourcesWrapper::wrapResources($records); $result = ServiceManager::handleRequest( $service, Verbs::POST, $resource, ['continue' => true], [], $payload, null, true, true ); if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } } catch (\Exception $e) { // if ($e->getCode() === HttpStatusCodes::HTTP_FORBIDDEN) { // $this->log( // 'error', // 'Failed to insert ' . // $service . // '/' . // $resource . // '. ' . // $this->getErrorDetails($e) // ); // } else { // throw new InternalServerErrorException('Failed to insert ' . // $service . // '/' . // $resource . // '. ' . // $this->getErrorDetails($e) // ); // } $this->throwExceptions($e, 'Failed to insert ' . $service . '/' . $resource); } } } return true; } return false; }
Insert DB table data. @param $service @return bool @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
protected function insertEventScripts() { if (empty($data = $this->package->getResourceFromZip('system/event_script.json'))) { // pre-2.3.0 version $data = $this->package->getResourceFromZip('system/event.json'); } $scripts = $this->cleanDuplicates($data, 'system', 'event_script'); if (!empty($scripts)) { try { foreach ($scripts as $script) { $name = array_get($script, 'name'); $this->fixCommonFields($script); $result = ServiceManager::handleRequest( 'system', Verbs::POST, 'event_script/' . $name, [], [], $script, null, true, true ); if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } } return true; } catch (\Exception $e) { // if ($e->getCode() === HttpStatusCodes::HTTP_FORBIDDEN) { // $this->log('error', 'Failed to insert event_script. ' . $this->getErrorDetails($e)); // } else { // throw new InternalServerErrorException( // 'Failed to insert event_script. ' . // $this->getErrorDetails($e) // ); // } $this->throwExceptions($e, 'Failed to insert event_script'); } } return false; }
Imports system/event_scripts. @return bool @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
protected function insertGenericResources($service, $resource) { $data = $this->package->getResourceFromZip($service . '/' . $resource . '.json'); $merged = $this->mergeSchemas($service, $resource, $data); $records = $this->cleanDuplicates($data, $service, $resource); if (!empty($records)) { try { foreach ($records as $i => $record) { $this->fixCommonFields($record); $this->unsetImportedRelations($record); $records[$i] = $record; } $payload = ResourcesWrapper::wrapResources($records); $result = ServiceManager::handleRequest( $service, Verbs::POST, $resource, ['continue' => true], [], $payload, null, true, true ); if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } if ($service . '/' . $resource === 'system/admin') { static::updateUserPassword($records); } return true; } catch (\Exception $e) { // if ($e->getCode() === HttpStatusCodes::HTTP_FORBIDDEN) { // $this->log( // 'error', // 'Failed to insert ' . // $service . // '/' . // $resource . // '. ' . // $this->getErrorDetails($e) // ); // } else { // throw new InternalServerErrorException('Failed to insert ' . // $service . // '/' . // $resource . // '. ' . // $this->getErrorDetails($e) // ); // } $this->throwExceptions($e, 'Failed to insert ' . $service . '/' . $resource); } } return $merged; }
Imports generic resources. @param string $service @param string $resource @return bool @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
protected function mergeSchemas($service, $resource, $data) { $merged = false; if ('db/_schema' === $service . '/' . $resource) { $payload = (true === config('df.always_wrap_resources')) ? [config('df.resources_wrapper') => $data] : $data; $result = ServiceManager::handleRequest($service, Verbs::PATCH, $resource, [], [], $payload); if ($result->getStatusCode() === 200) { $merged = true; } } return $merged; }
Merges any schema changes. @param $service @param $resource @param $data @return bool
entailment
protected function storeFiles() { $items = $this->package->getStorageServices(); $stored = false; foreach ($items as $service => $resources) { if (is_string($resources)) { $resources = explode(',', $resources); } try { /** @type FileServiceInterface $storage */ $storage = ServiceManager::getService($service); foreach ($resources as $resource) { try { // checkServicePermission throws exception below if action not allowed for the user. Session::checkServicePermission( Verbs::POST, $service, trim($resource, '/'), Session::getRequestor() ); $resourcePath = $service . '/' . ltrim($resource, '/'); $file = $this->package->getFileFromZip($resourcePath); if (!empty($file)) { $storage->moveFile(ltrim($resource, '/'), $file, true); } else { $resourcePath = $service . '/' . trim($resource, '/') . '/' . md5($resource) . '.zip'; $zip = $this->package->getZipFromZip($resourcePath); if (!empty($zip)) { $storage->extractZipFile( rtrim($resource, '/') . '/', $zip, false, rtrim($resource, '/') . '/' ); } } $stored = true; } catch (\Exception $e) { // Not throwing exceptions here. File storage process is not // transactional. There is no way to rollback if exception // is thrown in the middle of import process. Instead, log // the error and finish the process. $logLevel = 'warning'; if ($e->getCode() === HttpStatusCodes::HTTP_FORBIDDEN) { $logLevel = 'error'; } $this->log( $logLevel, 'Skipping storage resource ' . $service . '/' . $resource . '. ' . $e->getMessage() ); } } } catch (\Exception $e) { $this->log('error', 'Failed to store files for service ' . $service . '. ' . $e->getMessage()); } } return $stored; }
Imports app files or other storage files from package.
entailment
protected function getNewRoleId($oldRoleId) { if (empty($oldRoleId)) { return null; } $roles = $this->package->getResourceFromZip('system/role.json'); $roleName = null; foreach ($roles as $role) { if ($oldRoleId === $role['id']) { $roleName = $role['name']; break; } } if (!empty($roleName)) { $newRole = Role::whereName($roleName)->first(['id']); if (!empty($newRole)) { return $newRole->id; } } return null; }
Finds and returns the new role id by old id. @param int $oldRoleId @return int|null
entailment
protected function getNewAppId($oldAppId) { if (empty($oldAppId)) { return null; } $apps = $this->package->getResourceFromZip('system/app.json'); $appName = null; foreach ($apps as $app) { if ($oldAppId === $app['id']) { $appName = $app['name']; break; } } if (!empty($appName)) { $newApp = App::whereName($appName)->first(['id']); if (!empty($newApp)) { return $newApp->id; } } else { $existingApp = App::find($oldAppId); if (!empty($existingApp)) { $appName = $existingApp->name; if (in_array($appName, ['admin', 'api_docs', 'file_manager'])) { // If app is one of the pre-defined system apps // then new id is most likely the same as the old id. return $oldAppId; } } } return null; }
Finds and returns new App id by old App id. @param $oldAppId @return int|null
entailment
protected function getNewServiceId($oldServiceId) { if (empty($oldServiceId)) { return null; } $services = $this->package->getResourceFromZip('system/service.json'); $serviceName = null; foreach ($services as $service) { if ($oldServiceId === $service['id']) { $serviceName = $service['name']; break; } } if (!empty($serviceName)) { if (!empty($id = ServiceManager::getServiceIdByName($serviceName))) { return $id; } } else { if (!empty($serviceName = ServiceManager::getServiceNameById($oldServiceId))) { if (in_array($serviceName, ['system', 'api_docs', 'files', 'db', 'email', 'user'])) { // If service is one of the pre-defined system services // then new id is most likely the same as the old id. return $oldServiceId; } } } return null; }
Finds and returns the new service id by old id. @param int $oldServiceId @return int|null
entailment
protected function log($level, $msg, $context = []) { $this->log[$level][] = $msg; \Log::log($level, $msg, $context); }
Stores internal log and write to system log. @param string $level @param string $msg @param array $context
entailment
protected function fixCommonFields(array & $record, $unsetIdField = true) { if ($unsetIdField) { unset($record['id']); } if (isset($record['last_modified_by_id'])) { unset($record['last_modified_by_id']); } if (isset($record['created_by_id'])) { $record['created_by_id'] = Session::getCurrentUserId(); } }
Fix some common fields to make record ready for inserting into db table. @param array $record @param bool $unsetIdField
entailment
protected function unsetImportedRelations(array & $record) { foreach ($record as $key => $value) { if (strpos($key, 'role_by_') !== false || strpos($key, 'service_by_') !== false || strpos($key, 'role_service_access_by_') !== false || strpos($key, 'user_to_app_to_role_by_') !== false ) { if (empty($value) || is_array($value)) { unset($record[$key]); } } } }
Unset relations from record that are already imported such as Role, Service, Role_Service_Access. @param array $record
entailment
protected function cleanDuplicates($data, $service, $resource) { $cleaned = []; if (!empty($data)) { $rSeg = explode('/', $resource); $api = $service . '/' . $resource; switch ($api) { case 'system/admin': case 'system/user': $key = 'email'; break; case 'system/cors': $key = 'path'; break; case $service . '/_table/' . array_get($rSeg, 1); $key = 'id'; break; default: $key = 'name'; } foreach ($data as $rec) { if (isset($rec[$key])) { $value = array_get($rec, $key); if (!$this->isDuplicate($service, $resource, array_get($rec, $key), $key)) { $cleaned[] = $rec; } elseif ($this->overwriteExisting === true) { try { if (true === static::patchExisting($service, $resource, $rec, $key)) { $this->overwrote = true; $this->log( 'notice', 'Overwrote duplicate found for ' . $api . ' with ' . $key . ' ' . $value ); } } catch (RestException $e) { $this->throwExceptions( $e, 'An unexpected error occurred. ' . 'Could not overwrite an existing ' . $api . ' resource with ' . $key . ' ' . $value . '. It could be due to your existing resource being exactly ' . 'same as your overwriting resource. Try deleting your existing resource and re-import.' ); } } else { $this->log( 'notice', 'Ignored duplicate found for ' . $api . ' with ' . $key . ' ' . $value ); } } else { $cleaned[] = $rec; $this->log( 'warning', 'Skipped duplicate check for ' . $api . ' by key/field ' . $key . '. Key/Field is not set' ); } } } return $cleaned; }
Removes records from packaged resource that already exists in the target instance. @param $data @param $service @param $resource @return array @throws \DreamFactory\Core\Exceptions\ForbiddenException @throws \DreamFactory\Core\Exceptions\InternalServerErrorException @throws \DreamFactory\Core\Exceptions\RestException
entailment
protected function throwExceptions(\Exception $e, $genericMsg = null, $trace = false) { $msg = 'An error occurred. '; if(!empty($genericMsg)){ $msg = rtrim(trim($genericMsg), '.') . '. '; } $errorMessage = $this->getErrorDetails($e, $trace); $msg .= $errorMessage; if($e->getCode() === HttpStatusCodes::HTTP_FORBIDDEN){ throw new ForbiddenException($msg); } else { throw new InternalServerErrorException($msg); } }
@param \Exception $e @param null $genericMsg @param bool $trace @throws \DreamFactory\Core\Exceptions\ForbiddenException @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
entailment
protected static function patchExisting($service, $resource, $record, $key) { $api = $service . '/' . $resource; $value = array_get($record, $key); switch ($api) { case 'system/event_script': case 'system/custom': case 'user/custom': case $service . '/_schema': $result = ServiceManager::handleRequest( $service, Verbs::PATCH, $resource . '/' . $value, [], [], $record, null, true, true ); if ($result->getStatusCode() === 404) { throw new InternalServerErrorException( 'Could not find existing resource to PATCH for ' . $service . '/' . $resource . '/' . $value ); } if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } return true; default: /** @var ServiceResponseInterface $result */ $result = ServiceManager::handleRequest( $service, Verbs::GET, $resource, ['filter' => "$key='$value'"], [], null, null, true, true ); if ($result->getStatusCode() === 404) { throw new InternalServerErrorException( 'Could not find existing resource for ' . $service . '/' . $resource . ' using ' . $key . ' = ' . $value ); } if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } $content = ResourcesWrapper::unwrapResources($result->getContent()); $existing = array_get($content, 0); $existingId = array_get($existing, BaseModel::getPrimaryKeyStatic()); if (!empty($existingId)) { unset($record[BaseModel::getPrimaryKeyStatic()]); $payload = $record; if (in_array($api, ['system/admin', 'system/user'])) { unset($payload['password']); } $result = ServiceManager::handleRequest( $service, Verbs::PATCH, $resource . '/' . $existingId, [], [], $payload, null, true, true ); if ($result->getStatusCode() === 404) { throw new InternalServerErrorException( 'Could not find existing resource to PATCH for ' . $service . '/' . $resource . '/' . $existingId ); } if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } if (in_array($api, ['system/admin', 'system/user'])) { static::updateUserPassword([$record]); } return true; } else { throw new InternalServerErrorException( 'Could not get ID for ' . $service . '/' . $resource . ' resource using ID field ' . BaseModel::getPrimaryKeyStatic() ); } break; } }
@param $service @param $resource @param $record @param $key @return bool @throws \DreamFactory\Core\Exceptions\InternalServerErrorException @throws \DreamFactory\Core\Exceptions\RestException
entailment
protected function isDuplicate($service, $resource, $value, $key = 'name') { $api = $service . '/' . $resource; switch ($api) { case 'system/role': return Role::where($key, $value)->exists(); case 'system/service': return Service::where($key, $value)->exists(); case 'system/app': return App::where($key, $value)->exists(); case 'system/event_script': case 'system/custom': case 'user/custom': case $service . '/_schema': try { $result = ServiceManager::handleRequest($service, Verbs::GET, $resource . '/' . $value); if ($result->getStatusCode() === 404) { return false; } if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } $result = $result->getContent(); if (is_string($result)) { $result = ['value' => $result]; } $result = array_get($result, config('df.resources_wrapper'), $result); return (count($result) > 0) ? true : false; } catch (NotFoundException $e) { return false; } default: try { $result = ServiceManager::handleRequest($service, Verbs::GET, $resource, ['filter' => "$key = $value"]); if ($result->getStatusCode() === 404) { return false; } if ($result->getStatusCode() >= 300) { throw ResponseFactory::createExceptionFromResponse($result); } $result = $result->getContent(); if (is_string($result)) { $result = ['value' => $result]; } $result = array_get($result, config('df.resources_wrapper'), $result); return (count($result) > 0) ? true : false; } catch (NotFoundException $e) { return false; } } }
Checks to see if a resource record is a duplicate. @param string $service @param string $resource @param mixed $value @param string $key @return bool @throws \DreamFactory\Core\Exceptions\RestException
entailment
public function handleResponse(Request $request, Response $response) { if ($response->getStatusCode() == 422) { $errors = $response->getOriginalContent()['validation_errors']; throw new HttpResponseException( redirect()->back()->withInput($request->input())->withErrors($errors) ); } if ($response->getStatusCode() == 403) { abort(403); } return $response->isNotFound() ? abort(404) : $response->getOriginalContent(); }
Handle a response from the dispatcher for the given request. @param Request $request @param Response $response @return Response|mixed
entailment
protected function bulkActionResponse(Collection $models, $transKey) { if ($models->count()) { Forum::alert('success', $transKey, $models->count()); } else { Forum::alert('warning', 'general.invalid_selection'); } return redirect()->back(); }
Helper: Bulk action response. @param Collection $models @param string $transKey @return \Illuminate\Http\RedirectResponse
entailment
public function up() { $driver = Schema::getConnection()->getDriverName(); // Even though we take care of this scenario in the code, // SQL Server does not allow potential cascading loops, // so set the default no action and clear out created/modified by another user when deleting a user. $onDelete = (('sqlsrv' === $driver) ? 'no action' : 'set null'); $output = new ConsoleOutput(); $output->writeln("Migration driver used: $driver"); // User table Schema::create( 'user', function (Blueprint $t) use ($onDelete){ $t->increments('id'); $t->string('name'); $t->string('first_name')->nullable(); $t->string('last_name')->nullable(); $t->dateTime('last_login_date')->nullable(); $t->string('email')->unique(); $t->text('password')->nullable(); $t->boolean('is_sys_admin')->default(0); $t->boolean('is_active')->default(1); $t->string('phone', 32)->nullable(); $t->string('security_question')->nullable(); $t->text('security_answer')->nullable(); $t->string('confirm_code')->nullable(); $t->integer('default_app_id')->unsigned()->nullable(); $t->rememberToken(); $t->timestamp('created_date')->nullable(); $t->timestamp('last_modified_date')->useCurrent(); $t->integer('created_by_id')->unsigned()->nullable(); $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete); $t->integer('last_modified_by_id')->unsigned()->nullable(); $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete); } ); // Password reset table Schema::create( 'password_resets', function (Blueprint $t){ $t->string('email')->index(); $t->string('token')->index(); $t->timestamp('created_date')->nullable(); } ); // Services Schema::create( 'service', function (Blueprint $t) use ($onDelete){ $t->increments('id'); $t->string('name', 40)->unique(); $t->string('label', 80); $t->string('description')->nullable(); $t->boolean('is_active')->default(0); $t->string('type', 40); $t->boolean('mutable')->default(1); $t->boolean('deletable')->default(1); $t->timestamp('created_date')->nullable(); $t->timestamp('last_modified_date')->useCurrent(); $t->integer('created_by_id')->unsigned()->nullable(); $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete); $t->integer('last_modified_by_id')->unsigned()->nullable(); $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete); } ); // Service API Docs Schema::create( 'service_doc', function (Blueprint $t){ $t->integer('service_id')->unsigned()->primary(); $t->foreign('service_id')->references('id')->on('service')->onDelete('cascade'); $t->integer('format')->unsigned()->default(0); $t->mediumText('content')->nullable(); $t->timestamp('created_date')->nullable(); $t->timestamp('last_modified_date')->useCurrent(); } ); // Roles Schema::create( 'role', function (Blueprint $t) use ($onDelete){ $t->increments('id'); $t->string('name', 64)->unique(); $t->string('description')->nullable(); $t->boolean('is_active')->default(0); $t->timestamp('created_date')->nullable(); $t->timestamp('last_modified_date')->useCurrent(); $t->integer('created_by_id')->unsigned()->nullable(); $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete); $t->integer('last_modified_by_id')->unsigned()->nullable(); $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete); } ); // Roles to Services Allowed Accesses Schema::create( 'role_service_access', function (Blueprint $t) use ($onDelete){ $t->increments('id'); $t->integer('role_id')->unsigned(); $t->foreign('role_id')->references('id')->on('role')->onDelete('cascade'); $t->integer('service_id')->unsigned()->nullable(); $t->foreign('service_id')->references('id')->on('service')->onDelete('cascade'); $t->string('component')->nullable(); $t->integer('verb_mask')->unsigned()->default(0); $t->integer('requestor_mask')->unsigned()->default(0); $t->text('filters')->nullable(); $t->string('filter_op', 32)->default('and'); $t->timestamp('created_date')->nullable(); $t->timestamp('last_modified_date')->useCurrent(); $t->integer('created_by_id')->unsigned()->nullable(); $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete); $t->integer('last_modified_by_id')->unsigned()->nullable(); $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete); } ); // Email Templates Schema::create( 'email_template', function (Blueprint $t) use ($onDelete){ $t->increments('id'); $t->string('name', 64)->unique(); $t->string('description')->nullable(); $t->text('to')->nullable(); $t->text('cc')->nullable(); $t->text('bcc')->nullable(); $t->string('subject', 80)->nullable(); $t->text('body_text')->nullable(); $t->text('body_html')->nullable(); $t->string('from_name', 80)->nullable(); $t->string('from_email')->nullable(); $t->string('reply_to_name', 80)->nullable(); $t->string('reply_to_email')->nullable(); $t->text('defaults')->nullable(); $t->timestamp('created_date')->nullable(); $t->timestamp('last_modified_date')->useCurrent(); $t->integer('created_by_id')->unsigned()->nullable(); $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete); $t->integer('last_modified_by_id')->unsigned()->nullable(); $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete); } ); //Cors config table Schema::create( 'cors_config', function (Blueprint $t) use ($onDelete){ $t->increments('id'); $t->string('path')->unique(); $t->string('origin')->nullable(); $t->text('header')->nullable(); $t->integer('method')->unsigned()->default(0); $t->integer('max_age')->unsigned()->default(0); $t->boolean('enabled')->default(true); $t->timestamp('created_date')->nullable(); $t->timestamp('last_modified_date')->useCurrent(); $t->integer('created_by_id')->unsigned()->nullable(); $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete); $t->integer('last_modified_by_id')->unsigned()->nullable(); $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete); } ); // Applications Schema::create( 'app', function (Blueprint $t) use ($onDelete){ $t->increments('id'); $t->string('name', 64)->unique(); $t->string('api_key')->nullable(); $t->string('description')->nullable(); $t->boolean('is_active')->default(0); $t->integer('type')->unsigned()->default(0); $t->text('path')->nullable(); $t->text('url')->nullable(); $t->integer('storage_service_id')->unsigned()->nullable(); $t->foreign('storage_service_id')->references('id')->on('service')->onDelete('set null'); $t->string('storage_container', 255)->nullable(); $t->boolean('requires_fullscreen')->default(0); $t->boolean('allow_fullscreen_toggle')->default(1); $t->string('toggle_location', 64)->default('top'); $t->integer('role_id')->unsigned()->nullable(); $t->foreign('role_id')->references('id')->on('role')->onDelete('set null'); $t->timestamp('created_date')->nullable(); $t->timestamp('last_modified_date')->useCurrent(); $t->integer('created_by_id')->unsigned()->nullable(); $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete); $t->integer('last_modified_by_id')->unsigned()->nullable(); $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete); } ); // App relationship for user Schema::create( 'user_to_app_to_role', function (Blueprint $t){ $t->increments('id'); $t->integer('user_id')->unsigned(); $t->foreign('user_id')->references('id')->on('user')->onDelete('cascade'); $t->integer('app_id')->unsigned(); $t->foreign('app_id')->references('id')->on('app')->onDelete('cascade'); $t->integer('role_id')->unsigned(); $t->foreign('role_id')->references('id')->on('role')->onDelete('cascade'); } ); // JSON Web Token to system resources map Schema::create( 'token_map', function (Blueprint $t){ $t->integer('user_id')->unsigned(); $t->foreign('user_id')->references('id')->on('user')->onDelete('cascade'); $t->text('token'); $t->integer('iat')->unsigned(); $t->integer('exp')->unsigned(); } ); Schema::create( 'file_service_config', function (Blueprint $t){ $t->integer('service_id')->unsigned()->primary(); $t->foreign('service_id')->references('id')->on('service')->onDelete('cascade'); $t->text('public_path')->nullable(); $t->text('container')->nullable(); } ); Schema::create( 'service_cache_config', function (Blueprint $t){ $t->integer('service_id')->unsigned()->primary(); $t->foreign('service_id')->references('id')->on('service')->onDelete('cascade'); $t->boolean('cache_enabled')->default(0); $t->integer('cache_ttl')->unsigned()->default(0); } ); // System Configuration Schema::create( 'system_config', function (Blueprint $t) use ($onDelete){ $t->integer('service_id')->unsigned()->primary(); $t->foreign('service_id')->references('id')->on('service')->onDelete('cascade'); $t->integer('default_app_id')->unsigned()->nullable(); $t->foreign('default_app_id')->references('id')->on('app')->onDelete('set null'); $t->integer('invite_email_service_id')->unsigned()->nullable(); $t->foreign('invite_email_service_id')->references('id')->on('service')->onDelete($onDelete); $t->integer('invite_email_template_id')->unsigned()->nullable(); $t->foreign('invite_email_template_id')->references('id')->on('email_template')->onDelete($onDelete); $t->integer('password_email_service_id')->unsigned()->nullable(); $t->foreign('password_email_service_id')->references('id')->on('service')->onDelete($onDelete); $t->integer('password_email_template_id')->unsigned()->nullable(); $t->foreign('password_email_template_id')->references('id')->on('email_template')->onDelete($onDelete); } ); // create system customizations Schema::create( 'system_custom', function (Blueprint $t) use ($onDelete){ $t->string('name')->primary(); $t->mediumText('value')->nullable(); $t->timestamp('created_date')->nullable(); $t->timestamp('last_modified_date')->useCurrent(); $t->integer('created_by_id')->unsigned()->nullable(); $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete); $t->integer('last_modified_by_id')->unsigned()->nullable(); $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete); } ); // Lookups Schema::create( 'lookup', function (Blueprint $t) use ($onDelete){ $t->increments('id'); $t->integer('app_id')->unsigned()->nullable(); $t->foreign('app_id')->references('id')->on('app')->onDelete('cascade'); $t->integer('role_id')->unsigned()->nullable(); $t->foreign('role_id')->references('id')->on('role')->onDelete('cascade'); $t->integer('user_id')->unsigned()->nullable(); $t->foreign('user_id')->references('id')->on('user')->onDelete('cascade'); $t->string('name'); $t->text('value')->nullable(); $t->boolean('private')->default(0); $t->text('description')->nullable(); $t->timestamp('created_date')->nullable(); $t->timestamp('last_modified_date')->useCurrent(); $t->integer('created_by_id')->unsigned()->nullable(); $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete); $t->integer('last_modified_by_id')->unsigned()->nullable(); $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete); } ); }
Run the migrations. @return void
entailment
public function down() { // Drop created tables in reverse order // Lookup Keys Schema::dropIfExists('lookup'); // System customizations Schema::dropIfExists('system_custom'); // System Configuration Schema::dropIfExists('system_config'); // File storage, public path designation Schema::dropIfExists('file_service_config'); // Cache-able service configuration Schema::dropIfExists('service_cache_config'); // JSON Web Token to system resources map Schema::dropIfExists('token_map'); // App relationship for user Schema::dropIfExists('user_to_app_to_role'); // Service Docs Schema::dropIfExists('service_doc'); // Role Service Accesses Schema::dropIfExists('role_service_access'); // Roles Schema::dropIfExists('role'); // Email Templates Schema::dropIfExists('email_template'); // Services Schema::dropIfExists('service'); //Cors config table Schema::dropIfExists('cors_config'); // App relationship for user Schema::dropIfExists('user_to_app_role'); // Applications Schema::dropIfExists('app'); //Password reset Schema::dropIfExists('password_resets'); // User table Schema::dropIfExists('user'); }
Reverse the migrations. @return void
entailment
public function render(array $assign_data = []) : string { extract($assign_data); ob_start(); include $this->getPath(); $content = ob_get_contents(); ob_end_clean(); return $content; }
渲染html页面 - 在渲染页面之前应该要设置模板文件路径 @return string
entailment
public function toArray() { $errorInfo['code'] = $this->getCode(); $errorInfo['context'] = $this->getContext(); $errorInfo['message'] = htmlentities($this->getMessage()); if (config('app.debug', false)) { $trace = $this->getTraceAsString(); $trace = str_replace(["\n", "#"], ["", "<br>"], $trace); $traceArray = explode("<br>", $trace); $cleanTrace = []; foreach ($traceArray as $k => $v) { if (!empty($v)) { $cleanTrace[] = $v; } } $errorInfo['trace'] = $cleanTrace; } return $errorInfo; }
Convert this exception to array output @return array
entailment
public static function bulkCreate(array $records, array $params = []) { $records = static::fixRecords($records); $params['admin'] = true; return parent::bulkCreate($records, $params); }
{@inheritdoc}
entailment
public static function updateById($id, array $record, array $params = []) { $record = static::fixRecords($record); $params['admin'] = true; return parent::updateById($id, $record, $params); }
{@inheritdoc}
entailment
public static function updateByIds($ids, array $record, array $params = []) { $record = static::fixRecords($record); $params['admin'] = true; return parent::updateByIds($ids, $record, $params); }
{@inheritdoc}
entailment
public static function bulkUpdate(array $records, array $params = []) { $records = static::fixRecords($records); $params['admin'] = true; return parent::bulkUpdate($records, $params); }
{@inheritdoc}
entailment
public static function selectById($id, array $options = [], array $fields = ['*']) { $fields = static::cleanFields($fields); $related = array_get($options, ApiOptions::RELATED, []); if (is_string($related)) { $related = explode(',', $related); } if ($model = static::whereIsSysAdmin(1)->with($related)->find($id, $fields)) { return static::cleanResult($model, $fields); } return null; }
{@inheritdoc}
entailment
protected static function fixRecords(array $records) { if (!Arr::isAssoc($records)) { foreach ($records as $key => $record) { $record['is_sys_admin'] = 1; $records[$key] = $record; } } else { $records['is_sys_admin'] = 1; } return $records; }
Fixes supplied records to always set is_set_admin flag to true. Encrypts passwords if it is supplied. @param array $records @return array
entailment
protected static function createInternal($record, $params = []) { try { /** @var App $model */ $key = array_get($record, 'api_key'); $uniqueKey = static::isApiKeyUnique($key); $model = static::create($record); if (empty($key) || !$uniqueKey) { $apiKey = static::generateApiKey($model->name); $model->api_key = $apiKey; } $model->save(); } catch (\PDOException $e) { throw $e; } return static::buildResult($model, $params); }
@param $record @param array $params @return array
entailment
public static function isApiKeyUnique($key) { $model = static::whereApiKey($key)->first(['id']); return (empty($model)) ? true : false; }
Checks to see if an API Key is uniques or not @param $key string @return bool
entailment
public static function getCachedInfo($id, $key = null, $default = null) { $cacheKey = 'app:' . $id; try { $result = \Cache::remember($cacheKey, \Config::get('df.default_cache_ttl'), function () use ($id){ $app = App::whereId($id)->first(); if (empty($app)) { throw new NotFoundException("App not found."); } if (!$app->is_active) { throw new ForbiddenException("App is not active."); } return $app->toArray(); }); if (is_null($result)) { return $default; } } catch (ModelNotFoundException $ex) { return $default; } if (is_null($key)) { return $result; } return (isset($result[$key]) ? $result[$key] : $default); }
Returns app info cached, or reads from db if not present. Pass in a key to return a portion/index of the cached data. @param int $id @param null|string $key @param null $default @return mixed|null
entailment
public static function setApiKeyToAppId($api_key, $app_id) { $cacheKey = 'apikey2appid:' . $api_key; \Cache::put($cacheKey, $app_id, \Config::get('df.default_cache_ttl')); }
Use this primarily in middle-ware or where no session is established yet. @param string $api_key @param int $app_id
entailment
public static function getAppIdByApiKey($api_key) { if (empty($api_key)) { return null; } $cacheKey = 'apikey2appid:' . $api_key; try { return \Cache::remember($cacheKey, \Config::get('df.default_cache_ttl'), function () use ($api_key){ return App::whereApiKey($api_key)->firstOrFail()->id; }); } catch (ModelNotFoundException $ex) { return null; } }
Use this primarily in middle-ware or where no session is established yet. @param string $api_key @return int The app id
entailment
public static function getApiKeyByAppId($id) { if (!empty($id)) { // use local app caching $key = static::getCachedInfo($id, 'api_key', null); if (!is_null($key)) { static::setApiKeyToAppId($key, $id); return $key; } } return null; }
Use this primarily in middle-ware or where no session is established yet. @param int $id @return string|null The API key for the designated app or null if not found
entailment
public static function getTypeByName($name) { /** @noinspection PhpUndefinedMethodInspection */ $typeRec = static::whereName($name)->get(['type'])->first(); return (isset($typeRec, $typeRec['type'])) ? $typeRec['type'] : null; }
@param $name @return null
entailment
public function setConfigAttribute($value) { $this->config = (array)$value; $localConfig = $this->getAttributeFromArray('config'); $localConfig = ($localConfig ? json_decode($localConfig, true) : []); // take the type information and get the config_handler class // set the config giving the service id and new config if (!empty($serviceCfg = $this->getConfigHandler())) { // go ahead and save the config here, otherwise we don't have key yet $localConfig = $serviceCfg::setConfig($this->getKey(), $this->config, $localConfig); if ($this->isJsonCastable('config') && !is_null($localConfig)) { $localConfig = $this->castAttributeAsJson('config', $localConfig); } $this->attributes['config'] = $localConfig; } else { if (null !== $typeInfo = ServiceManager::getServiceType($this->type)) { if ($subscription = $typeInfo->subscriptionRequired()) { throw new BadRequestException("Provisioning Failed. '$subscription' subscription required for this service type."); } } } }
@param array|null $value @throws \DreamFactory\Core\Exceptions\BadRequestException
entailment
protected function getConfigHandler() { if (null !== $typeInfo = ServiceManager::getServiceType($this->type)) { // lookup related service type config model return $typeInfo->getConfigHandler(); } return null; }
Determine the handler for the extra config settings @return \DreamFactory\Core\Contracts\ServiceConfigHandlerInterface|null @throws \DreamFactory\Core\Exceptions\BadRequestException
entailment
public static function cleanFields($fields) { $fields = parent::cleanFields($fields); //If config is requested add id and type as they are need to pull config. if (in_array('config', $fields)) { $fields[] = 'id'; $fields[] = 'type'; } //Removing config from field list as it is not a real column in the table. if (in_array('config', $fields)) { $key = array_keys($fields, 'config'); unset($fields[$key[0]]); } return $fields; }
Removes 'config' from field list if supplied as it chokes the model. @param mixed $fields @return array
entailment
protected static function cleanResult($response, $fields) { $response = parent::cleanResult($response, $fields); if (!is_array($fields)) { $fields = explode(',', $fields); } //config is only available when both id and type is present. Therefore only show config if id and type is there. if (array_get($fields, 0) !== '*' && (!in_array('type', $fields) || !in_array('id', $fields))) { $result = []; if (!Arr::isAssoc($response)) { foreach ($response as $r) { if (isset($r['config'])) { unset($r['config']); } $result[] = $r; } } else { foreach ($response as $k => $v) { if ('config' === $k) { unset($response[$k]); } } $result = $response; } return $result; } return $response; }
If fields is not '*' (all) then remove the empty 'config' property. @param mixed $response @param mixed $fields @return array
entailment
public function handle() { $path = $this->getPath(); if (is_file($path) || FileUtilities::url_exist($path)) { $this->importPackage($path); $this->printResult(); } elseif (is_dir($path)) { $files = static::getFilesFromPath($path); if (count($files) == 0) { $this->warn('No package to import from ' . $path); } else { foreach ($files as $file) { try { $this->importPackage($file); } catch (\Exception $e) { $this->errors[] = [ 'file' => $file, 'msg' => $e->getMessage() ]; } } $this->printResult(); } } else { $this->error('Invalid path ' . $path); } }
Runs the command.
entailment
protected function printResult() { $errorCount = count($this->errors); if ($errorCount > 0) { $fileCount = count(static::getFilesFromPath($this->getPath())); if ($errorCount < $fileCount) { $this->warn('Not all files were imported successfully. See details below.'); } elseif ($errorCount == $fileCount) { $this->error('None of your files where imported successfully. See details below.'); } $this->warn('---------------------------------------------------------------------------------------'); foreach ($this->errors as $error) { $this->warn('Failed importing: ' . array_get($error, 'file')); $this->warn('Error: ' . array_get($error, 'msg')); $this->warn('---------------------------------------------------------------------------------------'); } } else { $this->info('Successfully imported your file(s).'); } $this->printImportLog(); }
Prints result.
entailment
protected function importPackage($file) { $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION)); if ($extension === Packager::FILE_EXTENSION) { $this->importOldPackage($file); } else { $package = new Package($file, $this->option('delete'), $this->option('password')); $importer = new Importer($package); $importer->import(); $log = $importer->getLog(); $this->importLog[] = [ 'file' => $file, 'log' => $log ]; } }
Imports package. @param $file @throws \Exception
entailment
protected function printImportLog() { if (count($this->importLog) > 0) { $this->info('Import log'); $this->info('---------------------------------------------------------------------------------------'); foreach ($this->importLog as $il) { $this->info('Import File: ' . $il['file']); foreach ($il['log'] as $level => $logs) { $this->info(strtoupper($level)); foreach ($logs as $log) { $this->info(' -> ' . $log); } } $this->info('---------------------------------------------------------------------------------------'); } } }
Prints import log.
entailment
protected static function getFilesFromPath($path) { $files = []; $path = rtrim($path, '/') . DIRECTORY_SEPARATOR; if (false !== $items = scandir($path)) { foreach ($items as $item) { $file = $path . $item; if (is_file($file)) { $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION)); if (in_array($extension, [Packager::FILE_EXTENSION, Package::FILE_EXTENSION])) { $files[] = $file; } } } } return $files; }
Returns packaged file(s) from import path. @param $path @return array
entailment
public function addParameter(ParameterSchema $schema) { $key = strtolower($schema->name); $this->parameters[$key] = $schema; }
Sets the named parameter metadata. @param ParameterSchema $schema
entailment
public function getParameter($name) { $key = strtolower($name); if (isset($this->parameters[$key])) { return $this->parameters[$key]; } return null; }
Gets the named parameter metadata. @param string $name parameter name @return ParameterSchema metadata of the named parameter. Null if the named parameter does not exist.
entailment
public static function checkExtensions($extensions) { if (empty($extensions)) { $extensions = []; } elseif (is_string($extensions)) { $extensions = array_map('trim', explode(',', trim($extensions))); } foreach ($extensions as $extension) { if (!extension_loaded($extension)) { throw new ServiceUnavailableException("Required extension or module '$extension' is not installed or loaded."); } } return true; }
@param string|array $extensions @return bool Returns true if all required extensions are loaded, otherwise an exception is thrown @throws ServiceUnavailableException
entailment
public function setWidth(TcTable $table) { if (!$this->width) { $widths = []; foreach ($table->getColumns() as $key => $column) { $widths[$key] = $column['width']; } unset($widths[$this->columnIndex]); $this->width = $this->getRemainingColumnWidth($table, $widths); } $width = $this->width; $table->setColumnDefinition($this->columnIndex, 'width', $width); }
Check the max width of the stretched column. This method is called just before we start to add data rows @param TcTable $table @return void
entailment
private function getRemainingColumnWidth(TcTable $table, $width) { if (!$this->maxWidth) { $margins = $table->getPdf()->getMargins(); $content_width = $table->getPdf()->getPageWidth() - $margins['left'] - $margins['right']; } else { $content_width = $this->maxWidth; } $result = $content_width - (is_array($width) ? array_sum($width) : $width); return $result > 0 ? $result : 0; }
Get the remaining width available, taking into account margins and other cells width or the specified maxwidth if any. @param TcTable $table @param array|float $width sum of all other cells width @return float
entailment
public function output(Debug $plugin, array $data) { $tmp = !$this->printObjects ? $this->purgeObjects($data, 0) : $data; echo "<pre>"; print_r( array_merge( ['event' => $plugin->getEventInvoker()], $tmp ) ); echo "</pre>"; }
{@inheritDocs}
entailment
private function purgeObjects(array $data, $level) { $tmp = []; foreach ($data as $k => $v) { if (is_array($v)) { $tmp[$k] = ($this->deepLevel !== null && $level <= $this->deepLevel) || $this->deepLevel === null ? $this->purgeObjects($v, ++$level) : '(array)'; } elseif (is_object($v)) { $tmp[$k] = spl_object_hash($v) . ' ' . get_class($v); } else { ob_start(); var_dump($v); $tmp[$k] = str_replace('</pre>', '', preg_replace("/<pre[^>]+\>/i", '$1', ob_get_clean())); } } return $tmp; }
Replace objects by their classname, so the print_r function won't print the whole object tree (which can be huge sometimes) @param array $data @param int $level @return array
entailment
public static function getConfig($id, $local_config = null, $protect = true) { $config = parent::getConfig($id, $local_config, $protect); $serviceEventMaps = ServiceEventMap::whereServiceId($id)->get(); $maps = []; /** @var ServiceEventMap $map */ foreach ($serviceEventMaps as $map) { $map->protectedView = $protect; $maps[] = $map->toArray(); } $config['service_event_map'] = $maps; return $config; }
{@inheritdoc}
entailment
public static function setConfig($id, $config, $local_config = null) { if (isset($config['service_event_map'])) { $maps = $config['service_event_map']; if (!is_array($maps)) { throw new BadRequestException('Service to Event map must be an array.'); } // Deleting records using model as oppose to chaining with the where clause. // This way forcing model to trigger the 'deleted' event which clears necessary cache. // See the boot method in ServiceEventMap::class. $models = ServiceEventMap::whereServiceId($id)->get()->all(); foreach ($models as $model) { $model->delete(); } if (!empty($maps)) { foreach ($maps as $map) { ServiceEventMap::setConfig($id, $map, $local_config); } } } return parent::setConfig($id, $config, $local_config); }
{@inheritdoc}
entailment
public static function getConfigSchema() { $schema = parent::getConfigSchema(); $schema[] = [ 'name' => 'service_event_map', 'label' => 'Service Event', 'description' => 'Select event(s) to be used by this service.', 'type' => 'array', 'required' => false, 'allow_null' => true, 'items' => ServiceEventMap::getConfigSchema(), ]; return $schema; }
{@inheritdoc}
entailment
public function index(Request $request) { $categories = $this->api('category.index') ->parameters(['where' => ['category_id' => 0], 'orderBy' => 'weight', 'orderDir' => 'asc', 'with' => ['categories', 'threads']]) ->get(); event(new UserViewingIndex); return view('forum::category.index', compact('categories')); }
GET: Return an index of categories view (the forum index). @param Request $request @return \Illuminate\Http\Response
entailment
public function show(Request $request) { $category = $this->api('category.fetch', $request->route('category'))->get(); event(new UserViewingCategory($category)); $categories = []; if (Gate::allows('moveCategories')) { $categories = $this->api('category.index')->parameters(['where' => ['category_id' => 0]])->get(); } $threads = $category->threadsPaginated; return view('forum::category.show', compact('categories', 'category', 'threads')); }
GET: Return a category view. @param Request $request @return \Illuminate\Http\Response
entailment
public function store(Request $request) { $category = $this->api('category.store')->parameters($request->all())->post(); Forum::alert('success', 'categories.created'); return redirect(Forum::route('category.show', $category)); }
POST: Store a new category. @param Request $request @return \Illuminate\Http\RedirectResponse
entailment
public function destroy(Request $request) { $this->api('category.delete', $request->route('category'))->parameters($request->all())->delete(); Forum::alert('success', 'categories.deleted', 1); return redirect(config('forum.routing.prefix')); }
DELETE: Delete a category. @param Request $request @return \Illuminate\Http\RedirectResponse
entailment
public function validate($data, $throwException = true) { if (empty($rules = $this->getRules())) { return true; } else { $validator = Validator::make($data, $rules, $this->validationMessages); if ($validator->fails()) { $this->errors($validator->errors()->getMessages()); if ($throwException) { $errorString = DataFormatter::validationErrorsToString($this->getErrors()); throw new BadRequestException('Invalid data supplied.' . $errorString, null, null, $this->getErrors()); } else { return false; } } else { return true; } } }
Validates data based on $this->rules. @param array $data @param bool|true $throwException @return bool @throws \DreamFactory\Core\Exceptions\BadRequestException
entailment
public function getFromCache($key, $default = null) { $key = $this->getConfigBasedCachePrefix() . $key; return $this->getFromCacheOld($key, $default); }
@param string $key @param mixed $default @return mixed The value of cache associated with the given type, id and key
entailment
public function rememberCache($key, $callback) { $key = $this->getConfigBasedCachePrefix() . $key; return $this->rememberCacheOld($key, $callback); }
@param string $key @param mixed $callback @return mixed
entailment
public function rememberCacheForever($key, $callback) { $key = $this->getConfigBasedCachePrefix() . $key; return $this->rememberCacheForeverOld($key, $callback); }
@param string $key @param mixed $callback @return mixed
entailment
public function getService($name) { // If we haven't created this service, we'll create it based on the config provided. // todo: Caching the service is causing some strange PHP7 only memory issues. // if (!isset($this->services[$name])) { $service = $this->makeService($name); // if ($this->app->bound('events')) { // $connection->setEventDispatcher($this->app['events']); // } $this->services[$name] = $service; // } return $this->services[$name]; }
Get a service instance. @param string $name @return \DreamFactory\Core\Contracts\ServiceInterface @throws \DreamFactory\Core\Exceptions\NotFoundException
entailment
public function getServiceIdByName($name) { $map = array_flip($this->getServiceIdNameMap()); if (array_key_exists($name, $map)) { return $map[$name]; } return null; }
Get a service identifier by its name. @param string $name @return int|null
entailment
public function getServiceNameById($id) { $map = $this->getServiceIdNameMap(); if (array_key_exists($id, $map)) { return $map[$id]; } return null; }
Get a service name by its identifier. @param int $id @return string
entailment
public function getServiceById($id) { if ($name = $this->getServiceNameById($id)) { return $this->getService($name); } return null; }
Get a service instance by its identifier. @param int $id @return \DreamFactory\Core\Contracts\ServiceInterface @throws \DreamFactory\Core\Exceptions\NotFoundException
entailment
public function getServiceNamesByType($types, $only_active = false) { $names = []; $map = $this->getServiceNameTypeMap($only_active); if (is_string($types)) { $types = array_map('trim', explode(',', trim($types, ','))); } foreach ($map as $name => $type) { if (false !== array_search($type, $types)) { $names[] = $name; } } return $names; }
Return all of the created service names by type. @param string|array $types @param bool $only_active @return array
entailment
public function getServiceNamesByGroup($group, $only_active = false) { $types = $this->getServiceTypeNames($group); return $this->getServiceNamesByType($types, $only_active); }
Return all of the created service names. @param string|array $group @param bool $only_active @return array
entailment
public function getServiceList($fields = null, $only_active = false) { $allowed = ['id', 'name', 'label', 'description', 'is_active', 'type']; if (empty($fields)) { $fields = $allowed; } elseif (is_string($fields)) { $fields = array_map('trim', explode(',', trim($fields, ','))); } $includeGroup = in_array('group', $fields); $includeTypeLabel = in_array('type_label', $fields); if (($includeGroup || $includeTypeLabel) && !in_array('type', $fields)) { $fields[] = 'type'; } $fields = array_intersect($fields, $allowed); if ($only_active) { $results = Service::whereIsActive(true)->get($fields)->toArray(); } else { $results = Service::get($fields)->toArray(); } if ($includeGroup || $includeTypeLabel) { $services = []; foreach ($results as $result) { if ($typeInfo = $this->getServiceType(array_get($result, 'type'))) { if ($includeGroup) { $result['group'] = $typeInfo->getGroup(); } if ($includeTypeLabel) { $result['type_label'] = $typeInfo->getLabel(); } $services[] = $result; } } return $services; } return $results; }
Return all of the created service info. @param array|string $fields @param bool $only_active @return array
entailment
public function getServiceListByGroup($group, $fields = null, $only_active = false) { $types = $this->getServiceTypeNames($group); return $this->getServiceListByType($types, $fields, $only_active); }
Return all of the created service info. @param string|array $group @param array|string $fields @param bool $only_active @return array
entailment
public function purge($name) { try { if ($service = $this->getService($name)) { if ($service instanceof CacheInterface) { $service->flush(); } } } catch (\Exception $ex) { // could be due to purge triggered by ServiceDeleted event } unset($this->services[$name]); \Cache::forget('service_mgr:' . $name); \Cache::forget('service_mgr:id_name_map_active'); \Cache::forget('service_mgr:id_name_map'); \Cache::forget('service_mgr:name_type_map_active'); \Cache::forget('service_mgr:name_type_map'); }
Disconnect from the given service and remove from local cache. @param string $name @return void
entailment
public function getServiceType($name) { if (isset($this->types[$name])) { return $this->types[$name]; } return null; }
Return the service type info. @param string $name @return \DreamFactory\Core\Contracts\ServiceTypeInterface
entailment
public function getServiceTypes($group = null) { ksort($this->types, SORT_NATURAL); // sort by name for display if (!empty($group)) { if (!empty($group) && !is_array($group)) { $group = array_map('trim', explode(',', trim($group, ','))); } $group = array_map('strtolower', (array)$group); $types = []; foreach ($this->types as $type) { if (in_array(strtolower($type->getGroup()), $group)) { $types[$type->getName()] = $type; } } return $types; } return $this->types; }
Return all of the known service types. @param string $group @return \DreamFactory\Core\Contracts\ServiceTypeInterface[]
entailment
public function isAccessException($service, $component, $action) { if (is_string($action)) { $action = VerbsMask::toNumeric($action); } if ($serviceType = $this->getServiceTypeByName($service)) { if ($typeObj = $this->getServiceType($serviceType)) { if ($typeObj->isAccessException($action, $component)) { return true; } } } return false; }
Check for a service access exception. @param string $service @param string $component @param int|string $action @return boolean True if this is a routing access exception, false otherwise @throws \DreamFactory\Core\Exceptions\NotFoundException @throws \DreamFactory\Core\Exceptions\NotImplementedException
entailment