idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
58,500
public function actionGenerate ( ) { $ access = mb_strtolower ( StringHelper :: randomString ( 32 ) ) ; $ this -> line ( $ access , Console :: FG_GREEN ) ; return ExitCode :: OK ; }
Generate a new access token for dynamic IP authorization
58,501
public function getPaymentForm ( $ orderId , $ paymentId , $ amount , $ currency = self :: CURRENCY_RUR , $ paymentType = self :: PAYMENT_TYPE_CARD , $ successReturnUrl = '' , $ failReturnUrl = '' , $ description = '' , $ extraParams = [ ] , $ receipt = null ) { return $ this -> getCurrentDriver ( ) -> getPaymentForm ( $ orderId , $ paymentId , $ amount , $ currency , $ paymentType , $ successReturnUrl , $ failReturnUrl , $ description , $ extraParams , $ receipt ) ; }
Generate payment form
58,502
public static function connect ( $ host = 'localhost' , $ timeout = 2000 ) { if ( ! count ( self :: $ magic ) ) { foreach ( self :: $ commands as $ cmd => $ i ) { self :: $ magic [ $ i [ 0 ] ] = array ( $ cmd , $ i [ 1 ] ) ; } } $ err = '' ; $ errno = 0 ; $ port = self :: DEFAULT_PORT ; if ( strpos ( $ host , ':' ) ) { list ( $ host , $ port ) = explode ( ':' , $ host ) ; } $ start = microtime ( true ) ; do { $ socket = socket_create ( AF_INET , SOCK_STREAM , SOL_TCP ) ; $ socket_connected = @ socket_connect ( $ socket , $ host , $ port ) ; if ( $ socket_connected ) { socket_set_nonblock ( $ socket ) ; socket_set_option ( $ socket , SOL_TCP , 1 , 1 ) ; } $ timeLeft = ( ( microtime ( true ) - $ start ) * 1000 ) ; } while ( ! $ socket_connected && $ timeLeft < $ timeout ) ; if ( ! $ socket_connected ) { $ errno = socket_last_error ( $ socket ) ; $ errstr = socket_strerror ( $ errno ) ; throw new CouldNotConnectException ( "Can't connect to server ($errno: $errstr)" ) ; } self :: $ waiting [ ( int ) $ socket ] = array ( ) ; return $ socket ; }
Connect to Gearman .
58,503
public static function send ( $ socket , $ command , array $ params = array ( ) ) { if ( ! isset ( self :: $ commands [ $ command ] ) ) { throw new Exception ( 'Invalid command: ' . $ command ) ; } $ data = array ( ) ; foreach ( self :: $ commands [ $ command ] [ 1 ] as $ field ) { if ( isset ( $ params [ $ field ] ) ) { $ data [ ] = $ params [ $ field ] ; } } $ d = implode ( "\x00" , $ data ) ; $ cmd = "\0REQ" . pack ( 'NN' , self :: $ commands [ $ command ] [ 0 ] , self :: stringLength ( $ d ) ) . $ d ; $ cmdLength = self :: stringLength ( $ cmd ) ; $ written = 0 ; $ error = false ; do { $ check = @ socket_write ( $ socket , self :: subString ( $ cmd , $ written , $ cmdLength ) , $ cmdLength ) ; if ( $ check === false ) { if ( socket_last_error ( $ socket ) == SOCKET_EAGAIN or socket_last_error ( $ socket ) == SOCKET_EWOULDBLOCK or socket_last_error ( $ socket ) == SOCKET_EINPROGRESS ) { } else { $ error = true ; break ; } } $ written += ( int ) $ check ; } while ( $ written < $ cmdLength ) ; if ( $ error === true ) { $ errno = socket_last_error ( $ socket ) ; $ errstr = socket_strerror ( $ errno ) ; throw new Exception ( "Could not write command to socket ($errno: $errstr)" ) ; } }
Send a command to Gearman .
58,504
public static function read ( $ socket ) { $ header = '' ; do { $ buf = socket_read ( $ socket , 12 - self :: stringLength ( $ header ) ) ; $ header .= $ buf ; } while ( $ buf !== false && $ buf !== '' && self :: stringLength ( $ header ) < 12 ) ; if ( $ buf === '' ) { throw new Exception ( 'Connection was reset' ) ; } if ( self :: stringLength ( $ header ) == 0 ) { return array ( ) ; } $ resp = @ unpack ( 'a4magic/Ntype/Nlen' , $ header ) ; if ( ! count ( $ resp ) == 3 ) { throw new Exception ( 'Received an invalid response' ) ; } if ( ! isset ( self :: $ magic [ $ resp [ 'type' ] ] ) ) { throw new Exception ( 'Invalid response magic returned: ' . $ resp [ 'type' ] ) ; } $ return = array ( ) ; if ( $ resp [ 'len' ] > 0 ) { $ data = '' ; while ( self :: stringLength ( $ data ) < $ resp [ 'len' ] ) { $ data .= socket_read ( $ socket , $ resp [ 'len' ] - self :: stringLength ( $ data ) ) ; } $ d = explode ( "\x00" , $ data ) ; foreach ( self :: $ magic [ $ resp [ 'type' ] ] [ 1 ] as $ i => $ a ) { $ return [ $ a ] = $ d [ $ i ] ; } } $ function = self :: $ magic [ $ resp [ 'type' ] ] [ 0 ] ; if ( $ function == 'error' ) { if ( ! self :: stringLength ( $ return [ 'err_text' ] ) ) { $ return [ 'err_text' ] = 'Unknown error; see error code.' ; } throw new Exception ( $ return [ 'err_text' ] , $ return [ 'err_code' ] ) ; } return array ( 'function' => self :: $ magic [ $ resp [ 'type' ] ] [ 0 ] , 'type' => $ resp [ 'type' ] , 'data' => $ return , ) ; }
Read command from Gearman .
58,505
public static function blockingRead ( $ socket , $ timeout = 500.0 ) { static $ cmds = array ( ) ; $ tv_sec = floor ( ( $ timeout % 1000 ) ) ; $ tv_usec = ( $ timeout * 1000 ) ; $ start = microtime ( true ) ; while ( count ( $ cmds ) == 0 ) { if ( ( ( microtime ( true ) - $ start ) * 1000 ) > $ timeout ) { throw new Exception ( 'Blocking read timed out' ) ; } $ write = null ; $ except = null ; $ read = array ( $ socket ) ; socket_select ( $ read , $ write , $ except , $ tv_sec , $ tv_usec ) ; foreach ( $ read as $ s ) { $ cmds [ ] = self :: read ( $ s ) ; } } return array_shift ( $ cmds ) ; }
Blocking socket read .
58,506
public static function isConnected ( $ conn ) { return ( is_null ( $ conn ) !== true && is_resource ( $ conn ) === true && strtolower ( get_resource_type ( $ conn ) ) == 'socket' ) ; }
Are we connected?
58,507
public static function stringLength ( $ value ) { if ( is_null ( self :: $ multiByteSupport ) ) { self :: $ multiByteSupport = intval ( ini_get ( 'mbstring.func_overload' ) ) ; } if ( self :: $ multiByteSupport & 2 ) { return mb_strlen ( $ value , '8bit' ) ; } else { return strlen ( $ value ) ; } }
Determine if we should use mb_strlen or stock strlen .
58,508
public function handleSslRouting ( ) { if ( $ this -> settings -> sslRoutingEnabled && ! Craft :: $ app -> getRequest ( ) -> getIsConsoleRequest ( ) ) { $ requestedUrl = Craft :: $ app -> request -> getUrl ( ) ; $ restrictedUrls = $ this -> settings -> sslRoutingRestrictedUrls ; if ( ! Craft :: $ app -> request -> isSecureConnection ) { foreach ( $ restrictedUrls as $ restrictedUrl ) { if ( stripos ( $ restrictedUrl , '{' ) !== false ) { $ restrictedUrl = Craft :: $ app -> view -> renderObjectTemplate ( $ restrictedUrl , $ this -> getDynamicParams ( ) ) ; } $ restrictedUrl = '/' . ltrim ( $ restrictedUrl , '/' ) ; if ( stripos ( $ requestedUrl , $ restrictedUrl ) === 0 ) { $ this -> forceSsl ( ) ; } } return true ; } } return false ; }
Forces SSL based on restricted URLs The environment settings take priority over those defined in the control panel
58,509
protected function getDynamicParams ( ) { if ( is_null ( $ this -> dynamicParams ) ) { $ this -> dynamicParams = [ 'siteUrl' => UrlHelper :: siteUrl ( ) , 'cpTrigger' => Craft :: $ app -> config -> general -> cpTrigger , 'actionTrigger' => Craft :: $ app -> config -> general -> actionTrigger , ] ; } return $ this -> dynamicParams ; }
Returns a list of dynamic parameters and their values that can be used in restricted area settings
58,510
protected function forceSsl ( ) { $ baseUrl = trim ( $ this -> settings -> sslRoutingBaseUrl ) ; if ( mb_stripos ( $ baseUrl , '{' ) !== false ) { $ baseUrl = Craft :: $ app -> view -> renderObjectTemplate ( $ this -> settings -> sslRoutingBaseUrl , $ this -> getDynamicParams ( ) ) ; } if ( empty ( $ baseUrl ) || $ baseUrl == '/' ) { $ baseUrl = trim ( Craft :: $ app -> request -> hostInfo ) ; } $ requestUri = trim ( Craft :: $ app -> request -> getUrl ( ) ) ; $ url = sprintf ( '%s%s' , rtrim ( $ baseUrl , '/' ) , $ requestUri ) ; $ url = str_replace ( 'http:' , 'https:' , $ url ) ; if ( ! filter_var ( $ url , FILTER_VALIDATE_URL ) ) { throw new ErrorException ( Craft :: t ( 'patrol' , '{url} is not a valid URL' , [ 'url' => $ url ] ) ) ; } Craft :: $ app -> response -> redirect ( $ url , $ this -> settings -> redirectStatusCode ) ; }
Redirects to the HTTPS version of the requested URL
58,511
public function handleMaintenanceMode ( ) { if ( $ this -> doesCurrentUserHaveAccess ( ) ) { return true ; } if ( Craft :: $ app -> request -> isSiteRequest && $ this -> settings -> maintenanceModeEnabled ) { $ requestingIp = $ this -> getRequestingIp ( ) ; $ authorizedIps = $ this -> settings -> maintenanceModeAuthorizedIps ; $ maintenanceUrl = $ this -> settings -> maintenanceModePageUrl ; if ( $ maintenanceUrl == Craft :: $ app -> request -> getUrl ( ) ) { return true ; } if ( empty ( $ authorizedIps ) ) { $ this -> forceRedirect ( $ maintenanceUrl ) ; } if ( is_array ( $ authorizedIps ) && count ( $ authorizedIps ) ) { if ( in_array ( $ requestingIp , $ authorizedIps ) ) { return true ; } foreach ( $ authorizedIps as $ authorizedIp ) { $ authorizedIp = str_replace ( '*' , '' , $ authorizedIp ) ; if ( stripos ( $ requestingIp , $ authorizedIp ) === 0 ) { return true ; } } $ this -> forceRedirect ( $ maintenanceUrl ) ; } } }
Restricts accessed based on authorizedIps
58,512
protected function doesCurrentUserHaveAccess ( ) { if ( Craft :: $ app -> user -> getIsAdmin ( ) ) { return true ; } if ( Craft :: $ app -> user -> checkPermission ( Patrol :: MAINTENANCE_MODE_BYPASS_PERMISSION ) ) { return true ; } return false ; }
Returns whether or not the current user has access during maintenance mode
58,513
public function getRequestingIp ( ) { if ( isset ( $ _SERVER [ 'HTTP_CF_CONNECTING_IP' ] ) ) { return $ _SERVER [ 'HTTP_CF_CONNECTING_IP' ] ; } elseif ( isset ( $ _SERVER [ 'HTTP_X_FORWARDED_FOR' ] ) ) { return isset ( $ _SERVER [ 'HTTP_X_FORWARDED_FOR' ] ) ; } elseif ( isset ( $ _SERVER [ 'HTTP_X_REAL_IP' ] ) ) { return isset ( $ _SERVER [ 'HTTP_X_REAL_IP' ] ) ; } else { return $ _SERVER [ 'REMOTE_ADDR' ] ; } }
Ensures that we get the right IP address even if behind CloudFlare or most proxies
58,514
public function parseAuthorizedIps ( $ ips ) { $ ips = trim ( $ ips ) ; if ( is_string ( $ ips ) && ! empty ( $ ips ) ) { $ ips = explode ( PHP_EOL , $ ips ) ; } return $ this -> filterOutArrayValues ( $ ips , function ( $ val ) { return preg_match ( '/^[0-9\.\*]{5,15}$/i' , $ val ) ; } ) ; }
Parses authorizedIps to ensure they are valid even when created from a string
58,515
protected function filterOutArrayValues ( $ values = null , \ Closure $ filter = null , $ preserveKeys = false ) { $ data = [ ] ; if ( is_array ( $ values ) && count ( $ values ) ) { foreach ( $ values as $ key => $ value ) { $ value = trim ( $ value ) ; if ( ! empty ( $ value ) ) { if ( is_callable ( $ filter ) && $ filter ( $ value ) ) { $ data [ $ key ] = $ value ; } } } if ( ! $ preserveKeys ) { $ data = array_values ( $ data ) ; } } return $ data ; }
Filters out array values by using a custom filter
58,516
public function parseRestrictedAreas ( $ areas ) { if ( is_string ( $ areas ) && ! empty ( $ areas ) ) { $ areas = trim ( $ areas ) ; $ areas = explode ( PHP_EOL , $ areas ) ; } return $ this -> filterOutArrayValues ( $ areas , function ( $ val ) { $ valid = preg_match ( '/^[\/\{\}a-z\_\-\?\=]{1,255}$/i' , $ val ) ; if ( ! $ valid ) { return false ; } return true ; } ) ; }
Parse restricted areas to ensure they are valid even when created from a string
58,517
protected function doWork ( $ socket ) { Connection :: send ( $ socket , 'grab_job' ) ; $ resp = array ( 'function' => 'noop' ) ; while ( count ( $ resp ) && $ resp [ 'function' ] == 'noop' ) { $ resp = Connection :: blockingRead ( $ socket ) ; } if ( in_array ( $ resp [ 'function' ] , array ( 'noop' , 'no_job' ) ) ) { return false ; } if ( $ resp [ 'function' ] != 'job_assign' ) { throw new Exception ( 'Internal error - Job was not assigned after it was grabbed by this worker' ) ; } $ name = $ resp [ 'data' ] [ 'func' ] ; $ handle = $ resp [ 'data' ] [ 'handle' ] ; $ arg = array ( ) ; if ( isset ( $ resp [ 'data' ] [ 'arg' ] ) && Connection :: stringLength ( $ resp [ 'data' ] [ 'arg' ] ) ) { $ arg = json_decode ( $ resp [ 'data' ] [ 'arg' ] , true ) ; if ( $ arg === null ) { $ arg = $ resp [ 'data' ] [ 'arg' ] ; } } try { $ this -> callStartCallbacks ( $ handle , $ name , $ arg ) ; $ functionCallback = $ this -> functions [ $ name ] [ 'callback' ] ; $ result = call_user_func ( $ functionCallback , $ arg ) ; if ( ! $ result ) { $ result = '' ; } $ this -> jobComplete ( $ socket , $ handle , $ result ) ; $ this -> callCompleteCallbacks ( $ handle , $ name , $ result ) ; } catch ( JobException $ e ) { $ this -> jobFail ( $ socket , $ handle ) ; $ this -> callFailCallbacks ( $ handle , $ name , $ e ) ; } $ job = null ; return true ; }
Listen on the socket for work .
58,518
public function jobStatus ( $ numerator , $ denominator ) { Connection :: send ( $ this -> conn , 'work_status' , array ( 'handle' => $ this -> handle , 'numerator' => $ numerator , 'denominator' => $ denominator , ) ) ; }
Update Gearman with your job s status .
58,519
public function doNormal ( $ functionName , $ workload , $ unique = null ) { return $ this -> runSingleTaskSet ( $ this -> createSet ( $ functionName , $ workload , $ unique ) ) ; }
Runs a single task and returns a string representation of the result .
58,520
public function doEpoch ( $ functionName , $ workload , $ epoch , $ unique = null ) { $ set = $ this -> createSet ( $ functionName , $ workload , $ unique , Task :: JOB_EPOCH , $ epoch ) ; $ this -> runSet ( $ set ) ; return current ( $ set -> tasks ) ; }
Schedule a background task returning a job handle which can be used to get the status of the running task .
58,521
protected function submitTask ( Task $ task ) { switch ( $ task -> type ) { case Task :: JOB_LOW : $ type = 'submit_job_low' ; break ; case Task :: JOB_LOW_BACKGROUND : $ type = 'submit_job_low_bg' ; break ; case Task :: JOB_HIGH_BACKGROUND : $ type = 'submit_job_high_bg' ; break ; case Task :: JOB_BACKGROUND : $ type = 'submit_job_bg' ; break ; case Task :: JOB_EPOCH : $ type = 'submit_job_epoch' ; break ; case Task :: JOB_HIGH : $ type = 'submit_job_high' ; break ; default : $ type = 'submit_job' ; break ; } $ arg = $ task -> arg ; $ params = array ( 'func' => $ task -> func , 'uniq' => $ task -> uniq , 'arg' => $ arg , ) ; if ( $ task -> type == Task :: JOB_EPOCH ) { $ params [ 'epoch' ] = $ task -> epoch ; } $ s = $ this -> getConnection ( ) ; Connection :: send ( $ s , $ type , $ params ) ; if ( ! is_array ( Connection :: $ waiting [ ( int ) $ s ] ) ) { Connection :: $ waiting [ ( int ) $ s ] = array ( ) ; } array_push ( Connection :: $ waiting [ ( int ) $ s ] , $ task ) ; }
Submit a task to Gearman .
58,522
public function runSet ( Set $ set , $ timeout = null ) { foreach ( $ this -> getServers ( ) as $ server ) { $ conn = Connection :: connect ( $ server , $ timeout ) ; if ( ! Connection :: isConnected ( $ conn ) ) { unset ( $ this -> servers [ $ server ] ) ; continue ; } $ this -> conn [ ] = $ conn ; } $ totalTasks = $ set -> tasksCount ; $ taskKeys = array_keys ( $ set -> tasks ) ; $ t = 0 ; if ( $ timeout !== null ) { $ socket_timeout = min ( 10 , ( int ) $ timeout ) ; } else { $ socket_timeout = 10 ; } while ( ! $ set -> finished ( ) ) { if ( $ timeout !== null ) { if ( empty ( $ start ) ) { $ start = microtime ( true ) ; } else { $ now = microtime ( true ) ; if ( $ now - $ start >= $ timeout ) { break ; } } } if ( $ t < $ totalTasks ) { $ k = $ taskKeys [ $ t ] ; $ this -> submitTask ( $ set -> tasks [ $ k ] ) ; if ( $ set -> tasks [ $ k ] -> type == Task :: JOB_BACKGROUND || $ set -> tasks [ $ k ] -> type == Task :: JOB_HIGH_BACKGROUND || $ set -> tasks [ $ k ] -> type == Task :: JOB_LOW_BACKGROUND || $ set -> tasks [ $ k ] -> type == Task :: JOB_EPOCH ) { $ set -> tasks [ $ k ] -> finished = true ; -- $ set -> tasksCount ; } ++ $ t ; } $ write = null ; $ except = null ; $ read = $ this -> conn ; socket_select ( $ read , $ write , $ except , $ socket_timeout ) ; foreach ( $ read as $ socket ) { $ resp = Connection :: read ( $ socket ) ; if ( count ( $ resp ) ) { $ this -> handleResponse ( $ resp , $ socket , $ set ) ; } } } }
Run a set of tasks .
58,523
protected function handleResponse ( $ resp , $ s , Set $ tasks ) { if ( isset ( $ resp [ 'data' ] [ 'handle' ] ) && $ resp [ 'function' ] != 'job_created' ) { $ task = $ tasks -> getTask ( $ resp [ 'data' ] [ 'handle' ] ) ; } switch ( $ resp [ 'function' ] ) { case 'work_complete' : $ tasks -> tasksCount -- ; $ task -> complete ( $ resp [ 'data' ] [ 'result' ] ) ; break ; case 'work_status' : $ n = ( int ) $ resp [ 'data' ] [ 'numerator' ] ; $ d = ( int ) $ resp [ 'data' ] [ 'denominator' ] ; $ task -> status ( $ n , $ d ) ; break ; case 'work_fail' : $ tasks -> tasksCount -- ; $ task -> fail ( ) ; break ; case 'job_created' : $ task = array_shift ( Connection :: $ waiting [ ( int ) $ s ] ) ; $ task -> handle = $ resp [ 'data' ] [ 'handle' ] ; if ( $ task -> type == Task :: JOB_BACKGROUND ) { $ task -> finished = true ; } $ tasks -> handles [ $ task -> handle ] = $ task -> uniq ; break ; case 'error' : throw new Exception ( 'An error occurred' ) ; default : throw new Exception ( 'Invalid function ' . $ resp [ 'function' ] ) ; } }
Handle the response read in .
58,524
public function disconnect ( ) { if ( ! is_array ( $ this -> conn ) || ! count ( $ this -> conn ) ) { return ; } foreach ( $ this -> conn as $ conn ) { Connection :: close ( $ conn ) ; } }
Disconnect from Gearman .
58,525
function it_provides_access_to_error_details ( ) { $ this -> getCode ( ) -> shouldBe ( 400 ) ; $ this -> getErrorMessage ( ) -> shouldBeString ( ) ; $ this -> getErrorMessage ( ) -> shouldBe ( 'BadRequestError: "Missing personalisation: name"' ) ; $ this -> getErrors ( ) -> shouldBeArray ( ) ; $ this -> getErrors ( ) [ 0 ] -> shouldBeArray ( ) ; $ this -> getErrors ( ) [ 0 ] [ 'error' ] -> shouldBe ( 'BadRequestError' ) ; $ this -> getErrors ( ) [ 0 ] [ 'message' ] -> shouldBe ( 'Missing personalisation: name' ) ; }
Test constructor variations
58,526
public function sendSms ( $ phoneNumber , $ templateId , array $ personalisation = array ( ) , $ reference = '' , $ smsSenderId = NULL ) { return $ this -> httpPost ( self :: PATH_NOTIFICATION_SEND_SMS , $ this -> buildSmsPayload ( 'sms' , $ phoneNumber , $ templateId , $ personalisation , $ reference , $ smsSenderId ) ) ; }
Send an SMS message .
58,527
public function sendEmail ( $ emailAddress , $ templateId , array $ personalisation = array ( ) , $ reference = '' , $ emailReplyToId = NULL ) { return $ this -> httpPost ( self :: PATH_NOTIFICATION_SEND_EMAIL , $ this -> buildEmailPayload ( 'email' , $ emailAddress , $ templateId , $ personalisation , $ reference , $ emailReplyToId ) ) ; }
Send an Email message .
58,528
public function sendLetter ( $ templateId , array $ personalisation = array ( ) , $ reference = '' ) { $ payload = $ this -> buildPayload ( 'letter' , '' , $ templateId , $ personalisation , $ reference ) ; return $ this -> httpPost ( self :: PATH_NOTIFICATION_SEND_LETTER , $ payload ) ; }
Send a Letter
58,529
public function getNotification ( $ notificationId ) { $ path = sprintf ( self :: PATH_NOTIFICATION_LOOKUP , $ notificationId ) ; return $ this -> httpGet ( $ path ) ; }
Returns details about the passed notification ID .
58,530
public function listNotifications ( array $ filters = array ( ) ) { $ filters = array_intersect_key ( $ filters , array_flip ( [ 'older_than' , 'reference' , 'status' , 'template_type' , ] ) ) ; return $ this -> httpGet ( self :: PATH_NOTIFICATION_LIST , $ filters ) ; }
Returns a list of all notifications for the current Service ID .
58,531
public function listReceivedTexts ( array $ filters = array ( ) ) { $ filters = array_intersect_key ( $ filters , array_flip ( [ 'older_than' ] ) ) ; return $ this -> httpGet ( self :: PATH_RECEIVED_TEXT_LIST , $ filters ) ; }
Returns a list of all received texts for the current Service ID .
58,532
public function getTemplate ( $ templateId ) { $ path = sprintf ( self :: PATH_TEMPLATE_LOOKUP , $ templateId ) ; return $ this -> httpGet ( $ path ) ; }
Get a template by ID .
58,533
public function getTemplateVersion ( $ templateId , $ version ) { $ path = sprintf ( self :: PATH_TEMPLATE_VERSION_LOOKUP , $ templateId , $ version ) ; return $ this -> httpGet ( $ path ) ; }
Get a template by ID and version .
58,534
public function listTemplates ( $ templateType = null ) { $ queryParams = is_null ( $ templateType ) ? [ ] : [ 'type' => $ templateType ] ; return $ this -> httpGet ( self :: PATH_TEMPLATE_LIST , $ queryParams ) ; }
Get all templates
58,535
public function previewTemplate ( $ templateId , $ personalisation ) { $ path = sprintf ( self :: PATH_TEMPLATE_PREVIEW , $ templateId ) ; $ payload = [ 'personalisation' => $ personalisation ] ; return $ this -> httpPost ( $ path , $ payload ) ; }
Get a preview of a template
58,536
private function buildPayload ( $ type , $ to , $ templateId , array $ personalisation , $ reference ) { $ payload = [ 'template_id' => $ templateId ] ; if ( $ type == 'sms' ) { $ payload [ 'phone_number' ] = $ to ; } else if ( $ type == 'email' ) { $ payload [ 'email_address' ] = $ to ; } if ( count ( $ personalisation ) > 0 ) { $ payload [ 'personalisation' ] = $ personalisation ; } if ( isset ( $ reference ) && $ reference != '' ) { $ payload [ 'reference' ] = $ reference ; } return $ payload ; }
Generates the payload expected by the API .
58,537
private function buildEmailPayload ( $ type , $ to , $ templateId , array $ personalisation , $ reference , $ emailReplyToId = NULL ) { $ payload = $ this -> buildPayload ( $ type , $ to , $ templateId , $ personalisation , $ reference ) ; if ( isset ( $ emailReplyToId ) && $ emailReplyToId != '' ) { $ payload [ 'email_reply_to_id' ] = $ emailReplyToId ; } return $ payload ; }
Generates the payload expected by the API for email adding the optional items .
58,538
private function buildSmsPayload ( $ type , $ to , $ templateId , array $ personalisation , $ reference , $ smsSenderId = NULL ) { $ payload = $ this -> buildPayload ( $ type , $ to , $ templateId , $ personalisation , $ reference ) ; if ( isset ( $ smsSenderId ) && $ smsSenderId != '' ) { $ payload [ 'sms_sender_id' ] = $ smsSenderId ; } return $ payload ; }
Generates the payload expected by the API for sms adding the optional items .
58,539
private function httpGet ( $ path , array $ query = array ( ) ) { $ url = new Uri ( $ this -> baseUrl . $ path ) ; foreach ( $ query as $ name => $ value ) { $ url = URI :: withQueryValue ( $ url , $ name , $ value ) ; } $ request = new Request ( 'GET' , $ url , $ this -> buildHeaders ( ) ) ; try { $ response = $ this -> getHttpClient ( ) -> sendRequest ( $ request ) ; } catch ( \ RuntimeException $ e ) { throw new Exception \ NotifyException ( $ e -> getMessage ( ) , $ e -> getCode ( ) , $ e ) ; } switch ( $ response -> getStatusCode ( ) ) { case 200 : return $ this -> handleResponse ( $ response ) ; case 404 : return null ; default : return $ this -> handleErrorResponse ( $ response ) ; } }
Performs a GET against the Notify API .
58,540
private function httpPost ( $ path , Array $ payload ) { $ url = new Uri ( $ this -> baseUrl . $ path ) ; $ request = new Request ( 'POST' , $ url , $ this -> buildHeaders ( ) , json_encode ( $ payload ) ) ; try { $ response = $ this -> getHttpClient ( ) -> sendRequest ( $ request ) ; } catch ( \ RuntimeException $ e ) { throw new Exception \ NotifyException ( $ e -> getMessage ( ) , $ e -> getCode ( ) , $ e ) ; } switch ( $ response -> getStatusCode ( ) ) { case 200 : case 201 : return $ this -> handleResponse ( $ response ) ; default : return $ this -> handleErrorResponse ( $ response ) ; } }
Performs a POST against the Notify API .
58,541
protected function handleResponse ( ResponseInterface $ response ) { $ body = json_decode ( $ response -> getBody ( ) , true ) ; if ( ! is_array ( $ body ) ) { throw new Exception \ ApiException ( 'Malformed JSON response from server' , $ response -> getStatusCode ( ) , $ body , $ response ) ; } return $ body ; }
Called with a response from the API when the response code was successful . i . e . 20X .
58,542
protected function handleErrorResponse ( ResponseInterface $ response ) { $ body = json_decode ( $ response -> getBody ( ) , true ) ; $ message = "HTTP:{$response->getStatusCode()}" ; throw new Exception \ ApiException ( $ message , $ response -> getStatusCode ( ) , $ body , $ response ) ; }
Called with a response from the API when the response code was unsuccessful . i . e . not 20X .
58,543
public static function getISBN10CheckDigit ( $ isbn ) { $ sum = 0 ; for ( $ x = 0 ; $ x < strlen ( $ isbn ) ; $ x ++ ) { $ sum += intval ( substr ( $ isbn , $ x , 1 ) ) * ( 1 + $ x ) ; } $ checkdigit = $ sum % 11 ; return $ checkdigit == 10 ? 'X' : $ checkdigit ; }
Given the first 9 digits of an ISBN - 10 generate the check digit .
58,544
public static function isValidISBN10 ( $ isbn ) { $ isbn = self :: normalizeISBN ( $ isbn ) ; if ( strlen ( $ isbn ) != 10 ) { return false ; } return substr ( $ isbn , 9 ) == self :: getISBN10CheckDigit ( substr ( $ isbn , 0 , 9 ) ) ; }
Is the provided ISBN - 10 valid?
58,545
public static function getISBN13CheckDigit ( $ isbn ) { $ sum = 0 ; $ weight = 1 ; for ( $ x = 0 ; $ x < strlen ( $ isbn ) ; $ x ++ ) { $ sum += intval ( substr ( $ isbn , $ x , 1 ) ) * $ weight ; $ weight = $ weight == 1 ? 3 : 1 ; } $ retval = 10 - ( $ sum % 10 ) ; return $ retval == 10 ? 0 : $ retval ; }
Given the first 12 digits of an ISBN - 13 generate the check digit .
58,546
public static function isValidISBN13 ( $ isbn ) { $ isbn = self :: normalizeISBN ( $ isbn ) ; if ( strlen ( $ isbn ) != 13 ) { return false ; } return substr ( $ isbn , 12 ) == self :: getISBN13CheckDigit ( substr ( $ isbn , 0 , 12 ) ) ; }
Is the provided ISBN - 13 valid?
58,547
public function settingsHtml ( ) { Craft :: $ app -> view -> registerAssetBundle ( PatrolPluginAssetBundle :: class ) ; $ settings = $ this -> getSettings ( ) ; $ variables = [ 'plugin' => $ this , 'settings' => $ settings , 'settingsJson' => $ settings -> getJsonObject ( ) , ] ; $ html = Craft :: $ app -> view -> renderTemplate ( 'patrol/_settings' , $ variables ) ; return Template :: raw ( $ html ) ; }
Returns rendered settings UI as a twig markup object
58,548
public function setDataFor ( $ arrValues ) { $ tableName = $ this -> getMetaModel ( ) -> getTableName ( ) ; $ colName = $ this -> getColName ( ) ; foreach ( $ arrValues as $ id => $ value ) { if ( null === $ value ) { $ value = [ 'bin' => [ ] , 'value' => [ ] , 'path' => [ ] , 'sort' => null ] ; } $ files = ToolboxFile :: convertValuesToDatabase ( $ value ) ; if ( $ this -> get ( 'file_multiple' ) ) { $ files = \ serialize ( $ files ) ; } else { $ files = $ files [ 0 ] ; } $ this -> connection -> update ( $ this -> quoteReservedWord ( $ tableName ) , [ $ this -> quoteReservedWord ( $ colName ) => $ files ] , [ $ this -> quoteReservedWord ( 'id' ) => $ id ] ) ; } }
This method is called to store the data for certain items to the database .
58,549
public function serializeData ( $ mixValues ) { $ data = ToolboxFile :: convertValuesToDatabase ( $ mixValues ? : [ 'bin' => [ ] , 'value' => [ ] , 'path' => [ ] ] ) ; if ( $ this -> get ( 'file_multiple' ) ) { return \ serialize ( $ data ) ; } return $ data [ 0 ] ; }
Take the data from the system and serialize it for the database .
58,550
public function attachCallback ( $ callback , $ type = self :: TASK_COMPLETE ) { if ( ! is_callable ( $ callback ) ) { throw new Exception ( 'Invalid callback specified' ) ; } if ( ! in_array ( $ type , array ( self :: TASK_COMPLETE , self :: TASK_FAIL , self :: TASK_STATUS ) ) ) { throw new Exception ( 'Invalid callback type specified' ) ; } $ this -> callback [ $ type ] [ ] = $ callback ; return $ this ; }
Attach a callback to this task .
58,551
public function complete ( $ result ) { $ this -> finished = true ; $ this -> result = $ result ; if ( ! count ( $ this -> callback [ self :: TASK_COMPLETE ] ) ) { return ; } foreach ( $ this -> callback [ self :: TASK_COMPLETE ] as $ callback ) { call_user_func ( $ callback , $ this -> func , $ this -> handle , $ result ) ; } }
Run the complete callbacks .
58,552
public function fail ( ) { $ this -> finished = true ; if ( ! count ( $ this -> callback [ self :: TASK_FAIL ] ) ) { return ; } foreach ( $ this -> callback [ self :: TASK_FAIL ] as $ callback ) { call_user_func ( $ callback , $ this ) ; } }
Run the failure callbacks .
58,553
public function status ( $ numerator , $ denominator ) { if ( ! count ( $ this -> callback [ self :: TASK_STATUS ] ) ) { return ; } foreach ( $ this -> callback [ self :: TASK_STATUS ] as $ callback ) { call_user_func ( $ callback , $ this -> func , $ this -> handle , $ numerator , $ denominator ) ; } }
Run the status callbacks .
58,554
public function getHash ( $ text = null ) { $ time = time ( ) + $ this -> timeout ; $ textHash = $ this -> getTextHash ( $ text ) ; $ session = $ this -> getSession ( ) ; if ( $ session -> isSessionStarted ( ) ) { $ hash = oxUtilsObject :: getInstance ( ) -> generateUID ( ) ; $ hashArray = $ session -> getVariable ( 'captchaHashes' ) ; $ hashArray [ $ hash ] = array ( $ textHash => $ time ) ; $ session -> setVariable ( 'captchaHashes' , $ hashArray ) ; } else { $ database = DatabaseProvider :: getDb ( ) ; $ query = "insert into oecaptcha (oxhash, oxtime) values (" . $ database -> quote ( $ textHash ) . ", " . $ database -> quote ( $ time ) . ")" ; $ database -> execute ( $ query ) ; $ hash = $ database -> getOne ( 'select LAST_INSERT_ID()' , false , false ) ; } return $ hash ; }
Returns text hash
58,555
public function getTextHash ( $ text ) { if ( ! $ text ) { $ text = $ this -> getText ( ) ; } $ text = strtolower ( $ text ) ; return md5 ( 'ox' . $ text ) ; }
Returns given string captcha hash
58,556
public function getImageUrl ( ) { $ config = \ OxidEsales \ Eshop \ Core \ Registry :: getConfig ( ) ; $ url = $ config -> getCurrentShopUrl ( ) . 'modules/oe/captcha/core/utils/verificationimg.php?e_mac=' ; $ key = $ config -> getConfigParam ( 'oecaptchakey' ) ; $ key = $ key ? $ key : $ config -> getConfigParam ( 'sConfigKey' ) ; $ encryptor = new \ OxidEsales \ Eshop \ Core \ Encryptor ( ) ; $ url .= $ encryptor -> encrypt ( $ this -> getText ( ) , $ key ) ; return $ url ; }
Returns url to CAPTCHA image generator .
58,557
public function passCaptcha ( $ displayError = true ) { $ return = true ; $ mac = $ this -> getConfig ( ) -> getRequestParameter ( 'c_mac' ) ; $ macHash = $ this -> getConfig ( ) -> getRequestParameter ( 'c_mach' ) ; if ( ! $ this -> pass ( $ mac , $ macHash ) ) { $ return = false ; } if ( ! $ return && $ displayError ) { oxRegistry :: get ( 'oxUtilsView' ) -> addErrorToDisplay ( 'MESSAGE_WRONG_VERIFICATION_CODE' ) ; } return $ return ; }
Check if captcha is passed .
58,558
protected function pass ( $ mac , $ macHash ) { $ time = time ( ) ; $ hash = $ this -> getTextHash ( $ mac ) ; $ pass = $ this -> passFromSession ( $ macHash , $ hash , $ time ) ; if ( $ pass === null ) { $ pass = $ this -> passFromDb ( ( int ) $ macHash , $ hash , $ time ) ; } return ( bool ) $ pass ; }
Verifies captcha input vs supplied hash . Returns true on success .
58,559
protected function passFromSession ( $ macHash , $ hash , $ time ) { $ pass = null ; $ session = $ this -> getSession ( ) ; if ( ( $ hashArray = $ session -> getVariable ( 'captchaHashes' ) ) ) { $ pass = ( isset ( $ hashArray [ $ macHash ] [ $ hash ] ) && $ hashArray [ $ macHash ] [ $ hash ] >= $ time ) ? true : false ; unset ( $ hashArray [ $ macHash ] ) ; if ( ! empty ( $ hashArray ) ) { $ session -> setVariable ( 'captchaHashes' , $ hashArray ) ; } else { $ session -> deleteVariable ( 'captchaHashes' ) ; } } return $ pass ; }
Checks for session captcha hash validity
58,560
protected function passFromDb ( $ macHash , $ hash , $ time ) { $ database = DatabaseProvider :: getDb ( ) ; $ where = "where oxid = " . $ database -> quote ( $ macHash ) . " and oxhash = " . $ database -> quote ( $ hash ) ; $ query = "select 1 from oecaptcha " . $ where ; $ pass = ( bool ) $ database -> getOne ( $ query , false , false ) ; if ( $ pass ) { $ query = "delete from oecaptcha " . $ where ; $ database -> execute ( $ query ) ; } $ query = "delete from oecaptcha where oxtime < $time" ; $ database -> execute ( $ query ) ; return $ pass ; }
Checks for DB captcha hash validity
58,561
private function databaseConnect ( ) { $ dsn = 'mysql:host=' . $ this -> db [ 'host' ] . ';port=' . $ this -> db [ 'port' ] . ';dbname=' . $ this -> db [ 'name' ] ; $ options = array ( \ PDO :: MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8' , \ PDO :: ATTR_PERSISTENT => true , \ PDO :: ATTR_ERRMODE => \ PDO :: ERRMODE_EXCEPTION ) ; try { $ this -> dbh = new \ PDO ( $ dsn , $ this -> db [ 'user' ] , $ this -> db [ 'password' ] , $ options ) ; } catch ( \ PDOException $ e ) { exit ( $ e -> getMessage ( ) ) ; } }
Database connection link
58,562
public function addTable ( $ table ) { if ( ! in_array ( $ table , $ this -> tables ) ) { $ this -> tables [ ] = $ table ; } return $ this ; }
Add table name to dump
58,563
public function addTables ( array $ tables ) { if ( is_array ( $ tables ) && count ( $ tables ) > 0 ) { foreach ( $ tables as $ t ) { $ this -> addTable ( $ t ) ; } } return $ this ; }
Dump selected tables
58,564
public function addAllTables ( ) { $ result = $ this -> query ( 'SHOW TABLES' ) ; foreach ( $ result as $ row ) { $ this -> addTable ( $ row [ 0 ] ) ; } return $ this ; }
Dump all tables
58,565
private function download ( ) { header ( 'Content-disposition: attachment; filename="' . $ this -> filename . '.' . $ this -> extension . '"' ) ; header ( 'Content-type: application/octet-stream' ) ; readfile ( $ this -> filename . '.' . $ this -> extension ) ; }
Download the dump file
58,566
private function compress ( ) { switch ( $ this -> compressFormat ) { case 'zip' : if ( class_exists ( '\ZipArchive' ) ) { $ zip = new \ ZipArchive ; if ( $ zip -> open ( $ this -> filename . '.zip' , \ ZipArchive :: CREATE ) === true ) { $ zip -> addFile ( $ this -> filename . '.' . $ this -> extension , basename ( $ this -> filename ) . '.' . $ this -> extension ) ; $ zip -> close ( ) ; $ this -> delete ( ) ; $ this -> extension = 'zip' ; } } else { throw new \ Exception ( '\ZipArchive object does not exists' ) ; } break ; case 'gz' : case 'gzip' : $ content = file_get_contents ( $ this -> filename . '.' . $ this -> extension ) ; file_put_contents ( $ this -> filename . '.sql.gz' , gzencode ( $ content , 9 ) ) ; $ this -> delete ( ) ; $ this -> extension = 'sql.gz' ; break ; } }
Compress the file
58,567
protected function doMatch ( $ actual ) { $ this -> validateActual ( $ actual ) ; if ( $ this -> isDeep ( ) ) { return $ this -> matchDeep ( $ actual ) ; } $ actual = $ this -> actualToArray ( $ actual ) ; return $ this -> matchArrayIndex ( $ actual ) ; }
Matches if the actual value has a property optionally matching the expected value of that property . If the deep flag is set the matcher will use the ObjectPath utility to parse deep expressions .
58,568
protected function matchArrayIndex ( $ actual ) { if ( isset ( $ actual [ $ this -> getKey ( ) ] ) ) { $ this -> assertion -> setActual ( $ actual [ $ this -> getKey ( ) ] ) ; return $ this -> isExpected ( $ actual [ $ this -> getKey ( ) ] ) ; } return false ; }
Match that an array index exists and matches the expected value if set .
58,569
protected function matchDeep ( $ actual ) { $ path = new ObjectPath ( $ actual ) ; $ value = $ path -> get ( $ this -> getKey ( ) ) ; if ( $ value === null ) { return false ; } $ this -> assertion -> setActual ( $ value -> getPropertyValue ( ) ) ; return $ this -> isExpected ( $ value -> getPropertyValue ( ) ) ; }
Uses ObjectPath to parse an expression if the deep flag is set .
58,570
protected function isExpected ( $ value ) { if ( $ expected = $ this -> getValue ( ) ) { $ this -> setActualValue ( $ value ) ; return $ this -> getActualValue ( ) === $ expected ; } return true ; }
Check if the given value is expected .
58,571
protected function getTemplateStrings ( ) { $ default = 'Expected {{actual}} to have a{{deep}}property {{key}}' ; $ negated = 'Expected {{actual}} to not have a{{deep}}property {{key}}' ; if ( $ this -> getValue ( ) && $ this -> isActualValueSet ( ) ) { $ default = 'Expected {{actual}} to have a{{deep}}property {{key}} of {{value}}, but got {{actualValue}}' ; $ negated = 'Expected {{actual}} to not have a{{deep}}property {{key}} of {{value}}' ; } $ deep = ' ' ; if ( $ this -> isDeep ( ) ) { $ deep = ' deep ' ; } return str_replace ( '{{deep}}' , $ deep , [ $ default , $ negated ] ) ; }
Returns the strings used in creating the template for the matcher .
58,572
protected function getTransactionCode ( ) { $ transactionCode = $ this -> transactionCode ; if ( $ this -> getRequireAvsCheck ( ) ) { $ transactionCode += 1 ; } if ( $ this -> getCreateCard ( ) ) { $ transactionCode += 128 ; } return $ transactionCode ; }
Returns the transaction code based on the AVS check requirement
58,573
public function validate ( ) { $ parameters = func_get_args ( ) ; if ( count ( $ parameters ) == 0 ) { $ parameters = [ 'number' , 'cvv' , 'expiryMonth' , 'expiryYear' ] ; } foreach ( $ parameters as $ key ) { $ value = $ this -> parameters -> get ( $ key ) ; if ( empty ( $ value ) ) { throw new InvalidCreditCardException ( "The $key parameter is required" ) ; } } if ( isset ( $ parameters [ 'expiryMonth' ] ) && isset ( $ parameters [ 'expiryYear' ] ) ) { if ( $ this -> getExpiryDate ( 'Ym' ) < gmdate ( 'Ym' ) ) { throw new InvalidCreditCardException ( 'Card has expired' ) ; } } if ( isset ( $ parameters [ 'number' ] ) ) { if ( ! Helper :: validateLuhn ( $ this -> getNumber ( ) ) ) { throw new InvalidCreditCardException ( 'Card number is invalid' ) ; } if ( ! is_null ( $ this -> getNumber ( ) ) && ! preg_match ( '/^\d{12,19}$/i' , $ this -> getNumber ( ) ) ) { throw new InvalidCreditCardException ( 'Card number should have 12 to 19 digits' ) ; } } if ( isset ( $ parameters [ 'cvv' ] ) ) { if ( ! is_null ( $ this -> getCvv ( ) ) && ! preg_match ( '/^\d{3,4}$/i' , $ this -> getCvv ( ) ) ) { throw new InvalidCreditCardException ( 'Card CVV should have 3 to 4 digits' ) ; } } }
Validate this credit card . If the card is invalid InvalidCreditCardException is thrown .
58,574
public function getNumericCountry ( ) { $ country = $ this -> getCountry ( ) ; if ( ! is_null ( $ country ) && ! is_numeric ( $ country ) ) { $ iso3166 = new ISO3166 ( ) ; if ( strlen ( $ country ) == 2 ) { $ country = $ iso3166 -> getByAlpha2 ( $ country ) [ 'numeric' ] ; } elseif ( strlen ( $ country ) == 3 ) { $ country = $ iso3166 -> getByAlpha3 ( $ country ) [ 'numeric' ] ; } else { throw new InvalidRequestException ( "The country parameter must be ISO 3166-1 numeric, aplha2 or alpha3." ) ; } } return $ country ; }
Returns the country as the numeric ISO 3166 - 1 code
58,575
public function requireCheck ( $ requiredCheck ) { if ( ! $ this -> checkRepository -> has ( $ requiredCheck ) ) { throw new InvalidArgumentException ( sprintf ( 'Check: "%s" does not exist' , $ requiredCheck ) ) ; } $ check = $ this -> checkRepository -> getByClass ( $ requiredCheck ) ; if ( $ check instanceof SimpleCheckInterface ) { switch ( $ check -> getPosition ( ) ) { case SimpleCheckInterface :: CHECK_BEFORE : $ this -> checksToRunBefore [ ] = $ check ; break ; case SimpleCheckInterface :: CHECK_AFTER : $ this -> checksToRunAfter [ ] = $ check ; break ; default : throw InvalidArgumentException :: notValidParameter ( 'position' , [ SimpleCheckInterface :: CHECK_BEFORE , SimpleCheckInterface :: CHECK_AFTER ] , $ check -> getPosition ( ) ) ; } return ; } if ( ! $ check instanceof ListenableCheckInterface ) { throw new InvalidArgumentException ( sprintf ( 'Check: "%s" is not a listenable check' , $ requiredCheck ) ) ; } $ check -> attach ( $ this -> eventDispatcher ) ; }
Queue a specific check to be run when the exercise is verified . When the exercise is verified the check specified as the first argument will also be executed . Throws an InvalidArgumentException if the check does not exist in the CheckRepository .
58,576
public function verify ( ExerciseInterface $ exercise , Input $ input ) { $ exercise -> configure ( $ this ) ; $ runner = $ this -> runnerManager -> getRunner ( $ exercise ) ; foreach ( $ runner -> getRequiredChecks ( ) as $ requiredCheck ) { $ this -> requireCheck ( $ requiredCheck ) ; } $ this -> eventDispatcher -> dispatch ( new ExerciseRunnerEvent ( 'verify.start' , $ exercise , $ input ) ) ; $ this -> validateChecks ( $ this -> checksToRunBefore , $ exercise ) ; $ this -> validateChecks ( $ this -> checksToRunAfter , $ exercise ) ; foreach ( $ this -> checksToRunBefore as $ check ) { $ this -> results -> add ( $ check -> check ( $ exercise , $ input ) ) ; if ( ! $ this -> results -> isSuccessful ( ) ) { return $ this -> results ; } } $ this -> eventDispatcher -> dispatch ( new ExerciseRunnerEvent ( 'verify.pre.execute' , $ exercise , $ input ) ) ; try { $ this -> results -> add ( $ runner -> verify ( $ input ) ) ; } finally { $ this -> eventDispatcher -> dispatch ( new ExerciseRunnerEvent ( 'verify.post.execute' , $ exercise , $ input ) ) ; } foreach ( $ this -> checksToRunAfter as $ check ) { $ this -> results -> add ( $ check -> check ( $ exercise , $ input ) ) ; } $ this -> eventDispatcher -> dispatch ( new ExerciseRunnerEvent ( 'verify.post.check' , $ exercise , $ input ) ) ; $ exercise -> tearDown ( ) ; $ this -> eventDispatcher -> dispatch ( new ExerciseRunnerEvent ( 'verify.finish' , $ exercise , $ input ) ) ; return $ this -> results ; }
Verify a students solution against a specific exercise . Runs queued checks based on their position . Invokes the correct runner for the exercise based on the exercise type . Various events are triggered throughout the process .
58,577
public function run ( ExerciseInterface $ exercise , Input $ input , OutputInterface $ output ) { $ exercise -> configure ( $ this ) ; $ this -> eventDispatcher -> dispatch ( new ExerciseRunnerEvent ( 'run.start' , $ exercise , $ input ) ) ; try { $ exitStatus = $ this -> runnerManager -> getRunner ( $ exercise ) -> run ( $ input , $ output ) ; } finally { $ this -> eventDispatcher -> dispatch ( new ExerciseRunnerEvent ( 'run.finish' , $ exercise , $ input ) ) ; } return $ exitStatus ; }
Run a student s solution against a specific exercise . Does not invoke checks . Invokes the correct runner for the exercise based on the exercise type . Various events are triggered throughout the process . The output of the solution is written directly to the OutputInterface instance .
58,578
public function request ( callable $ fn , array $ arguments = [ ] ) { $ result = call_user_func_array ( $ fn , $ arguments ) ; if ( $ result instanceof MatcherInterface ) { return $ this -> assert ( $ result ) ; } return $ result ; }
A request to an Assertion will attempt to resolve the result as an assertion before returning the result .
58,579
public function assert ( MatcherInterface $ matcher ) { if ( $ this -> flag ( 'not' ) ) { $ matcher -> invert ( ) ; } $ match = $ matcher -> setAssertion ( $ this ) -> match ( $ this -> getActual ( ) ) ; $ message = $ this -> flag ( 'message' ) ; $ this -> clearFlags ( ) ; $ this -> responder -> respond ( $ match , $ matcher -> getTemplate ( ) , $ message ) ; return $ this ; }
Assert against the given matcher .
58,580
public function serialize ( UserState $ state ) { $ saveFile = sprintf ( '%s/%s' , $ this -> path , static :: SAVE_FILE ) ; $ data = file_exists ( $ saveFile ) ? $ this -> readJson ( $ saveFile ) : [ ] ; $ data [ $ this -> workshopName ] = [ 'completed_exercises' => $ state -> getCompletedExercises ( ) , 'current_exercise' => $ state -> getCurrentExercise ( ) , ] ; return file_put_contents ( $ saveFile , json_encode ( $ data ) ) ; }
Save the students state for this workshop to disk .
58,581
public function deSerialize ( ) { $ legacySaveFile = sprintf ( '%s/%s' , $ this -> path , static :: LEGACY_SAVE_FILE ) ; if ( file_exists ( $ legacySaveFile ) ) { $ userState = $ this -> migrateData ( $ legacySaveFile ) ; if ( $ userState instanceof UserState ) { return $ userState ; } } $ json = $ this -> readJson ( sprintf ( '%s/%s' , $ this -> path , static :: SAVE_FILE ) ) ; if ( null === $ json ) { $ this -> wipeFile ( ) ; return new UserState ( ) ; } if ( ! isset ( $ json [ $ this -> workshopName ] ) ) { return new UserState ( ) ; } $ json = $ json [ $ this -> workshopName ] ; if ( ! array_key_exists ( 'completed_exercises' , $ json ) ) { return new UserState ( ) ; } if ( ! array_key_exists ( 'current_exercise' , $ json ) ) { return new UserState ( ) ; } if ( ! is_array ( $ json [ 'completed_exercises' ] ) ) { $ json [ 'completed_exercises' ] = [ ] ; } foreach ( $ json [ 'completed_exercises' ] as $ i => $ exercise ) { if ( ! is_string ( $ exercise ) ) { unset ( $ json [ 'completed_exercises' ] [ $ i ] ) ; } } if ( null !== $ json [ 'current_exercise' ] && ! is_string ( $ json [ 'current_exercise' ] ) ) { $ json [ 'current_exercise' ] = null ; } return new UserState ( $ json [ 'completed_exercises' ] , $ json [ 'current_exercise' ] ) ; }
Read a students state for this workshop from the disk .
58,582
private function migrateData ( $ legacySaveFile ) { $ data = $ this -> readJson ( $ legacySaveFile ) ; if ( null === $ data ) { unlink ( $ legacySaveFile ) ; return null ; } if ( ! isset ( $ data [ 'completed_exercises' ] ) || ! isset ( $ data [ 'current_exercise' ] ) ) { unlink ( $ legacySaveFile ) ; return null ; } $ completedExercises = $ data [ 'completed_exercises' ] ; $ availableExercises = $ this -> exerciseRepository -> getAllNames ( ) ; foreach ( $ completedExercises as $ completedExercise ) { if ( ! in_array ( $ completedExercise , $ availableExercises ) ) { return null ; } } $ userState = new UserState ( $ data [ 'completed_exercises' ] , $ data [ 'current_exercise' ] ) ; $ this -> serialize ( $ userState ) ; unlink ( $ legacySaveFile ) ; return $ userState ; }
On early versions of the workshop the save data was not namespaced and therefore it was impossible to have data for more than one workshop at the same time . Therefore we must try to migrate that data in to the new namespaced format in order to preserve users save data .
58,583
protected function doMatch ( $ actual ) { if ( ! is_string ( $ actual ) ) { throw new \ InvalidArgumentException ( 'SubStringMatcher requires string value' ) ; } return strpos ( $ actual , $ this -> expected ) !== false ; }
Match that actual value has the expected sub string .
58,584
public function getMessage ( ) { return isset ( $ this -> data [ 'ErrorMsg' ] ) && ! empty ( $ this -> data [ 'ErrorMsg' ] ) ? $ this -> data [ 'ErrorMsg' ] : null ; }
Return the response s reason message
58,585
public function match ( $ actual ) { $ this -> validateCallable ( $ actual ) ; list ( $ exception , $ message ) = $ this -> callableException ( $ actual ) ; $ this -> setMessage ( $ message ) ; return $ this -> matchMessage ( $ actual , $ exception , $ message ) ; }
Executes the callable and matches the exception type and exception message .
58,586
public function set ( $ key , $ value ) { return $ this -> memcache -> set ( $ key , $ value , 0 , $ this -> lifetime ) ; }
adds a cache key for a specific lifetime into the cache
58,587
public function isSuccessful ( ) { return count ( array_filter ( $ this -> results , function ( $ result ) { if ( $ result instanceof ResultGroupInterface ) { return ! $ result -> isSuccessful ( ) ; } return $ result instanceof FailureInterface ; } ) ) === 0 ; }
Computes whether the results are considered a success . If there are any results which implement FailureInterface then the combined result is considered as a fail .
58,588
public function getCount ( ) { if ( is_string ( $ this -> countable ) ) { return strlen ( $ this -> countable ) ; } return count ( $ this -> countable ) ; }
Get the count of the countable value .
58,589
protected function map ( $ mapping , \ SimpleXMLElement $ xml , $ objekt ) { foreach ( $ mapping as $ key ) { if ( isset ( $ xml -> $ key ) ) { $ setter = $ this -> mapper -> getSetter ( $ key ) ; $ objekt -> $ setter ( $ this -> cast ( $ xml -> $ key , $ this -> mapper -> getType ( $ key ) ) ) ; } } }
maps an mapping array between a SimpleXML and Objekt
58,590
protected function cast ( \ SimpleXMLElement $ xml , $ type = 'string' ) { switch ( $ type ) { case 'string' : return ( string ) $ xml ; case 'int' : return ( int ) $ xml ; case 'double' : return ( double ) $ xml ; case 'boolean' : return ( bool ) ( ( string ) $ xml ) ; case 'datetime' : $ date = ( string ) $ xml ; if ( empty ( $ date ) ) { return null ; } return new \ DateTime ( $ date ) ; default : return $ xml ; } }
casts a simple xml element to a type
58,591
public function canRun ( ExerciseType $ exerciseType ) { return in_array ( $ exerciseType -> getValue ( ) , [ ExerciseType :: CGI , ExerciseType :: CLI ] ) ; }
This check can run on any exercise type .
58,592
protected function getTemplateVars ( TemplateInterface $ template ) { $ vars = [ 'expected' => $ this -> match -> getExpected ( ) , 'actual' => $ this -> match -> getActual ( ) , ] ; if ( $ tplVars = $ template -> getTemplateVars ( ) ) { $ vars = array_merge ( $ vars , $ tplVars ) ; } return $ vars ; }
Applies match results to other template variables .
58,593
public function getParameter ( $ name ) { if ( ! array_key_exists ( $ name , $ this -> parameters ) ) { throw new InvalidArgumentException ( sprintf ( 'Parameter: "%s" does not exist' , $ name ) ) ; } return $ this -> parameters [ $ name ] ; }
Get a parameter by it s name .
58,594
public static function fromCheckAndExercise ( CheckInterface $ check , ExerciseInterface $ exercise ) { return new static ( sprintf ( 'Check: "%s" cannot process exercise: "%s" with type: "%s"' , $ check -> getName ( ) , $ exercise -> getName ( ) , $ exercise -> getType ( ) ) ) ; }
Static constructor to create an instance from the check & exercise .
58,595
public function patch ( ExerciseInterface $ exercise , $ code ) { if ( null !== $ this -> defaultPatch ) { $ code = $ this -> applyPatch ( $ this -> defaultPatch , $ code ) ; } if ( $ exercise instanceof SubmissionPatchable ) { $ code = $ this -> applyPatch ( $ exercise -> getPatch ( ) , $ code ) ; } return $ code ; }
Accepts an exercise and a string containing the students solution to the exercise .
58,596
public function check ( ExerciseInterface $ exercise , Input $ input ) { if ( ! $ exercise instanceof FunctionRequirementsExerciseCheck ) { throw new \ InvalidArgumentException ; } $ requiredFunctions = $ exercise -> getRequiredFunctions ( ) ; $ bannedFunctions = $ exercise -> getBannedFunctions ( ) ; $ code = file_get_contents ( $ input -> getArgument ( 'program' ) ) ; try { $ ast = $ this -> parser -> parse ( $ code ) ; } catch ( Error $ e ) { return Failure :: fromCheckAndCodeParseFailure ( $ this , $ e , $ input -> getArgument ( 'program' ) ) ; } $ visitor = new FunctionVisitor ( $ requiredFunctions , $ bannedFunctions ) ; $ traverser = new NodeTraverser ; $ traverser -> addVisitor ( $ visitor ) ; $ traverser -> traverse ( $ ast ) ; $ bannedFunctions = [ ] ; if ( $ visitor -> hasUsedBannedFunctions ( ) ) { $ bannedFunctions = array_map ( function ( FuncCall $ node ) { return [ 'function' => $ node -> name -> __toString ( ) , 'line' => $ node -> getLine ( ) ] ; } , $ visitor -> getBannedUsages ( ) ) ; } $ missingFunctions = [ ] ; if ( ! $ visitor -> hasMetFunctionRequirements ( ) ) { $ missingFunctions = $ visitor -> getMissingRequirements ( ) ; } if ( ! empty ( $ bannedFunctions ) || ! empty ( $ missingFunctions ) ) { return new FunctionRequirementsFailure ( $ this , $ bannedFunctions , $ missingFunctions ) ; } return Success :: fromCheck ( $ this ) ; }
Parse the students solution and check that there are usages of required functions and that banned functions are not used . The requirements are pulled from the exercise .
58,597
private function createDocumentFieldsTables ( ) : void { $ this -> createDocumentFieldsTable ( Types :: TEXT , 'text' ) ; $ this -> createDocumentFieldsTable ( Types :: KEYWORD , 'text' ) ; $ this -> createDocumentFieldsTable ( TYPES :: FLOAT , 'float' ) ; $ this -> createDocumentFieldsTable ( TYPES :: INTEGER , 'bigint' ) ; $ this -> createDocumentFieldsTable ( Types :: DATE , 'datetime' ) ; $ this -> createDocumentFieldsTable ( Types :: BOOLEAN , 'boolean' ) ; }
Create table per mapping type .
58,598
private function _compareMac ( $ a , $ b ) { $ result = "\x00" ; for ( $ i = 0 ; $ i < $ this -> _macByteCount ; $ i ++ ) { $ result |= substr ( $ a , $ i , 1 ) ^ substr ( $ b , $ i , 1 ) ; } return ( $ result === "\x00" ) ; }
Constant - time comparison function
58,599
public function run ( Input $ input , OutputInterface $ output ) { $ message = 'Nothing to run here. This exercise does not require a code solution, ' ; $ message .= 'so there is nothing to execute.' ; $ output -> writeLine ( $ message ) ; return true ; }
Running a custom verifying exercise does nothing . There is no program required therefore there is nothing to run .