idx
int64 0
60.3k
| question
stringlengths 64
4.24k
| target
stringlengths 5
618
|
|---|---|---|
49,400
|
public function getComment ( ) { $ returnValue = ( string ) '' ; if ( $ this -> comment == '' ) { $ comment = $ this -> getOnePropertyValue ( $ this -> getProperty ( OntologyRdfs :: RDFS_COMMENT ) ) ; $ this -> comment = $ comment != null ? $ comment -> literal : '' ; } $ returnValue = $ this -> comment ; return ( string ) $ returnValue ; }
|
Short description of method getComment
|
49,401
|
public function getPropertyValues ( core_kernel_classes_Property $ property , $ options = array ( ) ) { $ returnValue = array ( ) ; $ returnValue = $ this -> getImplementation ( ) -> getPropertyValues ( $ this , $ property , $ options ) ; return ( array ) $ returnValue ; }
|
Returns a collection of triples with all objects found for the provided regarding the contextual resource . The return format is an array of strings
|
49,402
|
public function getUniquePropertyValue ( core_kernel_classes_Property $ property ) { $ returnValue = null ; $ collection = $ this -> getPropertyValuesCollection ( $ property ) ; if ( $ collection -> isEmpty ( ) ) { throw new core_kernel_classes_EmptyProperty ( $ this , $ property ) ; } if ( $ collection -> count ( ) == 1 ) { $ returnValue = $ collection -> get ( 0 ) ; } else { throw new core_kernel_classes_MultiplePropertyValuesException ( $ this , $ property ) ; } return $ returnValue ; }
|
Short description of method getUniquePropertyValue
|
49,403
|
public function getOnePropertyValue ( core_kernel_classes_Property $ property , $ last = false ) { $ returnValue = null ; if ( $ last ) { throw new core_kernel_persistence_Exception ( 'parameter \'last\' for getOnePropertyValue no longer supported' ) ; } ; $ options = array ( 'forceDefaultLg' => true , 'one' => true ) ; $ value = $ this -> getPropertyValues ( $ property , $ options ) ; if ( count ( $ value ) ) { $ returnValue = common_Utils :: toResource ( current ( $ value ) ) ; } return $ returnValue ; }
|
Helper to return one property value since there is no order if there are multiple values the value to be returned will be choosen by random
|
49,404
|
public function setPropertiesValues ( $ propertiesValues ) { $ returnValue = ( bool ) false ; $ returnValue = $ this -> getImplementation ( ) -> setPropertiesValues ( $ this , $ propertiesValues ) ; $ this -> onUpdate ( ) ; return ( bool ) $ returnValue ; }
|
Set multiple properties and their value at one time . Conveniance method isntead of adding the property values one by one .
|
49,405
|
public function editPropertyValueByLg ( core_kernel_classes_Property $ prop , $ value , $ lg ) { $ returnValue = ( bool ) false ; $ returnValue = $ this -> removePropertyValueByLg ( $ prop , $ lg ) ; $ returnValue &= $ this -> setPropertyValueByLg ( $ prop , $ value , $ lg ) ; return ( bool ) $ returnValue ; }
|
Short description of method editPropertyValueByLg
|
49,406
|
public function removePropertyValue ( core_kernel_classes_Property $ property , $ value ) { $ returnValue = ( bool ) false ; $ returnValue = $ this -> getImplementation ( ) -> removePropertyValues ( $ this , $ property , array ( 'pattern' => ( is_object ( $ value ) && $ value instanceof self ? $ value -> getUri ( ) : $ value ) , 'like' => false ) ) ; $ this -> onUpdate ( ) ; return ( bool ) $ returnValue ; }
|
remove a single triple with this subject and predicate
|
49,407
|
public function removePropertyValues ( core_kernel_classes_Property $ property , $ options = array ( ) ) { $ returnValue = ( bool ) false ; $ returnValue = $ this -> getImplementation ( ) -> removePropertyValues ( $ this , $ property , $ options ) ; $ this -> onUpdate ( ) ; return ( bool ) $ returnValue ; }
|
remove all triples with this subject and predicate
|
49,408
|
public function getUsedLanguages ( core_kernel_classes_Property $ property ) { $ returnValue = array ( ) ; $ returnValue = $ this -> getImplementation ( ) -> getUsedLanguages ( $ this , $ property ) ; return ( array ) $ returnValue ; }
|
return the languages in which a value exists for uriProperty for this
|
49,409
|
public function delete ( $ deleteReference = false ) { $ returnValue = $ this -> getImplementation ( ) -> delete ( $ this , $ deleteReference ) ; $ eventManager = $ this -> getServiceManager ( ) -> get ( EventManager :: SERVICE_ID ) ; $ eventManager -> trigger ( new ResourceDeleted ( $ this -> getUri ( ) ) ) ; return ( bool ) $ returnValue ; }
|
remove any assignation made to this resource the uri is consequently
|
49,410
|
public function hasType ( core_kernel_classes_Class $ class ) { $ returnValue = ( bool ) false ; foreach ( $ this -> getTypes ( ) as $ type ) { if ( $ class -> equals ( $ type ) ) { $ returnValue = true ; break ; } } return ( bool ) $ returnValue ; }
|
Short description of method hasType
|
49,411
|
public function exists ( ) { $ returnValue = ( bool ) false ; try { $ returnValue = count ( $ this -> getTypes ( ) ) ? true : false ; } catch ( Exception $ e ) { ; } return ( bool ) $ returnValue ; }
|
Short description of method exists
|
49,412
|
public function equals ( core_kernel_classes_Resource $ resource ) { $ returnValue = ( bool ) false ; $ returnValue = $ this -> getUri ( ) == $ resource -> getUri ( ) ; return ( bool ) $ returnValue ; }
|
Short description of method equals
|
49,413
|
public function isInstanceOf ( core_kernel_classes_Class $ class ) { $ returnValue = ( bool ) false ; foreach ( $ this -> getTypes ( ) as $ type ) { if ( $ class -> equals ( $ type ) || $ type -> isSubClassOf ( $ class ) ) { $ returnValue = true ; break ; } } return ( bool ) $ returnValue ; }
|
Whenever or not the current resource is an instance of the specified class
|
49,414
|
public static function getInstance ( array $ arguments ) { if ( in_array ( '-nc' , $ arguments ) || in_array ( '--no-color' , $ arguments ) ) { return new VerboseLogger ( static :: getLogLevel ( $ arguments ) ) ; } return new ColoredVerboseLogger ( static :: getLogLevel ( $ arguments ) ) ; }
|
Returns the configured instance of the verbose logger based on the arguments .
|
49,415
|
protected static function getLogLevel ( array $ arguments ) { $ argumentsForSearch = implode ( ' ' , $ arguments ) ; foreach ( static :: $ levels as $ argumentPattern => $ currentLevel ) { if ( strpos ( $ argumentsForSearch , $ argumentPattern ) !== false ) { return $ currentLevel ; } } return LogLevel :: ERROR ; }
|
Returns the current log level based on the verbosity parameters .
|
49,416
|
protected function preUpdateArtisanCommands ( ) { collect ( config ( 'self-update.artisan_commands.pre_update' ) ) -> every ( function ( $ commandParams , $ commandKey ) { Artisan :: call ( $ commandKey , $ commandParams [ 'params' ] ) ; } ) ; }
|
Run pre update artisan commands from config .
|
49,417
|
protected function postUpdateArtisanCommands ( ) { collect ( config ( 'self-update.artisan_commands.post_update' ) ) -> every ( function ( $ commandParams , $ commandKey ) { Artisan :: call ( $ commandKey , $ commandParams [ 'params' ] ) ; } ) ; }
|
Run post update artisan commands from config .
|
49,418
|
protected function getRepositoryReleases ( ) { if ( empty ( $ this -> config [ 'repository_vendor' ] ) || empty ( $ this -> config [ 'repository_name' ] ) ) { throw new \ Exception ( 'No repository specified. Please enter a valid Github repository owner and name in your config.' ) ; } return $ this -> client -> request ( 'GET' , self :: GITHUB_API_URL . '/repos/' . $ this -> config [ 'repository_vendor' ] . '/' . $ this -> config [ 'repository_name' ] . '/tags' ) ; }
|
Get all releases for a specific repository .
|
49,419
|
protected function unzipArchive ( $ file = '' , $ targetDir = '' , $ deleteZipArchive = true ) : bool { if ( empty ( $ file ) || ! File :: exists ( $ file ) ) { throw new \ InvalidArgumentException ( "Archive [{$file}] cannot be found or is empty." ) ; } $ zip = new \ ZipArchive ( ) ; $ res = $ zip -> open ( $ file ) ; if ( ! $ res ) { throw new \ Exception ( "Cannot open zip archive [{$file}]." ) ; } if ( empty ( $ targetDir ) ) { $ extracted = $ zip -> extractTo ( File :: dirname ( $ file ) ) ; } else { $ extracted = $ zip -> extractTo ( $ targetDir ) ; } $ zip -> close ( ) ; if ( $ extracted && $ deleteZipArchive === true ) { File :: delete ( $ file ) ; } return true ; }
|
Unzip an archive .
|
49,420
|
protected function hasCorrectPermissionForUpdate ( ) : bool { if ( ! $ this -> pathToUpdate ) { throw new \ Exception ( 'No directory set for update. Please set the update with: setPathToUpdate(path).' ) ; } $ collection = collect ( $ this -> pathToUpdate -> files ( ) ) -> each ( function ( $ file ) { if ( ! File :: isWritable ( $ file -> getRealPath ( ) ) ) { event ( new HasWrongPermissions ( $ this ) ) ; return false ; } } ) ; return true ; }
|
Check a given directory recursively if all files are writeable .
|
49,421
|
protected function isSourceAlreadyFetched ( $ version ) : bool { $ storagePath = $ this -> config [ 'download_path' ] . '/' . $ version ; if ( ! File :: exists ( $ storagePath ) || empty ( File :: directories ( $ storagePath ) ) ) { return false ; } return true ; }
|
Check if the source has already been downloaded .
|
49,422
|
protected function setPathToUpdate ( string $ path , array $ exclude ) { $ finder = ( new Finder ( ) ) -> in ( $ path ) -> exclude ( $ exclude ) ; $ this -> pathToUpdate = $ finder ; }
|
Set the paths to be updated .
|
49,423
|
public function createReleaseFolder ( $ storagePath , $ releaseName ) { $ subDirName = File :: directories ( $ storagePath ) ; $ directories = File :: directories ( $ subDirName [ 0 ] ) ; File :: makeDirectory ( $ storagePath . '/' . $ releaseName ) ; foreach ( $ directories as $ directory ) { File :: moveDirectory ( $ directory , $ storagePath . '/' . $ releaseName . '/' . File :: name ( $ directory ) ) ; } $ files = File :: allFiles ( $ subDirName [ 0 ] , true ) ; foreach ( $ files as $ file ) { File :: move ( $ file -> getRealPath ( ) , $ storagePath . '/' . $ releaseName . '/' . $ file -> getFilename ( ) ) ; } File :: deleteDirectory ( $ subDirName [ 0 ] ) ; }
|
Create a releas sub - folder inside the storage dir .
|
49,424
|
protected function registerCommands ( ) { $ this -> commands ( [ CheckForUpdate :: class , ] ) ; collect ( config ( 'self-update.artisan_commands.pre_update' ) ) -> each ( function ( $ command ) { $ this -> commands ( [ $ command [ 'class' ] ] ) ; } ) ; collect ( config ( 'self-update.artisan_commands.post_update' ) ) -> each ( function ( $ command ) { $ this -> commands ( [ $ command [ 'class' ] ] ) ; } ) ; }
|
Register the package its commands .
|
49,425
|
public function source ( $ name = '' ) : SourceRepository { $ name = $ name ? : $ this -> getDefaultSourceRepository ( ) ; return $ this -> sources [ $ name ] = $ this -> get ( $ name ) ; }
|
Get a source repository type instance .
|
49,426
|
protected function getConfig ( string $ name ) : array { if ( isset ( $ this -> app [ 'config' ] [ 'self-update' ] [ 'repository_types' ] [ $ name ] ) ) { return $ this -> app [ 'config' ] [ 'self-update' ] [ 'repository_types' ] [ $ name ] ; } return [ ] ; }
|
Get the source repository connection configuration .
|
49,427
|
protected function get ( $ name ) { return isset ( $ this -> sources [ $ name ] ) ? $ this -> sources [ $ name ] : $ this -> resolve ( $ name ) ; }
|
Attempt to get the right source repository instance .
|
49,428
|
protected function resolve ( $ name ) { $ config = $ this -> getConfig ( $ name ) ; if ( empty ( $ config ) ) { throw new InvalidArgumentException ( "Source repository [{$name}] is not defined." ) ; } if ( isset ( $ this -> customSourceCreators [ $ config [ 'type' ] ] ) ) { return $ this -> callCustomSourceCreators ( $ config ) ; } $ repositoryMethod = 'create' . ucfirst ( $ name ) . 'Repository' ; if ( method_exists ( $ this , $ repositoryMethod ) ) { return $ this -> { $ repositoryMethod } ( $ config ) ; } throw new InvalidArgumentException ( "Repository [{$name}] is not supported." ) ; }
|
Try to find the correct source repository implementation ; - ) .
|
49,429
|
public function isNewVersionAvailable ( $ currentVersion = '' ) : bool { $ version = $ currentVersion ? : $ this -> getVersionInstalled ( ) ; if ( ! $ version ) { throw new \ InvalidArgumentException ( 'No currently installed version specified.' ) ; } $ this -> deleteVersionFile ( ) ; if ( version_compare ( $ version , $ this -> getVersionAvailable ( ) , '<' ) ) { if ( ! $ this -> versionFileExists ( ) ) { $ this -> setVersionFile ( $ this -> getVersionAvailable ( ) ) ; event ( new UpdateAvailable ( $ this -> getVersionAvailable ( ) ) ) ; } return true ; } return false ; }
|
Check repository if a newer version than the installed one is available .
|
49,430
|
protected function getPackageReleases ( ) { if ( empty ( $ url = $ this -> config [ 'repository_url' ] ) ) { throw new \ Exception ( 'No repository specified. Please enter a valid URL in your config.' ) ; } $ format = str_replace ( '_VERSION_' , '\d+\.\d+\.\d+' , str_replace ( '.' , '\.' , $ this -> config [ 'pkg_filename_format' ] ) ) . '.zip' ; $ count = preg_match_all ( "/<a.*href=\".*$format\">($format)<\/a>/i" , $ this -> client -> get ( $ url ) -> getBody ( ) -> getContents ( ) , $ files ) ; $ collection = [ ] ; $ url = preg_replace ( '/\/$/' , '' , $ url ) ; for ( $ i = 0 ; $ i < $ count ; $ i ++ ) { $ basename = preg_replace ( "/^$this->prepend/" , '' , preg_replace ( "/$this->append$/" , '' , preg_replace ( '/.zip$/' , '' , $ files [ 1 ] [ $ i ] ) ) ) ; array_push ( $ collection , ( object ) [ 'name' => $ basename , 'zipball_url' => $ url . '/' . $ files [ 1 ] [ $ i ] , ] ) ; } array_multisort ( $ collection , SORT_DESC ) ; return new Collection ( $ collection ) ; }
|
Retrieve html body with list of all releases from archive URL .
|
49,431
|
public function download ( Request $ request ) { $ disk = $ request -> get ( 'disk' ) ; $ file = $ request -> get ( 'file' ) ; $ storage = Storage :: disk ( $ disk ) ; $ fullPath = $ storage -> getDriver ( ) -> getAdapter ( ) -> applyPathPrefix ( $ file ) ; if ( File :: isFile ( $ fullPath ) ) { return response ( ) -> download ( $ fullPath ) ; } return response ( '' , 404 ) ; }
|
Download a backup zip file .
|
49,432
|
public function delete ( Request $ request ) { $ disk = Storage :: disk ( $ request -> get ( 'disk' ) ) ; $ file = $ request -> get ( 'file' ) ; if ( $ disk -> exists ( $ file ) ) { $ disk -> delete ( $ file ) ; return response ( ) -> json ( [ 'status' => true , 'message' => trans ( 'admin.delete_succeeded' ) , ] ) ; } return response ( ) -> json ( [ 'status' => false , 'message' => trans ( 'admin.delete_failed' ) , ] ) ; }
|
Delete a backup file .
|
49,433
|
private function configureSecurity ( array $ mergedConfig , ContainerBuilder $ container ) { foreach ( $ mergedConfig [ 'commandbus' ] as $ commandBusConfig ) { if ( in_array ( 'tactician.middleware.security' , $ commandBusConfig [ 'middleware' ] ) ) { return $ this -> configureCommandSecurityVoter ( $ mergedConfig , $ container ) ; } } }
|
Configure the security voter if the security middleware is loaded .
|
49,434
|
private function configureCommandSecurityVoter ( array $ mergedConfig , ContainerBuilder $ container ) { if ( ! $ container -> has ( 'tactician.middleware.security_voter' ) ) { $ definition = new Definition ( HandleCommandVoter :: class , [ new Reference ( 'security.access.decision_manager' ) , $ mergedConfig [ 'security' ] ] ) ; $ definition -> addTag ( 'security.voter' ) ; $ container -> setDefinition ( 'tactician.middleware.security_voter' , $ definition ) ; } }
|
Configure the security voter .
|
49,435
|
private function configureLogger ( array $ mergedConfig , ContainerBuilder $ container ) { $ this -> configureLoggerFormatters ( $ container ) ; $ loggerMiddleware = new Definition ( LoggerMiddleware :: class , [ new Reference ( $ mergedConfig [ 'logger_formatter' ] ) , new Reference ( 'logger' ) ] ) ; $ loggerMiddleware -> setPublic ( false ) ; $ loggerMiddleware -> addTag ( 'monolog.logger' , [ 'channel' => 'command_bus' ] ) ; $ container -> setDefinition ( 'tactician.middleware.logger' , $ loggerMiddleware ) ; }
|
Configure the logger middleware .
|
49,436
|
public function getConfigTreeBuilder ( ) { $ treeBuilder = new TreeBuilder ( 'tactician' ) ; if ( \ method_exists ( $ treeBuilder , 'getRootNode' ) ) { $ rootNode = $ treeBuilder -> getRootNode ( ) ; } else { $ rootNode = $ treeBuilder -> root ( 'tactician' ) ; } $ rootNode -> children ( ) -> arrayNode ( 'commandbus' ) -> defaultValue ( [ 'default' => [ 'middleware' => [ 'tactician.middleware.command_handler' ] ] ] ) -> requiresAtLeastOneElement ( ) -> useAttributeAsKey ( 'name' ) -> prototype ( 'array' ) -> children ( ) -> arrayNode ( 'middleware' ) -> requiresAtLeastOneElement ( ) -> useAttributeAsKey ( 'name' ) -> prototype ( 'scalar' ) -> end ( ) -> validate ( ) -> ifTrue ( function ( $ config ) { $ isPresent = in_array ( 'tactician.middleware.command_handler' , $ config ) ; $ isLast = end ( $ config ) == 'tactician.middleware.command_handler' ; return $ isPresent && ! $ isLast ; } ) -> thenInvalid ( '"tactician.middleware.command_handler" should be the last middleware loaded ' . 'when it is used.' ) -> end ( ) -> end ( ) -> scalarNode ( 'method_inflector' ) -> end ( ) -> end ( ) -> end ( ) -> end ( ) -> scalarNode ( 'default_bus' ) -> defaultValue ( BusBuildersFromConfig :: DEFAULT_BUS_ID ) -> cannotBeEmpty ( ) -> end ( ) -> scalarNode ( 'method_inflector' ) -> defaultValue ( BusBuildersFromConfig :: DEFAULT_METHOD_INFLECTOR ) -> cannotBeEmpty ( ) -> end ( ) -> arrayNode ( 'security' ) -> defaultValue ( [ ] ) -> useAttributeAsKey ( 'name' ) -> prototype ( 'array' ) -> prototype ( 'scalar' ) -> end ( ) -> end ( ) -> end ( ) -> scalarNode ( 'logger_formatter' ) -> defaultValue ( 'tactician.logger.class_properties_formatter' ) -> cannotBeEmpty ( ) -> end ( ) -> end ( ) -> validate ( ) -> ifTrue ( function ( $ config ) { return is_array ( $ config ) && array_key_exists ( 'default_bus' , $ config ) && array_key_exists ( 'commandbus' , $ config ) ; } ) -> then ( function ( $ config ) { $ busNames = [ ] ; foreach ( $ config [ 'commandbus' ] as $ busName => $ busConfig ) { $ busNames [ ] = $ busName ; } if ( ! in_array ( $ config [ 'default_bus' ] , $ busNames ) ) { throw new InvalidConfigurationException ( sprintf ( 'The default_bus "%s" was not defined as a command bus. Valid option(s): %s' , $ config [ 'default_bus' ] , implode ( ', ' , $ busNames ) ) ) ; } return $ config ; } ) -> end ( ) ; return $ treeBuilder ; }
|
Create a rootnode tree for configuration that can be injected into the DI container .
|
49,437
|
public function mapParameter ( array $ mapping ) { if ( isset ( $ this -> fieldMappings [ $ mapping [ 'parameterName' ] ] ) ) { throw MappingException :: duplicateParameterMapping ( $ this -> className , $ mapping [ 'parameterName' ] ) ; } $ this -> parameters [ $ mapping [ 'parameterName' ] ] = $ mapping ; }
|
Adds a mapped parameter to the class .
|
49,438
|
public function persist ( $ objects ) { if ( ! is_array ( $ objects ) && ! $ objects instanceof \ Traversable ) { $ objects = array ( $ objects ) ; } foreach ( $ objects as $ object ) { if ( ! is_object ( $ object ) ) { throw new UnexpectedTypeException ( $ object , 'object' ) ; } $ this -> unitOfWork -> persist ( $ object ) ; } }
|
Adds the object to the index
|
49,439
|
public function getRepositories ( array $ entityNames ) { $ repositoryCollection = new EntityRepositoryCollection ( $ this ) ; foreach ( $ entityNames as $ entityName ) { $ repositoryCollection -> addRepository ( $ this -> getRepository ( $ entityName ) ) ; } return $ repositoryCollection ; }
|
Gets a collection of entity repositories .
|
49,440
|
protected function getParameters ( $ paramMapping ) { $ parameters = array ( ) ; foreach ( $ paramMapping as $ propertyName => $ mapping ) { $ paramName = isset ( $ mapping [ 'fieldName' ] ) ? $ mapping [ 'fieldName' ] : $ propertyName ; $ parameters [ $ paramName ] = $ propertyName ; } return $ parameters ; }
|
Generates parameter mapping from entity annotations
|
49,441
|
protected function getRootMapping ( $ mappings ) { $ properties = array ( ) ; foreach ( $ mappings as $ rootMapping ) { $ propertyName = $ rootMapping [ 'fieldName' ] ; $ mapping = array ( ) ; if ( isset ( $ rootMapping [ 'value' ] ) ) { $ mapping = $ rootMapping [ 'value' ] ; } if ( isset ( $ rootMapping [ 'match' ] ) ) { $ mapping [ 'match' ] = $ rootMapping [ 'match' ] ; } if ( isset ( $ rootMapping [ 'pathMatch' ] ) ) { $ mapping [ 'path_match' ] = $ rootMapping [ 'pathMatch' ] ; } if ( isset ( $ rootMapping [ 'unmatch' ] ) ) { $ mapping [ 'unmatch' ] = $ rootMapping [ 'unmatch' ] ; } if ( isset ( $ rootMapping [ 'pathUnmatch' ] ) ) { $ mapping [ 'path_unmatch' ] = $ rootMapping [ 'pathUnmatch' ] ; } if ( isset ( $ rootMapping [ 'matchPattern' ] ) ) { $ mapping [ 'match_pattern' ] = $ rootMapping [ 'matchPattern' ] ; } if ( isset ( $ rootMapping [ 'matchMappingType' ] ) ) { $ mapping [ 'match_mapping_type' ] = $ rootMapping [ 'matchMappingType' ] ; } if ( isset ( $ rootMapping [ 'mapping' ] ) ) { $ mapping [ 'mapping' ] = current ( $ this -> getMapping ( array ( $ rootMapping [ 'mapping' ] ) ) ) ; } if ( isset ( $ rootMapping [ 'id' ] ) ) { $ properties [ $ propertyName ] [ ] [ $ rootMapping [ 'id' ] ] = $ mapping ; } else { $ properties [ $ propertyName ] = $ mapping ; } } return $ properties ; }
|
Generates root mapping from entity annotations
|
49,442
|
public function useResultCache ( $ useCache , $ cacheLifetime = null ) { $ this -> useResultCache = $ useCache ; $ this -> cacheLifetime = $ cacheLifetime ; return $ this ; }
|
If hydrating with Doctrine then you can use the result cache on the default or provided query
|
49,443
|
public function hydrateWith ( $ hydrationQuery , $ parameter = null ) { $ this -> hydrationQuery = $ hydrationQuery ; if ( $ parameter ) { $ this -> hydrationParameter = $ parameter ; } return $ this ; }
|
Set a custom Doctrine Query to execute in order to hydrate the search engine results into required entities . The assumption is made the the search engine result id is correlated to the entity id . An optional query parameter override can be specified .
|
49,444
|
public function getSingleResult ( $ hydrationMode = null ) { $ this -> query -> setSize ( 1 ) ; $ results = $ this -> getResult ( $ hydrationMode ) ; if ( count ( $ results ) < 1 ) { throw new NoResultException ( 'No results found' ) ; } return $ results [ 0 ] ; }
|
Execute search for single result and hydrate results if required .
|
49,445
|
public function getResult ( $ hydrationMode = null ) { if ( $ hydrationMode ) { $ this -> hydrationMode = $ hydrationMode ; } $ classes = array ( ) ; foreach ( array_unique ( $ this -> entityClasses ) as $ entityClass ) { $ classes [ ] = $ this -> sm -> getClassMetadata ( $ entityClass ) ; } $ resultSet = $ this -> getSearchManager ( ) -> getClient ( ) -> search ( $ this -> query , $ classes ) ; if ( $ resultSet instanceof Elastica \ ResultSet ) { $ this -> count = $ resultSet -> getTotalHits ( ) ; $ this -> facets = $ resultSet -> getFacets ( ) ; $ results = $ resultSet -> getResults ( ) ; } else { $ resultClass = get_class ( $ resultSet ) ; throw new DoctrineSearchException ( "Unexpected result set class '$resultClass'" ) ; } if ( $ this -> hydrationMode == self :: HYDRATE_BYPASS ) { return $ resultSet ; } elseif ( $ this -> hydrationMode == self :: HYDRATE_INTERNAL ) { return $ this -> sm -> getUnitOfWork ( ) -> hydrateCollection ( $ classes , $ resultSet ) ; } $ fn = function ( $ result ) { return ( string ) $ result -> getId ( ) ; } ; $ ids = array_map ( $ fn , $ results ) ; return $ this -> getHydrationQuery ( ) -> setParameter ( $ this -> hydrationParameter , $ ids ? : null ) -> useResultCache ( $ this -> useResultCache , $ this -> cacheLifetime ) -> getResult ( $ this -> hydrationMode ) ; }
|
Execute search and hydrate results if required .
|
49,446
|
protected function doLoadMetadata ( $ class , $ parent , $ rootEntityFound , array $ nonSuperclassParents ) { $ this -> driver -> loadMetadataForClass ( $ class -> getName ( ) , $ class ) ; if ( $ this -> evm -> hasListeners ( Events :: loadClassMetadata ) ) { $ eventArgs = new LoadClassMetadataEventArgs ( $ class , $ this -> sm ) ; $ this -> evm -> dispatchEvent ( Events :: loadClassMetadata , $ eventArgs ) ; } }
|
Actually load the metadata from the underlying metadata
|
49,447
|
public function search ( $ query ) { $ classes = $ this -> getClassMetadata ( ) ; return $ this -> _sm -> getUnitOfWork ( ) -> loadCollection ( $ classes , $ query ) ; }
|
Execute a direct search query on the associated index and type
|
49,448
|
public function delete ( $ query ) { $ classes = $ this -> getClassMetadata ( ) ; foreach ( $ classes as $ class ) { $ this -> _sm -> getClient ( ) -> removeAll ( $ class , $ query ) ; } }
|
Execute a direct delete by query on the associated index and type
|
49,449
|
public function getClassName ( ) { $ classNames = array ( ) ; foreach ( $ this -> _repositories as $ repository ) { $ classNames [ ] = $ repository -> getClassName ( ) ; } return $ classNames ; }
|
Returns the class names of the objects managed by the repository
|
49,450
|
protected function getClassMetadata ( ) { $ classes = array ( ) ; foreach ( $ this -> _repositories as $ repository ) { $ classes [ ] = $ repository -> getClassMetadata ( ) ; } return $ classes ; }
|
Returns the class metadata of the objects managed by the repository
|
49,451
|
public function getClassMetadataFactory ( ) { if ( ! isset ( $ this -> attributes [ 'classMetadataFactory' ] ) ) { $ classMetaDataFactoryName = $ this -> getClassMetadataFactoryName ( ) ; $ this -> attributes [ 'classMetadataFactory' ] = new $ classMetaDataFactoryName ; } return $ this -> attributes [ 'classMetadataFactory' ] ; }
|
Gets the class metadata factory .
|
49,452
|
public function commit ( $ entity = null ) { if ( $ this -> evm -> hasListeners ( Events :: preFlush ) ) { $ this -> evm -> dispatchEvent ( Events :: preFlush , new Event \ PreFlushEventArgs ( $ this -> sm ) ) ; } $ this -> commitRemoved ( ) ; $ this -> commitPersisted ( ) ; if ( $ entity === true ) { $ client = $ this -> sm -> getClient ( ) ; foreach ( array_unique ( $ this -> updatedIndexes ) as $ index ) { $ client -> refreshIndex ( $ index ) ; } } $ this -> clear ( ) ; if ( $ this -> evm -> hasListeners ( Events :: postFlush ) ) { $ this -> evm -> dispatchEvent ( Events :: postFlush , new Event \ PostFlushEventArgs ( $ this -> sm ) ) ; } }
|
Commits the UnitOfWork executing all operations that have been postponed up to this point .
|
49,453
|
private function commitPersisted ( ) { $ sortedDocuments = $ this -> sortObjects ( $ this -> scheduledForPersist ) ; $ client = $ this -> sm -> getClient ( ) ; foreach ( $ sortedDocuments as $ entityName => $ documents ) { $ classMetadata = $ this -> sm -> getClassMetadata ( $ entityName ) ; $ this -> updatedIndexes [ ] = $ classMetadata -> index ; $ client -> addDocuments ( $ classMetadata , $ documents ) ; } }
|
Commit persisted entities to the database
|
49,454
|
private function commitRemoved ( ) { $ documents = $ this -> sortObjects ( $ this -> scheduledForDelete , false ) ; $ client = $ this -> sm -> getClient ( ) ; foreach ( $ documents as $ entityName => $ documents ) { $ classMetadata = $ this -> sm -> getClassMetadata ( $ entityName ) ; $ this -> updatedIndexes [ ] = $ classMetadata -> index ; $ client -> removeDocuments ( $ classMetadata , $ documents ) ; } }
|
Commit deleted entities to the database
|
49,455
|
private function sortObjects ( array $ objects , $ serialize = true ) { $ documents = array ( ) ; $ serializer = $ this -> sm -> getSerializer ( ) ; foreach ( $ objects as $ object ) { $ document = $ serialize ? $ serializer -> serialize ( $ object ) : $ object ; $ id = ( string ) $ object -> getId ( ) ; if ( ! $ id ) { throw new DoctrineSearchException ( 'Entity must have an id to be indexed' ) ; } $ documents [ get_class ( $ object ) ] [ $ id ] = $ document ; } return $ documents ; }
|
Prepare entities for commit . Entities scheduled for deletion do not need to be serialized .
|
49,456
|
public function load ( ClassMetadata $ class , $ value , $ options = array ( ) ) { $ client = $ this -> sm -> getClient ( ) ; if ( isset ( $ options [ 'field' ] ) ) { $ document = $ client -> findOneBy ( $ class , $ options [ 'field' ] , $ value ) ; } else { $ document = $ client -> find ( $ class , $ value , $ options ) ; } return $ this -> hydrateEntity ( $ class , $ document ) ; }
|
Load and hydrate a document model
|
49,457
|
public function loadCollection ( array $ classes , $ query ) { $ results = $ this -> sm -> getClient ( ) -> search ( $ query , $ classes ) ; return $ this -> hydrateCollection ( $ classes , $ results ) ; }
|
Load and hydrate a document collection
|
49,458
|
public function hydrateCollection ( array $ classes , Traversable $ resultSet ) { $ collection = new ArrayCollection ( ) ; foreach ( $ resultSet as $ document ) { foreach ( $ classes as $ class ) { if ( $ document -> getIndex ( ) == $ class -> index && $ document -> getType ( ) == $ class -> type ) { break ; } } $ collection [ ] = $ this -> hydrateEntity ( $ class , $ document ) ; } return $ collection ; }
|
Construct an entity collection
|
49,459
|
public function hydrateEntity ( ClassMetadata $ class , $ document ) { $ data = $ document -> getData ( ) ; $ fields = array_merge ( $ document -> hasFields ( ) ? $ document -> getFields ( ) : array ( ) , array ( '_version' => $ document -> getVersion ( ) ) ) ; foreach ( $ fields as $ name => $ value ) { if ( isset ( $ class -> parameters [ $ name ] ) ) { $ data [ $ name ] = $ value ; } else { foreach ( $ class -> parameters as $ param => $ mapping ) { if ( isset ( $ mapping [ 'fieldName' ] ) && $ mapping [ 'fieldName' ] == $ name ) { $ data [ $ param ] = $ value ; break ; } } } } $ data [ $ class -> getIdentifier ( ) ] = $ document -> getId ( ) ; $ entity = $ this -> sm -> getSerializer ( ) -> deserialize ( $ class -> className , json_encode ( $ data ) ) ; if ( $ this -> evm -> hasListeners ( Events :: postLoad ) ) { $ this -> evm -> dispatchEvent ( Events :: postLoad , new Event \ LifecycleEventArgs ( $ entity , $ this -> sm ) ) ; } return $ entity ; }
|
Construct an entity object
|
49,460
|
public function startLtiSession ( common_http_Request $ request ) { try { $ factoryAuth = $ this -> getServiceLocator ( ) -> get ( FactoryLtiAuthAdapterServiceInterface :: SERVICE_ID ) ; $ adapter = $ factoryAuth -> create ( $ request ) ; $ user = $ adapter -> authenticate ( ) ; $ session = new TaoLtiSession ( $ user ) ; $ this -> getServiceLocator ( ) -> propagate ( $ session ) ; common_session_SessionManager :: startSession ( $ session ) ; } catch ( LtiInvalidVariableException $ e ) { $ this -> getServiceLocator ( ) -> get ( LoggerService :: SERVICE_ID ) -> log ( LogLevel :: INFO , $ e -> getMessage ( ) ) ; throw new LtiException ( __ ( 'You are not authorized to use this system' ) , LtiErrorMessage :: ERROR_UNAUTHORIZED ) ; } }
|
start a session from the provided OAuth Request
|
49,461
|
public function getLtiSession ( ) { $ session = common_session_SessionManager :: getSession ( ) ; if ( ! $ session instanceof TaoLtiSession ) { throw new LtiException ( __FUNCTION__ . ' called on a non LTI session' , LtiErrorMessage :: ERROR_SYSTEM_ERROR ) ; } $ this -> getServiceLocator ( ) -> propagate ( $ session ) ; return $ session ; }
|
Returns the current LTI session
|
49,462
|
protected function run ( ) { if ( empty ( $ this -> getOption ( 'key' ) ) || empty ( $ this -> getOption ( 'secret' ) ) ) { return new Report ( Report :: TYPE_ERROR , 'Not all arguments were provided. Try to run the script with -h option' ) ; } $ consumerService = $ this -> getClassService ( ) ; $ clazz = $ this -> getClass ( ConsumerService :: CLASS_URI ) ; $ label = $ this -> hasOption ( 'label' ) ? $ this -> getOption ( 'label' ) : $ consumerService -> createUniqueLabel ( $ clazz ) ; try { $ consumer = $ consumerService -> createInstance ( $ clazz , $ label ) ; } catch ( \ Exception $ e ) { return new Report ( Report :: TYPE_ERROR , 'Error while creating consumer. Actual message is: ' . $ e -> getMessage ( ) ) ; } $ consumer -> setPropertyValue ( $ this -> getProperty ( DataStore :: PROPERTY_OAUTH_KEY ) , $ this -> getOption ( 'key' ) ) ; $ consumer -> setPropertyValue ( $ this -> getProperty ( DataStore :: PROPERTY_OAUTH_SECRET ) , $ this -> getOption ( 'secret' ) ) ; if ( $ this -> hasOption ( 'callbackUrl' ) ) { $ consumer -> setPropertyValue ( $ this -> getProperty ( DataStore :: PROPERTY_OAUTH_CALLBACK ) , $ this -> getOption ( 'callbackUrl' ) ) ; } return new Report ( Report :: TYPE_SUCCESS , sprintf ( 'Lti consumer "%s" was created. Check GUI to edit its properties' , $ consumer -> getLabel ( ) ) ) ; }
|
Run the script
|
49,463
|
public function getUserId ( $ id , $ key ) { $ dataStore = new \ tao_models_classes_oauth_DataStore ( ) ; try { $ consumerResource = $ dataStore -> findOauthConsumerResource ( $ key ) ; } catch ( \ tao_models_classes_oauth_Exception $ e ) { throw new \ common_exception_NotFound ( $ e -> getMessage ( ) ) ; } $ service = $ this -> getServiceLocator ( ) -> get ( LtiUserService :: SERVICE_ID ) ; $ userIdentifier = $ service -> getUserIdentifier ( $ id , $ consumerResource ) ; if ( is_null ( $ userIdentifier ) ) { return null ; } return array ( 'id' => $ userIdentifier ) ; }
|
Get common user uri associated to Lti user id
|
49,464
|
public function getUserId ( ) { try { $ parameters = $ this -> getParameters ( ) ; if ( ! isset ( $ parameters [ self :: LTI_USER_ID ] ) ) { throw new \ common_exception_MissingParameter ( self :: LTI_USER_ID , __FUNCTION__ ) ; } if ( ! isset ( $ parameters [ self :: LTI_CONSUMER_KEY ] ) ) { throw new \ common_exception_MissingParameter ( self :: LTI_CONSUMER_KEY , __FUNCTION__ ) ; } $ id = $ parameters [ self :: LTI_USER_ID ] ; $ key = $ parameters [ self :: LTI_CONSUMER_KEY ] ; $ data = $ this -> getCrudService -> getUserId ( $ id , $ key ) ; if ( ! $ data ) { \ common_Logger :: i ( 'Id ' . $ id . ' is not found.' ) ; throw new \ common_exception_NotFound ( 'No data found for the given id.' ) ; } $ this -> returnSuccess ( $ data ) ; } catch ( \ Exception $ e ) { \ common_Logger :: w ( $ e -> getMessage ( ) ) ; $ this -> returnFailure ( $ e ) ; } }
|
End point to get common user uri by lti user id
|
49,465
|
protected function getParametersAliases ( ) { return array ( 'user_id' => self :: LTI_USER_ID , 'oauth_consumer_key' => self :: LTI_CONSUMER_KEY , 'label' => OntologyRdfs :: RDFS_LABEL , 'oauth-key' => DataStore :: PROPERTY_OAUTH_KEY , 'oauth-secret' => DataStore :: PROPERTY_OAUTH_SECRET , 'oauth-callback-url' => DataStore :: PROPERTY_OAUTH_CALLBACK , ) ; }
|
Optionally a specific rest controller may declare aliases for parameters used for the rest communication
|
49,466
|
protected function getKeyValuePersistence ( ) { $ persistenceName = $ this -> getOption ( 'kv-persistence' ) ; $ persistenceManager = $ this -> getServiceLocator ( ) -> get ( \ common_persistence_Manager :: SERVICE_ID ) ; $ persistence = $ persistenceManager -> getPersistenceById ( $ persistenceName ) ; if ( ! $ persistence instanceof \ common_persistence_KeyValuePersistence ) { throw new \ common_Exception ( 'Given persistence is not a key value' ) ; } return $ persistence ; }
|
Create the persistence from option and validate as KeyValue persistence
|
49,467
|
protected function setVerbosity ( ) { if ( $ this -> getOption ( 'verbose' ) === true ) { $ verboseLogger = VerboseLoggerFactory :: getInstance ( [ '-nc' , '-vv' ] ) ; $ this -> setLogger ( new LoggerAggregator ( array ( $ this -> getLogger ( ) , $ verboseLogger ) ) ) ; } }
|
If verbose option is set set the appropriate logger
|
49,468
|
public function getLtiLinkResource ( ) { if ( is_null ( $ this -> ltiLink ) ) { $ service = $ this -> getServiceLocator ( ) -> get ( LinkService :: SERVICE_ID ) ; $ consumer = $ this -> getLaunchData ( ) -> getLtiConsumer ( ) ; $ linkId = $ service -> getLinkId ( $ consumer -> getUri ( ) , $ this -> getLaunchData ( ) -> getResourceLinkID ( ) ) ; $ this -> ltiLink = new core_kernel_classes_Resource ( $ linkId ) ; } return $ this -> ltiLink ; }
|
Returns an resource representing the incoming link
|
49,469
|
public function send ( ) { try { $ this -> requestParams = common_http_Request :: currentRequest ( ) -> getParams ( ) ; $ this -> launchData = LtiLaunchData :: fromRequest ( common_http_Request :: currentRequest ( ) ) ; $ baseUrl = null ; if ( $ this -> requiresRedirect ( ) && ! empty ( $ this -> getReturnBaseUrl ( ) ) ) { $ this -> errorRedirectResponse ( ) ; } else { echo $ this -> showLtiErrorPage ( ) ; } } catch ( \ Exception $ e ) { $ this -> renderer -> setTemplate ( Template :: getTemplate ( 'error/error500.tpl' , 'tao' ) ) ; echo $ this -> renderer -> render ( ) ; } }
|
Send LTI error response .
|
49,470
|
protected function getLtiErrorMessage ( ) { $ message = __ ( 'Error: ' ) . $ this -> exception -> getMessage ( ) ; $ log = __ ( 'Error: [key %s] "%s"' , $ this -> exception -> getKey ( ) , $ this -> exception -> getMessage ( ) ) ; return new LtiErrorMessage ( $ message , $ log ) ; }
|
Generate LtiErrorMessage based on exception
|
49,471
|
protected function showLtiErrorPage ( ) { if ( isset ( $ this -> requestParams [ LtiLaunchData :: TOOL_CONSUMER_INSTANCE_NAME ] ) ) { $ this -> renderer -> setData ( 'consumerLabel' , $ this -> requestParams [ LtiLaunchData :: TOOL_CONSUMER_INSTANCE_NAME ] ) ; } elseif ( isset ( $ this -> requestParams [ LtiLaunchData :: TOOL_CONSUMER_INSTANCE_DESCRIPTION ] ) ) { $ this -> renderer -> setData ( 'consumerLabel' , $ this -> requestParams [ LtiLaunchData :: TOOL_CONSUMER_INSTANCE_DESCRIPTION ] ) ; } if ( isset ( $ this -> requestParams [ LtiLaunchData :: LAUNCH_PRESENTATION_RETURN_URL ] ) ) { $ returnUrl = $ this -> requestParams [ LtiLaunchData :: LAUNCH_PRESENTATION_RETURN_URL ] ; $ serverName = $ _SERVER [ 'SERVER_NAME' ] ; $ pieces = parse_url ( $ returnUrl ) ; $ domain = isset ( $ pieces [ 'host' ] ) ? $ pieces [ 'host' ] : '' ; if ( $ serverName == $ domain ) { $ this -> renderer -> setData ( 'returnUrl' , $ returnUrl ) ; } } return $ this -> renderLtiErrorPage ( $ this -> exception , false ) ; }
|
Show error page
|
49,472
|
protected function renderLtiErrorPage ( LtiException $ error , $ returnLink = true ) { $ consumerLabel = $ this -> launchData -> getToolConsumerName ( ) ; if ( ! is_null ( $ consumerLabel ) ) { $ this -> renderer -> setData ( 'consumerLabel' , $ consumerLabel ) ; } $ this -> renderer -> setData ( 'message' , $ error -> getMessage ( ) ) ; $ this -> renderer -> setTemplate ( Template :: getTemplate ( 'error.tpl' , 'taoLti' ) ) ; return $ this -> renderer -> render ( ) ; }
|
Render an error page .
|
49,473
|
private function errorRedirectResponse ( ) { $ queryParams = $ this -> getLtiErrorMessage ( ) -> getUrlParams ( ) ; $ url = $ this -> getRedirectUrl ( $ queryParams ) ; $ this -> ltiRedirect ( $ url ) ; }
|
Send LTI error redirect response .
|
49,474
|
private function getRedirectUrl ( array $ queryParams ) { $ baseUrl = $ this -> getReturnBaseUrl ( ) ; if ( ! empty ( $ baseUrl ) ) { return $ baseUrl . ( parse_url ( $ baseUrl , PHP_URL_QUERY ) ? '&' : '?' ) . http_build_query ( $ queryParams ) ; } else { throw new LtiException ( 'Invalid LTI return url.' ) ; } }
|
Build LTI return url with query parameters .
|
49,475
|
private function getReturnBaseUrl ( ) { $ baseUrl = '' ; $ session = \ common_session_SessionManager :: getSession ( ) ; if ( $ session instanceof TaoLtiSession ) { $ launchData = $ session -> getLaunchData ( ) ; if ( $ launchData -> hasReturnUrl ( ) ) { $ baseUrl = $ launchData -> getReturnUrl ( ) ; } } else { if ( $ this -> launchData -> hasVariable ( LtiLaunchData :: LAUNCH_PRESENTATION_RETURN_URL ) ) { $ baseUrl = $ this -> launchData -> getVariable ( LtiLaunchData :: LAUNCH_PRESENTATION_RETURN_URL ) ; } } return $ baseUrl ; }
|
Get lti return url from LTI session or from request data .
|
49,476
|
public function findOrSpawnUser ( LtiLaunchData $ launchData ) { $ dataModel = ModelManager :: getModel ( ) ; $ transactionSafe = $ this -> getOption ( self :: OPTION_TRANSACTION_SAFE ) ; if ( ! $ dataModel instanceof \ core_kernel_persistence_smoothsql_SmoothModel || ! $ transactionSafe ) { $ taoUser = $ this -> findUser ( $ launchData ) ; if ( is_null ( $ taoUser ) ) { $ taoUser = $ this -> spawnUser ( $ launchData ) ; } return $ taoUser ; } else { $ platform = $ dataModel -> getPersistence ( ) -> getPlatform ( ) ; $ retry = 0 ; $ maxRetry = $ this -> getRetryOption ( ) ; $ previousIsolationLevel = $ platform -> getTransactionIsolation ( ) ; while ( $ retry <= $ maxRetry ) { $ platform -> setTransactionIsolation ( \ common_persistence_sql_Platform :: TRANSACTION_SERIALIZABLE ) ; $ platform -> beginTransaction ( ) ; try { $ taoUser = $ this -> findUser ( $ launchData ) ; if ( is_null ( $ taoUser ) ) { $ taoUser = $ this -> spawnUser ( $ launchData ) ; } $ platform -> commit ( ) ; return $ taoUser ; } catch ( \ common_persistence_sql_SerializationException $ e ) { \ common_Logger :: w ( 'SQL Serialization Failure occured in ' . __CLASS__ . '::' . __LINE__ . ' while finding or spawing LTI Ontology user. Retried ' . $ retry . ' times.' ) ; $ retry ++ ; } catch ( \ Exception $ e ) { if ( $ platform -> isTransactionActive ( ) ) { \ common_Logger :: d ( 'Rollbacking LTI Ontology user transaction.' ) ; $ platform -> rollback ( ) ; } \ common_Logger :: e ( $ e -> getMessage ( ) ) ; throw new LtiException ( 'LTI Ontology user could not be created. Process had to be rolled back.' , 0 , $ e ) ; } finally { $ platform -> setTransactionIsolation ( $ previousIsolationLevel ) ; } } } }
|
Returns the existing tao User that corresponds to the LTI request or spawns it . Overriden to implement transaction safe implementation for Ontology Storage .
|
49,477
|
protected function determineTaoRoles ( LtiLaunchData $ ltiLaunchData ) { $ roles = array ( ) ; if ( $ ltiLaunchData -> hasVariable ( LtiLaunchData :: ROLES ) ) { foreach ( $ ltiLaunchData -> getUserRoles ( ) as $ role ) { $ taoRole = LtiUtils :: mapLTIRole2TaoRole ( $ role ) ; if ( ! is_null ( $ taoRole ) ) { $ roles [ ] = $ taoRole ; } } $ roles = array_unique ( $ roles ) ; } else { return array ( LtiRoles :: INSTANCE_LTI_BASE ) ; } return $ roles ; }
|
Calculate your primary tao roles from the launchdata
|
49,478
|
public function validate ( LtiLaunchData $ data ) { try { if ( ! $ this -> isValidLinkId ( $ this -> getLaunchDataParameter ( $ data , LtiLaunchData :: RESOURCE_LINK_ID ) ) ) { throw new LtiInvalidLaunchDataException ( "Required parameter resource_link_id can not be empty." ) ; } $ ltiVersion = $ this -> getLaunchDataParameter ( $ data , LtiLaunchData :: LTI_VERSION ) ; if ( ! $ this -> isValidLtiVersion ( $ ltiVersion ) ) { throw new LtiInvalidLaunchDataException ( "Invalid LTI version provided." ) ; } if ( ! $ this -> isCorrectLtiVersion ( $ ltiVersion ) ) { throw new LtiInvalidLaunchDataException ( "Wrong LTI version provided." ) ; } if ( ! $ this -> isValidLtiMessageType ( $ this -> getLaunchDataParameter ( $ data , LtiLaunchData :: LTI_MESSAGE_TYPE ) ) ) { throw new LtiInvalidLaunchDataException ( 'Invalid LTI message type provided.' ) ; } } catch ( LtiException $ e ) { $ e -> setLaunchData ( $ data ) ; throw $ e ; } return true ; }
|
Check if provides launch data object is valid .
|
49,479
|
private function getLaunchDataParameter ( LtiLaunchData $ data , $ name ) { if ( $ data -> hasVariable ( $ name ) ) { return $ data -> getVariable ( $ name ) ; } throw new LtiVariableMissingException ( $ name ) ; }
|
Get launch data parameter by name .
|
49,480
|
public function launch ( ) { try { $ request = common_http_Request :: currentRequest ( ) ; $ ltiLaunchData = LtiLaunchData :: fromRequest ( $ request ) ; $ validator = $ this -> getServiceLocator ( ) -> get ( LtiValidatorService :: SERVICE_ID ) ; $ validator -> validateLaunchData ( $ ltiLaunchData ) ; LtiService :: singleton ( ) -> startLtiSession ( $ request ) ; $ cookieService = $ this -> getServiceManager ( ) -> get ( CookieVerifyService :: SERVICE_ID ) ; if ( $ cookieService -> isVerifyCookieRequired ( ) ) { if ( tao_models_classes_accessControl_AclProxy :: hasAccess ( 'verifyCookie' , 'CookieUtils' , 'taoLti' ) ) { $ cookieRedirect = _url ( 'verifyCookie' , 'CookieUtils' , 'taoLti' , [ 'session' => session_id ( ) , 'redirect' => urlencode ( _url ( 'run' , null , null , $ _GET ) ) , ] ) ; $ this -> redirect ( $ cookieRedirect ) ; } else { throw new LtiException ( __ ( 'You are not authorized to use this system' ) , LtiErrorMessage :: ERROR_UNAUTHORIZED ) ; } } else { $ this -> forward ( 'run' , null , null , $ _GET ) ; } } catch ( common_user_auth_AuthFailedException $ e ) { common_Logger :: i ( $ e -> getMessage ( ) ) ; throw new LtiException ( __ ( 'The LTI connection could not be established' ) , LtiErrorMessage :: ERROR_UNAUTHORIZED ) ; } catch ( LtiException $ e ) { common_Logger :: i ( $ e -> __toString ( ) ) ; if ( tao_helpers_Request :: isAjax ( ) ) { throw new common_exception_IsAjaxAction ( __CLASS__ . '::' . __FUNCTION__ ) ; } throw $ e ; } catch ( tao_models_classes_oauth_Exception $ e ) { common_Logger :: i ( $ e -> getMessage ( ) ) ; throw new LtiException ( __ ( 'The LTI connection could not be established' ) , LtiErrorMessage :: ERROR_UNAUTHORIZED ) ; } }
|
Entrypoint of every tool
|
49,481
|
public function verifyCookie ( ) { $ url = $ this -> getRequestParameter ( 'redirect' ) ; $ url = rawurldecode ( $ url ) ; $ session = $ this -> getRequestParameter ( 'session' ) ; if ( session_id ( ) == $ session ) { $ this -> forwardUrl ( $ url ) ; } else { $ this -> setData ( 'session' , $ session ) ; $ this -> setData ( 'redirect' , $ url ) ; $ this -> setView ( 'cookieError.tpl' ) ; } }
|
Verifies whenever or not the cookie was set correctly Redirects the user to his destination if it was or prompts the user to restore the session if it wasn t
|
49,482
|
public function restoreSession ( ) { $ sessId = $ this -> getRequestParameter ( 'session' ) ; $ url = $ this -> getRequestParameter ( 'redirect' ) ; if ( session_id ( ) != $ sessId ) { common_Logger :: i ( 'Changing session to ' . $ sessId ) ; session_unset ( ) ; session_destroy ( ) ; session_id ( $ sessId ) ; session_start ( ) ; if ( session_id ( ) != $ sessId ) { $ this -> returnError ( __ ( 'Unable to restore Session' ) ) ; } session_regenerate_id ( true ) ; common_Logger :: d ( 'regenerated session to id \'' . session_id ( ) . '\'' ) ; } else { common_Logger :: w ( 'Restore session called with correct session id \'' . session_id ( ) . '\'' ) ; } $ this -> forwardUrl ( $ url ) ; }
|
Closses the current session restores the session provided in the parameter session regenerates a new sessionid and redirects the user to the original address
|
49,483
|
public function getToolConsumerName ( ) { return $ this -> hasVariable ( self :: TOOL_CONSUMER_INSTANCE_NAME ) ? $ this -> getVariable ( self :: TOOL_CONSUMER_INSTANCE_NAME ) : $ this -> hasVariable ( self :: TOOL_CONSUMER_INSTANCE_DESCRIPTION ) ? $ this -> getVariable ( self :: TOOL_CONSUMER_INSTANCE_DESCRIPTION ) : null ; }
|
Tries to return the tool consumer name
|
49,484
|
public static function mapLTIRole2TaoRole ( $ role ) { $ taoRole = null ; if ( filter_var ( $ role , FILTER_VALIDATE_URL ) ) { $ taoRole = new core_kernel_classes_Resource ( $ role ) ; } else { if ( strtolower ( substr ( $ role , 0 , 4 ) ) !== 'urn:' ) { $ role = self :: LIS_CONTEXT_ROLE_NAMESPACE . $ role ; } list ( $ prefix , $ nid , $ nss ) = explode ( ':' , $ role , 3 ) ; if ( $ nid != 'lti' ) { common_Logger :: w ( 'Non LTI URN ' . $ role . ' passed via LTI' ) ; } $ urn = 'urn:' . strtolower ( $ nid ) . ':' . $ nss ; $ class = new core_kernel_classes_Class ( LtiRoles :: CLASS_URI ) ; $ cand = $ class -> searchInstances ( array ( LtiRoles :: PROPERTY_URN => $ urn ) ) ; if ( count ( $ cand ) > 1 ) { throw new common_exception_Error ( 'Multiple instances share the URN ' . $ urn ) ; } if ( count ( $ cand ) == 1 ) { $ taoRole = current ( $ cand ) ; } else { common_Logger :: w ( 'Unknown LTI role with urn: ' . $ urn ) ; } } if ( ! is_null ( $ taoRole ) && $ taoRole -> exists ( ) ) { return $ taoRole -> getUri ( ) ; } else { return null ; } }
|
Maps a fuly qualified or abbreviated lti role to an existing tao role
|
49,485
|
public static function mapCode2InterfaceLanguage ( $ code ) { if ( ! empty ( $ code ) ) { $ languageService = tao_models_classes_LanguageService :: singleton ( ) ; $ usage = new core_kernel_classes_Resource ( tao_models_classes_LanguageService :: INSTANCE_LANGUAGE_USAGE_GUI ) ; if ( $ languageService -> isLanguageAvailable ( $ code , $ usage ) ) { return $ code ; } \ common_Logger :: d ( '[Fallback] The provided launch language is unavailable: ' . $ code ) ; } return DEFAULT_LANG ; }
|
Returns the tao language code that corresponds to the code provided not yet implemented will always use default
|
49,486
|
public function findOrSpawnUser ( LtiLaunchData $ launchData ) { $ taoUser = $ this -> findUser ( $ launchData ) ; if ( is_null ( $ taoUser ) ) { $ taoUser = $ this -> spawnUser ( $ launchData ) ; } return $ taoUser ; }
|
Returns the existing tao User that corresponds to the LTI request or spawns it
|
49,487
|
public function findUser ( LtiLaunchData $ ltiContext ) { $ ltiConsumer = $ ltiContext -> getLtiConsumer ( ) ; $ taoUserId = $ this -> getUserIdentifier ( $ ltiContext -> getUserID ( ) , $ ltiConsumer -> getUri ( ) ) ; if ( is_null ( $ taoUserId ) ) { return null ; } $ ltiUser = $ this -> createLtiUser ( $ ltiContext , $ taoUserId ) ; \ common_Logger :: t ( "LTI User '" . $ ltiUser -> getIdentifier ( ) . "' found." ) ; $ this -> updateUser ( $ ltiUser , $ ltiContext ) ; return $ ltiUser ; }
|
Searches if this user was already created in TAO
|
49,488
|
public function spawnUser ( LtiLaunchData $ ltiContext ) { $ userId = $ ltiContext -> getUserID ( ) ; $ ltiUser = $ this -> createLtiUser ( $ ltiContext , $ userId ) ; $ this -> updateUser ( $ ltiUser , $ ltiContext ) ; return $ ltiUser ; }
|
Creates a new LTI User with the absolute minimum of required informations
|
49,489
|
public function call ( ) { if ( ! $ this -> hasRequestParameter ( 'ltiConsumerUri' ) ) { throw new common_exception_MissingParameter ( 'ltiConsumerUri' , get_class ( $ this ) ) ; } if ( ! $ this -> hasRequestParameter ( 'ltiLaunchUrl' ) ) { throw new common_exception_MissingParameter ( 'ltiLaunchUrl' , get_class ( $ this ) ) ; } $ ltiConsumer = new tao_models_classes_oauth_Credentials ( $ this -> getRequestParameter ( 'ltiConsumerUri' ) ) ; $ launchUrl = $ this -> getRequestParameter ( 'ltiLaunchUrl' ) ; $ serviceCallId = $ this -> getServiceCallId ( ) . '_c' ; $ session = common_session_SessionManager :: getSession ( ) ; $ roles = array ( ) ; foreach ( $ session -> getUserRoles ( ) as $ role ) { foreach ( LtiUtils :: mapTaoRole2LTIRoles ( $ role ) as $ ltiRole ) { $ roles [ ] = $ ltiRole ; } } $ ltiData = array ( 'lti_message_type' => 'basic-lti-launch-request' , 'lti_version' => 'LTI-1p0' , 'resource_link_id' => rand ( 0 , 9999999 ) , 'resource_link_title' => 'Launch Title' , 'resource_link_label' => 'Launch label' , 'context_id' => $ serviceCallId , 'context_title' => 'Launch Title' , 'context_label' => 'Launch label' , 'user_id' => $ session -> getUserUri ( ) , 'roles' => implode ( ',' , $ roles ) , 'lis_person_name_full' => $ session -> getUserLabel ( ) , 'tool_consumer_info_product_family_code' => PRODUCT_NAME , 'tool_consumer_info_version' => TAO_VERSION ) ; $ request = new common_http_Request ( $ launchUrl , common_http_Request :: METHOD_POST , $ ltiData ) ; $ service = new tao_models_classes_oauth_Service ( ) ; $ signedRequest = $ service -> sign ( $ request , $ ltiConsumer ) ; $ this -> setData ( 'launchUrl' , $ launchUrl ) ; $ this -> setData ( 'ltiData' , $ signedRequest -> getParams ( ) ) ; $ this -> setData ( 'client_config_url' , $ this -> getClientConfigUrl ( ) ) ; $ this -> setView ( 'ltiConsumer.tpl' ) ; }
|
Launches a oauth tool
|
49,490
|
public function validateEmptyWith ( $ attribute , $ value , $ parameters ) { $ values = [ ] ; foreach ( $ parameters as $ parameter ) { $ values [ ] = $ this -> getValue ( $ parameter ) ; } return Validator :: isEmptyWith ( $ value , $ values ) ; }
|
Provides empty_with validation rule for Laravel
|
49,491
|
private static function getIbanLength ( $ iban ) { $ countrycode = substr ( $ iban , 0 , 2 ) ; $ lengths = array ( 'AL' => 28 , 'AD' => 24 , 'AT' => 20 , 'AZ' => 28 , 'BH' => 22 , 'BE' => 16 , 'BA' => 20 , 'BR' => 29 , 'BG' => 22 , 'CR' => 21 , 'HR' => 21 , 'CY' => 28 , 'CZ' => 24 , 'DK' => 18 , 'DO' => 28 , 'TL' => 23 , 'EE' => 20 , 'FO' => 18 , 'FI' => 18 , 'FR' => 27 , 'GE' => 22 , 'DE' => 22 , 'GI' => 23 , 'GR' => 27 , 'GL' => 18 , 'GT' => 28 , 'HU' => 28 , 'IS' => 26 , 'IE' => 22 , 'IL' => 23 , 'IT' => 27 , 'JO' => 30 , 'KZ' => 20 , 'XK' => 20 , 'KW' => 30 , 'LV' => 21 , 'LB' => 28 , 'LI' => 21 , 'LT' => 20 , 'LU' => 20 , 'MK' => 19 , 'MT' => 31 , 'MR' => 27 , 'MU' => 30 , 'MC' => 27 , 'MD' => 24 , 'ME' => 22 , 'NL' => 18 , 'NO' => 15 , 'PK' => 24 , 'PS' => 29 , 'PL' => 28 , 'PT' => 25 , 'QA' => 29 , 'RO' => 24 , 'SM' => 27 , 'SA' => 24 , 'RS' => 22 , 'SK' => 24 , 'SI' => 19 , 'ES' => 24 , 'SE' => 24 , 'CH' => 21 , 'TN' => 24 , 'TR' => 26 , 'AE' => 23 , 'GB' => 22 , 'VG' => 24 , 'DZ' => 24 , 'AO' => 25 , 'BJ' => 28 , 'BF' => 27 , 'BI' => 16 , 'CM' => 27 , 'CV' => 25 , 'IR' => 26 , 'CI' => 28 , 'MG' => 27 , 'ML' => 28 , 'MZ' => 25 , 'SN' => 28 , 'UA' => 29 ) ; return isset ( $ lengths [ $ countrycode ] ) ? $ lengths [ $ countrycode ] : false ; }
|
Returns the designated length of IBAN for given IBAN
|
49,492
|
public static function isCreditcard ( $ value ) { $ length = strlen ( $ value ) ; if ( $ length < 13 || $ length > 19 ) { return false ; } $ sum = 0 ; $ weight = 2 ; for ( $ i = $ length - 2 ; $ i >= 0 ; $ i -- ) { $ digit = $ weight * $ value [ $ i ] ; $ sum += floor ( $ digit / 10 ) + $ digit % 10 ; $ weight = $ weight % 2 + 1 ; } $ mod = ( 10 - $ sum % 10 ) % 10 ; return ( $ mod == $ value [ $ length - 1 ] ) ; }
|
Checks if value is valid creditcard number .
|
49,493
|
public static function isDomainname ( $ value ) { if ( strlen ( $ value ) > 253 ) { return false ; } $ pattern = "/^(?!\-)(?:[a-zA-Z\d\-]{0,62}[a-zA-Z\d]\.){1,126}(?!\d+)[a-zA-Z\d]{1,63}$/" ; return ( boolean ) preg_match ( $ pattern , $ value ) ; }
|
Checks if value is domainname
|
49,494
|
private function getErrorMessage ( $ translator , $ messages , $ key ) { if ( isset ( $ messages [ $ key ] ) ) { return $ messages [ $ key ] ; } if ( $ translator -> has ( "validation.{$key}" ) ) { return $ translator -> get ( "validation.{$key}" ) ; } return $ translator -> get ( "validation::validation.{$key}" ) ; }
|
Return the matching error message for the key
|
49,495
|
public function history ( ) { try { $ sessions = $ this -> getRequestParameter ( 'session' ) ; $ requestOptions = $ this -> getRequestOptions ( [ 'sortby' => 'timestamp' , 'sortorder' => 'desc' , 'periodStart' => '' , 'periodEnd' => '' , ] ) ; if ( ! is_array ( $ sessions ) ) { $ sessions = $ sessions ? explode ( ',' , $ sessions ) : [ ] ; } $ historyService = $ this -> getServiceManager ( ) -> get ( TestSessionHistoryService :: SERVICE_ID ) ; $ this -> returnJson ( DataTableHelper :: paginate ( $ historyService -> getSessionsHistory ( $ sessions , $ requestOptions ) , $ requestOptions ) ) ; } catch ( ServiceNotFoundException $ e ) { \ common_Logger :: w ( 'No history service defined for proctoring' ) ; $ this -> returnError ( 'Proctoring interface not available' ) ; } }
|
Display the activity reporting of the current test center
|
49,496
|
public function printRubric ( ) { if ( ! $ this -> hasRequestParameter ( 'id' ) ) { throw new \ common_exception_MissingParameter ( 'id' ) ; } $ idList = $ this -> getRequestParameter ( 'id' ) ; if ( ! is_array ( $ idList ) ) { $ idList = [ $ idList ] ; } $ result = [ ] ; $ assessmentResultsService = $ this -> getServiceManager ( ) -> get ( AssessmentResultsService :: SERVICE_ID ) ; foreach ( $ idList as $ deliveryExecutionId ) { $ deliveryExecution = ServiceProxy :: singleton ( ) -> getDeliveryExecution ( $ deliveryExecutionId ) ; $ deliveryData = $ assessmentResultsService -> getDeliveryData ( $ deliveryExecution ) ; if ( ! $ deliveryData [ 'end' ] ) { continue ; } $ result [ ] = [ 'testData' => $ assessmentResultsService -> getTestData ( $ deliveryExecution ) , 'rubricContent' => $ assessmentResultsService -> getPrintableRubric ( $ deliveryExecution ) , 'testTakerData' => $ assessmentResultsService -> getTestTakerData ( $ deliveryExecution ) , 'deliveryData' => $ deliveryData , ] ; } $ this -> setData ( 'rubrics' , $ result ) ; $ this -> setData ( 'content-template' , 'Reporting/print_rubric.tpl' ) ; $ this -> setView ( 'Reporting/layout.tpl' ) ; }
|
Render printable rubrics
|
49,497
|
public static function getPrimaryColumns ( ) { return [ MonitoringStorage :: COLUMN_DELIVERY_EXECUTION_ID , MonitoringStorage :: COLUMN_STATUS , MonitoringStorage :: COLUMN_CURRENT_ASSESSMENT_ITEM , MonitoringStorage :: COLUMN_TEST_TAKER , MonitoringStorage :: COLUMN_AUTHORIZED_BY , MonitoringStorage :: COLUMN_START_TIME , MonitoringStorage :: COLUMN_END_TIME , MonitoringStorage :: DELIVERY_ID , MonitoringStorage :: DELIVERY_NAME , ] ; }
|
Returns a list of columns stored in the primary table
|
49,498
|
public function isPausable ( TestSession $ session = null ) { if ( $ this -> couldBePaused ( $ session ) ) { $ itemRef = $ session -> getCurrentAssessmentItemRef ( ) ; return $ this -> isItemPausable ( $ itemRef ) ; } return false ; }
|
Checked that section can be paused
|
49,499
|
private function isProctored ( TestSession $ session ) { if ( is_null ( $ this -> isProctored ) ) { $ this -> isProctored = false ; if ( ! is_null ( $ session ) ) { $ user = \ common_session_SessionManager :: getSession ( ) -> getUser ( ) ; $ deliveryExecution = ServiceProxy :: singleton ( ) -> getDeliveryExecution ( $ session -> getSessionId ( ) ) ; $ this -> isProctored = $ this -> getServiceManager ( ) -> get ( TestTakerAuthorizationService :: SERVICE_ID ) -> isProctored ( $ deliveryExecution -> getDelivery ( ) , $ user ) ; } } return $ this -> isProctored ; }
|
Is the given section proctored
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.