idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
50,900
protected function fixDefaultRelations ( array & $ relations ) { foreach ( $ relations as $ key => $ relation ) { if ( 'role_adldap_by_role_id' === $ relation && ! class_exists ( LDAP :: class ) ) { unset ( $ relations [ $ key ] ) ; } } }
Removes any relation where related service is not installed .
50,901
protected function getResource ( $ service , $ resource , $ params = [ ] , $ payload = null , $ checkPermission = true ) { try { $ result = ServiceManager :: handleRequest ( $ service , Verbs :: GET , $ resource , $ params , [ ] , $ payload , null , $ checkPermission ) ; if ( $ result -> getStatusCode ( ) >= 300 ) { throw ResponseFactory :: createExceptionFromResponse ( $ result ) ; } $ result = $ result -> getContent ( ) ; if ( $ result instanceof Arrayable ) { $ result = $ result -> toArray ( ) ; } if ( is_string ( $ result ) ) { $ result = [ 'value' => $ result ] ; } elseif ( Arr :: isAssoc ( $ result ) && config ( 'df.always_wrap_resources' ) === true && isset ( $ result [ config ( 'df.resources_wrapper' ) ] ) ) { $ result = $ result [ config ( 'df.resources_wrapper' ) ] ; } $ rSeg = explode ( '/' , $ resource ) ; $ api = $ service . '/' . $ rSeg [ 0 ] ; if ( isset ( $ rSeg [ 1 ] ) && in_array ( $ api , [ 'system/custom' , 'user/custom' ] ) ) { $ result = [ 'name' => $ rSeg [ 1 ] , 'value' => $ result ] ; } elseif ( isset ( $ rSeg [ 1 ] ) && $ api === $ service . '/_table' ) { $ result = [ 'name' => $ rSeg [ 1 ] , 'record' => $ result ] ; } if ( in_array ( $ api , [ 'system/user' , 'system/admin' ] ) ) { $ this -> setUserPassword ( $ result ) ; } return $ result ; } catch ( NotFoundException $ e ) { $ e -> setMessage ( 'Resource not found for ' . $ service . '/' . $ resource ) ; throw $ e ; } }
Extracts a resource
50,902
protected function setUserPassword ( array & $ users ) { if ( ! empty ( $ users ) ) { if ( Arr :: isAssoc ( $ users ) ) { $ users = [ $ users ] ; } foreach ( $ users as $ i => $ user ) { $ model = User :: find ( $ user [ 'id' ] ) ; if ( ! empty ( $ model ) ) { $ users [ $ i ] [ 'password' ] = $ model -> password ; } } } }
Sets user password encrypted when package is secured with a password .
50,903
public function getManifest ( $ key = null , $ default = null ) { if ( empty ( $ key ) ) { return $ this -> manifest ; } return array_get ( $ this -> manifest , $ key , $ default ) ; }
Get package manifest .
50,904
public function getExportStorageService ( $ default = null ) { $ storage = array_get ( $ this -> manifest , 'storage' , $ default ) ; if ( is_array ( $ storage ) ) { $ name = array_get ( $ storage , 'name' , array_get ( $ storage , 'id' , $ default ) ) ; if ( is_numeric ( $ name ) ) { return ServiceManager :: getServiceNameById ( $ name ) ; } return $ name ; } return $ storage ; }
Gets the storage service from the manifest to use for storing the exported zip file .
50,905
public function getExportStorageFolder ( $ default = null ) { $ folder = array_get ( $ this -> manifest , 'storage.folder' , array_get ( $ this -> manifest , 'storage.path' , $ default ) ) ; return ( empty ( $ folder ) ) ? $ default : $ folder ; }
Gets the storage folder from the manifest to use for storing the exported zip file in .
50,906
public function getExportFilename ( ) { $ host = php_uname ( 'n' ) ; $ default = $ host . '_' . date ( 'Y-m-d_H.i.s' , time ( ) ) ; $ filename = array_get ( $ this -> manifest , 'storage.filename' , array_get ( $ this -> manifest , 'storage.file' , $ default ) ) ; $ filename = ( empty ( $ filename ) ) ? $ default : $ filename ; if ( strpos ( $ filename , static :: FILE_EXTENSION ) === false ) { $ filename .= '.' . static :: FILE_EXTENSION ; } return $ filename ; }
Returns the filename for export file .
50,907
protected function isUploadedFile ( $ package ) { if ( isset ( $ package [ 'name' ] , $ package [ 'tmp_name' ] , $ package [ 'type' ] , $ package [ 'size' ] ) ) { if ( in_array ( $ package [ 'type' ] , [ 'application/zip' , 'application/x-zip-compressed' ] ) ) { return true ; } } return false ; }
Checks for valid uploaded file .
50,908
protected function getManifestFromUrlImport ( $ 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 { $ this -> zipFile = FileUtilities :: importUrlFileToTemp ( $ url ) ; } catch ( \ Exception $ ex ) { throw new InternalServerErrorException ( "Failed to import package from $url. " . $ ex -> getMessage ( ) ) ; } return $ this -> getManifestFromZipFile ( ) ; }
Returns the manifest from url imported package file .
50,909
protected function getManifestFromLocalFile ( $ file ) { $ extension = strtolower ( pathinfo ( $ file , PATHINFO_EXTENSION ) ) ; if ( static :: FILE_EXTENSION != $ extension ) { throw new BadRequestException ( "Only package files ending with '" . static :: FILE_EXTENSION . "' are allowed for import." ) ; } if ( file_exists ( $ file ) ) { $ this -> zipFile = $ file ; } else { throw new InternalServerErrorException ( "Failed to import. File not found $file" ) ; } return $ this -> getManifestFromZipFile ( ) ; }
Retrieves manifest from a local zip file .
50,910
protected function getManifestFromZipFile ( ) { $ this -> zip = new \ ZipArchive ( ) ; if ( true !== $ this -> zip -> open ( $ this -> zipFile ) ) { throw new InternalServerErrorException ( 'Failed to open imported zip file.' ) ; } $ password = $ this -> getPassword ( ) ; if ( ! empty ( $ password ) ) { $ this -> zip -> setPassword ( $ password ) ; } $ manifest = $ this -> zip -> getFromName ( 'package.json' ) ; if ( false === $ manifest ) { throw new BadRequestException ( 'Cannot read package manifest. A valid password is required if this is a secured package.' ) ; } $ manifest = DataFormatter :: jsonToArray ( $ manifest ) ; return $ manifest ; }
Retrieves the manifest file from package file .
50,911
protected function setManifestItems ( ) { $ m = $ this -> manifest ; if ( ! empty ( $ m ) ) { if ( isset ( $ m [ 'service' ] ) && is_array ( $ m [ 'service' ] ) ) { foreach ( $ m [ 'service' ] as $ item => $ value ) { if ( $ this -> isFileService ( $ item , $ value ) ) { $ this -> storageItems [ $ item ] = $ value ; } else { $ this -> nonStorageItems [ $ item ] = $ value ; } } } if ( count ( $ this -> getServices ( ) ) == 0 ) { throw new InternalServerErrorException ( 'No items found in package manifest.' ) ; } } }
Sets manifest items as class property .
50,912
public function zipResourceFile ( $ file , $ resource ) { if ( ! $ this -> zip -> addFromString ( $ file , json_encode ( $ resource , JSON_UNESCAPED_SLASHES ) ) ) { throw new InternalServerErrorException ( "Failed to add $file to the Zip Archive." ) ; } }
Adds resource file to ZipArchive .
50,913
public function getResourceFromZip ( $ resourceFile ) { $ data = [ ] ; $ json = $ this -> zip -> getFromName ( $ resourceFile ) ; if ( false !== $ json ) { $ data = json_decode ( $ json , JSON_UNESCAPED_SLASHES ) ; } return $ data ; }
Retrieves resource data from ZipArchive .
50,914
public function getZipFromZip ( $ file ) { $ fh = $ this -> zip -> getStream ( $ file ) ; if ( false !== $ fh ) { $ contents = null ; while ( ! feof ( $ fh ) ) { $ contents .= fread ( $ fh , 2 ) ; } $ tmpDir = rtrim ( sys_get_temp_dir ( ) , DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR ; $ zipFile = $ tmpDir . md5 ( $ file ) . time ( ) . '.' . static :: FILE_EXTENSION ; file_put_contents ( $ zipFile , $ contents ) ; $ zip = new \ ZipArchive ( ) ; if ( true !== $ zip -> open ( $ zipFile ) ) { throw new InternalServerErrorException ( 'Error opening zip file ' . $ file . '.' ) ; } $ this -> destructible [ ] = $ zipFile ; return $ zip ; } return null ; }
Retrieves zipped folder from ZipArchive .
50,915
public function getFileFromZip ( $ file ) { if ( false !== $ content = $ this -> zip -> getFromName ( $ file ) ) { $ tmpDir = rtrim ( sys_get_temp_dir ( ) , DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR ; $ fileName = $ tmpDir . md5 ( $ file ) . time ( ) . '.' . pathinfo ( $ file , PATHINFO_EXTENSION ) ; file_put_contents ( $ fileName , $ content ) ; $ this -> destructible [ ] = $ fileName ; return $ fileName ; } return null ; }
Retrieves a file from ZipArchive .
50,916
public function saveZipFile ( $ storageService , $ storageFolder ) { try { $ this -> zip -> close ( ) ; if ( $ this -> isSecured ( ) ) { $ password = $ this -> getPassword ( ) ; $ tmpDir = rtrim ( sys_get_temp_dir ( ) , DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR ; $ extractDir = $ tmpDir . substr ( basename ( $ this -> zipFile ) , 0 , strlen ( basename ( $ this -> zipFile ) ) - 4 ) ; $ tmpZip = new \ ZipArchive ( ) ; $ tmpZip -> open ( $ this -> zipFile ) ; $ tmpZip -> extractTo ( $ extractDir ) ; $ tmpZip -> close ( ) ; @ unlink ( $ this -> zipFile ) ; $ server = strtolower ( php_uname ( 's' ) ) ; $ commandSeparator = ';' ; if ( strpos ( $ server , 'windows' ) !== false ) { $ commandSeparator = '&' ; } @ exec ( "cd $extractDir $commandSeparator zip -r -P $password $this->zipFile ." , $ output ) ; \ Log :: info ( 'Encrypting zip file with a password.' , $ output ) ; @ FileUtilities :: deleteTree ( $ extractDir , true ) ; } $ storage = ServiceManager :: getService ( $ storageService ) ; if ( ! $ storage -> folderExists ( $ storageFolder ) ) { $ storage -> createFolder ( $ storageFolder ) ; } $ storage -> moveFile ( $ storageFolder . '/' . basename ( $ this -> zipFile ) , $ this -> zipFile ) ; $ url = Environment :: getURI ( ) . '/api/v2/' . $ storageService . '/' . $ storageFolder . '/' . basename ( $ this -> zipFile ) ; return $ url ; } catch ( \ Exception $ e ) { throw new InternalServerErrorException ( 'Failed to save the exported package using storage service ' . $ storageService . '. ' . $ e -> getMessage ( ) ) ; } }
Saves ZipArchive .
50,917
public function setDescriptionAttribute ( $ value ) { if ( strlen ( $ value ) > 255 ) { $ value = substr ( $ value , 0 , 255 ) ; } $ this -> attributes [ 'description' ] = $ value ; }
Making sure description is no longer than 255 characters .
50,918
public function quoteName ( $ name ) { if ( strpos ( $ name , '.' ) === false ) { return $ this -> quoteSimpleName ( $ name ) ; } $ parts = explode ( '.' , $ name ) ; foreach ( $ parts as $ i => $ part ) { if ( '*' !== $ part ) { $ parts [ $ i ] = $ this -> quoteSimpleName ( $ part ) ; } } return implode ( '.' , $ parts ) ; }
Quotes a resource name for use in a query . If the resource name contains schema prefix the prefix will also be properly quoted .
50,919
public static function export ( $ data ) { if ( is_object ( $ data ) ) { if ( $ data instanceof Arrayable || method_exists ( $ data , 'toArray' ) ) { $ data = $ data -> toArray ( ) ; } else { $ data = get_object_vars ( $ data ) ; } } if ( ! is_array ( $ data ) ) { return $ data ; } $ output = [ ] ; foreach ( $ data as $ key => $ value ) { $ output [ $ key ] = static :: export ( $ value ) ; } return $ output ; }
Build the array from data .
50,920
public static function validationErrorsToString ( $ messages ) { if ( $ messages instanceof MessageBag ) { $ messages = $ messages -> getMessages ( ) ; } $ errorString = '' ; if ( is_array ( $ messages ) ) { foreach ( $ messages as $ field => $ errors ) { foreach ( $ errors as $ error ) { $ errorString .= ' ' . $ error ; } } } return $ errorString ; }
Converts validation errors to plain string .
50,921
public static function getExternalIP ( ) { $ ip = \ Cache :: rememberForever ( 'external-ip-address' , function ( ) { $ response = Curl :: get ( 'http://ipinfo.io/ip' ) ; $ ip = trim ( $ response , "\t\r\n" ) ; try { $ validator = Validator :: make ( [ 'ip' => $ ip ] , [ 'ip' => 'ip' ] ) ; $ validator -> validate ( ) ; } catch ( ValidationException $ e ) { $ ip = null ; } return $ ip ; } ) ; return $ ip ; }
Returns instance s external IP address .
50,922
public static function getURI ( ) { $ s = $ _SERVER ; $ ssl = ( ! empty ( $ s [ 'HTTPS' ] ) && $ s [ 'HTTPS' ] == 'on' ) ; $ sp = strtolower ( array_get ( $ s , 'SERVER_PROTOCOL' , 'http://' ) ) ; $ protocol = substr ( $ sp , 0 , strpos ( $ sp , '/' ) ) . ( ( $ ssl ) ? 's' : '' ) ; $ port = array_get ( $ s , 'SERVER_PORT' , '80' ) ; $ port = ( ( ! $ ssl && $ port == '80' ) || ( $ ssl && $ port == '443' ) ) ? '' : ':' . $ port ; $ host = ( isset ( $ s [ 'HTTP_HOST' ] ) ? $ s [ 'HTTP_HOST' ] : array_get ( $ s , 'SERVER_NAME' , 'localhost' ) ) ; $ host = ( strpos ( $ host , ':' ) !== false ) ? $ host : $ host . $ port ; return $ protocol . '://' . $ host ; }
Returns instance s URI
50,923
public function getMask ( ) : IP { if ( $ this -> mask === null ) { if ( $ this -> prefix == 0 ) { $ this -> mask = new static :: $ ip_class ( 0 ) ; } else { $ max_int = gmp_init ( static :: $ ip_class :: MAX_INT ) ; $ mask = gmp_shiftl ( $ max_int , static :: $ ip_class :: NB_BITS - $ this -> prefix ) ; $ mask = gmp_and ( $ mask , $ max_int ) ; $ this -> mask = new static :: $ ip_class ( $ mask ) ; } } return $ this -> mask ; }
Return netmask .
50,924
public function getDelta ( ) : IP { if ( $ this -> delta === null ) { if ( $ this -> prefix == 0 ) { $ this -> delta = new static :: $ ip_class ( static :: $ ip_class :: MAX_INT ) ; } else { $ this -> delta = new static :: $ ip_class ( gmp_sub ( gmp_shiftl ( 1 , static :: $ ip_class :: NB_BITS - $ this -> prefix ) , 1 ) ) ; } } return $ this -> delta ; }
Return delta to last IP address .
50,925
public function getSubBlocks ( $ prefix ) : IPBlockIterator { $ prefix = ltrim ( $ prefix , '/' ) ; $ this -> checkPrefix ( $ prefix ) ; if ( $ prefix <= $ this -> prefix ) { throw new \ InvalidArgumentException ( "Prefix must be smaller than {$this->prefix} ($prefix given)" ) ; } $ first_block = new static ( $ this -> first_ip , $ prefix ) ; $ number_of_blocks = gmp_pow ( 2 , $ prefix - $ this -> prefix ) ; return new IPBlockIterator ( $ first_block , $ number_of_blocks ) ; }
Split the block into smaller blocks .
50,926
public function getSuperBlock ( $ prefix ) : IPBlock { $ prefix = ltrim ( $ prefix , '/' ) ; $ this -> checkPrefix ( $ prefix ) ; if ( $ prefix >= $ this -> prefix ) { throw new \ InvalidArgumentException ( "Prefix must be bigger than {$this->prefix} ($prefix given)" ) ; } return new static ( $ this -> first_ip , $ prefix ) ; }
Return the super block containing the current block .
50,927
public function contains ( $ ip_or_block ) : bool { if ( ( is_string ( $ ip_or_block ) && strpos ( $ ip_or_block , '/' ) !== false ) || $ ip_or_block instanceof IPBlock ) { return $ this -> containsBlock ( $ ip_or_block ) ; } else { return $ this -> containsIP ( $ ip_or_block ) ; } }
Determine if the current block contains an IP address or block .
50,928
public function containsIP ( $ ip ) : bool { if ( ! $ ip instanceof IP ) { $ ip = IP :: create ( $ ip ) ; } return ( $ ip -> numeric ( ) >= $ this -> getFirstIp ( ) -> numeric ( ) ) && ( $ ip -> numeric ( ) <= $ this -> getLastIp ( ) -> numeric ( ) ) ; }
Determine if the current block contains an IP address .
50,929
public function containsBlock ( $ block ) : bool { if ( ! $ block instanceof IPBlock ) { $ block = new static ( $ block ) ; } return $ block -> getFirstIp ( ) -> numeric ( ) >= $ this -> first_ip -> numeric ( ) && $ block -> getLastIp ( ) -> numeric ( ) <= $ this -> last_ip -> numeric ( ) ; }
Determine if the current block contains another block .
50,930
public function isIn ( $ block ) : bool { if ( ! $ block instanceof IPBlock ) { $ block = new static ( $ block ) ; } return $ block -> containsBlock ( $ this ) ; }
Determine if the current block is contained in another block .
50,931
public function getNbAddresses ( ) : string { if ( $ this -> nb_addresses === null ) { $ this -> nb_addresses = gmp_strval ( gmp_pow ( 2 , $ this -> getMaxPrefix ( ) - $ this -> prefix ) ) ; } return $ this -> nb_addresses ; }
Return the number of IP addresses in the block .
50,932
public function count ( ) : int { $ network_size = gmp_init ( $ this -> getNbAddresses ( ) ) ; if ( gmp_cmp ( $ network_size , PHP_INT_MAX ) > 0 ) { throw new \ RuntimeException ( 'The number of addresses is bigger than PHP_INT_MAX, use getNbAddresses() instead' ) ; } return gmp_intval ( $ network_size ) ; }
Count the number of addresses contained with the address block . May exceed PHP s internal maximum integer .
50,933
public static function setUserInfoWithJWT ( $ user , $ forever = false , $ appId = null ) { $ userInfo = null ; if ( $ user instanceof User ) { $ userInfo = $ user -> toArray ( ) ; $ userInfo [ 'is_sys_admin' ] = $ user -> is_sys_admin ; } if ( ! empty ( $ userInfo ) ) { $ id = array_get ( $ userInfo , 'id' ) ; $ email = array_get ( $ userInfo , 'email' ) ; $ token = JWTUtilities :: makeJWTByUser ( $ id , $ email , $ forever ) ; static :: setSessionToken ( $ token ) ; if ( ! empty ( $ appId ) && ! $ user -> is_sys_admin ) { static :: setSessionData ( $ appId , $ id ) ; return true ; } else { return static :: setUserInfo ( $ userInfo ) ; } } return false ; }
Sets basic info of the user in session with JWT when authenticated .
50,934
public static function setUserInfo ( $ user ) { if ( ! empty ( $ user ) ) { \ Session :: put ( 'user.id' , array_get ( $ user , 'id' ) ) ; \ Session :: put ( 'user.name' , array_get ( $ user , 'name' ) ) ; \ Session :: put ( 'user.username' , array_get ( $ user , 'username' ) ) ; \ Session :: put ( 'user.display_name' , array_get ( $ user , 'name' ) ) ; \ Session :: put ( 'user.first_name' , array_get ( $ user , 'first_name' ) ) ; \ Session :: put ( 'user.last_name' , array_get ( $ user , 'last_name' ) ) ; \ Session :: put ( 'user.email' , array_get ( $ user , 'email' ) ) ; \ Session :: put ( 'user.is_sys_admin' , array_get ( $ user , 'is_sys_admin' ) ) ; \ Session :: put ( 'user.last_login_date' , array_get ( $ user , 'last_login_date' ) ) ; \ Session :: put ( 'user.ldap_username' , array_get ( $ user , 'ldap_username' ) ) ; return true ; } return false ; }
Sets basic info of the user in session when authenticated .
50,935
public static function getPublicInfo ( ) { if ( empty ( session ( 'user' ) ) ) { throw new UnauthorizedException ( 'There is no valid session for the current request.' ) ; } $ sessionData = [ 'session_token' => session ( 'session_token' ) , 'session_id' => session ( 'session_token' ) , 'id' => session ( 'user.id' ) , 'name' => session ( 'user.display_name' ) , 'first_name' => session ( 'user.first_name' ) , 'last_name' => session ( 'user.last_name' ) , 'email' => session ( 'user.email' ) , 'is_sys_admin' => session ( 'user.is_sys_admin' ) , 'last_login_date' => session ( 'user.last_login_date' ) , 'host' => gethostname ( ) ] ; $ role = static :: get ( 'role' ) ; if ( ! session ( 'user.is_sys_admin' ) && ! empty ( $ role ) ) { $ sessionData [ 'role' ] = array_get ( $ role , 'name' ) ; $ sessionData [ 'role_id' ] = array_get ( $ role , 'id' ) ; } return $ sessionData ; }
Fetches user session data based on the authenticated user .
50,936
public static function verify ( $ url , $ caDir ) { static $ hostsByDir = [ ] ; if ( ! isset ( $ hostsByDir [ $ caDir ] ) ) { $ hostsByDir [ $ caDir ] = [ ] ; } $ extensions = [ 'crt' , 'pem' , 'cer' , 'der' ] ; if ( substr ( $ url , 0 , 5 ) != 'https' ) { return false ; } $ defaultCA = $ caDir . 'curl-ca-bundle.crt' ; $ host = strtolower ( parse_url ( $ url , PHP_URL_HOST ) ) ; if ( ! $ host ) { return $ defaultCA ; } if ( array_key_exists ( $ host , $ hostsByDir [ $ caDir ] ) ) { return $ hostsByDir [ $ caDir ] [ $ host ] ; } $ filename = $ host ; do { foreach ( $ extensions as $ ext ) { if ( file_exists ( $ verify = $ caDir . $ filename . '.' . $ ext ) ) { $ hostsByDir [ $ caDir ] [ $ host ] = $ verify ; return $ verify ; } } $ filename = substr ( $ filename , strpos ( $ filename , '.' ) + 1 ) ; } while ( substr_count ( $ filename , '.' ) > 0 ) ; $ hostsByDir [ $ caDir ] [ $ host ] = $ defaultCA ; return $ defaultCA ; }
Looks for a Certificate Authority file in the CA folder that matches the host and return the values for the verify option to its full path . If no specific file regarding a host is found uses curl - ca - bundle . crt by default .
50,937
public static function getRoleIdByAppIdAndUserId ( $ app_id , $ user_id ) { $ cacheKey = static :: makeRoleIdCacheKey ( $ app_id , $ user_id ) ; $ result = \ Cache :: remember ( $ cacheKey , \ Config :: get ( 'df.default_cache_ttl' ) , function ( ) use ( $ app_id , $ user_id ) { try { return static :: whereAppId ( $ app_id ) -> whereUserId ( $ user_id ) -> value ( 'role_id' ) ; } catch ( ModelNotFoundException $ ex ) { return null ; } } ) ; return $ result ; }
Use this primarily in middle - ware or where no session is established yet . Once session is established the role id is accessible via Session .
50,938
public function isConfirmationExpired ( ) { $ ttl = \ Config :: get ( 'df.confirm_code_ttl' , 1440 ) ; $ lastModTime = strtotime ( $ this -> last_modified_date ) ; $ code = $ this -> confirm_code ; if ( 'y' !== $ code && ! is_null ( $ code ) && ( ( time ( ) - $ lastModTime ) > ( $ ttl * 60 ) ) ) { return true ; } else { return false ; } }
Checks to se if confirmation period is expired .
50,939
public static function applyDefaultUserAppRole ( $ user , $ defaultRole ) { $ apps = App :: all ( ) ; if ( count ( $ apps ) === 0 ) { return false ; } foreach ( $ apps as $ app ) { if ( ! UserAppRole :: whereUserId ( $ user -> id ) -> whereAppId ( $ app -> id ) -> exists ( ) ) { $ userAppRoleData = [ 'user_id' => $ user -> id , 'app_id' => $ app -> id , 'role_id' => $ defaultRole ] ; UserAppRole :: create ( $ userAppRoleData ) ; } } return true ; }
Assigns a role to a user for all apps in the system .
50,940
public static function applyAppRoleMapByService ( $ user , $ serviceId ) { $ maps = AppRoleMap :: whereServiceId ( $ serviceId ) -> get ( ) ; foreach ( $ maps as $ map ) { UserAppRole :: whereUserId ( $ user -> id ) -> whereAppId ( $ map -> app_id ) -> delete ( ) ; $ userAppRoleData = [ 'user_id' => $ user -> id , 'app_id' => $ map -> app_id , 'role_id' => $ map -> role_id ] ; UserAppRole :: create ( $ userAppRoleData ) ; } }
Applies App to Role mapping to a user .
50,941
public function setPasswordAttribute ( $ password ) { if ( ! empty ( $ password ) ) { $ password = bcrypt ( $ password ) ; JWTUtilities :: invalidateTokenByUserId ( $ this -> id ) ; if ( isset ( $ this -> attributes [ 'confirm_code' ] ) && $ this -> attributes [ 'confirm_code' ] !== 'y' ) { $ this -> attributes [ 'confirm_code' ] = null ; } } $ this -> attributes [ 'password' ] = $ password ; }
Encrypts password .
50,942
public static function createFirstAdmin ( array & $ data ) { if ( empty ( $ data [ 'username' ] ) ) { $ data [ 'username' ] = $ data [ 'email' ] ; } $ validationRules = [ 'name' => 'required|max:255' , 'first_name' => 'required|max:255' , 'last_name' => 'required|max:255' , 'email' => 'required|email|max:255|unique:user' , 'password' => 'required|confirmed|min:6' , 'username' => 'min:6|unique:user,username|regex:/^\S*$/u|required' ] ; $ validator = Validator :: make ( $ data , $ validationRules ) ; if ( $ validator -> fails ( ) ) { $ errors = $ validator -> getMessageBag ( ) -> all ( ) ; $ data = array_merge ( $ data , [ 'errors' => $ errors , 'version' => \ Config :: get ( 'app.version' ) ] ) ; return false ; } else { $ attributes = array_only ( $ data , [ 'name' , 'first_name' , 'last_name' , 'email' , 'username' ] ) ; $ attributes [ 'is_active' ] = 1 ; $ user = static :: create ( $ attributes ) ; $ user -> password = array_get ( $ data , 'password' ) ; $ user -> is_sys_admin = 1 ; $ user -> save ( ) ; RegisterContact :: registerUser ( $ user ) ; \ Cache :: forever ( 'admin_exists' , true ) ; return $ user ; } }
Creates first admin user .
50,943
protected static function createRecordId ( $ table ) { $ randomTime = abs ( time ( ) ) ; if ( $ randomTime == 0 ) { $ randomTime = 1 ; } $ random1 = rand ( 1 , $ randomTime ) ; $ random2 = rand ( 1 , 2000000000 ) ; $ generateId = strtolower ( md5 ( $ random1 . $ table . $ randomTime . $ random2 ) ) ; $ randSmall = rand ( 10 , 99 ) ; return $ generateId . $ randSmall ; }
General method for creating a pseudo - random identifier
50,944
public function binary ( ) : string { $ hex = str_pad ( $ this -> numeric ( 16 ) , static :: NB_BITS / 4 , '0' , STR_PAD_LEFT ) ; return pack ( 'H*' , $ hex ) ; }
Return binary string representation .
50,945
public function bit_and ( $ value ) : IP { if ( ! $ value instanceof self ) { $ value = new static ( $ value ) ; } return new static ( gmp_and ( $ this -> ip , $ value -> ip ) ) ; }
Bitwise AND .
50,946
public function bit_or ( $ value ) : IP { if ( ! $ value instanceof self ) { $ value = new static ( $ value ) ; } return new static ( gmp_or ( $ this -> ip , $ value -> ip ) ) ; }
Bitwise OR .
50,947
public function isIn ( $ block ) : bool { if ( ! $ block instanceof IPBlock ) { $ block = IPBlock :: create ( $ block ) ; } return $ block -> contains ( $ this ) ; }
Check if the IP is contained in given block .
50,948
public function isLinkLocal ( ) : bool { if ( $ this -> is_link_local === null ) { $ this -> is_link_local = $ this -> isIn ( static :: $ link_local_block ) ; } return $ this -> is_link_local ; }
Determine if the address is a Link - Local address .
50,949
public function isLoopback ( ) : bool { if ( $ this -> is_loopback === null ) { $ this -> is_loopback = $ this -> isIn ( static :: $ loopback_range ) ; } return $ this -> is_loopback ; }
Return true if the address is within the loopback range .
50,950
public static function verifyUser ( $ payload ) { $ userId = $ payload -> get ( 'user_id' ) ; $ userKey = $ payload -> get ( 'sub' ) ; $ userInfo = ( $ userId ) ? User :: getCachedInfo ( $ userId ) : null ; if ( ! empty ( $ userInfo ) && $ userKey === md5 ( $ userInfo [ 'email' ] ) ) { return true ; } else { throw new TokenInvalidException ( 'User verification failed.' ) ; } }
Verifies JWT user .
50,951
public static function refreshToken ( ) { $ token = Session :: getSessionToken ( ) ; JWTAuth :: manager ( ) -> setRefreshFlow ( ) ; try { JWTAuth :: setToken ( $ token ) ; JWTAuth :: checkOrFail ( ) ; $ payloadArray = JWTAuth :: manager ( ) -> getJWTProvider ( ) -> decode ( $ token ) ; $ forever = boolval ( array_get ( $ payloadArray , 'forever' ) ) ; $ userId = array_get ( $ payloadArray , 'user_id' ) ; $ user = User :: find ( $ userId ) ; if ( $ forever ) { JWTFactory :: claims ( [ ] ) ; Session :: setUserInfoWithJWT ( $ user , $ forever ) ; } else { $ newToken = JWTAuth :: refresh ( true ) ; JWTAuth :: setToken ( $ newToken ) ; $ payload = JWTAuth :: getPayload ( ) ; static :: setTokenMap ( $ payload , $ newToken ) ; Session :: setSessionToken ( $ newToken ) ; $ userInfo = $ user -> toArray ( ) ; $ userInfo [ 'is_sys_admin' ] = $ user -> is_sys_admin ; Session :: setUserInfo ( $ userInfo ) ; } static :: invalidate ( $ token ) ; } catch ( JWTException $ e ) { throw new UnauthorizedException ( 'Token refresh failed. ' . $ e -> getMessage ( ) ) ; } return Session :: getSessionToken ( ) ; }
Refreshes a JWT token . Re - issues new JWT token if the original token is marked as forever
50,952
public function unconfigure ( TcTable $ table ) { $ this -> table = $ table ; $ table -> un ( TcTable :: EV_BODY_ADD , [ $ this , 'initialize' ] ) -> un ( TcTable :: EV_ROW_ADD , [ $ this , 'checkAvailableHeight' ] ) -> un ( TcTable :: EV_ROW_ADDED , [ $ this , 'checkFooter' ] ) -> un ( TcTable :: EV_ROW_SKIPPED , [ $ this , 'onRowSkipped' ] ) -> un ( TcTable :: EV_ROW_HEIGHT_GET , [ $ this , 'onRowHeightGet' ] ) -> un ( TcTable :: EV_BODY_ADDED , [ $ this , 'purge' ] ) ; }
Unconfigure the plugin
50,953
public function initialize ( TcTable $ table , $ rows , callable $ fn = null ) { $ this -> _widowsCalculatedHeight = [ ] ; $ this -> height = $ this -> getCalculatedWidowsHeight ( $ table , $ rows , $ fn ) ; $ this -> count = count ( $ rows ) ; $ this -> rows = $ rows ; $ this -> resetPageBreakTrigger ( ) ; }
Called before body is added . Configure everything about widows
50,954
public function onRowHeightGet ( TcTable $ table , $ row = null , $ rowIndex = null ) { if ( $ rowIndex !== null && isset ( $ this -> _widowsCalculatedHeight [ $ rowIndex ] ) ) { return $ this -> _widowsCalculatedHeight [ $ rowIndex ] ; } }
Called when TcTable copy default column definition inside the current row definition . We set an action here so we can use the widow s cache height instead of calculating it a second time
50,955
public function checkFooter ( TcTable $ table , $ row , $ rowIndex ) { $ pdf = $ table -> getPdf ( ) ; if ( $ rowIndex == $ this -> count - 1 && $ pdf -> GetY ( ) + $ this -> height >= $ this -> pageBreakTrigger ) { if ( $ table -> trigger ( TcTable :: EV_PAGE_ADD , [ $ this -> rows , $ rowIndex , true ] ) !== false ) { $ pdf -> AddPage ( ) ; $ table -> trigger ( TcTable :: EV_PAGE_ADDED , [ $ this -> rows , $ rowIndex , true ] ) ; } } }
Check if there s space for the footer after the last row is added
50,956
private function getCalculatedWidowsHeight ( TcTable $ table , $ rows , callable $ fn = null ) { $ count = count ( $ rows ) ; $ limit = $ count - $ this -> minWidowsOnPage ; $ h = 0 ; if ( $ this -> minWidowsOnPage && $ count && $ limit >= 0 ) { for ( $ i = $ count - 1 ; $ i >= $ limit ; $ i -- ) { if ( ! isset ( $ rows [ $ i ] ) ) { return $ h ; } $ data = $ fn ? $ fn ( $ table , $ rows [ $ i ] , $ i , true ) : $ rows [ $ i ] ; if ( is_array ( $ data ) || is_object ( $ data ) ) { $ this -> _widowsCalculatedHeight [ $ i ] = $ table -> getCurrentRowHeight ( $ data ) ; $ h += $ this -> _widowsCalculatedHeight [ $ i ] ; } else { $ limit -- ; } } } return $ h ; }
Get real height that widows will take . Used to force a page break if the remaining height isn t enough to draw all the widows on the current page .
50,957
public function flush ( ) { $ keys = $ this -> getCacheKeys ( ) ; foreach ( $ keys as $ key ) { Cache :: forget ( $ this -> makeCacheKey ( $ key ) ) ; } $ this -> removeKeys ( $ keys ) ; }
Forget all keys that we know
50,958
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 .
50,959
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
50,960
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 .
50,961
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." ) ; } $ 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 .
50,962
private function packageServices ( ) { if ( ! empty ( $ this -> exportServices ) ) { $ services = [ ] ; foreach ( $ this -> exportServices as $ serviceName ) { if ( is_numeric ( $ serviceName ) ) { $ service = Service :: find ( $ serviceName ) ; } else { $ 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 .
50,963
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 ) ) { $ service = Service :: find ( $ serviceName ) ; } else { $ 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 .
50,964
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
50,965
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 .
50,966
protected static function updateUserPassword ( $ users ) { if ( ! empty ( $ users ) ) { foreach ( $ users as $ i => $ user ) { if ( isset ( $ user [ 'password' ] ) ) { $ model = User :: where ( 'email' , '=' , $ user [ 'email' ] ) -> first ( ) ; $ model -> updatePasswordHash ( $ user [ 'password' ] ) ; } } } }
Updates user password when package is secured with a password .
50,967
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 ) { $ this -> throwExceptions ( $ e , 'Failed to insert role service access records for roles' ) ; } } return $ imported ; }
Imports Role Service Access relations for role .
50,968
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 .
50,969
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 .
50,970
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 .
50,971
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' : break ; case $ service . '/_table' : $ imported = $ this -> insertDbTableResources ( $ service ) ; break ; case $ service . '/_proc' : case $ service . '/_func' : $ 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 .
50,972
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 ) { $ this -> throwExceptions ( $ e , 'Failed to insert ' . $ service . '/' . $ resource ) ; } } } return true ; } return false ; }
Insert DB table data .
50,973
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 ) { $ this -> throwExceptions ( $ e , 'Failed to insert ' . $ service . '/' . $ resource ) ; } } return $ merged ; }
Imports generic resources .
50,974
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 .
50,975
protected function storeFiles ( ) { $ items = $ this -> package -> getStorageServices ( ) ; $ stored = false ; foreach ( $ items as $ service => $ resources ) { if ( is_string ( $ resources ) ) { $ resources = explode ( ',' , $ resources ) ; } try { $ storage = ServiceManager :: getService ( $ service ) ; foreach ( $ resources as $ resource ) { try { 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 ) { $ 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 .
50,976
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 .
50,977
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' ] ) ) { return $ oldAppId ; } } } return null ; }
Finds and returns new App id by old App id .
50,978
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' ] ) ) { return $ oldServiceId ; } } } return null ; }
Finds and returns the new service id by old id .
50,979
protected function log ( $ level , $ msg , $ context = [ ] ) { $ this -> log [ $ level ] [ ] = $ msg ; \ Log :: log ( $ level , $ msg , $ context ) ; }
Stores internal log and write to system log .
50,980
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 .
50,981
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 .
50,982
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 .
50,983
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 .
50,984
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 .
50,985
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
50,986
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 .
50,987
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
50,988
protected function getConfigHandler ( ) { if ( null !== $ typeInfo = ServiceManager :: getServiceType ( $ this -> type ) ) { return $ typeInfo -> getConfigHandler ( ) ; } return null ; }
Determine the handler for the extra config settings
50,989
public static function cleanFields ( $ fields ) { $ fields = parent :: cleanFields ( $ fields ) ; if ( in_array ( 'config' , $ fields ) ) { $ fields [ ] = 'id' ; $ fields [ ] = 'type' ; } 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 .
50,990
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 .
50,991
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 .
50,992
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 .
50,993
public function addParameter ( ParameterSchema $ schema ) { $ key = strtolower ( $ schema -> name ) ; $ this -> parameters [ $ key ] = $ schema ; }
Sets the named parameter metadata .
50,994
public function getParameter ( $ name ) { $ key = strtolower ( $ name ) ; if ( isset ( $ this -> parameters [ $ key ] ) ) { return $ this -> parameters [ $ key ] ; } return null ; }
Gets the named parameter metadata .
50,995
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
50,996
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 .
50,997
public function getService ( $ name ) { $ service = $ this -> makeService ( $ name ) ; $ this -> services [ $ name ] = $ service ; return $ this -> services [ $ name ] ; }
Get a service instance .
50,998
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 .
50,999
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 .