idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
45,900
public function getPlaylistByName ( string $ name ) : PlaylistInterface { $ roughMatch = false ; $ playlists = $ this -> getPlaylists ( ) ; foreach ( $ playlists as $ playlist ) { if ( $ playlist -> getName ( ) === $ name ) { return $ playlist ; } if ( strtolower ( $ playlist -> getName ( ) ) === strtolower ( $ name ) ) { $ roughMatch = $ playlist ; } } if ( $ roughMatch ) { return $ roughMatch ; } throw new NotFoundException ( "No playlist called '{$name}' exists on this network" ) ; }
Get the playlist with the specified name .
45,901
public function getPlaylistById ( string $ id ) : PlaylistInterface { $ controller = $ this -> getController ( ) ; return new Playlist ( $ id , $ controller ) ; }
Get the playlist with the specified id .
45,902
public function createPlaylist ( string $ name ) : PlaylistInterface { $ controller = $ this -> getController ( ) ; $ data = $ controller -> soap ( "AVTransport" , "CreateSavedQueue" , [ "Title" => $ name , "EnqueuedURI" => "" , "EnqueuedURIMetaData" => "" , ] ) ; $ playlist = new Playlist ( $ data [ "AssignedObjectID" ] , $ controller ) ; $ this -> playlists [ ] = $ playlist ; return $ playlist ; }
Create a new playlist .
45,903
public function getAlarms ( ) : array { if ( is_array ( $ this -> alarms ) ) { return $ this -> alarms ; } $ data = $ this -> getController ( ) -> soap ( "AlarmClock" , "ListAlarms" ) ; $ parser = new XmlParser ( $ data [ "CurrentAlarmList" ] ) ; $ alarms = [ ] ; foreach ( $ parser -> getTags ( "Alarm" ) as $ tag ) { $ alarms [ ] = new Alarm ( $ tag , $ this ) ; } return $ this -> alarms = $ alarms ; }
Get all the alarms available on the network .
45,904
public function getAlarmById ( int $ id ) : AlarmInterface { $ alarms = $ this -> getAlarms ( ) ; foreach ( $ alarms as $ alarm ) { if ( $ alarm -> getId ( ) === $ id ) { return $ alarm ; } } throw new NotFoundException ( "Unable to find an alarm with the id {$id} on this network" ) ; }
Get the alarm from the specified id .
45,905
private function applyVolume ( ControllerInterface $ controller ) : ControllerStateInterface { $ this -> speakers = [ ] ; foreach ( $ controller -> getSpeakers ( ) as $ speaker ) { $ this -> speakers [ $ speaker -> getUuid ( ) ] = $ speaker -> getVolume ( ) ; } return $ this ; }
Get the current volume of all the speakers in this group .
45,906
private function applyTracks ( ControllerInterface $ controller ) : ControllerStateInterface { $ this -> tracks = $ controller -> getQueue ( ) -> getTracks ( ) ; if ( $ controller -> isStreaming ( ) ) { $ media = $ controller -> getMediaInfo ( ) ; $ this -> stream = new Stream ( $ media [ "CurrentURI" ] ) ; } return $ this ; }
Get the current tracks in the queue .
45,907
public function getXml ( string $ url ) : XmlParser { $ uri = "http://{$this->ip}:1400{$url}" ; $ key = str_replace ( "/" , "_" , $ this -> ip . $ url ) ; if ( $ this -> cache -> has ( $ key ) ) { $ this -> logger -> info ( "getting xml from cache: {$uri}" ) ; $ xml = $ this -> cache -> get ( $ key ) ; if ( $ xml ) { return new XmlParser ( $ xml ) ; } $ this -> logger -> error ( "empty xml in cache" ) ; } $ this -> logger -> notice ( "requesting xml from: {$uri}" ) ; $ xml = ( string ) ( new Client ( ) ) -> get ( $ uri ) -> getBody ( ) ; $ this -> cache -> set ( $ key , $ xml , new \ DateInterval ( "P1D" ) ) ; return new XmlParser ( $ xml ) ; }
Retrieve some xml from the device .
45,908
public function soap ( string $ service , string $ action , array $ params = [ ] ) { switch ( $ service ) { case "AVTransport" : case "RenderingControl" : $ path = "MediaRenderer" ; break ; case "ContentDirectory" : $ path = "MediaServer" ; break ; case "AlarmClock" : case "DeviceProperties" : case "ZoneGroupTopology" : $ path = null ; break ; default : throw new \ InvalidArgumentException ( "Unknown service: {$service}" ) ; } $ location = "http://{$this->ip}:1400/" ; if ( is_string ( $ path ) ) { $ location .= "{$path}/" ; } $ location .= "{$service}/Control" ; $ this -> logger -> info ( "sending soap request to: {$location}" , $ params ) ; $ soap = new \ SoapClient ( null , [ "location" => $ location , "uri" => "urn:schemas-upnp-org:service:{$service}:1" , "trace" => true , ] ) ; $ soapParams = [ ] ; $ params [ "InstanceID" ] = 0 ; foreach ( $ params as $ key => $ val ) { $ soapParams [ ] = new \ SoapParam ( new \ SoapVar ( $ val , \ XSD_STRING ) , $ key ) ; } try { $ result = $ soap -> __soapCall ( $ action , $ soapParams ) ; $ this -> logger -> debug ( "REQUEST: " . $ soap -> __getLastRequest ( ) ) ; $ this -> logger -> debug ( "RESPONSE: " . $ soap -> __getLastResponse ( ) ) ; } catch ( \ SoapFault $ e ) { $ this -> logger -> debug ( "REQUEST: " . $ soap -> __getLastRequest ( ) ) ; $ this -> logger -> debug ( "RESPONSE: " . $ soap -> __getLastResponse ( ) ) ; throw new SoapException ( $ e , $ soap ) ; } return $ result ; }
Send a soap request to the device .
45,909
public function getModel ( ) : string { if ( $ this -> model === null ) { $ parser = $ this -> getXml ( "/xml/device_description.xml" ) ; if ( $ device = $ parser -> getTag ( "device" ) ) { $ this -> model = ( string ) $ device -> getTag ( "modelNumber" ) ; } if ( ! is_string ( $ this -> model ) || strlen ( $ this -> model ) === 0 ) { $ this -> model = "UNKNOWN" ; } $ this -> logger -> debug ( "{$this->ip} model: {$this->model}" ) ; } return $ this -> model ; }
Get the model of this device .
45,910
public static function vehicleModel ( $ brand = null ) : string { $ brandsWithModels = CarData :: getBrandsWithModels ( ) ; return static :: randomElement ( $ brandsWithModels [ $ brand ? : static :: vehicleBrand ( ) ] ) ; }
Get random vehicle model
45,911
public static function getRandomElementsFromArray ( array $ values , int $ count = 0 ) : array { $ valuesLength = count ( $ values ) ; if ( $ count > $ valuesLength ) { throw new \ InvalidArgumentException ( 'Count larger than array length.' ) ; } if ( ! $ count ) { $ count = random_int ( 0 , $ valuesLength ) ; } if ( $ count === 0 ) { return [ ] ; } return array_intersect_key ( $ values , array_flip ( ( array ) array_rand ( $ values , $ count ) ) ) ; }
Get random elements from input array
45,912
public static function getWeighted ( array $ values ) : string { $ currentTotal = 0 ; $ firstRand = random_int ( 1 , 100 ) ; $ total = array_sum ( $ values ) ; $ rand = ( $ firstRand / 100 ) * $ total ; foreach ( $ values as $ key => $ weight ) { $ currentTotal += $ weight ; if ( $ rand <= $ currentTotal ) { return $ key ; } } return '' ; }
Get one element out of an input array with specified weights to get the distribution of the generated elements as you want them .
45,913
public function implementedEvents ( ) { $ events = [ ] ; if ( $ this -> getConfig ( 'events' ) === false ) { return $ events ; } foreach ( ( array ) $ this -> getConfig ( 'events' ) as $ eventKey => $ event ) { if ( is_numeric ( $ eventKey ) ) { $ eventKey = $ event ; $ event = null ; } if ( $ event === null || is_string ( $ event ) ) { $ event = [ 'callable' => $ event ] ; } if ( ! is_array ( $ event ) ) { throw new \ InvalidArgumentException ( 'Event should be string or array' ) ; } $ priority = $ this -> getConfig ( 'priority' ) ; if ( ! array_key_exists ( 'callable' , $ event ) || $ event [ 'callable' ] === null ) { list ( , $ event [ 'callable' ] ) = pluginSplit ( $ eventKey ) ; } if ( $ priority && ! array_key_exists ( 'priority' , $ event ) ) { $ event [ 'priority' ] = $ priority ; } $ events [ $ eventKey ] = $ event ; } return $ events ; }
Return list of events this behavior is interested in .
45,914
public function beforeDelete ( Event $ event , EntityInterface $ entity , ArrayObject $ options ) { if ( ! $ this -> trash ( $ entity , $ options -> getArrayCopy ( ) ) ) { throw new RuntimeException ( ) ; } $ event -> stopPropagation ( ) ; $ table = $ event -> getSubject ( ) ; $ table -> dispatchEvent ( 'Model.afterDelete' , [ 'entity' => $ entity , 'options' => $ options , ] ) ; return true ; }
Callback to never really delete a record but instead mark it as trashed .
45,915
public function trash ( EntityInterface $ entity , array $ options = [ ] ) { $ primaryKey = ( array ) $ this -> _table -> getPrimaryKey ( ) ; foreach ( $ primaryKey as $ field ) { if ( ! $ entity -> has ( $ field ) ) { throw new RuntimeException ( ) ; } } foreach ( $ this -> _table -> associations ( ) as $ association ) { if ( $ this -> _isRecursable ( $ association , $ this -> _table ) ) { $ association -> cascadeDelete ( $ entity , [ '_primary' => false ] + $ options ) ; } } $ data = [ $ this -> getTrashField ( false ) => new Time ( ) ] ; $ entity -> set ( $ data , [ 'guard' => false ] ) ; if ( $ this -> _table -> save ( $ entity , $ options ) ) { return true ; } return false ; }
Trash given entity .
45,916
public function beforeFind ( Event $ event , Query $ query , ArrayObject $ options , $ primary ) { $ field = $ this -> getTrashField ( ) ; $ addCondition = true ; $ query -> traverseExpressions ( function ( $ expression ) use ( & $ addCondition , $ field ) { if ( ! $ addCondition ) { return ; } if ( $ expression instanceof IdentifierExpression && $ expression -> getIdentifier ( ) === $ field ) { $ addCondition = false ; return ; } if ( ( $ expression instanceof Comparison || $ expression instanceof BetweenExpression ) && $ expression -> getField ( ) === $ field ) { $ addCondition = false ; } } ) ; if ( $ addCondition ) { $ query -> andWhere ( $ query -> newExpr ( ) -> isNull ( $ field ) ) ; } }
Callback to always return rows that have not been trashed .
45,917
public function findOnlyTrashed ( Query $ query , array $ options ) { return $ query -> andWhere ( $ query -> newExpr ( ) -> isNotNull ( $ this -> getTrashField ( ) ) ) ; }
Custom finder to get only the trashed rows .
45,918
public function cascadingRestoreTrash ( EntityInterface $ entity = null , array $ options = [ ] ) { $ result = $ this -> restoreTrash ( $ entity , $ options ) ; foreach ( $ this -> _table -> associations ( ) as $ association ) { if ( $ this -> _isRecursable ( $ association , $ this -> _table ) ) { if ( $ entity === null ) { $ result += $ association -> getTarget ( ) -> cascadingRestoreTrash ( null , $ options ) ; } else { $ foreignKey = ( array ) $ association -> getForeignKey ( ) ; $ bindingKey = ( array ) $ association -> getBindingKey ( ) ; $ conditions = array_combine ( $ foreignKey , $ entity -> extract ( $ bindingKey ) ) ; foreach ( $ association -> find ( 'withTrashed' ) -> where ( $ conditions ) as $ related ) { if ( ! $ association -> getTarget ( ) -> cascadingRestoreTrash ( $ related , [ '_primary' => false ] + $ options ) ) { $ result = false ; } } } } } return $ result ; }
Restore an item from trashed status and all its related data
45,919
public function getTrashField ( $ aliased = true ) { $ field = $ this -> getConfig ( 'field' ) ; if ( empty ( $ field ) ) { $ columns = $ this -> _table -> getSchema ( ) -> columns ( ) ; foreach ( [ 'deleted' , 'trashed' ] as $ name ) { if ( in_array ( $ name , $ columns , true ) ) { $ field = $ name ; break ; } } if ( empty ( $ field ) ) { $ field = Configure :: read ( 'Muffin/Trash.field' ) ; } if ( empty ( $ field ) ) { throw new RuntimeException ( 'TrashBehavior: "field" config needs to be provided.' ) ; } $ this -> setConfig ( 'field' , $ field ) ; } if ( $ aliased ) { return $ this -> _table -> aliasField ( $ field ) ; } return $ field ; }
Returns the table s field used to mark a trashed row .
45,920
protected function _isRecursable ( Association $ association , Table $ table ) { if ( $ association -> getTarget ( ) -> hasBehavior ( 'Trash' ) && $ association -> isOwningSide ( $ table ) && $ association -> getDependent ( ) && $ association -> getCascadeCallbacks ( ) ) { return true ; } return false ; }
Find out if an associated Table has the Trash behaviour and it s records can be trashed
45,921
public function receiveFrame ( Frame $ frame ) { if ( 'ERROR' === $ frame -> command ) { throw new ServerErrorException ( $ frame ) ; } if ( $ this -> state -> isConnecting ( ) ) { if ( 'CONNECTED' !== $ frame -> command ) { throw new InvalidFrameException ( sprintf ( "Received frame with command '%s', expected 'CONNECTED'." , $ frame -> command ) ) ; } $ this -> state -> doneConnecting ( $ frame -> getHeader ( 'session' ) , $ frame -> getHeader ( 'server' ) ) ; return new ConnectionEstablishedCommand ( ) ; } if ( 'CONNECTED' === $ frame -> command ) { throw new InvalidFrameException ( sprintf ( "Received 'CONNECTED' frame outside a connecting window." ) ) ; } if ( $ this -> state -> isDisconnecting ( ) ) { if ( 'RECEIPT' === $ frame -> command && $ this -> state -> isDisconnectionReceipt ( $ frame -> getHeader ( 'receipt-id' ) ) ) { $ this -> state -> doneDisconnecting ( ) ; return new CloseCommand ( ) ; } } return new NullCommand ( ) ; }
Feed frame from the server
45,922
protected function setStarted ( $ time = null ) { $ this -> started = $ time ? : microtime ( true ) ; $ this -> setState ( RunInterface :: STATE_RUNNING ) ; }
Starts this thing
45,923
protected function setFinished ( $ time = null ) { $ this -> finished = $ time ? : microtime ( true ) ; $ this -> setState ( RunInterface :: STATE_NOT_RUNNING ) ; }
this thing has finished
45,924
public function poll ( ) { if ( $ this -> completed || ! $ this -> hasStarted ( ) ) { return false ; } if ( $ this -> process -> isRunning ( ) ) { if ( $ this -> updateOnPoll ) { $ this -> dispatch ( RunEvent :: UPDATED , new RunEvent ( $ this ) ) ; } return true ; } $ this -> completed = true ; $ this -> setFinished ( ) ; if ( $ this -> process -> isSuccessful ( ) ) { $ this -> successful = true ; $ this -> dispatch ( RunEvent :: SUCCESSFUL , new RunEvent ( $ this ) ) ; } else { $ this -> dispatch ( RunEvent :: FAILED , new RunEvent ( $ this ) ) ; } $ this -> dispatch ( RunEvent :: COMPLETED , new RunEvent ( $ this ) ) ; return false ; }
Poll the process to see if it is still running and trigger events
45,925
private function render ( $ row = 0 ) { if ( $ this -> output -> getVerbosity ( ) >= OutputInterface :: VERBOSITY_VERBOSE ) { $ rows = ( $ this -> showSummary ? array_merge ( $ this -> rows , [ $ this -> getSummary ( ) ] ) : $ this -> rows ) ; $ this -> output -> reWrite ( $ rows , ! $ this -> showSummary ) ; } else { $ this -> output -> writeln ( $ this -> rows [ $ row ] ) ; } }
Render a specific row
45,926
public function onRunStarted ( RunEvent $ event ) { $ index = array_search ( $ event -> getRun ( ) , $ this -> waiting , true ) ; if ( $ index !== false ) { unset ( $ this -> waiting [ $ index ] ) ; } $ this -> running [ ] = $ event -> getRun ( ) ; if ( $ this -> state == static :: STATE_NOT_STARTED ) { $ this -> setStarted ( ) ; $ this -> dispatch ( RunEvent :: STARTED , new RunEvent ( $ this ) ) ; } $ this -> dispatch ( RunEvent :: UPDATED , new RunEvent ( $ this ) ) ; }
When a run starts check our current state and start ourselves in required
45,927
public function onRunCompleted ( RunEvent $ event ) { $ index = array_search ( $ event -> getRun ( ) , $ this -> running , true ) ; if ( $ index !== false ) { unset ( $ this -> running [ $ index ] ) ; } $ this -> complete [ ] = $ event -> getRun ( ) ; $ this -> dispatch ( RunEvent :: UPDATED , new RunEvent ( $ this ) ) ; if ( count ( $ this -> waiting ) === 0 && count ( $ this -> running ) === 0 ) { $ this -> setFinished ( ) ; if ( $ this -> isSuccessful ( ) ) { $ this -> dispatch ( RunEvent :: SUCCESSFUL , new RunEvent ( $ this ) ) ; } else { $ this -> dispatch ( RunEvent :: FAILED , new RunEvent ( $ this ) ) ; } $ this -> dispatch ( RunEvent :: COMPLETED , new RunEvent ( $ this ) ) ; } }
When a run is completed check if everything has finished
45,928
public function onRunFailed ( RunEvent $ event ) { $ this -> exceptions = array_merge ( $ this -> exceptions , $ event -> getRun ( ) -> getExceptions ( ) ) ; }
Handle any errors returned from the child run
45,929
public function start ( ) { foreach ( $ this -> items as $ run ) { if ( ! $ run -> hasStarted ( ) ) { $ run -> start ( ) ; } } return $ this ; }
Start all non running children
45,930
public function isSuccessful ( ) { if ( $ this -> getState ( ) === static :: STATE_NOT_RUNNING ) { foreach ( $ this -> items as $ run ) { if ( ! $ run -> isSuccessful ( ) ) { return false ; } } return true ; } return false ; }
Was this run successful
45,931
public function run ( $ interval = self :: CHECK_INTERVAL ) { $ this -> start ( ) ; $ sleep = ( int ) ( $ interval * 1000000 ) ; while ( $ this -> poll ( ) ) { usleep ( $ sleep ) ; } return $ this -> isSuccessful ( ) ; }
Run this pool of runs and block until they are complete .
45,932
public function monitor ( $ item ) { if ( $ item instanceof PoolInterface ) { $ item -> addListener ( PoolRunEvent :: POOL_RUN_ADDED , [ $ this , 'onPoolRunAdded' ] ) ; $ item -> addListener ( PoolRunEvent :: UPDATED , [ $ this , 'onPoolUpdated' ] ) ; array_map ( [ $ this , 'monitor' ] , $ item -> getAll ( ) ) ; } if ( $ item instanceof RunInterface ) { $ item -> addListener ( RunEvent :: STARTED , [ $ this , 'onRunStarted' ] ) ; $ item -> addListener ( RunEvent :: SUCCESSFUL , [ $ this , 'onRunSuccessful' ] ) ; $ item -> addListener ( RunEvent :: FAILED , [ $ this , 'onRunFailed' ] ) ; $ item -> addListener ( RunEvent :: COMPLETED , [ $ this , 'onRunCompleted' ] ) ; } }
Monitor a Pool or Run and log all activity
45,933
protected function updateRowKeyLengths ( array $ data = [ ] ) { $ lengths = array_map ( 'mb_strlen' , $ data ) ; $ keys = array_merge ( array_keys ( $ lengths ) , array_keys ( $ this -> maxLengths ) ) ; foreach ( $ keys as $ key ) { if ( ! isset ( $ this -> maxLengths [ $ key ] ) || ( isset ( $ lengths [ $ key ] ) && $ lengths [ $ key ] > $ this -> maxLengths [ $ key ] ) ) { $ this -> maxLengths [ $ key ] = $ lengths [ $ key ] ; } } }
Parses the rows to determine the key lengths to make a pretty table
45,934
protected function formatTags ( array $ data = [ ] , $ colour = null ) { $ info = [ ] ; foreach ( $ data as $ key => $ value ) { $ length = isset ( $ this -> maxLengths [ $ key ] ) ? '-' . $ this -> maxLengths [ $ key ] : '' ; if ( ! is_null ( $ colour ) ) { $ valueFormat = sprintf ( "<options=bold;fg=%s>%{$length}s</>" , $ colour , $ value ) ; } else { $ valueFormat = sprintf ( "%{$length}s" , $ value ) ; } if ( is_int ( $ key ) ) { $ info [ ] = $ valueFormat ; } else { $ info [ ] = sprintf ( "<info>%s</info>: %s" , $ key , $ valueFormat ) ; } } return implode ( ' ' , $ info ) ; }
Format an array of input tags
45,935
public function add ( $ item , array $ tags = [ ] ) { if ( $ item instanceof RunInterface && ! ( $ this -> isRunning ( ) || $ this -> runInstantly ) && $ item -> isRunning ( ) ) { throw new NotRunningException ( "add: unable to add a running item when the pool has not started" ) ; } if ( $ item instanceof PoolInterface ) { $ item -> addListener ( PoolRunEvent :: POOL_RUN_ADDED , function ( PoolRunEvent $ event ) { $ this -> add ( $ event -> getRun ( ) ) ; } ) ; foreach ( $ item -> getAll ( ) as $ child ) { $ this -> add ( $ child ) ; } return $ this ; } parent :: add ( $ item , $ tags ) ; if ( $ item instanceof RunInterface && ! $ item -> hasStarted ( ) ) { $ this -> waitingQueue -> insert ( $ item , $ item -> getPriority ( ) ) ; if ( $ this -> runInstantly ) { $ this -> startNext ( ) ; } } if ( $ item instanceof PrioritisedInterface && $ item instanceof DispatcherInterface ) { $ item -> addListener ( PriorityChangedEvent :: CHANGED , [ $ this , 'onPriorityChanged' ] ) ; } return $ this ; }
Add a new process to the pool
45,936
public function run ( $ checkInterval = self :: CHECK_INTERVAL ) { $ this -> startNext ( ) ; $ interval = ( int ) ( $ checkInterval * 1000000 ) ; while ( $ this -> poll ( ) ) { usleep ( $ interval ) ; } return $ this -> isSuccessful ( ) ; }
Blocking call to run processes ;
45,937
private function startNext ( ) { if ( ! $ this -> initialised ) { return ; } if ( $ this -> maxSimultaneous !== static :: NO_MAX && $ this -> waitingQueue -> valid ( ) && count ( $ this -> running ) < $ this -> maxSimultaneous ) { for ( $ i = count ( $ this -> running ) ; $ i < $ this -> maxSimultaneous && $ this -> waitingQueue -> valid ( ) ; $ i ++ ) { $ this -> startRun ( $ this -> waitingQueue -> extract ( ) ) ; } } elseif ( $ this -> maxSimultaneous === static :: NO_MAX ) { while ( $ this -> waitingQueue -> valid ( ) ) { $ this -> startRun ( $ this -> waitingQueue -> extract ( ) ) ; } } }
Check when a run has finished if there are processes waiting start them
45,938
private function append_str ( $ str ) { $ this -> check_closed ( ) ; $ this -> string_buffer .= $ str ; $ len = strlen ( $ str ) ; $ this -> current_index += $ len ; return $ len ; }
Appends bytes to this buffer .
45,939
static function attributes_match ( $ schema_one , $ schema_two , $ attribute_names ) { foreach ( $ attribute_names as $ attribute_name ) if ( $ schema_one -> attribute ( $ attribute_name ) != $ schema_two -> attribute ( $ attribute_name ) ) return false ; return true ; }
Checks equivalence of the given attributes of the two given schemas .
45,940
static function shift_right ( $ g , $ shift ) { if ( 0 == $ shift ) return $ g ; if ( 0 <= gmp_sign ( $ g ) ) $ m = gmp_div ( $ g , gmp_pow ( self :: gmp_2 ( ) , $ shift ) ) ; else { $ g = gmp_and ( $ g , self :: gmp_0xfs ( ) ) ; $ m = gmp_div ( $ g , gmp_pow ( self :: gmp_2 ( ) , $ shift ) ) ; $ m = gmp_and ( $ m , self :: gmp_0xfs ( ) ) ; for ( $ i = 63 ; $ i >= ( 63 - $ shift ) ; $ i -- ) gmp_setbit ( $ m , $ i ) ; $ m = gmp_neg ( gmp_add ( gmp_and ( gmp_com ( $ m ) , self :: gmp_0xfs ( ) ) , self :: gmp_1 ( ) ) ) ; } return $ m ; }
Arithmetic right shift
45,941
public static function buildItemTypeDiscount ( $ product_reference , $ name , $ unit_price , $ tax_rate , $ discount , $ discount_description , $ total_amount ) { return self :: initInternalItem ( $ product_reference , $ name , 1 , $ unit_price , $ tax_rate , $ discount , $ total_amount , TypeItems :: DISCOUNT , $ discount_description ) ; }
Hydrate an item with type Discount
45,942
private static function initInternalItem ( $ product_reference , $ name , $ quantity , $ unit_price , $ tax_rate , $ discount , $ total_amount , $ type , $ discount_description = null ) { $ cartItem = new Item ( ) ; $ cartItem -> setProductReference ( $ product_reference ) -> setName ( $ name ) -> setType ( $ type ) -> setQuantity ( $ quantity ) -> setUnitPrice ( $ unit_price ) -> setTaxRate ( $ tax_rate ) -> setDiscount ( $ discount ) -> setTotalAmount ( $ total_amount ) ; if ( $ type == TypeItems :: DISCOUNT ) { $ cartItem -> setDiscountDescription ( $ discount_description ) ; } return $ cartItem ; }
Hydrate generic item
45,943
public static function buildItemTypeFees ( $ product_reference , $ name , $ unit_price , $ tax_rate , $ discount , $ total_amount ) { return self :: initInternalItem ( $ product_reference , $ name , 1 , $ unit_price , $ tax_rate , $ discount , $ total_amount , TypeItems :: FEE ) ; }
Build an item of type Fees with quantity to 1
45,944
public function __constructItem ( $ european_article_numbering , $ product_reference , $ type , $ name , $ quantity , $ unit_price , $ tax_rate , $ discount , $ total_amount , $ discount_description , $ product_description , $ delivery_method , $ delivery_company , $ delivery_delay , $ delivery_number , $ product_category , $ shop_id ) { $ this -> _european_article_numbering = $ european_article_numbering ; $ this -> _product_reference = $ product_reference ; $ this -> _type = $ type ; $ this -> _name = $ name ; $ this -> _quantity = $ quantity ; $ this -> _unit_price = $ unit_price ; $ this -> _tax_rate = $ tax_rate ; $ this -> _discount = $ discount ; $ this -> _total_amount = $ total_amount ; $ this -> _discount_description = $ discount_description ; $ this -> _product_description = $ product_description ; $ this -> _delivery_method = $ delivery_method ; $ this -> _delivery_company = $ delivery_company ; $ this -> _delivery_delay = $ delivery_delay ; $ this -> _delivery_number = $ delivery_number ; $ this -> _product_category = $ product_category ; $ this -> _shop_id = $ shop_id ; }
Item constructor .
45,945
public static function getItem ( $ product_code ) { $ jsonArr = json_decode ( self :: $ _JSON , true ) ; foreach ( $ jsonArr as $ item ) { if ( $ item [ 'productCode' ] == $ product_code ) { return new PaymentProduct ( $ item [ 'productCode' ] , $ item [ 'brandName' ] , $ item [ 'category' ] , $ item [ 'can3ds' ] , $ item [ 'canRefund' ] , $ item [ 'canRecurring' ] , $ item [ 'comment' ] , $ item [ 'basketRequired' ] ) ; break ; } } }
Get a Payment Product item with a code
45,946
static protected function getComputedSignature ( $ secretPassphrase , $ hashAlgorithm ) { switch ( $ hashAlgorithm ) { case HashAlgorithm :: SHA256 : $ computedSignature = hash ( HashAlgorithm :: SHA256 , static :: getStringToCompute ( $ secretPassphrase ) ) ; break ; case HashAlgorithm :: SHA512 : $ computedSignature = hash ( HashAlgorithm :: SHA512 , static :: getStringToCompute ( $ secretPassphrase ) ) ; break ; default : $ computedSignature = sha1 ( static :: getStringToCompute ( $ secretPassphrase ) ) ; break ; } return $ computedSignature ; }
Compute signature according to hash and passphrase
45,947
static public function isSameHashAlgorithm ( $ secretPassphrase , $ hashAlgorithm ) { if ( strlen ( static :: getComputedSignature ( $ secretPassphrase , $ hashAlgorithm ) ) == strlen ( static :: getSignature ( ) ) ) { return true ; } return false ; }
Detects is same hash algorithm is used for signature
45,948
public function unserialize ( $ data ) { $ vars = unserialize ( $ data ) ; foreach ( $ vars as $ var => $ value ) { $ this -> { $ var } = $ value ; } }
Takes the string representation of this object so it can be reconstructed .
45,949
protected function basicSerialize ( ) { return [ 'type' => $ this -> getEventType ( ) , 'transaction' => $ this -> transactionId , 'primary_key' => $ this -> id , 'source' => $ this -> source , 'parent_source' => $ this -> parentSource , '@timestamp' => $ this -> timestamp , 'meta' => $ this -> meta ] ; }
Returns an array with the basic variables that should be json serialized .
45,950
protected function toErrorLog ( EntityInterface $ entity , $ depth = 4 ) { return sprintf ( '[%s] Persisting audit log failed. Data:' . PHP_EOL . '%s' , __CLASS__ , Debugger :: exportVar ( $ entity , $ depth ) ) ; }
Converts an entity to an error log message .
45,951
public function connection ( $ connection = null ) { if ( $ connection === null ) { if ( $ this -> connection === null ) { $ this -> connection = ConnectionManager :: get ( $ this -> options [ 'connection' ] ) ; } return $ this -> connection ; } return $ this -> connection = $ connection ; }
Sets the client connection to elastic search when passed . If no arguments are provided it returns the current connection .
45,952
protected function mapType ( $ schema , $ column ) { $ baseType = $ schema -> baseColumnType ( $ column ) ; switch ( $ baseType ) { case 'uuid' : return [ 'type' => 'text' , 'index' => false , 'null_value' => '_null_' ] ; case 'integer' : return [ 'type' => 'integer' , 'null_value' => pow ( - 2 , 31 ) ] ; case 'date' : return [ 'type' => 'date' , 'format' => 'dateOptionalTime||basic_date||yyy-MM-dd' , 'null_value' => '0001-01-01' ] ; case 'datetime' : case 'timestamp' : return [ 'type' => 'date' , 'format' => 'basic_t_time_no_millis||dateOptionalTime||basic_date_time||ordinal_date_time_no_millis||yyyy-MM-dd HH:mm:ss||basic_date' , 'null_value' => '0001-01-01 00:00:00' ] ; case 'float' : case 'decimal' : return [ 'type' => 'float' , 'null_value' => pow ( - 2 , 31 ) ] ; case 'float' : case 'decimal' : return [ 'type' => 'float' , 'null_value' => pow ( - 2 , 31 ) ] ; case 'boolean' : return [ 'type' => 'boolean' ] ; default : return [ 'type' => 'text' , 'fields' => [ $ column => [ 'type' => 'text' ] , 'raw' => [ 'type' => 'text' , 'index' => false ] ] ] ; } }
Returns the correct mapping properties for a table column .
45,953
public function getId ( ) { if ( is_array ( $ this -> id ) && count ( $ this -> id ) === 1 ) { return current ( $ this -> id ) ; } return $ this -> id ; }
Returns the id of the entity that was created or altered .
45,954
protected function _configIndex ( $ repository , $ request ) { $ client = $ repository -> connection ( ) ; $ indexTemplate = $ repository -> getName ( ) ; $ client -> setConfig ( [ 'index' => sprintf ( $ indexTemplate , '*' ) ] ) ; if ( $ request -> query ( 'at' ) ) { $ client -> setConfig ( [ 'index' => sprintf ( $ indexTemplate , ( new DateTime ( $ request -> query ( 'at' ) ) ) -> format ( '-Y.m.d' ) ) ] ) ; } }
Configures the index to use in elastic search by completing the placeholders with the current date if needed .
45,955
public function persist ( array $ events ) { $ factory = new EventFactory ( ) ; $ events = array_map ( function ( $ event ) use ( $ factory ) { return is_array ( $ event ) ? $ factory -> create ( $ event ) : $ event ; } , $ events ) ; $ this -> persister ( ) -> logEvents ( $ events ) ; }
Persists a list of event logs represented in arrays or that actually are instances of EventInterface .
45,956
public function persister ( PersisterInterface $ persister = null ) { if ( $ persister === null && $ this -> persister === null ) { $ persister = new ElasticSearchPersister ( ) ; } if ( $ persister === null ) { return $ this -> persister ; } return $ this -> persister = $ persister ; }
Sets the persister object to use for logging al audit events . If called if no arguments it will return the ElasitSearchPersister .
45,957
public function create ( array $ data ) { $ map = [ 'create' => AuditCreateEvent :: class , 'update' => AuditUpdateEvent :: class , 'delete' => AuditDeleteEvent :: class , ] ; if ( $ data [ 'type' ] !== 'delete' ) { $ event = new $ map [ $ data [ 'type' ] ] ( $ data [ 'transaction' ] , $ data [ 'primary_key' ] , $ data [ 'source' ] , $ data [ 'changed' ] , $ data [ 'original' ] ) ; } else { $ event = new $ map [ $ data [ 'type' ] ] ( $ data [ 'transaction' ] , $ data [ 'primary_key' ] , $ data [ 'source' ] ) ; } if ( isset ( $ data [ 'parent_source' ] ) ) { $ event -> setParentSourceName ( $ data [ 'parent_source' ] ) ; } $ reflection = new ReflectionObject ( $ event ) ; $ timestamp = $ reflection -> getProperty ( 'timestamp' ) ; $ timestamp -> setAccessible ( true ) ; $ timestamp -> setValue ( $ event , $ data [ '@timestamp' ] ) ; $ event -> setMetaInfo ( $ data [ 'meta' ] ) ; return $ event ; }
Converts an array of data as comming from elastic search and converts it into an AuditStash \ EventInterface object .
45,958
protected function extractBasicFields ( EventInterface $ event , $ serialize = true ) { $ fields = [ 'transaction' => $ event -> getTransactionId ( ) , 'type' => $ event -> getEventType ( ) , 'source' => $ event -> getSourceName ( ) , 'parent_source' => null , 'original' => null , 'changed' => null , 'created' => new \ DateTime ( $ event -> getTimestamp ( ) ) ] ; if ( method_exists ( $ event , 'getParentSourceName' ) ) { $ fields [ 'parent_source' ] = $ event -> getParentSourceName ( ) ; } if ( $ event instanceof BaseEvent ) { $ fields [ 'original' ] = $ serialize ? $ this -> serialize ( $ event -> getOriginal ( ) ) : $ event -> getOriginal ( ) ; $ fields [ 'changed' ] = $ serialize ? $ this -> serialize ( $ event -> getChanged ( ) ) : $ event -> getChanged ( ) ; } return $ fields ; }
Extracts the basic fields from the audit event object .
45,959
protected function extractPrimaryKeyFields ( EventInterface $ event , $ strategy = 'automatic' ) { $ primaryKeyFields = [ ] ; switch ( $ strategy ) { case 'automatic' : $ id = ( array ) $ event -> getId ( ) ; if ( count ( $ id ) === 1 ) { $ id = array_pop ( $ id ) ; } else { $ id = $ this -> serialize ( $ id ) ; } $ primaryKeyFields [ 'primary_key' ] = $ id ; break ; case 'properties' : $ id = ( array ) $ event -> getId ( ) ; if ( count ( $ id ) === 1 ) { $ primaryKeyFields [ 'primary_key' ] = array_pop ( $ id ) ; } else { foreach ( $ id as $ key => $ value ) { $ primaryKeyFields [ 'primary_key_' . $ key ] = $ value ; } } break ; case 'raw' : $ primaryKeyFields [ 'primary_key' ] = $ event -> getId ( ) ; break ; case 'serialized' : $ id = $ event -> getId ( ) ; $ primaryKeyFields [ 'primary_key' ] = $ this -> serialize ( $ id ) ; break ; } return $ primaryKeyFields ; }
Extracts the primary key fields from the audit event object .
45,960
protected function extractMetaFields ( EventInterface $ event , $ fields , $ unsetExtracted = true , $ serialize = true ) { $ extracted = [ 'meta' => $ event -> getMetaInfo ( ) ] ; if ( ! is_array ( $ extracted [ 'meta' ] ) ) { return $ extracted ; } if ( ! $ fields || empty ( $ extracted [ 'meta' ] ) ) { if ( $ serialize ) { $ extracted [ 'meta' ] = $ this -> serialize ( $ extracted [ 'meta' ] ) ; } return $ extracted ; } if ( $ fields === true ) { $ extracted += $ extracted [ 'meta' ] ; if ( ! $ unsetExtracted ) { if ( $ serialize ) { $ extracted [ 'meta' ] = $ this -> serialize ( $ extracted [ 'meta' ] ) ; } return $ extracted ; } $ extracted [ 'meta' ] = $ serialize ? $ this -> serialize ( [ ] ) : [ ] ; return $ extracted ; } if ( is_array ( $ fields ) ) { foreach ( $ fields as $ name => $ alias ) { if ( ! is_string ( $ name ) ) { $ name = $ alias ; } $ extracted [ $ alias ] = Hash :: get ( $ extracted [ 'meta' ] , $ name ) ; if ( $ unsetExtracted ) { $ extracted [ 'meta' ] = Hash :: remove ( $ extracted [ 'meta' ] , $ name ) ; } } } if ( $ serialize ) { $ extracted [ 'meta' ] = $ this -> serialize ( $ extracted [ 'meta' ] ) ; } return $ extracted ; }
Extracts the metadata fields from the audit event object .
45,961
public function habtmFormatter ( $ value , $ key ) { if ( empty ( $ key ) || ! ctype_upper ( $ key [ 0 ] ) ) { return $ value ; } if ( isset ( $ value [ $ key ] ) ) { $ value = $ value [ $ key ] ; } if ( is_array ( $ value ) ) { return $ value ; } $ list = explode ( ',' , $ value ) ; if ( empty ( $ list ) ) { return [ ] ; } return array_map ( 'intval' , $ list ) ; }
Converts the string data from HABTM reference into an array of integers .
45,962
public function changesExtractor ( $ audits ) { $ suffix = isset ( $ audits [ 0 ] [ '_matchingData' ] [ 'AuditDeltas' ] [ 0 ] ) ? '.{*}' : '' ; $ changes = collection ( $ audits ) -> extract ( '_matchingData.AuditDeltas' . $ suffix ) -> indexBy ( 'property_name' ) -> toArray ( ) ; $ audit = $ audits [ 0 ] ; unset ( $ audit [ '_matchingData' ] ) ; $ audit [ 'original' ] = collection ( $ changes ) -> map ( function ( $ c ) { return $ c [ 'old_value' ] ; } ) -> map ( [ $ this , 'habtmFormatter' ] ) -> map ( [ $ this , 'allBallsRemover' ] ) -> toArray ( ) ; $ audit [ 'changed' ] = collection ( $ changes ) -> map ( function ( $ c ) { return $ c [ 'new_value' ] ; } ) -> map ( [ $ this , 'habtmFormatter' ] ) -> map ( [ $ this , 'allBallsRemover' ] ) -> toArray ( ) ; return $ audit ; }
Converts a group of related audit logs into a single one with the original and changed keys set .
45,963
public function eventFormatter ( $ audit , $ index , $ meta = [ ] ) { $ data = [ '@timestamp' => $ audit [ 'created' ] , 'transaction' => $ audit [ 'id' ] , 'type' => $ audit [ 'event' ] === 'EDIT' ? 'update' : strtolower ( $ audit [ 'event' ] ) , 'primary_key' => $ audit [ 'entity_id' ] , 'original' => $ audit [ 'original' ] , 'changed' => $ audit [ 'changed' ] , 'meta' => $ meta + [ 'ip' => $ audit [ 'source_ip' ] , 'url' => $ audit [ 'source_url' ] , 'user' => $ audit [ 'source_id' ] , ] ] ; $ index = sprintf ( $ index , \ DateTime :: createFromFormat ( 'Y-m-d H:i:s' , $ audit [ 'created' ] ) -> format ( '-Y.m.d' ) ) ; $ type = isset ( $ map [ $ audit [ 'model' ] ] ) ? $ map [ $ audit [ 'model' ] ] : Inflector :: tableize ( $ audit [ 'model' ] ) ; return new Document ( $ audit [ 'id' ] , $ data , $ type , $ index ) ; }
Converts the single audit log event array into a Elastica \ Document so it can be stored .
45,964
public function persistBulk ( $ documents ) { if ( empty ( $ documents ) ) { $ this -> log ( 'No more documents to index' , 'info' ) ; return ; } $ this -> log ( sprintf ( 'Indexing %d documents' , count ( $ documents ) ) , 'info' ) ; ConnectionManager :: get ( 'auditlog_elastic' ) -> addDocuments ( $ documents ) ; }
Persists the array of passed documents into elastic search .
45,965
public function persister ( PersisterInterface $ persister = null ) { if ( $ persister === null && $ this -> persister === null ) { $ class = Configure :: read ( 'AuditStash.persister' ) ? : ElasticSearchPersister :: class ; $ index = $ this -> getConfig ( 'index' ) ? : $ this -> _table -> getTable ( ) ; $ type = $ this -> getConfig ( 'type' ) ? : Inflector :: singularize ( $ index ) ; $ persister = new $ class ( compact ( 'index' , 'type' ) ) ; } if ( $ persister === null ) { return $ this -> persister ; } return $ this -> persister = $ persister ; }
Sets the persister object to use for logging al audit events . If called if no arguments it will return the currently configured persister .
45,966
protected function getAssociationProperties ( $ associated ) { $ associations = $ this -> _table -> associations ( ) ; $ result = [ ] ; foreach ( $ associated as $ name ) { $ result [ ] = $ associations -> get ( $ name ) -> getProperty ( ) ; } return $ result ; }
Helper method used to get the property names of associations for a table .
45,967
public function logEvents ( array $ auditLogs ) { foreach ( $ auditLogs as $ log ) { $ eventType = $ log -> getEventType ( ) ; $ primaryKey = $ log -> getId ( ) ; if ( is_array ( $ primaryKey ) ) { if ( count ( $ primaryKey ) == 1 ) { $ primaryKey = array_pop ( $ primaryKey ) ; } else { $ primaryKey = json_encode ( $ primaryKey ) ; } } $ date = new DateTime ( $ log -> getTimestamp ( ) ) ; $ meta = ( array ) $ log -> getMetaInfo ( ) ; $ data = [ 'created' => $ date , 'transaction' => $ log -> getTransactionId ( ) , 'type' => $ eventType , 'source_key' => $ primaryKey , 'source' => $ log -> getSourceName ( ) , 'parent_source' => $ log -> getParentSourceName ( ) , 'original' => $ eventType === 'delete' ? null : json_encode ( $ log -> getOriginal ( ) ) , 'changed' => $ eventType === 'delete' ? null : json_encode ( $ log -> getChanged ( ) ) , 'meta' => json_encode ( $ meta ) ] ; $ Audit = $ this -> loadModel ( 'Audits' ) ; if ( ! empty ( $ meta [ 'user' ] ) ) { $ data [ 'user_id' ] = $ meta [ 'user' ] ; } $ record = $ Audit -> newEntity ( $ data ) ; $ Audit -> save ( $ record ) ; } }
Persists all of the audit log event objects that are provided
45,968
public function findTypes ( $ query ) { $ facet = new TermsAggregation ( 'type' ) ; $ facet -> setField ( '_type' ) ; $ facet -> setSize ( 200 ) ; $ query -> aggregate ( $ facet ) ; return $ query -> limit ( 1 ) ; }
Returns a query setup for getting the type aggregation .
45,969
protected function _findRecord ( $ id , Subject $ subject ) { $ repository = $ this -> _table ( ) ; $ this -> _configIndex ( $ repository , $ this -> _request ( ) ) ; if ( $ this -> _request ( ) -> query ( 'type' ) ) { $ repository -> name ( $ this -> _request ( ) -> query ( 'type' ) ) ; } $ query = $ repository -> find ( $ this -> findMethod ( ) ) ; $ query -> where ( [ '_id' => $ id ] ) ; $ subject -> set ( [ 'repository' => $ repository , 'query' => $ query ] ) ; $ this -> _trigger ( 'beforeFind' , $ subject ) ; $ entity = $ query -> first ( ) ; if ( ! $ entity ) { return $ this -> _notFound ( $ id , $ subject ) ; } $ subject -> set ( [ 'entity' => $ entity , 'success' => true ] ) ; $ this -> _trigger ( 'afterFind' , $ subject ) ; return $ entity ; }
Find a audit log by id .
45,970
protected function _handle ( ) { $ request = $ this -> _request ( ) ; $ this -> _configIndex ( $ this -> _table ( ) , $ request ) ; $ query = $ this -> _table ( ) -> find ( ) ; $ repository = $ query -> repository ( ) ; $ query -> searchOptions ( [ 'ignore_unavailable' => true ] ) ; if ( $ request -> query ( 'type' ) ) { $ repository -> name ( $ request -> query ( 'type' ) ) ; } if ( $ request -> query ( 'primary_key' ) ) { $ query -> where ( [ 'primary_key' => $ request -> query ( 'primary_key' ) ] ) ; } if ( $ request -> query ( 'transaction' ) ) { $ query -> where ( [ 'transaction' => $ request -> query ( 'transaction' ) ] ) ; } if ( $ request -> query ( 'user' ) ) { $ query -> where ( [ 'meta.user' => $ request -> query ( 'user' ) ] ) ; } if ( $ request -> query ( 'changed_fields' ) ) { $ query -> where ( function ( $ builder ) use ( $ request ) { $ fields = explode ( ',' , $ request -> query ( 'changed_fields' ) ) ; $ fields = array_map ( function ( $ f ) { return 'changed.' . $ f ; } , array_map ( 'trim' , $ fields ) ) ; $ fields = array_map ( [ $ builder , 'exists' ] , $ fields ) ; return $ builder -> and_ ( $ fields ) ; } ) ; } if ( $ request -> query ( 'query' ) ) { $ query -> where ( function ( $ builder ) use ( $ request ) { return $ builder -> query ( new \ Elastica \ Query \ QueryString ( $ request -> query ( 'query' ) ) ) ; } ) ; } try { $ this -> addTimeConstraints ( $ request , $ query ) ; } catch ( \ Exception $ e ) { } $ subject = $ this -> _subject ( [ 'success' => true , 'query' => $ query ] ) ; $ this -> _trigger ( 'beforePaginate' , $ subject ) ; $ items = $ this -> _controller ( ) -> paginate ( $ subject -> query ) ; $ subject -> set ( [ 'entities' => $ items ] ) ; $ this -> _trigger ( 'afterPaginate' , $ subject ) ; $ this -> _trigger ( 'beforeRender' , $ subject ) ; }
Renders the index action by searching all documents matching the URL conditions .
45,971
protected function addTimeConstraints ( $ request , $ query ) { if ( $ request -> query ( 'from' ) ) { $ from = new \ DateTime ( $ request -> query ( 'from' ) ) ; $ until = new \ DateTime ( ) ; } if ( $ request -> query ( 'until' ) ) { $ until = new \ DateTime ( $ request -> query ( 'until' ) ) ; } if ( ! empty ( $ from ) ) { $ query -> where ( function ( $ builder ) use ( $ from , $ until ) { return $ builder -> between ( '@timestamp' , $ from -> format ( 'Y-m-d H:i:s' ) , $ until -> format ( 'Y-m-d H:i:s' ) ) ; } ) ; return ; } if ( ! empty ( $ until ) ) { $ query -> where ( [ '@timestamp <=' => $ until -> format ( 'Y-m-d H:i:s' ) ] ) ; } }
Alters the query object to add the time constraints as they can be found in the request object .
45,972
public function getTable ( ) { if ( $ this -> _table === null ) { $ this -> setTable ( $ this -> getConfig ( 'table' ) ) ; } return $ this -> _table ; }
Returns the table to use for persisting logs .
45,973
public function setTable ( $ table ) { if ( is_string ( $ table ) ) { $ table = $ this -> getTableLocator ( ) -> get ( $ table ) ; } if ( ! ( $ table instanceof Table ) ) { throw new \ InvalidArgumentException ( 'The `$table` argument must be either a table alias, or an instance of `\Cake\ORM\Table`.' ) ; } $ this -> _table = $ table ; return $ this ; }
Sets the table to use for persisting logs .
45,974
public function logEvents ( array $ auditLogs ) { $ PersisterTable = $ this -> getTable ( ) ; $ serializeFields = $ this -> getConfig ( 'serializeFields' ) ; $ primaryKeyExtractionStrategy = $ this -> getConfig ( 'primaryKeyExtractionStrategy' ) ; $ extractMetaFields = $ this -> getConfig ( 'extractMetaFields' ) ; $ unsetExtractedMetaFields = $ this -> getConfig ( 'unsetExtractedMetaFields' ) ; $ logErrors = $ this -> getConfig ( 'logErrors' ) ; foreach ( $ auditLogs as $ log ) { $ fields = $ this -> extractBasicFields ( $ log , $ serializeFields ) ; $ fields += $ this -> extractPrimaryKeyFields ( $ log , $ primaryKeyExtractionStrategy ) ; $ fields += $ this -> extractMetaFields ( $ log , $ extractMetaFields , $ unsetExtractedMetaFields , $ serializeFields ) ; $ persisterEntity = $ PersisterTable -> newEntity ( $ fields ) ; if ( ! $ PersisterTable -> save ( $ persisterEntity ) && $ logErrors ) { $ this -> log ( $ this -> toErrorLog ( $ persisterEntity ) ) ; } } }
Persists each of the passed EventInterface objects .
45,975
protected function transformToDocuments ( $ auditLogs ) { $ index = $ this -> getIndex ( ) ; $ type = $ this -> getType ( ) ; $ documents = [ ] ; foreach ( $ auditLogs as $ log ) { $ primary = $ log -> getId ( ) ; $ primary = is_array ( $ primary ) ? array_values ( $ primary ) : $ primary ; $ eventType = $ log -> getEventType ( ) ; $ data = [ '@timestamp' => $ log -> getTimestamp ( ) , 'transaction' => $ log -> getTransactionId ( ) , 'type' => $ eventType , 'primary_key' => $ primary , 'source' => $ log -> getSourceName ( ) , 'parent_source' => $ log -> getParentSourceName ( ) , 'original' => $ eventType === 'delete' ? null : $ log -> getOriginal ( ) , 'changed' => $ eventType === 'delete' ? null : $ log -> getChanged ( ) , 'meta' => $ log -> getMetaInfo ( ) ] ; $ id = $ this -> useTransactionId ? $ log -> getTransactionId ( ) : '' ; $ documents [ ] = new Document ( $ id , $ data , $ type , $ index ) ; } return $ documents ; }
Transforms the EventInterface objects to Elastica Documents .
45,976
public function getConnection ( ) { if ( $ this -> connection === null ) { $ this -> connection = ConnectionManager :: get ( 'auditlog_elastic' ) ; } return $ this -> connection ; }
Gets the client connection to elastic search .
45,977
function clientside_validation ( $ properties ) { $ defaults = array ( 'clientside_disabled' => false , 'close_tips' => true , 'disable_upload_validation' => false , 'on_ready' => false , 'scroll_to_error' => true , 'tips_position' => 'left' , 'validate_on_the_fly' => false , 'validate_all' => false , ) ; if ( ! isset ( $ this -> form_properties [ 'clientside_validation' ] ) ) $ this -> form_properties [ 'clientside_validation' ] = $ defaults ; if ( $ properties == false ) $ this -> form_properties [ 'clientside_validation' ] [ 'clientside_disabled' ] = true ; elseif ( is_array ( $ properties ) ) $ this -> form_properties [ 'clientside_validation' ] = array_merge ( $ this -> form_properties [ 'clientside_validation' ] , $ properties ) ; }
Sets properties for the client - side validation .
45,978
private function _extract_values ( $ array ) { $ result = array ( ) ; foreach ( $ array as $ index => $ value ) if ( is_array ( $ value ) ) $ result = array_merge ( $ result , $ this -> _extract_values ( $ value ) ) ; else $ result [ ] = $ index ; return $ result ; }
Helper method for validating select boxes . It extract all the values from an infinitely nested array and puts them in an uni - dimensional array so that we can check if the submitted value is allowed .
45,979
private function _load_mime_types ( ) { if ( ! isset ( $ this -> form_properties [ 'mimes' ] ) ) { $ rows = file ( $ this -> form_properties [ 'assets_server_path' ] . 'mimes.json' ) ; $ this -> form_properties [ 'mimes' ] = array ( ) ; foreach ( $ rows as $ row ) { if ( strpos ( $ row , ':' ) !== false ) { $ items = explode ( ':' , $ row ) ; $ index = trim ( str_replace ( '"' , '' , $ items [ 0 ] ) ) ; if ( strpos ( $ items [ 1 ] , '[' ) !== false ) $ value = array_diff ( array_map ( 'trim' , explode ( ',' , str_replace ( array ( '[' , ']' , '"' , '\/' ) , array ( '' , '' , '' , '/' ) , $ items [ 1 ] ) ) ) , array ( '' ) ) ; else $ value = trim ( str_replace ( array ( '"' , ',' , '\/' ) , array ( '' , '' , '/' ) , $ items [ 1 ] ) ) ; $ this -> form_properties [ 'mimes' ] [ $ index ] = $ value ; } } } }
Load MIME types from mimes . json
45,980
private function _resize ( $ control , $ prefix , $ width , $ height , $ preserve_aspect_ratio = true , $ method = ZEBRA_IMAGE_BOXED , $ background_color = 'FFFFFF' , $ enlarge_smaller_images = true , $ jpeg_quality = 85 ) { if ( isset ( $ this -> file_upload [ $ control ] ) && isset ( $ this -> file_upload [ $ control ] [ 'imageinfo' ] ) ) { if ( ! isset ( $ this -> Zebra_Image ) ) $ this -> Zebra_Image = new Zebra_Image ( ) ; $ this -> Zebra_Image -> chmod_value = $ this -> file_upload_permissions ; $ this -> Zebra_Image -> source_path = $ this -> file_upload [ $ control ] [ 'path' ] . $ this -> file_upload [ $ control ] [ 'file_name' ] ; $ this -> Zebra_Image -> target_path = $ this -> file_upload [ $ control ] [ 'path' ] . trim ( $ prefix ) . $ this -> file_upload [ $ control ] [ 'file_name' ] ; $ this -> Zebra_Image -> maintain_ratio = $ preserve_aspect_ratio ; $ this -> Zebra_Image -> jpeg_quality = $ jpeg_quality ; $ this -> Zebra_Image -> enlarge_smaller_images = $ enlarge_smaller_images ; if ( ! $ this -> Zebra_Image -> resize ( $ width , $ height , $ method , $ background_color ) ) return false ; } return true ; }
Resize an uploaded image
45,981
function add_options ( $ options , $ overwrite = false ) { if ( is_array ( $ options ) ) { $ attributes = $ this -> get_attributes ( array ( 'options' , 'multiple' ) ) ; if ( empty ( $ attributes [ 'options' ] ) && $ overwrite === false && ! isset ( $ attributes [ 'multiple' ] ) ) $ options = array ( '' => $ this -> form_properties [ 'language' ] [ 'select' ] ) + $ options ; $ this -> set_attributes ( array ( 'options' => ( $ overwrite ? $ options : $ attributes [ 'options' ] + $ options ) ) ) ; } else { _zebra_form_show_error ( ' Selectable values for the <strong>' . $ this -> attributes [ 'id' ] . '</strong> control must be specified as an array ' ) ; } }
Adds options to the select box control
45,982
private function _generate ( & $ options , & $ selected , $ level = 0 ) { $ content = '' ; $ indent = '&nbsp;&nbsp;' ; foreach ( $ options as $ value => $ caption ) { if ( is_array ( $ caption ) ) { $ content .= ' <optgroup label="' . str_repeat ( $ indent , $ level ) . $ value . '"> <option disabled="disabled" class="dummy"></option> </optgroup> ' ; $ content .= $ this -> _generate ( $ caption , $ selected , $ level + 1 ) ; } else { $ content .= '<option value="' . $ value . '"' . ( $ selected !== '' && $ value !== '' && ( ( is_array ( $ selected ) && in_array ( $ value , $ selected ) ) || ( ! is_array ( $ selected ) && ( string ) $ value === ( string ) $ selected ) ) ? ' selected="selected"' : '' ) . '>' . str_repeat ( $ indent , $ level ) . $ caption . '</option>' ; } } return $ content ; }
Takes the options array and recursively generates options and optiongroups
45,983
function get_attributes ( $ attributes ) { $ result = array ( ) ; if ( ! is_array ( $ attributes ) ) $ attributes = array ( $ attributes ) ; foreach ( $ attributes as $ attribute ) if ( array_key_exists ( $ attribute , $ this -> attributes ) ) $ result [ $ attribute ] = $ this -> attributes [ $ attribute ] ; return $ result ; }
Returns the values of requested attributes .
45,984
function set_attributes ( $ attributes , $ overwrite = true ) { if ( is_array ( $ attributes ) ) foreach ( $ attributes as $ attribute => $ value ) { if ( $ attribute == 'data-prefix' ) $ value = urlencode ( $ value ) ; if ( ! $ overwrite && isset ( $ this -> attributes [ $ attribute ] ) && ! is_array ( $ this -> attributes [ $ attribute ] ) ) $ this -> attributes [ $ attribute ] = $ this -> attributes [ $ attribute ] . ' ' . $ value ; else $ this -> attributes [ $ attribute ] = $ value ; } }
Sets one or more of the control s attributes .
45,985
function set_rule ( $ rules ) { if ( is_array ( $ rules ) ) foreach ( $ rules as $ rule_name => $ rule_properties ) { $ rule_name = strtolower ( $ rule_name ) ; if ( $ rule_name == 'custom' ) if ( is_array ( $ rule_properties [ 0 ] ) && count ( $ rule_properties [ 0 ] ) >= 3 ) foreach ( $ rule_properties as $ rule ) $ this -> rules [ $ rule_name ] [ ] = $ rule ; else $ this -> rules [ $ rule_name ] [ ] = $ rule_properties ; else $ this -> rules [ $ rule_name ] = $ rule_properties ; switch ( $ rule_name ) { case 'alphabet' : case 'digits' : case 'alphanumeric' : case 'number' : case 'float' : $ this -> set_attributes ( array ( 'onkeypress' => 'javascript:return $(\'#' . $ this -> form_properties [ 'name' ] . '\').data(\'Zebra_Form\').filter_input(\'' . $ rule_name . '\', event' . ( $ rule_properties [ 0 ] != '' ? ', \'' . addcslashes ( $ rule_properties [ 0 ] , '\'' ) . '\'' : '' ) . ');' ) ) ; if ( in_array ( $ rule_name , array ( 'digits' , 'number' , 'float' ) ) ) $ this -> set_attributes ( array ( 'type' => 'number' ) ) ; break ; case 'length' : if ( $ rule_properties [ 1 ] > 0 ) { $ this -> set_attributes ( array ( 'maxlength' => $ rule_properties [ 1 ] ) ) ; if ( isset ( $ rule_properties [ 4 ] ) && $ rule_properties [ 4 ] === true ) { $ this -> set_attributes ( array ( 'class' => 'show-character-counter' ) , false ) ; } } break ; case 'email' : $ this -> set_attributes ( array ( 'type' => 'email' ) ) ; break ; } } }
Sets a single or an array of validation rules for the control .
45,986
function sanitize ( $ str , $ rawurldecode = true ) { $ str = $ this -> _remove_invisible_characters ( $ str ) ; if ( $ rawurldecode ) $ str = rawurldecode ( $ str ) ; $ str = preg_replace_callback ( "/[a-z]+=([\'\"]).*?\\1/si" , array ( $ this , '_convert_attribute' ) , $ str ) ; $ str = preg_replace_callback ( '/<\w+.*?(?=>|<|$)/si' , array ( $ this , '_decode_entity' ) , $ str ) ; $ str = $ this -> _remove_invisible_characters ( $ str ) ; $ str = str_replace ( "\t" , ' ' , $ str ) ; $ converted_string = $ str ; $ str = $ this -> _do_never_allowed ( $ str ) ; $ str = str_replace ( array ( '<?' , '?' . '>' ) , array ( '&lt;?' , '?&gt;' ) , $ str ) ; $ words = array ( 'javascript' , 'expression' , 'vbscript' , 'script' , 'base64' , 'applet' , 'alert' , 'document' , 'write' , 'cookie' , 'window' ) ; foreach ( $ words as $ word ) { $ word = implode ( '\s*' , str_split ( $ word ) ) . '\s*' ; $ str = preg_replace_callback ( '#(' . substr ( $ word , 0 , - 3 ) . ')(\W)#is' , array ( $ this , '_compact_exploded_words' ) , $ str ) ; } do { $ original = $ str ; if ( preg_match ( '/<a/i' , $ str ) ) { $ str = preg_replace_callback ( '#<a\s+([^>]*?)(?:>|$)#si' , array ( $ this , '_js_link_removal' ) , $ str ) ; } if ( preg_match ( '/<img/i' , $ str ) ) { $ str = preg_replace_callback ( '#<img\s+([^>]*?)(?:\s?/?\>|$)#si' , array ( $ this , '_js_img_removal' ) , $ str ) ; } if ( preg_match ( '/script|xss/i' , $ str ) ) { $ str = preg_replace ( '#</*(?:script|xss).*?\>#si' , '[removed]' , $ str ) ; } } while ( $ original !== $ str ) ; unset ( $ original ) ; $ str = $ this -> _remove_evil_attributes ( $ str , false ) ; $ naughty = 'alert|applet|audio|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|isindex|layer|link|meta|object|plaintext|style|script|textarea|title|video|xml|xss' ; $ str = preg_replace_callback ( '#<(/*\s*)(' . $ naughty . ')([^><]*)([><]*)#is' , array ( $ this , '_sanitize_naughty_html' ) , $ str ) ; $ str = preg_replace ( '#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si' , '\\1\\2&#40;\\3&#41;' , $ str ) ; $ str = $ this -> _do_never_allowed ( $ str ) ; return $ str ; }
Sanitizes submitted data so that Cross Site Scripting Hacks can be prevented .
45,987
protected function isIdleTimeOut ( ) : bool { $ idleTime = time ( ) - $ this -> getLastTime ( ) ; $ maxIdleTime = $ this -> getPool ( ) -> getPoolConfig ( ) -> getMaxIdleTime ( ) ; return $ idleTime > $ maxIdleTime ; }
Verify whether the idle time exceeds the maximum value .
45,988
public function create ( ) { $ database = $ removeTablePrefix = '' ; $ tablesEnabled = $ tablesDisabled = [ ] ; $ this -> parseEntityFilePath ( ) ; $ this -> parseDatabaseCommand ( $ database ) ; $ this -> parseInstanceCommand ( $ instance ) ; $ this -> parseEnableTablesCommand ( $ tablesEnabled ) ; $ this -> parseDisableTablesCommand ( $ tablesDisabled ) ; $ this -> parseRemoveTablePrefix ( $ removeTablePrefix ) ; $ this -> parseExtends ( $ extends ) ; $ this -> initDatabase ( $ instance ) ; if ( empty ( $ database ) ) { output ( ) -> writeln ( 'databases doesn\'t not empty!' ) ; } else { $ this -> generatorEntity -> db = $ database ; $ this -> generatorEntity -> instance = $ instance ; $ this -> generatorEntity -> tablesEnabled = $ tablesEnabled ; $ this -> generatorEntity -> tablesDisabled = $ tablesDisabled ; $ this -> generatorEntity -> removeTablePrefix = $ removeTablePrefix ; if ( isset ( $ extends ) ) $ this -> generatorEntity -> setExtends ( $ extends ) ; $ this -> generatorEntity -> execute ( $ this -> schema ) ; } }
Auto create entity by table structure
45,989
protected function addOneDecorator ( ) { $ this -> addDecorator ( function ( $ result ) { if ( isset ( $ result [ 0 ] ) && ! empty ( $ this -> className ) ) { if ( $ result [ 0 ] instanceof $ this -> className ) { return $ result [ 0 ] ; } if ( is_array ( $ result [ 0 ] ) ) { return EntityHelper :: arrayToEntity ( $ result [ 0 ] , $ this -> className ) ; } throw new DbException ( 'The result is not instanceof ' . $ this -> className ) ; } if ( isset ( $ result [ 0 ] ) && empty ( $ this -> join ) && ! empty ( $ this -> className ) ) { $ tableName = $ this -> getTableName ( ) ; return EntityHelper :: formatRowByType ( $ result [ 0 ] , $ tableName ) ; } if ( empty ( $ result ) && ! empty ( $ this -> className ) ) { return null ; } if ( isset ( $ result [ 0 ] ) ) { return $ result [ 0 ] ; } return $ result ; } ) ; }
Add one decorator
45,990
protected function addGetDecorator ( ) { $ this -> addDecorator ( function ( $ result ) { if ( ! empty ( $ this -> className ) && ! empty ( $ result ) ) { $ entities = EntityHelper :: listToEntity ( $ result , $ this -> className ) ; return new Collection ( $ entities ) ; } if ( ! empty ( $ result ) && empty ( $ this -> join ) && ! empty ( $ this -> className ) ) { $ tableName = $ this -> getTableName ( ) ; $ result = EntityHelper :: formatListByType ( $ result , $ tableName ) ; } return $ result ; } ) ; }
Add get decorator
45,991
public static function query ( string $ sql , array $ params = [ ] , string $ instance = Pool :: INSTANCE , string $ className = '' , array $ resultDecorators = [ ] ) : ResultInterface { $ type = self :: getOperation ( $ sql ) ; $ instance = explode ( '.' , $ instance ) ; list ( $ instance , $ node , $ db ) = array_pad ( $ instance , 3 , '' ) ; list ( $ instance , $ node ) = self :: getInstanceAndNodeByType ( $ instance , $ node , $ type ) ; $ connection = self :: getConnection ( $ instance , $ node ) ; if ( ! empty ( $ db ) ) { $ connection -> selectDb ( $ db ) ; } $ pool = $ connection -> getPool ( ) ; $ poolConfig = $ pool -> getPoolConfig ( ) ; $ driver = $ poolConfig -> getDriver ( ) ; if ( App :: isCoContext ( ) ) { $ connection -> setDefer ( ) ; } $ sqlId = uniqid ( ) ; $ profileKey = sprintf ( '%s.%s' , $ driver , $ sqlId ) ; Log :: debug ( sprintf ( 'Execute sqlId=%s , sql=%s' , $ sqlId , $ sql ) ) ; Log :: profileStart ( $ profileKey ) ; $ connection -> prepare ( $ sql ) ; $ params = self :: transferParams ( $ params ) ; $ result = $ connection -> execute ( $ params ) ; $ dbResult = self :: getResult ( $ result , $ connection , $ profileKey ) ; $ dbResult -> setType ( $ type ) ; $ dbResult -> setClassName ( $ className ) ; $ dbResult -> setDecorators ( $ resultDecorators ) ; return $ dbResult ; }
Query by sql
45,992
public function find ( $ id ) { $ resourceName = constant ( $ this -> type . '::RESOURCE' ) ; $ url = sprintf ( "%s/%s/%s" , self :: ENDPOINT , $ resourceName , $ id ) ; $ response = $ this -> fetch ( $ url , substr ( $ resourceName , 0 , strlen ( $ resourceName ) - 1 ) ) ; return new $ this -> type ( $ response ) ; }
Get a resource by its id
45,993
public function findMany ( $ url , $ type , $ resource ) { $ data = [ ] ; $ response = json_decode ( file_get_contents ( $ url ) , true ) ; $ response = $ response [ $ resource ] ; if ( count ( $ response ) > 0 ) { foreach ( $ response as $ item ) { $ data [ ] = new $ type ( $ item ) ; } } return $ data ; }
Get a list of resources
45,994
public function where ( array $ arguments ) { foreach ( $ arguments as $ key => $ value ) { $ this -> params [ $ key ] = $ value ; } return $ this ; }
Adds a parameter to the dictionary of query parameters
45,995
public function all ( ) { $ data = [ ] ; $ page = 1 ; $ fetch_all = true ; $ resourceName = constant ( $ this -> type . '::RESOURCE' ) ; $ url = sprintf ( "%s/%s" , self :: ENDPOINT , $ resourceName ) ; if ( isset ( $ this -> params [ 'page' ] ) ) { $ page = $ this -> params [ 'page' ] ; $ fetch_all = false ; } while ( true ) { $ response = $ this -> fetch ( $ this -> buildUrl ( $ url , $ this -> params ) , $ resourceName ) ; if ( count ( $ response ) > 0 ) { foreach ( $ response as $ item ) { $ data [ ] = new $ this -> type ( $ item ) ; } if ( ! $ fetch_all ) { break ; } else { $ page ++ ; $ this -> where ( [ 'page' => $ page ] ) ; } } else { break ; } } return $ data ; }
Get all resources automatically paging through data
45,996
protected function isValidRename ( $ source , $ dest ) { $ adapter = $ this -> filesystem -> getAdapter ( ) ; if ( ! $ adapter -> has ( $ source ) ) { throw new FileNotFoundException ( $ source ) ; } $ subdir = Util :: dirname ( $ dest ) ; if ( strlen ( $ subdir ) && ! $ adapter -> has ( $ subdir ) ) { throw new FileNotFoundException ( $ source ) ; } if ( ! $ adapter -> has ( $ dest ) ) { return true ; } return $ this -> compareTypes ( $ source , $ dest ) ; }
Checks that a rename is valid .
45,997
public static function register ( $ protocol , FilesystemInterface $ filesystem , array $ configuration = null , $ flags = 0 ) { if ( static :: streamWrapperExists ( $ protocol ) ) { return false ; } static :: $ config [ $ protocol ] = $ configuration ? : static :: $ defaultConfiguration ; static :: registerPlugins ( $ protocol , $ filesystem ) ; static :: $ filesystems [ $ protocol ] = $ filesystem ; return stream_wrapper_register ( $ protocol , __CLASS__ , $ flags ) ; }
Registers the stream wrapper protocol if not already registered .
45,998
protected static function registerPlugins ( $ protocol , FilesystemInterface $ filesystem ) { $ filesystem -> addPlugin ( new ForcedRename ( ) ) ; $ filesystem -> addPlugin ( new Mkdir ( ) ) ; $ filesystem -> addPlugin ( new Rmdir ( ) ) ; $ stat = new Stat ( static :: $ config [ $ protocol ] [ 'permissions' ] , static :: $ config [ $ protocol ] [ 'metadata' ] ) ; $ filesystem -> addPlugin ( $ stat ) ; $ filesystem -> addPlugin ( new Touch ( ) ) ; }
Registers plugins on the filesystem .
45,999
public function dir_opendir ( $ uri , $ options ) { $ this -> uri = $ uri ; $ path = Util :: normalizePath ( $ this -> getTarget ( ) ) ; $ this -> listing = $ this -> invoke ( $ this -> getFilesystem ( ) , 'listContents' , [ $ path ] , 'opendir' ) ; if ( $ this -> listing === false ) { return false ; } if ( ! $ dirlen = strlen ( $ path ) ) { return true ; } $ dirlen ++ ; foreach ( $ this -> listing as $ delta => $ item ) { $ this -> listing [ $ delta ] [ 'path' ] = substr ( $ item [ 'path' ] , $ dirlen ) ; } reset ( $ this -> listing ) ; return true ; }
Opens a directory handle .