idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
47,800
private static function sendHeader ( $ key , $ value ) { if ( isset ( self :: $ send_header ) ) { call_user_func ( self :: $ send_header , $ key , $ value ) ; } else { header ( sprintf ( "%s: %s" , $ key , $ value ) ) ; } }
SendHeader hook used for testing .
47,801
private static function getUploadMaxFileSizeInBytes ( ) { $ val = trim ( ini_get ( 'upload_max_filesize' ) ) ; $ unit = strtolower ( substr ( $ val , - 1 ) ) ; switch ( $ unit ) { case 'g' : $ val *= 1024 ; case 'm' : $ val *= 1024 ; case 'k' : $ val *= 1024 ; break ; } return intval ( $ val ) ; }
Convert the upload_max_filesize ini setting to a number of bytes .
47,802
public function rewind ( ) { if ( $ this -> response !== null ) { if ( isset ( $ this -> origin ) ) { $ this -> request -> getOffset ( ) -> copyFrom ( $ this -> origin ) ; } else { $ this -> request -> clearOffset ( ) ; } } $ this -> current = null ; $ this -> response = null ; $ this -> position = 0 ; }
Reset to initial state . Called at start of foreach statement .
47,803
public function delete ( ) { $ token_header = $ this -> getOAuthTokenHeader ( parent :: WRITE_SCOPE ) ; if ( $ token_header === false ) { trigger_error ( "Unable to acquire OAuth token." , E_USER_WARNING ) ; return false ; } $ http_response = $ this -> makeHttpRequest ( $ this -> url , "DELETE" , $ token_header ) ; if ( $ http_response === false ) { return false ; } clearstatcache ( true , $ this -> filename ) ; if ( $ http_response [ 'status_code' ] === HttpResponse :: NO_CONTENT ) { return true ; } else { trigger_error ( $ this -> getErrorMessage ( $ http_response [ 'status_code' ] , $ http_response [ 'body' ] ) , E_USER_WARNING ) ; } return false ; }
Delete the object from the Cloud Storage Bucket .
47,804
public function get8 ( ) { if ( $ this -> idx >= $ this -> limit ) { throw new ProtocolBufferDecodeError ( "truncated" ) ; } $ c = unpack ( "C*" , substr ( $ this -> buf , $ this -> idx , 1 ) ) ; $ this -> idx += 1 ; return $ c [ 1 ] ; }
these are all unsigned gets
47,805
public function addAttachment ( $ filename , $ data , $ content_id = null ) { $ this -> addAttachmentsArray ( [ [ "name" => $ filename , "data" => $ data , "content_id" => $ content_id ] ] ) ; }
Adds an attachment to the Message object .
47,806
public function addHeader ( $ key , $ value ) { if ( ! is_string ( $ key ) ) { $ error = sprintf ( "Header key is not a string (Actual type: %s)." , gettype ( $ key ) ) ; throw new \ InvalidArgumentException ( $ error ) ; } $ this -> addHeaderArray ( array ( $ key => $ value ) ) ; }
Adds a header pair to the mail object .
47,807
public function addHeaderArray ( $ header_array ) { if ( ! is_array ( $ header_array ) ) { $ error = sprintf ( "Input is not an array (Actual type: %s)." , gettype ( $ header_array ) ) ; throw new \ InvalidArgumentException ( $ error ) ; } $ error = "" ; foreach ( $ header_array as $ key => $ value ) { if ( ! $ this -> checkValidHeader ( $ key , $ value , $ error ) ) { throw new \ InvalidArgumentException ( $ error ) ; } } foreach ( $ header_array as $ key => $ value ) { $ new_header = $ this -> message -> addHeader ( ) ; $ new_header -> setName ( $ key ) ; $ new_header -> setValue ( $ value ) ; } }
Adds an array of headers to the mail object .
47,808
protected function checkValidAttachment ( $ filename , & $ error ) { if ( ! is_string ( $ filename ) ) { $ error = sprintf ( "Filename must be a string but was type %s" , gettype ( $ filename ) ) ; return false ; } $ path_parts = pathinfo ( $ filename ) ; if ( isset ( $ path_parts [ 'extension' ] ) ) { if ( in_array ( $ path_parts [ 'extension' ] , self :: $ extension_blacklist ) ) { $ error = sprintf ( "'%s' is a blacklisted file extension." , $ path_parts [ 'extension' ] ) ; return false ; } } return true ; }
Checks that an attachment is valid .
47,809
protected function checkValidEmail ( $ email ) { if ( function_exists ( 'mailparse_rfc822_parse_addresses' ) ) { $ parsed = mailparse_rfc822_parse_addresses ( $ email ) ; if ( count ( $ parsed ) > 0 && array_key_exists ( 'address' , $ parsed [ 0 ] ) ) { $ email = $ parsed [ 0 ] [ 'address' ] ; } else { return false ; } } return filter_var ( $ email , FILTER_VALIDATE_EMAIL ) !== false ; }
Checks that an email is valid using the mailparse extension if available .
47,810
protected function checkValidHeader ( $ key , $ value , & $ error ) { if ( ! is_string ( $ key ) ) { $ error = sprintf ( "Header key is not a string (Actual type: %s)." , gettype ( $ key ) ) ; return false ; } else if ( ! in_array ( strtolower ( $ key ) , self :: $ allowed_headers ) ) { $ error = sprintf ( "Input header '%s: %s' is not whitelisted for use with" . " the Google App Engine Mail Service." , htmlspecialchars ( $ key ) , htmlspecialchars ( $ value ) ) ; return false ; } return true ; }
Check validity of a header pair .
47,811
protected function handleApplicationError ( $ e ) { switch ( $ e -> getApplicationError ( ) ) { case ErrorCode :: INTERNAL_ERROR : case ErrorCode :: BAD_REQUEST : throw new \ RuntimeException ( "Mail Service Error: " . $ e -> getMessage ( ) ) ; case ErrorCode :: UNAUTHORIZED_SENDER : $ error = sprintf ( "Mail Service Error: Sender (%s) is not an " . "authorized email address." , htmlspecialchars ( $ this -> message -> getSender ( ) ) ) ; throw new \ InvalidArgumentException ( $ error ) ; case ErrorCode :: INVALID_ATTACHMENT_TYPE : throw new \ InvalidArgumentException ( "Mail Service Error: Invalid attachment type." ) ; case ErrorCode :: INVALID_HEADER_NAME : throw new \ InvalidArgumentException ( "Mail Service Error: Invalid header name." ) ; default : throw $ e ; } }
Handles application errors generated by the RPC call .
47,812
public function setHtmlBody ( $ text ) { if ( ! is_string ( $ text ) ) { $ error = sprintf ( "HTML text given is not a string (Actual type: %s)." , gettype ( $ text ) ) ; throw new \ InvalidArgumentException ( $ error ) ; } $ this -> message -> setHtmlbody ( $ text ) ; }
Sets HTML content for the email body .
47,813
public function setReplyTo ( $ email ) { if ( ! $ this -> checkValidEmail ( $ email ) ) { throw new \ InvalidArgumentException ( "Invalid reply-to: " . htmlspecialchars ( $ email ) ) ; } $ this -> message -> setReplyto ( $ email ) ; }
Sets a reply - to address for the mail object .
47,814
public function setSender ( $ email ) { if ( ! $ this -> checkValidEmail ( $ email ) ) { throw new \ InvalidArgumentException ( "Invalid sender: " . htmlspecialchars ( $ email ) ) ; } $ this -> message -> setSender ( $ email ) ; }
Sets the sender for the mail object .
47,815
public function setSubject ( $ subject ) { if ( ! is_string ( $ subject ) ) { $ error = sprintf ( "Subject given is not a string (Actual type: %s)." , gettype ( $ subject ) ) ; throw new \ InvalidArgumentException ( $ error ) ; } $ this -> message -> setSubject ( $ subject ) ; }
Sets the subject for the mail object .
47,816
public function setTextBody ( $ text ) { if ( ! is_string ( $ text ) ) { $ error = sprintf ( "Plain text given is not a string (Actual type: %s)." , gettype ( $ text ) ) ; throw new \ InvalidArgumentException ( $ error ) ; } $ this -> message -> setTextbody ( $ text ) ; }
Sets plain text for the email body .
47,817
protected function getOAuthTokenHeader ( $ scopes ) { if ( $ this -> anonymous ) { return [ ] ; } try { $ token = AppIdentityService :: getAccessToken ( $ scopes ) ; return [ "Authorization" => sprintf ( self :: OAUTH_TOKEN_FORMAT , $ token [ 'access_token' ] ) ] ; } catch ( AppIdentityException $ e ) { return false ; } }
Get the OAuth Token HTTP header for the supplied scope .
47,818
protected static function createGcsFilename ( $ bucket , $ object = null ) { if ( ! isset ( $ object ) ) { $ object = "" ; } if ( StringUtil :: startsWith ( $ object , "/" ) ) { $ object = substr ( $ object , 1 ) ; } return CloudStorageTools :: getFilename ( $ bucket , $ object ) ; }
Create a GCS filename for a target bucket and optional object .
47,819
public static function createObjectUrl ( $ bucket , $ object = null ) { $ gs_filename = self :: createGcsFilename ( $ bucket , $ object ) ; return CloudStorageTools :: getPublicUrl ( $ gs_filename , true ) ; }
Create a URL for a target bucket and optional object .
47,820
public static function clearStatCache ( $ filename = null ) { if ( ! empty ( $ filename ) ) { unset ( self :: $ stat_cache [ self :: getHashValue ( $ filename ) ] ) ; } else { self :: $ stat_cache = [ ] ; } }
Clear the stat cache .
47,821
protected function tryGetFromStatCache ( & $ stat_result ) { if ( ! $ this -> hash_value ) { $ this -> hash_value = self :: getHashValue ( $ this -> filename ) ; } if ( array_key_exists ( $ this -> hash_value , self :: $ stat_cache ) ) { $ stat_result = self :: $ stat_cache [ $ this -> hash_value ] ; return true ; } return false ; }
Try and retrieve a stat result from the stat cache .
47,822
protected function addToStatCache ( $ stat_result ) { if ( ! $ this -> hash_value ) { $ this -> hash_value = self :: getHashValue ( $ this -> filename ) ; } self :: $ stat_cache [ $ this -> hash_value ] = $ stat_result ; }
Add a stat result from the stat cache .
47,823
protected function makeHttpRequest ( $ url , $ method , $ headers , $ body = null ) { $ request_headers = array_merge ( $ headers , self :: $ api_version_header ) ; $ result = $ this -> doHttpRequest ( $ url , $ method , $ request_headers , $ body ) ; if ( $ result === false ) { return false ; } return [ 'status_code' => $ result [ 'status_code' ] , 'headers' => $ result [ 'headers' ] , 'body' => $ result [ 'body' ] , ] ; }
Make a request to GCS using HttpStreams .
47,824
protected function getHeaderValue ( $ header_name , $ headers ) { foreach ( $ headers as $ key => $ value ) { if ( strcasecmp ( $ key , $ header_name ) === 0 ) { return $ value ; } } return null ; }
Return the value of a header stored in an associative array using a case insensitive comparison on the header name .
47,825
protected static function extractMetaData ( array $ headers ) { $ metadata = [ ] ; foreach ( $ headers as $ key => $ value ) { if ( StringUtil :: startsWith ( strtolower ( $ key ) , static :: METADATA_HEADER_PREFIX ) ) { $ metadata_key = substr ( $ key , strlen ( static :: METADATA_HEADER_PREFIX ) ) ; $ metadata [ $ metadata_key ] = $ value ; } } return $ metadata ; }
Extract metadata from HTTP response headers .
47,826
protected function getErrorMessage ( $ http_status_code , $ http_result , $ msg_prefix = "Cloud Storage Error:" ) { if ( $ this -> tryParseCloudStorageErrorMessage ( $ http_result , $ code , $ message ) ) { return sprintf ( "%s %s (%s)" , $ msg_prefix , $ message , $ code ) ; } else { return sprintf ( "%s %s" , $ msg_prefix , HttpResponse :: getStatusMessage ( $ http_status_code ) ) ; } }
Return a formatted error message for the http response .
47,827
public static function getReadMemcacheKey ( $ url , $ range ) { $ key = sprintf ( self :: MEMCACHE_KEY_FORMAT , $ url , $ range ) ; if ( strlen ( $ key ) > self :: MEMCACHE_KEY_MAX_LENGTH ) { $ hash = hash ( "ripemd256" , $ key ) ; $ key = sprintf ( self :: MEMCACHE_KEY_HASH_FORMAT , $ hash ) ; } return $ key ; }
Create a memcache key for the read data cache . If the filename is long enough that the key would exceed memcache limits then a hash of the filename and the range is used to generate the key .
47,828
public function getNickname ( ) { if ( $ this -> email != null && $ this -> auth_domain != null && StringUtil :: endsWith ( $ this -> email , '@' . $ this -> auth_domain ) ) { $ suffixLen = strlen ( $ this -> auth_domain ) + 1 ; return substr ( $ this -> email , 0 , - $ suffixLen ) ; } else if ( $ this -> federated_identity ) { return $ this -> federated_identity ; } else { return $ this -> email ; } }
Return this user s nickname .
47,829
public function setOptionsArray ( $ options ) { foreach ( $ options as $ key => $ value ) { if ( ! $ this -> setOption ( $ key , $ value ) ) { return false ; } } return true ; }
Set cURL options using an array .
47,830
public function exec ( ) { if ( ! $ this -> prepareRequest ( ) ) { return false ; } $ this -> response = new \ google \ appengine \ URLFetchResponse ( ) ; try { ApiProxy :: makeSyncCall ( 'urlfetch' , 'Fetch' , $ this -> request , $ this -> response ) ; } catch ( ApplicationError $ e ) { $ error_number = $ e -> getApplicationError ( ) ; $ curl_error_number = static :: $ urlfetch_curl_error_map [ $ error_number ] ; $ error_message = static :: $ curle_error_code_str_map [ $ curl_error_number ] ; static :: log ( LOG_ERR , sprintf ( 'Call to URLFetch failed with application error %d ' . '(%s) for url %s.' , $ error_number , $ error_message , $ this -> request -> getUrl ( ) ) ) ; $ this -> setCurlErrorFromUrlFetchError ( $ e -> getApplicationError ( ) , $ e -> getMessage ( ) ) ; return false ; } $ response = $ this -> prepareResponse ( ) ; $ this -> info = self :: $ default_getinfo_values ; $ this -> prepareCurlInfo ( ) ; if ( $ this -> tryGetOption ( CURLOPT_RETURNTRANSFER , $ value ) && $ value ) { return $ response ; } else if ( $ this -> tryGetOption ( CURLOPT_FILE , $ value ) && $ value ) { $ length = fwrite ( $ value , $ response ) ; return ( $ length === strlen ( $ response ) ) ; } else if ( $ this -> tryGetOption ( CURLOPT_WRITEFUNCTION , $ cb ) && $ cb ) { $ response_len = strlen ( $ response ) ; do { $ response_len -= $ cb ( $ this , $ response ) ; } while ( $ response_len > 0 ) ; } else { echo $ response ; } return true ; }
Execute a curl request .
47,831
private function setRequestUrl ( ) { if ( $ this -> tryGetOption ( CURLOPT_URL , $ value ) && $ value ) { if ( static :: isSupportedUrlScheme ( $ value , $ scheme ) ) { $ this -> request -> setUrl ( $ value ) ; return true ; } else { $ this -> setError ( CURLE_UNSUPPORTED_PROTOCOL , sprintf ( "Unsupported protocol '%s'" , $ scheme ) ) ; } } else { $ this -> setError ( CURLE_URL_MALFORMAT , "No URL set!" ) ; } return false ; }
Configure the request URL .
47,832
private static function isSupportedUrlScheme ( $ url , & $ scheme ) { $ scheme = parse_url ( $ url , PHP_URL_SCHEME ) ; return ( is_null ( $ scheme ) || in_array ( $ scheme , static :: $ supported_url_schemes ) ) ; }
Check if a URL scheme is supported by the CurlLite client .
47,833
private function setOption ( $ key , $ value ) { switch ( $ key ) { case CURLOPT_FOLLOWLOCATION : $ this -> request -> setFollowRedirects ( $ value ) ; break ; case CURLOPT_HTTPGET : $ this -> request -> setMethod ( RequestMethod :: GET ) ; break ; case CURLOPT_NOBODY : $ this -> request -> setMethod ( RequestMethod :: HEAD ) ; break ; case CURLOPT_POST : $ this -> request -> setMethod ( RequestMethod :: POST ) ; break ; case CURLOPT_PUT : $ this -> request -> setMethod ( RequestMethod :: PUT ) ; break ; case CURLOPT_SSL_VERIFYPEER : $ this -> request -> setMustValidateServerCertificate ( $ value ) ; break ; case CURLOPT_TIMEOUT : $ this -> request -> setDeadline ( $ value ) ; break ; case CURLOPT_TIMEOUT_MS : $ this -> request -> setDeadline ( $ value * 1000 ) ; break ; case CURLOPT_CUSTOMREQUEST : if ( ! in_array ( $ value , array_keys ( static :: $ custom_request_map ) ) ) { throw new CurlLiteOptionNotSupportedException ( 'Custom request ' . $ value . ' not supported by this curl ' . 'implementation.' ) ; } $ this -> request -> setMethod ( static :: $ custom_request_map [ $ value ] ) ; break ; case CURLOPT_RANGE : $ this -> headers [ 'Range' ] = $ value ; break ; case CURLOPT_REFERER : $ this -> headers [ 'Referer' ] = $ value ; $ break ; case CURLOPT_URL : $ this -> setRequestUrl ( $ value ) ; break ; case CURLOPT_USERAGENT : $ this -> headers [ 'User-Agent' ] = $ value ; break ; case CURLOPT_COOKIE : $ this -> headers [ 'Cookie' ] = $ value ; break ; case CURLOPT_HTTPHEADER : $ this -> headers = ArrayUtil :: arrayMergeIgnoreCase ( $ this -> headers , $ this -> parseHttpHeaders ( $ value ) ) ; break ; case CURLOPT_COOKIESESSION : case CURLOPT_CERTINFO : case CURLOPT_CONNECT_ONLY : case CURLOPT_FTP_USE_EPRT : case CURLOPT_FTP_USE_EPSV : case CURLOPT_FTP_CREATE_MISSING_DIRS : case CURLOPT_FTPAPPEND : case CURLOPT_FTPLISTONLY : case CURLOPT_HTTPPROXYTUNNEL : case CURLOPT_NETRC : case CURLOPT_NOSIGNAL : case CURLOPT_SAFE_UPLOAD : case CURLOPT_TRANSFERTEXT : case CURLOPT_FTPSSLAUTH : case CURLOPT_TIMEVALUE : case CURLOPT_CAINFO : case CURLOPT_COOKIEJAR : case CURLOPT_FTPPORT : case CURLOPT_KEYPASSWD : case CURLOPT_KRB4LEVEL : case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 : case CURLOPT_SSH_PUBLIC_KEYFILE : case CURLOPT_SSH_PRIVATE_KEYFILE : case CURLOPT_SSLCERT : case CURLOPT_SSLCERTPASSWD : case CURLOPT_SSLCERTTYPE : case CURLOPT_SSLENGINE : case CURLOPT_SSLENGINE_DEFAULT : case CURLOPT_SSLKEY : case CURLOPT_SSLKEYPASSWD : case CURLOPT_SSLKEYTYPE : case CURLOPT_POSTQUOTE : case CURLOPT_QUOTE : case CURLOPT_PROGRESSFUNCTION : case CURLOPT_SHARE : throw new CurlLiteOptionNotSupportedException ( 'Option ' . $ key . ' is not supported by this curl implementation.' ) ; default : } $ this -> options [ $ key ] = $ value ; return true ; }
Set a curl option for the request .
47,834
private function prepareResponse ( ) { if ( is_null ( $ this -> response ) ) { return false ; } $ response = "" ; $ this -> response_header_block = $ this -> extractHeadersFromResponse ( ) ; if ( $ this -> tryGetOption ( CURLOPT_HEADER , $ value ) && $ value ) { $ response .= $ this -> response_header_block ; } $ response .= $ this -> response -> getContent ( ) ; return $ response ; }
Prepare the response from the URLFetch request ready for delivery to the caller .
47,835
private function tryGetOption ( $ name , & $ value ) { if ( array_key_exists ( $ name , $ this -> options ) ) { $ value = $ this -> options [ $ name ] ; return true ; } return false ; }
Try and get a cURL option from the options array .
47,836
private function setCurlErrorFromUrlFetchError ( $ urlfetch_error , $ urlfetch_message ) { if ( array_key_exists ( $ urlfetch_error , self :: $ urlfetch_curl_error_map ) ) { $ this -> setError ( self :: $ urlfetch_curl_error_map [ $ urlfetch_error ] , $ urlfetch_message ) ; } else { $ this -> setError ( - 1 , $ urlfetch_message ) ; } }
Convert a URLFetch error code to a cURL error number with message .
47,837
private function extractHeadersFromResponse ( ) { $ response = "" ; $ code = $ this -> response -> getStatusCode ( ) ; $ text = HttpUtil :: getResponseTextForCode ( $ code ) ; $ response .= sprintf ( self :: STATUS_LINE_FORMAT , $ code , $ text ) ; foreach ( $ this -> response -> getHeaderList ( ) as $ header ) { $ response .= sprintf ( "%s: %s%s" , $ header -> getKey ( ) , $ header -> getValue ( ) , self :: CRLF ) ; } $ response .= self :: CRLF ; return $ response ; }
Create the header body from the URLFetch response .
47,838
public static function log ( $ severity , $ message ) { if ( ! is_int ( $ severity ) ) { throw new \ InvalidArgumentException ( 'Parameter $severity must be integer but was ' . self :: typeOrClass ( $ severity ) ) ; } if ( $ severity < self :: LEVEL_DEBUG || $ severity > self :: LEVEL_CRITICAL ) { throw new \ InvalidArgumentException ( 'Invalid severity level ' . $ severity ) ; } if ( ! is_string ( $ message ) ) { throw new \ InvalidArgumentException ( 'Parameter $message must be string but was ' . self :: typeOrClass ( $ message ) ) ; } if ( ! isset ( self :: $ app_log_group ) ) { self :: $ app_log_group = new UserAppLogGroup ( ) ; } $ app_log_line = self :: $ app_log_group -> addLogLine ( ) ; $ app_log_line -> setTimestampUsec ( intval ( microtime ( true ) * 1e6 ) ) ; $ app_log_line -> setLevel ( $ severity ) ; $ app_log_line -> setMessage ( $ message ) ; if ( function_exists ( '_gae_stderr_log' ) ) { _gae_stderr_log ( $ severity , $ message ) ; } self :: flushIfNeeded ( ) ; }
Add an app log at a particular Google App Engine severity level .
47,839
public static function flush ( ) { if ( isset ( self :: $ app_log_group ) ) { $ req = new FlushRequest ( ) ; $ req -> setLogs ( self :: $ app_log_group -> serializeToString ( ) ) ; $ resp = new VoidProto ( ) ; ApiProxy :: makeSyncCall ( 'logservice' , 'Flush' , $ req , $ resp ) ; self :: $ app_log_group -> clear ( ) ; self :: $ last_flush_time = microtime ( true ) ; } }
Write all buffered log messages to the log storage . Logs may not be immediately available to read .
47,840
public static function setAutoFlushEntries ( $ entries ) { if ( ! is_int ( $ entries ) ) { throw new \ InvalidArgumentException ( 'Entries must be an integer but was ' . self :: typeOrClass ( $ entries ) ) ; } self :: $ auto_flush_entries = $ entries ; }
Set the maximum number of log entries to buffer before they are automaticallly flushed upon adding the next log entry .
47,841
public static function setAutoFlushBytes ( $ bytes ) { if ( ! is_int ( $ bytes ) ) { throw new \ InvalidArgumentException ( 'Bytes must be an integer but was ' . self :: typeOrClass ( $ bytes ) ) ; } self :: $ auto_flush_bytes = $ bytes ; }
Sets the maximum size of logs to buffer before they are automaticallly flushed upon adding the next log entry .
47,842
public static function setLogFlushTimeLimit ( $ seconds ) { if ( ! is_int ( $ seconds ) ) { throw new \ InvalidArgumentException ( 'Seconds must be an integer but was ' . self :: typeOrClass ( $ seconds ) ) ; } self :: $ flush_time_limit = $ seconds ; }
Sets the maximum amount of time in seconds before the buffered logs are automatically flushed upon adding the next log entry .
47,843
public static function shutdownHook ( array $ files ) { foreach ( $ files as $ file ) { if ( ( connection_status ( ) & CONNECTION_TIMEOUT ) == CONNECTION_TIMEOUT ) { break ; } if ( isset ( $ file [ 'tmp_name' ] ) ) { if ( is_array ( $ file [ 'tmp_name' ] ) ) { foreach ( $ file [ 'tmp_name' ] as $ name ) { self :: checkAndUnlinkFile ( $ name ) ; } } else { self :: checkAndUnlinkFile ( $ file [ 'tmp_name' ] ) ; } } } }
Remove any left over uploads .
47,844
public function dir_readdir ( ) { if ( is_null ( $ this -> current_file_list ) ) { if ( ! $ this -> fillFileBuffer ( ) ) { return false ; } } else if ( empty ( $ this -> current_file_list ) ) { if ( ! isset ( $ this -> next_marker ) || ! $ this -> fillFileBuffer ( ) ) { return false ; } } if ( empty ( $ this -> current_file_list ) ) { return false ; } else { return array_shift ( $ this -> current_file_list ) ; } }
Read the next file in the directory list . If the list is empty and we believe that there are more results to read then fetch them
47,845
public function mkdir ( $ options ) { $ report_errors = ( $ options | STREAM_REPORT_ERRORS ) != 0 ; $ headers = $ this -> getOAuthTokenHeader ( parent :: WRITE_SCOPE ) ; if ( $ headers === false ) { if ( $ report_errors ) { trigger_error ( "Unable to acquire OAuth token." , E_USER_WARNING ) ; } return false ; } $ headers [ 'x-goog-if-generation-match' ] = 0 ; $ headers [ 'Content-Range' ] = sprintf ( parent :: FINAL_CONTENT_RANGE_NO_DATA , 0 ) ; $ url = $ this -> createObjectUrl ( $ this -> bucket_name , $ this -> object_name ) ; $ http_response = $ this -> makeHttpRequest ( $ url , "PUT" , $ headers ) ; if ( false === $ http_response ) { if ( $ report_errors ) { trigger_error ( "Unable to connect to Google Cloud Storage Service." , E_USER_WARNING ) ; } return false ; } $ status_code = $ http_response [ 'status_code' ] ; if ( $ status_code != HttpResponse :: OK && $ status_code != HttpResponse :: PRECONDITION_FAILED ) { if ( $ report_errors ) { trigger_error ( $ this -> getErrorMessage ( $ status_code , $ http_response [ 'body' ] ) , E_USER_WARNING ) ; } return false ; } return ( $ status_code === HttpResponse :: OK ) ; }
Make a directory in Google Cloud Storage .
47,846
public function rmdir ( $ options ) { if ( $ this -> dir_readdir ( ) !== false ) { trigger_error ( 'The directory is not empty.' , E_USER_WARNING ) ; return false ; } $ headers = $ this -> getOAuthTokenHeader ( parent :: WRITE_SCOPE ) ; if ( $ headers === false ) { if ( $ report_errors ) { trigger_error ( "Unable to acquire OAuth token." , E_USER_WARNING ) ; } return false ; } $ url = $ this -> createObjectUrl ( $ this -> bucket_name , $ this -> object_name ) ; $ http_response = $ this -> makeHttpRequest ( $ url , "DELETE" , $ headers ) ; if ( false === $ http_response ) { trigger_error ( "Unable to connect to Google Cloud Storage Service." , E_USER_WARNING ) ; return false ; } if ( HttpResponse :: NO_CONTENT == $ http_response [ 'status_code' ] ) { return true ; } else { trigger_error ( $ this -> getErrorMessage ( $ http_response [ 'status_code' ] , $ http_response [ 'body' ] ) , E_USER_WARNING ) ; return false ; } }
Attempts to remove the directory . The directory must be empty . A E_WARNING level error will be generated on failure .
47,847
private function fillFileBuffer ( ) { $ headers = $ this -> getOAuthTokenHeader ( parent :: READ_SCOPE ) ; if ( $ headers === false ) { trigger_error ( "Unable to acquire OAuth token." , E_USER_WARNING ) ; return false ; } $ query_arr = [ 'delimiter' => parent :: DELIMITER , 'max-keys' => self :: MAX_KEYS , ] ; if ( isset ( $ this -> prefix ) ) { $ query_arr [ 'prefix' ] = $ this -> prefix ; } if ( isset ( $ this -> next_marker ) ) { $ query_arr [ 'marker' ] = $ this -> next_marker ; } $ query_str = http_build_query ( $ query_arr ) ; $ url = $ this -> createObjectUrl ( $ this -> bucket_name ) ; $ http_response = $ this -> makeHttpRequest ( sprintf ( "%s?%s" , $ url , $ query_str ) , "GET" , $ headers ) ; if ( false === $ http_response ) { trigger_error ( "Unable to connect to Google Cloud Storage Service." , E_USER_WARNING ) ; return false ; } $ status_code = $ http_response [ 'status_code' ] ; if ( HttpResponse :: OK != $ status_code ) { trigger_error ( $ this -> getErrorMessage ( $ status_code , $ http_response [ 'body' ] ) , E_USER_WARNING ) ; return false ; } $ xml = simplexml_load_string ( $ http_response [ 'body' ] ) ; if ( isset ( $ xml -> NextMarker ) ) { $ this -> next_marker = ( string ) $ xml -> NextMarker ; } else { $ this -> next_marker = null ; } if ( is_null ( $ this -> current_file_list ) ) { $ this -> current_file_list = [ ] ; } $ prefix_len = isset ( $ this -> prefix ) ? strlen ( $ this -> prefix ) : 0 ; foreach ( $ xml -> Contents as $ content ) { $ key = ( string ) $ content -> Key ; if ( StringUtil :: endsWith ( $ key , parent :: FOLDER_SUFFIX ) || StringUtil :: endsWith ( $ key , parent :: DELIMITER ) ) { continue ; } if ( $ prefix_len != 0 ) { $ key = substr ( $ key , $ prefix_len ) ; } array_push ( $ this -> current_file_list , $ key ) ; } foreach ( $ xml -> CommonPrefixes as $ common_prefixes ) { $ key = ( string ) $ common_prefixes -> Prefix ; if ( $ prefix_len != 0 ) { $ key = substr ( $ key , $ prefix_len ) ; } array_push ( $ this -> current_file_list , $ key ) ; } return true ; }
Retrieve more directory entries from Cloud Storage .
47,848
public function dir_closedir ( ) { assert ( isset ( $ this -> client ) ) ; $ this -> client -> close ( ) ; $ this -> client = null ; }
Close an open directory handle .
47,849
public function dir_opendir ( $ path , $ options ) { if ( ! CloudStorageTools :: parseFilename ( $ path , $ bucket , $ object ) ) { trigger_error ( sprintf ( "Invalid Google Cloud Storage path: %s" , $ path ) , E_USER_ERROR ) ; return false ; } if ( ! isset ( $ object ) ) { $ object = "/" ; } $ this -> client = new CloudStorageDirectoryClient ( $ bucket , $ object , $ this -> context ) ; return $ this -> client -> initialise ( ) ; }
Open a directory handle .
47,850
public function rename ( $ from , $ to ) { if ( ! CloudStorageTools :: parseFilename ( $ from , $ from_bucket , $ from_object ) || ! isset ( $ from_object ) ) { trigger_error ( sprintf ( "Invalid Google Cloud Storage path: %s" , $ from ) , E_USER_ERROR ) ; return false ; } if ( ! CloudStorageTools :: parseFilename ( $ to , $ to_bucket , $ to_object ) || ! isset ( $ to_object ) ) { trigger_error ( sprintf ( "Invalid Google Cloud Storage path: %s" , $ to ) , E_USER_ERROR ) ; return false ; } $ allowed_buckets = $ this -> getAllowedBuckets ( ) ; foreach ( $ _FILES as $ file ) { if ( $ file [ 'tmp_name' ] == $ from ) { foreach ( $ allowed_buckets as $ allowed_bucket ) { if ( strpos ( $ to , $ allowed_bucket ) === 5 ) { trigger_error ( sprintf ( 'Moving uploaded file (%s) to an allowed ' . 'include bucket (%s) which may be ' . 'vulnerable to local file inclusion (LFI).' , $ from , $ allowed_bucket ) , E_USER_WARNING ) ; break 2 ; } } } } $ client = new CloudStorageRenameClient ( $ from_bucket , $ from_object , $ to_bucket , $ to_object , $ this -> context ) ; return $ client -> rename ( ) ; }
Rename a cloud storage object .
47,851
public function stream_close ( ) { assert ( isset ( $ this -> client ) ) ; $ this -> client -> close ( ) ; $ this -> client = null ; }
All resources that were locked or allocated by the wrapper should be released .
47,852
public function stream_read ( $ count ) { assert ( isset ( $ this -> client ) ) ; return $ this -> client -> read ( $ count ) ; }
Read from a stream return string of bytes .
47,853
public function serializeToString ( ) { $ uninitialized = $ this -> checkInitialized ( ) ; if ( $ uninitialized !== null ) { throw new ProtocolBufferEncodeError ( "Not initialized: " . $ uninitialized ) ; } return $ this -> serializePartialToString ( ) ; }
Serializes the message and return it as a string .
47,854
public function serializePartialToString ( ) { $ enc = new Encoder ( ) ; $ this -> outputPartial ( $ enc ) ; $ res = $ enc -> toString ( ) ; if ( mt_rand ( 0 , 99 ) === 0 && $ this -> byteSizePartial ( ) !== strlen ( $ res ) ) { throw new ProtocolBufferEncodeError ( "Internal bug: Encoded size doesn't match predicted" ) ; } return $ res ; }
Serializes a protocol buffer that might not have all of the required fields set .
47,855
public function mergeFromString ( $ s ) { $ this -> mergePartialFromString ( $ s ) ; $ uninitialized = $ this -> checkInitialized ( ) ; if ( $ uninitialized !== null ) { throw new ProtocolBufferDecodeError ( "Not initialized: " . $ uninitialized ) ; } }
Like parseFromString fills the message with a protocol buffer parsed from the given input string .
47,856
public function mergePartialFromString ( $ s ) { $ d = new Decoder ( $ s , 0 , strlen ( $ s ) ) ; $ this -> tryMerge ( $ d ) ; }
Like parsePartialFromString fills the message with a protocol buffer parsed from the given input string . Will not fail if the resulting protocol buffer is not fully initialized .
47,857
protected static function debugFormatString ( $ value ) { $ res = "" ; if ( ! empty ( $ value ) ) { foreach ( str_split ( $ value ) as $ c ) { $ res .= ProtocolMessage :: escapeByte ( $ c ) ; } } return '"' . $ res . '"' ; }
Format protocol buffer as a text string for debugging .
47,858
public function addBcc ( $ emails ) { $ email_array = $ this -> validEmailsArray ( $ emails , "'bcc' recipient" ) ; foreach ( $ email_array as $ email ) { $ this -> message -> addBcc ( $ email ) ; } }
Adds a bcc address or array of addresses to the mail object .
47,859
public function addCc ( $ emails ) { $ email_array = $ this -> validEmailsArray ( $ emails , "'cc' recipient" ) ; foreach ( $ email_array as $ email ) { $ this -> message -> addCc ( $ email ) ; } }
Adds a cc address or array of addresses to the mail object .
47,860
public function addTo ( $ emails ) { $ email_array = $ this -> validEmailsArray ( $ emails , "'to' recipient" ) ; foreach ( $ email_array as $ email ) { $ this -> message -> addTo ( $ email ) ; } }
Adds a to address or array of addresses to the mail object .
47,861
public function send ( ) { if ( ! $ this -> message -> hasSender ( ) ) { throw new \ InvalidArgumentException ( "Required field sender is not provided." ) ; } else if ( $ this -> message -> getToSize ( ) == 0 && $ this -> message -> getCcSize ( ) == 0 && $ this -> message -> getBccSize ( ) == 0 ) { throw new \ InvalidArgumentException ( "Neither to, cc or bcc is set - at least one is required." ) ; } else if ( ! $ this -> message -> hasSubject ( ) ) { throw new \ InvalidArgumentException ( "Required field subject is not provided." ) ; } else if ( ! $ this -> message -> hasTextbody ( ) && ! $ this -> message -> hasHtmlbody ( ) ) { throw new \ InvalidArgumentException ( "Neither a plain-text nor HTML body is provided - at least one is " . "required." ) ; } $ response = new VoidProto ( ) ; try { ApiProxy :: makeSyncCall ( 'mail' , 'Send' , $ this -> message , $ response ) ; } catch ( ApplicationError $ e ) { $ this -> handleApplicationError ( $ e ) ; } }
Send the pre - formed email from the Message object .
47,862
public static function createLoginURL ( $ destination_url = null , $ federated_identity = null ) { $ req = new CreateLoginURLRequest ( ) ; $ resp = new CreateLoginURLResponse ( ) ; if ( $ destination_url !== null ) { $ req -> setDestinationUrl ( $ destination_url ) ; } else { $ req -> setDestinationUrl ( '' ) ; } if ( $ federated_identity !== null ) { $ req -> setFederatedIdentity ( $ federated_identity ) ; } try { ApiProxy :: makeSyncCall ( 'user' , 'CreateLoginURL' , $ req , $ resp ) ; } catch ( ApplicationError $ e ) { throw self :: applicationErrorToException ( $ e , htmlspecialchars ( $ destination_url ) ) ; } return $ resp -> getLoginUrl ( ) ; }
Computes the login URL for redirection .
47,863
public static function createLogoutURL ( $ destination_url ) { $ req = new CreateLogoutURLRequest ( ) ; $ resp = new CreateLogoutURLResponse ( ) ; $ req -> setDestinationUrl ( $ destination_url ) ; try { ApiProxy :: makeSyncCall ( 'user' , 'CreateLogoutURL' , $ req , $ resp ) ; } catch ( ApplicationError $ e ) { throw self :: applicationErrorToException ( $ e , htmlspecialchars ( $ destination_url ) ) ; } return $ resp -> getLogoutUrl ( ) ; }
Computes the logout URL for this request and specified destination URL for both federated login App and Google Accounts App .
47,864
private static function applicationErrorToException ( $ error , $ destination_url ) { switch ( $ error -> getApplicationError ( ) ) { case ErrorCode :: REDIRECT_URL_TOO_LONG : return new UsersException ( 'URL too long: ' . $ destination_url ) ; case ErrorCode :: NOT_ALLOWED : return new UsersException ( 'Action not allowed.' ) ; default : return new UsersException ( 'Error code: ' . $ error -> getApplicationError ( ) ) ; } }
Convert a UserService RPC error to an exception .
47,865
private static function doGlobForPath ( $ path , $ options ) { $ dirname = static :: getDirNameForPath ( $ path ) ; $ basename = static :: getBaseNameForPath ( $ path ) ; $ expanded_path = static :: splitPathOnWildcard ( $ dirname ) ; if ( $ expanded_path === false ) { return static :: doGlobForExpandedPath ( $ path , $ options ) ; } $ path = $ expanded_path [ 0 ] . $ expanded_path [ 1 ] ; $ dirs = static :: doGlobForPath ( $ path , GLOB_ONLYDIR ) ; $ results = [ ] ; foreach ( $ dirs as $ dir ) { $ dirname = $ expanded_path [ 0 ] . $ dir . $ expanded_path [ 2 ] ; $ path = $ dirname . DIRECTORY_SEPARATOR . $ basename ; $ subdir = static :: doGlobForPath ( $ path , $ options ) ; $ results = array_merge ( $ results , $ subdir ) ; } return $ results ; }
Glob a given path after braces have been expanded but before wildcards have been expanded .
47,866
private static function doGlobForExpandedPath ( $ filename , $ options ) { $ openpath = static :: getDirNameForPath ( $ filename ) ; $ dirname = pathinfo ( $ filename , PATHINFO_DIRNAME ) ; $ basename = static :: getBaseNameForPath ( $ filename ) ; $ results = [ ] ; $ handle = @ opendir ( $ openpath ) ; if ( $ handle === false ) { return false ; } while ( ( $ name = readdir ( $ handle ) ) !== false ) { if ( static :: isFileNamePatternMatch ( $ name , $ basename , $ options ) ) { if ( strpos ( $ filename , DIRECTORY_SEPARATOR ) !== false ) { $ name = $ dirname . DIRECTORY_SEPARATOR . $ name ; } $ results [ ] = $ name ; } } closedir ( $ handle ) ; if ( $ options & ( GLOB_MARK | GLOB_ONLYDIR ) ) { $ results = static :: doDirectoryOptions ( $ dirname , $ results , $ options ) ; } return $ results ; }
Glob a given path .
47,867
private static function isFileNamePatternMatch ( $ name , $ pattern , $ options ) { if ( in_array ( $ name , static :: $ excluded_file_names ) ) { return false ; } $ fnmatch_flags = 0 ; if ( $ options & GLOB_NOESCAPE ) { $ fnmatch_flags |= FNM_NOESCAPE ; } return fnmatch ( $ pattern , $ name , $ fnmatch_flags ) ; }
Check if a file name matches the specified glob pattern .
47,868
private static function expandFilenameBraces ( $ pattern ) { $ result = [ ] ; if ( preg_match ( self :: BRACE_PATTERN , $ pattern , $ matches ) === 1 ) { $ items = explode ( "," , $ matches [ 2 ] ) ; foreach ( $ items as $ match ) { $ str = $ matches [ 1 ] . $ match . $ matches [ 3 ] ; $ exp = static :: expandFilenameBraces ( $ str ) ; $ result = array_merge ( $ result , $ exp ) ; } } else { $ result [ ] = $ pattern ; } return $ result ; }
Expand out any braces in the incomming pattern acording to shell brace rules .
47,869
private static function doDirectoryOptions ( $ basename , $ filenames , $ options ) { $ name_list = [ ] ; $ results = [ ] ; foreach ( $ filenames as $ file ) { $ name_list [ ] = [ 'name' => $ file , 'path' => implode ( DIRECTORY_SEPARATOR , [ rtrim ( $ basename , DIRECTORY_SEPARATOR ) , ltrim ( $ file , DIRECTORY_SEPARATOR ) ] ) , ] ; } foreach ( $ name_list as $ name_and_path ) { $ name = $ name_and_path [ 'name' ] ; $ isdir = is_dir ( $ name_and_path [ 'path' ] ) ; if ( ( $ options & GLOB_MARK ) && $ isdir ) { $ name = rtrim ( $ name , DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR ; } if ( $ options & GLOB_ONLYDIR ) { if ( $ isdir ) { $ results [ ] = $ name ; } } else { $ results [ ] = $ name ; } } return $ results ; }
Perform glob directory actions on a list of files .
47,870
private static function splitPathOnWildcard ( $ path ) { $ sep = addslashes ( DIRECTORY_SEPARATOR ) ; $ pattern = sprintf ( static :: WILDCARD_PATTERN , $ sep , $ sep ) ; if ( preg_match ( $ pattern , $ path , $ matches ) ) { return array_slice ( $ matches , 1 ) ; } return false ; }
Look for shell wildcards in a path if found split the path around the first wilcard segment .
47,871
private static function parseMimePart ( $ part , $ raw_mail , & $ email ) { $ data = mailparse_msg_get_part_data ( $ part ) ; $ type = ArrayUtil :: findByKeyOrDefault ( $ data , 'content-type' , 'text/plain' ) ; $ start = $ data [ 'starting-pos-body' ] ; $ end = $ data [ 'ending-pos-body' ] ; $ encoding = ArrayUtil :: findByKeyOrDefault ( $ data , 'transfer-encoding' , '' ) ; $ content = self :: decodeContent ( substr ( $ raw_mail , $ start , $ end - $ start ) , $ encoding ) ; if ( isset ( $ data [ 'content-disposition' ] ) ) { $ filename = ArrayUtil :: findByKeyOrDefault ( $ data , 'disposition-filename' , uniqid ( ) ) ; $ content_id = ArrayUtil :: findByKeyOrNull ( $ data , 'content-id' ) ; if ( $ content_id != null ) { $ content_id = "<$content_id>" ; } $ email -> addAttachment ( $ filename , $ content , $ content_id ) ; } else if ( $ type == 'text/html' ) { $ email -> setHtmlBody ( $ content ) ; } else if ( $ type == 'text/plain' ) { $ email -> setTextBody ( $ content ) ; } else if ( ! StringUtil :: startsWith ( $ type , 'multipart/' ) ) { trigger_error ( "Ignore MIME part with unknown Content-Type $type. " . "Did you forget to specifcy Content-Disposition header?" , E_USER_WARNING ) ; } }
Parse a MIME part and set the Message object accordingly .
47,872
private static function decodeContent ( $ content , $ encoding ) { switch ( strtolower ( $ encoding ) ) { case 'base64' : return base64_decode ( $ content ) ; case 'quoted-printable' : return quoted_printable_decode ( $ content ) ; default : return $ content ; } }
Decoded content based on the encoding scheme .
47,873
public function seek ( $ offset , $ whence ) { if ( $ whence == SEEK_END ) { if ( isset ( $ this -> object_total_length ) ) { $ whence = SEEK_SET ; $ offset = $ this -> object_total_length + $ offset ; } else { trigger_error ( "Unable to seek from end for objects with unknown size" , E_USER_WARNING ) ; return false ; } } if ( $ whence != SEEK_SET ) { trigger_error ( sprintf ( "Unsupported seek mode: %d" , $ whence ) , E_USER_WARNING ) ; return false ; } if ( isset ( $ this -> object_total_length ) && $ offset >= $ this -> object_total_length ) { return false ; } if ( $ offset < 0 ) { return false ; } $ this -> eof = false ; $ block_start = $ this -> object_block_start_position ; $ buffer_end = $ block_start + strlen ( $ this -> read_buffer ) ; if ( $ block_start <= $ offset && $ offset < $ buffer_end ) { $ this -> buffer_read_position = $ offset - $ block_start ; } else { $ this -> read_buffer = "" ; $ this -> buffer_read_position = 0 ; $ this -> next_read_position = $ offset ; } return true ; }
Seek within the current file . We expect the upper layers of PHP to convert SEEK_CUR to SEEK_SET .
47,874
protected function makeHttpRequest ( $ url , $ method , $ headers , $ body = null ) { if ( ! $ this -> context_options [ 'enable_cache' ] ) { return parent :: makeHttpRequest ( $ url , $ method , $ headers , $ body ) ; } $ cache_key = static :: getReadMemcacheKey ( $ url , $ headers [ 'Range' ] ) ; $ cache_obj = $ this -> memcache_client -> get ( $ cache_key ) ; if ( false !== $ cache_obj ) { if ( $ this -> context_options [ 'enable_optimistic_cache' ] ) { return $ cache_obj ; } else { $ cache_etag = $ this -> getHeaderValue ( 'ETag' , $ cache_obj [ 'headers' ] ) ; if ( array_key_exists ( 'If-Match' , $ headers ) ) { if ( $ headers [ 'If-Match' ] === $ cache_etag ) { unset ( $ headers [ 'If-Match' ] ) ; } else { $ cache_etag = null ; } } } if ( isset ( $ cache_etag ) ) { $ headers [ 'If-None-Match' ] = $ cache_etag ; } } $ result = parent :: makeHttpRequest ( $ url , $ method , $ headers , $ body ) ; if ( false === $ result ) { return false ; } $ status_code = $ result [ 'status_code' ] ; if ( HttpResponse :: NOT_MODIFIED === $ result [ 'status_code' ] ) { return $ cache_obj ; } if ( in_array ( $ status_code , self :: $ valid_status_codes ) ) { $ this -> memcache_client -> set ( $ cache_key , $ result , 0 , $ this -> context_options [ 'read_cache_expiry_seconds' ] ) ; } return $ result ; }
Override the makeHttpRequest function so we can implement caching . If caching is enabled then we try and retrieve a matching request for the object name and range from memcache . If we find a result in memcache and optimistic caching is enabled then we return that result immediately without checking if the object has changed in GCS . Otherwise we will issue a If - None - Match request with the ETag of the object to ensure it is still current .
47,875
public static function getUserEnvironmentVariable ( $ var_name ) { $ result = getenv ( $ var_name ) ; if ( $ result === false ) { $ result = getenv ( self :: HTTP_X_APPENGINE . $ var_name ) ; } return $ result ; }
Retrieve an environment variable specifically for the UserService .
47,876
public function write ( $ id , $ data ) { return $ this -> memcacheContainer -> set ( self :: SESSION_PREFIX . $ id , $ data , $ this -> expire ) ; }
Write an element to Memcache with the given ID and data .
47,877
public static function configure ( $ memcacheContainer = null ) { $ handler = new MemcacheSessionHandler ( $ memcacheContainer ) ; session_set_save_handler ( $ handler , true ) ; session_save_path ( "Memcache" ) ; }
Configure the session handler to use the Memcache API .
47,878
public static function signForApp ( $ bytes_to_sign ) { $ req = new SignForAppRequest ( ) ; $ resp = new SignForAppResponse ( ) ; if ( ! is_string ( $ bytes_to_sign ) ) { throw new \ InvalidArgumentException ( '$bytes_to_sign must be a string.' ) ; } $ req -> setBytesToSign ( $ bytes_to_sign ) ; try { ApiProxy :: makeSyncCall ( self :: PACKAGE_NAME , 'SignForApp' , $ req , $ resp ) ; } catch ( ApplicationError $ e ) { throw self :: applicationErrorToException ( $ e ) ; } return [ 'key_name' => $ resp -> getKeyName ( ) , 'signature' => $ resp -> getSignatureBytes ( ) , ] ; }
Signs arbitrary byte array using per app private key .
47,879
public static function getServiceAccountName ( ) { $ req = new GetServiceAccountNameRequest ( ) ; $ resp = new GetServiceAccountNameResponse ( ) ; try { ApiProxy :: makeSyncCall ( self :: PACKAGE_NAME , 'GetServiceAccountName' , $ req , $ resp ) ; } catch ( ApplicationError $ e ) { throw self :: applicationErrorToException ( $ e ) ; } return $ resp -> getServiceAccountName ( ) ; }
Get the service account name for the application .
47,880
public static function getPublicCertificates ( ) { $ req = new GetPublicCertificateForAppRequest ( ) ; $ resp = new GetPublicCertificateForAppResponse ( ) ; try { ApiProxy :: makeSyncCall ( self :: PACKAGE_NAME , 'GetPublicCertificatesForApp' , $ req , $ resp ) ; } catch ( ApplicationError $ e ) { throw self :: applicationErrorToException ( $ e ) ; } $ result = [ ] ; foreach ( $ resp -> getPublicCertificateListList ( ) as $ cert ) { $ result [ ] = new PublicCertificate ( $ cert -> getKeyName ( ) , $ cert -> getX509CertificatePem ( ) ) ; } return $ result ; }
Get the list of public certifates for the application .
47,881
public static function getApplicationId ( ) { $ app_id = getenv ( "APPLICATION_ID" ) ; $ psep = strpos ( $ app_id , self :: PARTITION_SEPARATOR ) ; if ( $ psep > 0 ) { $ app_id = substr ( $ app_id , $ psep + 1 ) ; } return $ app_id ; }
Get the application id of an app .
47,882
private static function putTokenInCache ( $ name , $ value , $ expiry_secs ) { $ expiry_time_from_epoch = $ expiry_secs - self :: EXPIRY_SAFETY_MARGIN_SECS - self :: EXPIRY_SHORT_MARGIN_SECS ; $ memcache = new \ Memcache ( ) ; $ memcache -> set ( $ name , $ value , null , $ expiry_time_from_epoch ) ; self :: putTokenInApc ( $ name , $ value , $ expiry_secs ) ; }
Add an access token to the cache .
47,883
private static function getTokenFromCache ( $ name ) { $ success = false ; $ result = apc_fetch ( $ name , $ success ) ; if ( $ success && time ( ) < $ result [ 'eviction_time_epoch' ] ) { unset ( $ result [ 'eviction_time_epoch' ] ) ; return $ result ; } $ memcache = new \ Memcache ( ) ; $ result = $ memcache -> get ( $ name ) ; if ( $ result !== false ) { self :: putTokenInApc ( $ name , $ result , $ result [ 'expiration_time' ] ) ; } return $ result ; }
Retrieve an access token from the cache .
47,884
private static function applicationErrorToException ( $ application_error ) { switch ( $ application_error -> getApplicationError ( ) ) { case ErrorCode :: UNKNOWN_SCOPE : return new \ InvalidArgumentException ( 'An unknown scope was supplied.' ) ; case ErrorCode :: BLOB_TOO_LARGE : return new \ InvalidArgumentException ( 'The supplied blob was too long.' ) ; case ErrorCode :: DEADLINE_EXCEEDED : return new AppIdentityException ( 'The deadline for the call was exceeded.' ) ; case ErrorCode :: NOT_A_VALID_APP : return new AppIdentityException ( 'The application is not valid.' ) ; case ErrorCode :: UNKNOWN_ERROR : return new AppIdentityException ( 'There was an unknown error using the AppIdentity service.' ) ; case ErrorCode :: GAIAMINT_NOT_INITIAILIZED : return new AppIdentityException ( 'There was a GAIA error using the AppIdentity service.' ) ; case ErrorCode :: NOT_ALLOWED : return new AppIdentityException ( 'The call is not allowed.' ) ; default : return new AppIdentityException ( 'The AppIdentity service threw an unexpected error.' ) ; } }
Converts an application error to the service specific exception .
47,885
public static function move_uploaded_file ( $ filename , $ destination , array $ context_options = null ) { if ( is_uploaded_file ( $ filename ) ) { if ( $ context_options !== null ) { $ context = stream_context_create ( $ context_options ) ; } else { $ context = stream_context_get_default ( [ 'gs' => [ 'Content-Type' => static :: lookupContentType ( $ filename ) ] , ] ) ; } if ( @ rename ( $ filename , $ destination , $ context ) ) { static :: removeUploadedFile ( $ filename ) ; return true ; } if ( copy ( $ filename , $ destination , $ context ) && unlink ( $ filename , $ context ) ) { static :: removeUploadedFile ( $ filename ) ; return true ; } } return false ; }
Moves an uploaded file to a new location .
47,886
private static function lookupContentType ( $ filename ) { foreach ( $ _FILES as $ file ) { if ( $ file [ 'tmp_name' ] == $ filename ) { return $ file [ 'type' ] ? : static :: DEFAULT_CONTENT_TYPE ; } } return static :: DEFAULT_CONTENT_TYPE ; }
Lookup the content type associated with an uploaded file .
47,887
public static function tempnam ( $ dir , $ prefix ) { $ temp_root = static :: sys_get_temp_dir ( ) ; if ( ! StringUtil :: startsWith ( $ dir , $ temp_root ) ) { $ dir = $ temp_root . '/' . str_replace ( '\\' , '/' , $ dir ) ; } @ mkdir ( $ dir , 0777 , true ) ; for ( $ retry = 0 ; $ retry < 10 || file_exists ( $ filename ) ; $ retry ++ ) { $ filename = $ dir . '/' . uniqid ( $ prefix , true ) ; } if ( file_exists ( $ filename ) ) { trigger_error ( 'Fail to generate a unique name for the temporary file' , E_USER_ERROR ) ; return false ; } if ( touch ( $ filename ) === false || chmod ( $ filename , static :: DEFAULT_TMPFILE_MODE ) === false ) { trigger_error ( 'Fail to create and change permission of temporary file ' . $ filename , E_USER_ERROR ) ; return false ; } return $ filename ; }
Create file with unique file name .
47,888
public function cas ( $ cas_token , $ key , $ value , $ expiration = 0 ) { $ key = $ this -> getPrefixKey ( $ key ) ; $ request = new MemcacheSetRequest ( ) ; $ response = new MemcacheSetResponse ( ) ; $ memcache_flag = 0 ; $ serialized_value = MemcacheUtils :: serializeValue ( $ value , $ memcache_flag ) ; $ item = $ request -> addItem ( ) ; $ item -> setKey ( $ key ) ; $ item -> setValue ( $ serialized_value ) ; $ item -> setFlags ( $ memcache_flag ) ; $ item -> setSetPolicy ( SetPolicy :: CAS ) ; $ item -> setCasId ( $ cas_token ) ; $ item -> setExpirationTime ( $ expiration ) ; try { ApiProxy :: makeSyncCall ( 'memcache' , 'Set' , $ request , $ response ) ; } catch ( Error $ e ) { $ this -> result_code = self :: RES_FAILURE ; return false ; } switch ( $ response -> getSetStatusList ( ) [ 0 ] ) { case SetStatusCode :: STORED : $ this -> result_code = self :: RES_SUCCESS ; return true ; case SetStatusCode :: NOT_STORED : $ this -> result_code = self :: RES_NOTSTORED ; return false ; case SetStatusCode :: EXISTS : $ this -> result_code = self :: RES_DATA_EXISTS ; return false ; default : $ this -> result_code = self :: RES_FAILURE ; return false ; } }
Performs a set and check operation so that the item will be stored only if no other client has updated it since it was last fetched by this client .
47,889
public function flush ( $ delay = 0 ) { $ result = $ this -> memcache -> flush ( ) ; $ this -> result_code = $ result ? self :: RES_SUCCESS : self :: RES_NOTSTORED ; return $ result ; }
Invalidates all existing cache items immediately .
47,890
public function getDelayed ( $ keys , $ with_cas = false , $ value_cb = null ) { $ this -> delayed_results = array ( ) ; $ cas_tokens = null ; if ( $ with_cas ) { $ results = $ this -> getMulti ( $ keys , $ cas_tokens ) ; } else { $ results = $ this -> getMulti ( $ keys ) ; } if ( ! $ results ) { return false ; } foreach ( $ results as $ key => $ value ) { $ val = [ 'key' => $ key , 'value' => $ value ] ; if ( ! empty ( $ cas_tokens ) ) { $ cas = array_shift ( $ cas_tokens ) ; $ val [ 'cas' ] = $ cas ; } $ this -> delayed_results [ ] = $ val ; } if ( isset ( $ value_cb ) ) { foreach ( $ this -> delayed_results as $ result ) { $ value_cb ( $ result ) ; } } return true ; }
Issues a request to memcache for multiple items the keys of which are specified in the keys array . Currently this method executes synchronously .
47,891
public function getResultMessage ( ) { switch ( $ this -> result_code ) { case self :: RES_SUCCESS : return "SUCCESS" ; case self :: RES_FAILURE : return "FAILURE" ; case self :: RES_NOTSTORED : return "NOT STORED" ; case self :: RES_NOTFOUND : return "NOT FOUND" ; } return "UNKNOWN" ; }
Return the message describing the result of the last operation .
47,892
public function increment ( $ key , $ offset = 1 , $ initial_value = 0 , $ expiry = 0 ) { return $ this -> incrementInternal ( $ key , $ offset , $ initial_value , $ expiry , true ) ; }
Increments a numeric item s value by the specified offset . If the item s value is not numeric and error will result .
47,893
public function prepend ( $ key , $ value ) { do { $ result = $ this -> get ( $ key , null , $ cas_token ) ; if ( ! $ result || ! is_string ( $ result ) ) { $ this -> result_code = self :: RES_NOTSTORED ; return false ; } $ result = $ value . $ result ; $ result = $ this -> cas ( $ cas_token , $ key , $ result ) ; } while ( ! $ result && $ this -> result_code == self :: RES_DATA_EXISTS ) ; $ this -> result_code = $ result ? self :: RES_SUCCESS : self :: RES_NOTSTORED ; return $ result ; }
Prepends the given value string to an existing item .
47,894
public function set ( $ key , $ value , $ expiration = 0 ) { $ key = $ this -> getPrefixKey ( $ key ) ; $ result = $ this -> memcache -> set ( $ key , $ value , null , $ expiration ) ; $ this -> result_code = $ result ? self :: RES_SUCCESS : self :: RES_FAILURE ; return $ result ; }
Stores the value on a memcache server under the specified key . The expiration parameters can be used to control when the value is considered expired .
47,895
public function setOption ( $ option , $ value ) { if ( $ option == self :: OPT_PREFIX_KEY ) { $ this -> options [ $ option ] = $ value ; return true ; } return false ; }
This method sets the vaue of a memcached option .
47,896
public function touch ( $ key , $ expiration = 0 ) { $ result = $ this -> get ( $ key , null , $ cas_token ) ; if ( $ result ) { $ result = $ this -> cas ( $ cas_token , $ key , $ result , $ expiration ) ; } $ this -> result_code = $ result ? self :: RES_SUCCESS : self :: RES_FAILURE ; return $ result ; }
Sets a new expiration time on an item .
47,897
public static function getStatusMessage ( $ code ) { if ( array_key_exists ( $ code , self :: $ status_messages ) ) { return self :: $ status_messages [ $ code ] ; } return sprintf ( "Unknown Code %d" , $ code ) ; }
Get the status message string for a given HTTP response code .
47,898
private static function getRpcErrorFromException ( $ error_no , $ package , $ call ) { if ( isset ( self :: $ exceptionLookupTable [ $ error_no ] ) ) { $ res = self :: $ exceptionLookupTable [ $ error_no ] ; return new $ res [ 0 ] ( sprintf ( $ res [ 1 ] , $ package , $ call ) ) ; } return new RPCFailedError ( sprintf ( 'Remote implementation for %s.%s failed' , $ package , $ call ) ) ; }
Create a runtime exception from an RPC Error Code .
47,899
public static function arrayMergeIgnoreCase ( ) { if ( func_num_args ( ) < 2 ) { throw new \ InvalidArgumentException ( "At least two arrays must be supplied." ) ; } $ result = [ ] ; $ key_mapping = [ ] ; $ input_args = func_get_args ( ) ; foreach ( $ input_args as $ args ) { if ( ! is_array ( $ args ) ) { throw new \ InvalidArgumentException ( "Arguments are expected to be arrays, found " . gettype ( $ arg ) ) ; } foreach ( $ args as $ key => $ val ) { $ lower_case_key = strtolower ( $ key ) ; if ( array_key_exists ( $ lower_case_key , $ key_mapping ) ) { $ result [ $ key_mapping [ $ lower_case_key ] ] = $ val ; } else { $ key_mapping [ $ lower_case_key ] = $ key ; $ result [ $ key ] = $ val ; } } } return $ result ; }
Merge a number of arrays using a case insensitive comparison for the array keys .