idx int64 0 60.3k | question stringlengths 99 4.85k | target stringlengths 5 718 |
|---|---|---|
300 | public static function slice ( & $ array , $ start = null , $ stop = null , $ step = null , $ byReference = false ) { $ result = array ( ) ; $ indexes = self :: sliceIndices ( count ( $ array ) , $ start , $ stop , $ step ) ; if ( $ byReference ) { foreach ( $ indexes as $ i ) { $ result [ ] = & $ array [ $ i ] ; } } else { foreach ( $ indexes as $ i ) { $ result [ ] = $ array [ $ i ] ; } } return $ result ; } | Implements the Python slice behaviour |
301 | public function get ( $ jsonPath ) { $ this -> hasDiverged = false ; $ result = $ this -> getReal ( $ this -> jsonObject , $ jsonPath ) ; if ( $ this -> smartGet && $ result !== false && ! $ this -> hasDiverged ) { return $ result [ 0 ] ; } return $ result ; } | Returns an array containing references to the objects that match the JsonPath . If the result is empty returns false . |
302 | public function getJsonObjects ( $ jsonPath ) { $ this -> hasDiverged = false ; $ result = $ this -> getReal ( $ this -> jsonObject , $ jsonPath ) ; if ( $ result !== false ) { $ objs = array ( ) ; foreach ( $ result as & $ value ) { $ jsonObject = new JsonObject ( null , $ this -> smartGet ) ; $ jsonObject -> jsonObject = & $ value ; $ objs [ ] = $ jsonObject ; } if ( $ this -> smartGet && ! $ this -> hasDiverged ) { return $ objs [ 0 ] ; } return $ objs ; } return $ result ; } | Return an array of new JsonObjects representing the results of the given JsonPath . These objects contain references to the elements in the original JsonObject . |
303 | public function get ( ) { $ fullPath = $ this -> getFilePath ( ) ; if ( $ this -> files -> exists ( $ fullPath ) ) { $ content = $ this -> files -> get ( $ fullPath ) ; return $ this -> makeCollection ( $ this -> parseResult ( $ content ) ) ; } return $ this -> makeCollection ( ) ; } | Return array parsed from file content . |
304 | protected function createDirectoryIfNotExists ( ) { if ( ! is_dir ( $ this -> getPath ( ) ) ) { $ this -> files -> makeDirectory ( $ this -> getPath ( ) , 0755 , true ) ; } } | Make directory path if not exists |
305 | protected function parseResult ( $ content ) { $ data = [ ] ; foreach ( explode ( static :: ROW_DELIMITER , $ content ) as $ row ) { if ( empty ( $ row ) ) { continue ; } $ data [ ] = json_decode ( $ row , true ) ; } return $ data ; } | Parse result form given string |
306 | private function prepareContent ( $ data ) { $ content = '' ; foreach ( $ data as $ row ) { $ content .= $ this -> convertToJson ( $ row ) . static :: ROW_DELIMITER ; } return $ content ; } | Prepare content string from given data |
307 | private function getMethods ( ) { if ( method_exists ( $ this -> route , 'getMethods' ) ) { return $ this -> route -> getMethods ( ) ; } return $ this -> route -> methods ( ) ; } | Cross version get methods . |
308 | protected function getUri ( ) { if ( method_exists ( $ this -> route , 'getPath' ) ) { return $ this -> route -> getPath ( ) ; } return $ this -> route -> uri ( ) ; } | Backwards compatible uri getter . |
309 | public function fill ( array $ data ) { $ this -> attributes = array_merge ( $ this -> attributes , $ this -> filterFillable ( $ data ) ) ; } | Fill attributes that can be filled . |
310 | public function filterMatch ( $ patterns ) { $ patterns = is_string ( $ patterns ) ? [ $ patterns ] : $ patterns ; foreach ( $ patterns as $ key => $ pattern ) { if ( is_string ( $ pattern ) ) { $ patterns [ $ key ] = [ 'path' => $ pattern ] ; } } return $ this -> filter ( function ( $ route ) use ( $ patterns ) { foreach ( $ patterns as $ pattern ) { if ( $ this -> isRouteMatchesPattern ( $ route , $ pattern ) ) { return true ; } } return false ; } ) ; } | Include routes that match patterns . |
311 | public function filterExcept ( $ patterns = [ ] ) { if ( empty ( $ patterns ) ) { return $ this ; } $ toExclude = $ this -> filterMatch ( $ patterns ) -> keys ( ) -> toArray ( ) ; return $ this -> except ( $ toExclude ) ; } | Exclude routes that match patterns . |
312 | public function load ( $ data ) { foreach ( $ data as $ row ) { $ this -> put ( $ row [ 'id' ] , RequestEntity :: createExisting ( $ row ) ) ; } return $ this ; } | Load data to collection . |
313 | public function get ( ) { $ result = $ this -> getFromFireBase ( ) ; $ data = $ this -> addHeadersIfEmpty ( $ result ) ; return $ this -> makeCollection ( $ data ) ; } | Get data from resource . |
314 | public function put ( RequestCollection $ data ) { $ this -> store ( $ data -> onlyDiff ( ) ) ; $ this -> delete ( $ data -> onlyToDelete ( ) ) ; } | Put data to resource . |
315 | public function index ( RouteRepositoryInterface $ repository ) { $ data = $ repository -> get ( config ( 'api-tester.include' ) , config ( 'api-tester.exclude' ) ) ; return response ( ) -> json ( compact ( 'data' ) ) ; } | Display list of all available routes . |
316 | public function cache ( $ path , $ lifetime = 3600 , $ compress = true , $ chmod = 0755 ) { if ( $ path !== false ) { if ( ! is_dir ( $ path ) ) @ mkdir ( $ path , $ chmod , true ) ; $ this -> cache = array ( 'path' => $ path , 'lifetime' => $ lifetime , 'chmod' => $ chmod , 'compress' => $ compress , ) ; } else $ this -> cache = false ; } | Use this method to enable caching of requests . |
317 | public function http_authentication ( $ username = '' , $ password = '' , $ type = CURLAUTH_ANY ) { $ this -> option ( array ( CURLOPT_HTTPAUTH => ( $ username == '' && $ password == '' ? null : $ type ) , CURLOPT_USERPWD => ( $ username == '' && $ password == '' ? null : ( $ username . ':' . $ password ) ) , ) ) ; } | Use this method to make requests to pages that require prior HTTP authentication . |
318 | public function proxy ( $ proxy , $ port = 80 , $ username = '' , $ password = '' ) { if ( $ proxy ) { $ this -> option ( array ( CURLOPT_HTTPPROXYTUNNEL => 1 , CURLOPT_PROXY => $ proxy , CURLOPT_PROXYPORT => $ port , ) ) ; if ( $ username != '' ) $ this -> option ( CURLOPT_PROXYUSERPWD , $ username . ':' . $ password ) ; } else $ this -> option ( array ( CURLOPT_HTTPPROXYTUNNEL => null , CURLOPT_PROXY => null , CURLOPT_PROXYPORT => null , ) ) ; } | Instruct the library to tunnel all requests through a proxy server . |
319 | public function start ( ) { $ this -> _queue = false ; if ( $ this -> pause_interval > 0 ) $ this -> _process_paused ( ) ; else $ this -> _process ( ) ; } | Executes queued requests . |
320 | private function _debug ( ) { $ result = '' ; foreach ( get_defined_constants ( ) as $ name => $ number ) foreach ( $ this -> options as $ index => $ value ) if ( substr ( $ name , 0 , 7 ) == 'CURLOPT' && $ number == $ index ) $ result .= str_pad ( $ index , 5 , ' ' , STR_PAD_LEFT ) . ' ' . $ name . ' => ' . var_export ( $ value , true ) . '<br>' ; return $ result ; } | Returns the currently set options in human - readable format . |
321 | private function _get_cache_file_name ( $ request ) { foreach ( $ request [ 'options' ] as $ key => $ value ) if ( is_null ( $ value ) || $ value == '' ) unset ( $ request [ 'options' ] [ $ key ] ) ; $ request = array_diff_key ( $ request , array ( 'callback' => '' , 'arguments' => '' , 'file_handler' => '' ) ) ; return rtrim ( $ this -> cache [ 'path' ] , '/' ) . '/' . md5 ( serialize ( $ request ) ) ; } | Returns the cache file name associated with a specific request . |
322 | private function _parse_headers ( $ headers ) { $ result = array ( ) ; if ( $ headers != '' ) { $ headers = preg_split ( '/^\s*$/m' , trim ( $ headers ) ) ; foreach ( $ headers as $ index => $ header ) { $ arguments_count = func_num_args ( ) ; preg_match_all ( '/^(.*?)\:\s(.*)$/m' , ( $ arguments_count == 2 ? 'Request Method: ' : 'Status: ' ) . trim ( $ header ) , $ matches ) ; foreach ( $ matches [ 0 ] as $ key => $ value ) $ result [ $ index ] [ $ matches [ 1 ] [ $ key ] ] = trim ( $ matches [ 2 ] [ $ key ] ) ; } } return $ result ; } | Parse response headers . |
323 | private function _prepare_urls ( $ urls ) { if ( is_array ( $ urls ) && ! empty ( array_intersect ( array ( 'url' , 'options' , 'data' ) , array_keys ( $ urls ) ) ) ) { if ( ! isset ( $ urls [ 'url' ] ) ) trigger_error ( '<strong>url</strong> key is missing from argument' , E_USER_ERROR ) ; return array ( $ urls ) ; } elseif ( is_array ( $ urls ) ) { $ result = array ( ) ; foreach ( $ urls as $ key => $ values ) { if ( is_numeric ( $ key ) ) { if ( is_array ( $ values ) && ! empty ( array_intersect ( array ( 'url' , 'options' , 'data' ) , array_keys ( $ values ) ) ) ) { if ( ! isset ( $ values [ 'url' ] ) ) trigger_error ( '<strong>url</strong> key is missing from argument' , E_USER_ERROR ) ; $ result [ ] = $ values ; } else { $ result [ ] = array ( 'url' => $ values ) ; } } else { $ result [ ] = array ( 'url' => $ key , 'data' => $ values ) ; } } $ urls = $ result ; } else { $ urls = array ( array ( 'url' => $ urls ) ) ; } array_walk_recursive ( $ urls , function ( & $ value ) { if ( strpos ( $ value , '@' ) === 0 ) if ( version_compare ( PHP_VERSION , '5.5' ) >= 0 ) { $ file = substr ( $ value , 1 ) ; $ value = new CURLFile ( $ file ) ; } } ) ; return $ urls ; } | Normalizes URLs . |
324 | public function register ( ) { $ this -> app -> singleton ( EmailChecker :: class , function ( $ app ) { return new EmailChecker ( ) ; } ) ; $ this -> app -> alias ( EmailChecker :: class , 'email.checker' ) ; } | Register the factory in the application container . |
325 | public static function parseEmailAddress ( $ email ) { $ pattern = sprintf ( '/^(?<local>%s)@(?<domain>%s)$/iD' , self :: EMAIL_REGEX_LOCAL , self :: EMAIL_REGEX_DOMAIN ) ; if ( ! preg_match ( $ pattern , $ email , $ parts ) ) { throw new InvalidEmailException ( sprintf ( '"%s" is not a valid email' , $ email ) ) ; } return array_map ( 'strtolower' , [ $ parts [ 'local' ] , $ parts [ 'domain' ] ] ) ; } | Extract parts of an email address . |
326 | public static function parseLines ( $ content ) { $ lines = explode ( "\n" , $ content ) ; $ lines = array_map ( 'trim' , $ lines ) ; $ lines = array_map ( 'strtolower' , $ lines ) ; $ lines = array_filter ( $ lines , function ( $ line ) { return ( 0 === strlen ( $ line ) || '#' === $ line [ 0 ] ) ? false : $ line ; } ) ; return $ lines ; } | Parse content and extract lines . |
327 | public function isValid ( $ email ) { if ( false === $ email = filter_var ( $ email , FILTER_VALIDATE_EMAIL ) ) { return false ; } try { list ( $ local , $ domain ) = Utilities :: parseEmailAddress ( $ email ) ; } catch ( InvalidEmailException $ e ) { return false ; } return ! $ this -> adapter -> isThrowawayDomain ( $ domain ) ; } | Check if it s a valid email ie . not a throwaway email . |
328 | public function assessTarget ( TargetInterface $ target , array $ policies , \ DateTime $ start = NULL , \ DateTime $ end = NULL , $ remediate = FALSE ) { $ start = $ start ? : new \ DateTime ( '-1 day' ) ; $ end = $ end ? : new \ DateTime ( ) ; $ policies = array_filter ( $ policies , function ( $ policy ) { return $ policy instanceof Policy ; } ) ; $ log = Container :: getLogger ( ) ; $ is_progress_bar = $ log instanceof ProgressBar ; foreach ( $ policies as $ policy ) { if ( $ is_progress_bar ) { $ log -> setTopic ( $ this -> uri . '][' . $ policy -> get ( 'title' ) ) ; } $ log -> info ( "Assessing policy..." ) ; $ sandbox = new Sandbox ( $ target , $ policy , $ this ) ; $ sandbox -> setReportingPeriod ( $ start , $ end ) ; $ response = $ sandbox -> run ( ) ; if ( $ remediate && ! $ response -> isSuccessful ( ) ) { $ log -> info ( "\xE2\x9A\xA0 Remediating " . $ policy -> get ( 'title' ) ) ; $ response = $ sandbox -> remediate ( ) ; } if ( $ is_progress_bar ) { $ log -> advance ( ) ; } } return $ this ; } | Assess a Target . |
329 | public function setPolicyResult ( AuditResponse $ response ) { $ this -> results [ $ response -> getPolicy ( ) -> get ( 'name' ) ] = $ response ; $ this -> successful = $ this -> successful && $ response -> isSuccessful ( ) ; $ severity = $ response -> getPolicy ( ) -> getSeverity ( ) ; if ( ! $ response -> isSuccessful ( ) && ( $ this -> severity < $ severity ) ) { $ this -> setSeverity ( $ severity ) ; } } | Set the result of a Policy . |
330 | public function getPolicyResult ( $ name ) { if ( ! isset ( $ this -> results [ $ name ] ) ) { throw new NoAuditResponseFoundException ( $ name , "Policy '$name' does not have an AuditResponse." ) ; } return $ this -> results [ $ name ] ; } | Get an AuditResponse object by Policy name . |
331 | public function get ( $ property , $ replacements = [ ] ) { if ( ! isset ( $ this -> { $ property } ) ) { throw new \ Exception ( "Attempt to retrieve unknown property: $property. Available properties: \n" . print_r ( ( array ) $ this , 1 ) ) ; } if ( in_array ( $ property , $ this -> renderableProperties ) ) { return $ this -> render ( $ this -> { $ property } , $ replacements ) ; } return $ this -> { $ property } ; } | Retrieve a property value and token replacement . |
332 | public function variable_get ( $ name , $ default = NULL ) { $ vars = $ this -> drush -> setDrushOptions ( [ 'format' => 'json' ] ) -> variableGet ( ) ; if ( ! isset ( $ vars [ $ name ] ) ) { return $ default ; } return $ vars [ $ name ] ; } | Function like the Drupal 7 variable_get function . |
333 | public static function getSources ( ) { $ item = Container :: cache ( __CLASS__ ) -> getItem ( 'sources' ) ; if ( $ item -> isHit ( ) ) { return $ item -> get ( ) ; } $ sources = array_filter ( array_map ( function ( $ class ) { $ object = new $ class ( ) ; if ( ! ( $ object instanceof ProfileSourceInterface ) ) { return false ; } return $ object ; } , Config :: get ( 'ProfileSource' ) ) ) ; usort ( $ sources , function ( $ a , $ b ) { if ( $ a -> getWeight ( ) == $ b -> getWeight ( ) ) { return 0 ; } return $ a -> getWeight ( ) > $ b -> getWeight ( ) ? 1 : - 1 ; } ) ; Container :: cache ( __CLASS__ ) -> save ( $ item -> set ( $ sources ) -> expiresAfter ( 3600 ) ) ; return $ sources ; } | Load the sources that provide policies . |
334 | public static function getSource ( $ name ) { foreach ( self :: getSources ( ) as $ source ) { if ( $ source -> getName ( ) == $ name ) { return $ source ; } } throw new \ Exception ( "ProfileSource not found: $name." ) ; } | Load a single source . |
335 | public function getParameter ( $ key , $ default_value = NULL ) { if ( isset ( $ this -> params [ $ key ] ) ) { return $ this -> params [ $ key ] ; } $ defaults = $ this -> sandbox ( ) -> getPolicy ( ) -> getParameterDefaults ( ) ; if ( isset ( $ defaults [ $ key ] ) ) { $ default_value = $ defaults [ $ key ] ; } $ this -> setParameter ( $ key , $ default_value ) ; return $ default_value ; } | Expose parameters to the check . |
336 | public function run ( ) { $ response = new AuditResponse ( $ this -> getPolicy ( ) ) ; $ watchdog = Container :: getLogger ( ) ; $ watchdog -> info ( 'Auditing ' . $ this -> getPolicy ( ) -> get ( 'name' ) ) ; try { foreach ( $ this -> getPolicy ( ) -> getDepends ( ) as $ dependency ) { $ dependency -> execute ( $ this ) ; } $ outcome = $ this -> getAuditor ( ) -> execute ( $ this ) ; $ watchdog -> debug ( "Tokens:\n" . Yaml :: dump ( $ this -> getParameterTokens ( ) , 4 ) ) ; $ response -> set ( $ outcome , $ this -> getParameterTokens ( ) ) ; } catch ( \ Drutiny \ Policy \ DependencyException $ e ) { $ this -> setParameter ( 'exception' , $ e -> getMessage ( ) ) ; $ response -> set ( $ e -> getDependency ( ) -> getFailBehaviour ( ) , $ this -> getParameterTokens ( ) ) ; } catch ( \ Drutiny \ AuditValidationException $ e ) { $ this -> setParameter ( 'exception' , $ e -> getMessage ( ) ) ; $ watchdog -> warning ( $ e -> getMessage ( ) ) ; $ response -> set ( Audit :: NOT_APPLICABLE , $ this -> getParameterTokens ( ) ) ; } catch ( \ Exception $ e ) { $ message = $ e -> getMessage ( ) ; if ( Container :: getVerbosity ( ) > OutputInterface :: VERBOSITY_NORMAL ) { $ message .= PHP_EOL . $ e -> getTraceAsString ( ) ; } $ this -> setParameter ( 'exception' , $ message ) ; $ response -> set ( Audit :: ERROR , $ this -> getParameterTokens ( ) ) ; } if ( ! $ response -> isIrrelevant ( ) ) { $ this -> getAssessment ( ) -> setPolicyResult ( $ response ) ; } return $ response ; } | Run the check and capture the outcomes . |
337 | public function remediate ( ) { $ response = new AuditResponse ( $ this -> getPolicy ( ) ) ; try { if ( ! ( $ this -> getAuditor ( ) instanceof RemediableInterface ) ) { throw new \ Exception ( get_class ( $ this -> getAuditor ( ) ) . ' is not remediable.' ) ; } Cache :: purge ( ) ; $ outcome = $ this -> getAuditor ( ) -> remediate ( $ this ) ; $ response -> set ( $ outcome , $ this -> getParameterTokens ( ) ) ; } catch ( \ Exception $ e ) { $ this -> setParameter ( 'exception' , $ e -> getMessage ( ) ) ; $ response -> set ( Audit :: ERROR , $ this -> getParameterTokens ( ) ) ; } $ this -> getAssessment ( ) -> setPolicyResult ( $ response ) ; return $ response ; } | Remediate the check if available . |
338 | public function setOutput ( $ filepath = 'stdout' ) { if ( $ filepath != 'stdout' && ! ( $ filepath instanceof OutputInterface ) && ! file_exists ( dirname ( $ filepath ) ) ) { throw new \ InvalidArgumentException ( "Cannot write to $filepath. Parent directory doesn't exist." ) ; } $ this -> output = $ filepath ; return $ this ; } | Set the title of the profile . |
339 | public function set ( $ state = NULL , array $ tokens ) { switch ( TRUE ) { case ( $ state === Audit :: SUCCESS ) : case ( $ state === Audit :: PASS ) : $ state = Audit :: SUCCESS ; break ; case ( $ state === Audit :: FAILURE ) : case ( $ state === Audit :: FAIL ) : $ state = Audit :: FAIL ; break ; case ( $ state === Audit :: NOT_APPLICABLE ) : case ( $ state === NULL ) : $ state = Audit :: NOT_APPLICABLE ; break ; case ( $ state === Audit :: IRRELEVANT ) : case ( $ state === Audit :: WARNING ) : case ( $ state === Audit :: WARNING_FAIL ) : case ( $ state === Audit :: NOTICE ) : case ( $ state === Audit :: ERROR ) : break ; default : throw new AuditResponseException ( "Unknown state set in Audit Response: $state" ) ; } $ this -> state = $ state ; $ this -> tokens = $ tokens ; } | Set the state of the response . |
340 | public function getType ( ) { if ( $ this -> isNotApplicable ( ) ) { return 'not-applicable' ; } if ( $ this -> hasError ( ) ) { return 'error' ; } if ( $ this -> isNotice ( ) ) { return 'notice' ; } if ( $ this -> hasWarning ( ) ) { return 'warning' ; } $ policy_type = $ this -> policy -> get ( 'type' ) ; if ( $ policy_type == 'data' ) { return 'notice' ; } return $ this -> isSuccessful ( ) ? 'success' : 'failure' ; } | Get the type of response based on policy type and audit response . |
341 | public function getSummary ( ) { $ summary = [ ] ; switch ( TRUE ) { case ( $ this -> state === Audit :: NOT_APPLICABLE ) : $ summary [ ] = "This policy is not applicable to this site." ; break ; case ( $ this -> state === Audit :: ERROR ) : $ tokens = [ 'exception' => isset ( $ this -> tokens [ 'exception' ] ) ? $ this -> tokens [ 'exception' ] : 'Unknown exception occured.' ] ; $ summary [ ] = strtr ( 'Could not determine the state of ' . $ this -> getTitle ( ) . ' due to an error:```exception```' , $ tokens ) ; break ; case ( $ this -> state === Audit :: WARNING ) : $ summary [ ] = $ this -> getWarning ( ) ; case ( $ this -> state === Audit :: SUCCESS ) : case ( $ this -> state === Audit :: PASS ) : case ( $ this -> state === Audit :: NOTICE ) : $ summary [ ] = $ this -> getSuccess ( ) ; break ; case ( $ this -> state === Audit :: WARNING_FAIL ) : $ summary [ ] = $ this -> getWarning ( ) ; case ( $ this -> state === Audit :: FAILURE ) : case ( $ this -> state === Audit :: FAIL ) : $ summary [ ] = $ this -> getFailure ( ) ; break ; default : throw new AuditResponseException ( "Unknown AuditResponse state ({$this->state}). Cannot generate summary for '" . $ this -> getTitle ( ) . "'." ) ; break ; } return implode ( PHP_EOL , $ summary ) ; } | Get the response based on the state outcome . |
342 | public function getParameterDefaults ( ) { $ defaults = [ ] ; foreach ( $ this -> parameters as $ name => $ info ) { $ defaults [ $ name ] = isset ( $ info [ 'default' ] ) ? $ info [ 'default' ] : null ; } return $ defaults ; } | Pull default values from each parameter . |
343 | public static function createFromProfile ( $ name , $ weight = 0 , $ definition = [ ] ) { $ policyDefinition = new static ( ) ; $ policyDefinition -> setName ( $ name ) -> setWeight ( $ weight ) ; if ( isset ( $ definition [ 'parameters' ] ) ) { $ policyDefinition -> setParameters ( $ definition [ 'parameters' ] ) ; } $ policy = Policy :: load ( $ name ) ; if ( isset ( $ definition [ 'severity' ] ) ) { $ policyDefinition -> setSeverity ( $ definition [ 'severity' ] ) ; } else { $ policyDefinition -> setSeverity ( $ policy -> getSeverity ( ) ) ; } return $ policyDefinition ; } | Build a PolicyDefinition from Profile input . |
344 | public function getPolicy ( ) { $ policy = Policy :: load ( $ this -> getName ( ) ) ; if ( $ this -> getSeverity ( ) !== NULL ) { $ policy -> setSeverity ( $ this -> getSeverity ( ) ) ; } foreach ( $ this -> parameters as $ param => $ value ) { $ info = [ 'default' => $ value ] ; $ policy -> addParameter ( $ param , $ info ) ; } return $ policy ; } | Get the policy for the profile . |
345 | public function setDependencyPolicyName ( $ name ) { $ this -> positionBefore [ $ name ] = self :: createFromProfile ( $ name , $ this -> getWeight ( ) ) ; return $ this ; } | Track a policy dependency as a policy definition . |
346 | public static function createFromTarget ( TargetInterface $ target , $ options = [ ] ) { try { $ info = $ target -> getOptions ( ) ; $ launchers = [ 'drush-launcher' , 'drush.launcher' , 'drush' ] ; $ binary = 'which ' . implode ( ' || which ' , $ launchers ) ; $ info = trim ( $ target -> exec ( '$(' . $ binary . ') -r ' . $ info [ 'root' ] . ' status --format=json' ) ) ; $ info = \ Drutiny \ Utility :: jsonDecodeDirty ( $ info , TRUE ) ; if ( Comparator :: greaterThanOrEqualTo ( $ info [ 'drush-version' ] , '9.0.0' ) ) { array_unshift ( $ launchers , 'drush9' ) ; $ binary = 'which ' . implode ( ' || which ' , $ launchers ) ; } $ binary = trim ( $ target -> exec ( $ binary ) ) ; $ info = trim ( $ target -> exec ( $ binary . ' -r ' . $ info [ 'root' ] . ' status --format=json' ) ) ; $ info = json_decode ( $ info , TRUE ) ; } catch ( ProcessFailedException $ e ) { Container :: getLogger ( ) -> error ( $ e -> getProcess ( ) -> getOutput ( ) ) ; throw $ e ; } switch ( TRUE ) { case Comparator :: greaterThanOrEqualTo ( $ info [ 'drush-version' ] , '9.0.0' ) : $ driver = Drush9Driver :: createFromTarget ( $ target , $ binary ) ; break ; default : $ driver = DrushDriver :: createFromTarget ( $ target , $ binary ) ; } $ driver -> setOptions ( $ options ) ; return $ driver ; } | Derive a drush driver from a given Target . |
347 | static public function parseTarget ( $ target ) { $ target_name = 'drush' ; $ target_data = $ target ; if ( strpos ( $ target , ':' ) !== FALSE ) { list ( $ target_name , $ target_data ) = explode ( ':' , $ target , 2 ) ; } return [ $ target_name , $ target_data ] ; } | Parse a target argument into the target driver and data . |
348 | final public function getMetadata ( ) { $ item = Container :: cache ( 'target' ) -> getItem ( 'metadata' ) ; if ( ! $ item -> isHit ( ) ) { $ metadata = [ ] ; $ reflection = new \ ReflectionClass ( $ this ) ; $ interfaces = $ reflection -> getInterfaces ( ) ; $ reader = new AnnotationReader ( ) ; foreach ( $ interfaces as $ interface ) { $ methods = $ interface -> getMethods ( \ ReflectionMethod :: IS_PUBLIC ) ; foreach ( $ methods as $ method ) { $ annotation = $ reader -> getMethodAnnotation ( $ method , 'Drutiny\Annotation\Metadata' ) ; if ( empty ( $ annotation ) ) { continue ; } $ metadata [ $ annotation -> name ] = $ method -> name ; } } Container :: cache ( 'target' ) -> save ( $ item -> set ( $ metadata ) ) ; } return $ item -> get ( ) ; } | Pull metadata from Drutiny \ Target \ Metadata interfaces . |
349 | public static function createFromTarget ( TargetInterface $ target , $ drush_bin = 'drush' ) { $ options = [ ] ; $ alias = '@self' ; if ( $ target instanceof DrushTargetInterface ) { $ alias = $ target -> getAlias ( ) ; } return new static ( $ target , $ drush_bin , $ options , $ alias ) ; } | Instansiate a new Drush Driver instance . |
350 | protected function runCommand ( $ method , $ args , $ pipe = '' ) { if ( $ this -> target instanceof DrushExecutableTargetInterface ) { return $ this -> target -> runDrushCommand ( $ method , $ args , $ this -> getOptions ( ) , $ pipe , $ this -> drushBin ) ; } return $ this -> target -> exec ( '@pipe @bin @alias @options @method @args' , [ '@method' => $ method , '@alias' => $ this -> getAlias ( ) , '@bin' => $ this -> drushBin , '@args' => implode ( ' ' , $ args ) , '@options' => implode ( ' ' , $ this -> getOptions ( ) ) , '@pipe' => $ pipe ] ) ; } | Run the drush command . |
351 | public function setOptions ( array $ options ) { foreach ( $ options as $ key => $ value ) { if ( is_int ( $ key ) ) { $ option = '--' . $ value ; } elseif ( strlen ( $ key ) == 1 ) { $ option = '-' . $ key ; if ( ! empty ( $ value ) ) { $ option .= ' ' . escapeshellarg ( $ value ) ; } } else { if ( $ key == 'uri' && $ value == 'default' ) { continue ; } $ option = '--' . $ key ; if ( ! empty ( $ value ) ) { $ option .= '=' . escapeshellarg ( $ value ) ; } } if ( ! in_array ( $ option , $ this -> options ) ) { $ this -> options [ ] = $ option ; } } return $ this ; } | Set drush options . |
352 | private function cleanOutput ( $ output ) { if ( ! is_array ( $ output ) ) { $ output = explode ( PHP_EOL , $ output ) ; } foreach ( $ output as $ key => $ value ) { $ invalid_strings = [ 'date_timezone_set() expects parameter' , 'date_format() expects parameter' , 'common.inc:20' , 'given common.inc:20' , 'Warning: Using a password on the command line interface can be insecure.' , ] ; foreach ( $ invalid_strings as $ invalid_string ) { if ( strpos ( $ value , $ invalid_string ) === 0 ) { unset ( $ output [ $ key ] ) ; } } } $ output = array_filter ( $ output ) ; return array_values ( $ output ) ; } | Clean up the output of Drush . |
353 | public function moduleEnabled ( $ name ) { $ this -> options [ ] = '--format=json' ; $ modules = $ this -> __call ( 'pmList' , [ ] ) ; if ( ! $ modules = json_decode ( $ modules , TRUE ) ) { throw new DrushFormatException ( "Cannot parse json output from drush: $modules" , $ modules ) ; } $ this -> options = [ ] ; return isset ( $ modules [ $ name ] ) && $ modules [ $ name ] [ 'status' ] === 'Enabled' ; } | Determine if a module is enabled or not . |
354 | public function configSet ( $ collection , $ key , $ value ) { $ value = base64_encode ( Yaml :: dump ( $ value ) ) ; if ( $ index = array_search ( '--format=json' , $ this -> options ) ) { unset ( $ this -> options [ $ index ] ) ; } $ this -> options [ ] = '--format=yaml' ; $ this -> options [ ] = '-y' ; $ pipe = "echo '$value' | base64 --decode |" ; $ this -> runCommand ( 'config-set' , [ $ collection , $ key , '-' ] , $ pipe ) ; return TRUE ; } | Override config - set to allow better value setting . |
355 | public function sqlq ( $ sql ) { $ sql = strtr ( $ sql , [ "{" => '' , "}" => '' ] ) ; $ output = trim ( $ this -> __call ( 'sqlq' , [ '"' . $ sql . '"' ] ) ) ; $ output = $ this -> cleanOutput ( $ output ) ; return $ output ; } | Override for drush command sqlq . |
356 | public static function loadFromFile ( $ filepath ) { $ info = Yaml :: parseFile ( $ filepath ) ; $ name = str_replace ( '.profile.yml' , '' , pathinfo ( $ filepath , PATHINFO_BASENAME ) ) ; $ profile = new static ( ) ; $ profile -> setTitle ( $ info [ 'title' ] ) -> setName ( $ name ) -> setFilepath ( $ filepath ) ; if ( isset ( $ info [ 'description' ] ) ) { $ profile -> setDescription ( $ info [ 'description' ] ) ; } if ( isset ( $ info [ 'policies' ] ) ) { $ v21_keys = [ 'parameters' , 'severity' ] ; foreach ( $ info [ 'policies' ] as $ name => $ metadata ) { if ( ! empty ( $ metadata ) && ! count ( array_intersect ( $ v21_keys , array_keys ( $ metadata ) ) ) ) { throw new \ Exception ( "{$info['title']} is a v2.0.x profile. Please upgrade $filepath to v2.2.x schema." ) ; } $ weight = array_search ( $ name , array_keys ( $ info [ 'policies' ] ) ) ; $ profile -> addPolicyDefinition ( PolicyDefinition :: createFromProfile ( $ name , $ weight , $ metadata ) ) ; } } if ( isset ( $ info [ 'excluded_policies' ] ) && is_array ( $ info [ 'excluded_policies' ] ) ) { $ profile -> addExcludedPolicies ( $ info [ 'excluded_policies' ] ) ; } if ( isset ( $ info [ 'include' ] ) ) { foreach ( $ info [ 'include' ] as $ name ) { $ include = ProfileSource :: loadProfileByName ( $ name ) ; $ profile -> addInclude ( $ include ) ; } } if ( isset ( $ info [ 'format' ] ) ) { foreach ( $ info [ 'format' ] as $ format => $ options ) { $ profile -> addFormatOptions ( Format :: create ( $ format , $ options ) ) ; } } return $ profile ; } | Load a profile from file . |
357 | public function getFormatOption ( $ format , $ options = [ ] ) { $ format = isset ( $ this -> format [ $ format ] ) ? $ this -> format [ $ format ] : Format :: create ( $ format , $ options ) ; if ( isset ( $ options [ 'output' ] ) && empty ( $ format -> getOutput ( ) ) ) { $ format -> setOutput ( $ options [ 'output' ] ) ; } return $ format ; } | Add a FormatOptions to the profile . |
358 | public function getParent ( $ name = NULL ) { if ( ! $ this -> parent ) { return FALSE ; } if ( $ name ) { if ( $ this -> parent -> getName ( ) == $ name ) { return $ this -> parent ; } if ( $ parent = $ this -> parent -> getInclude ( $ name ) ) { return $ parent ; } return $ this -> parent -> getParent ( $ name ) ; } return $ this -> parent ; } | Find a parent in the tree of parent profiles . |
359 | public function execute ( Sandbox $ sandbox ) { $ language = new ExpressionLanguage ( $ sandbox ) ; Container :: getLogger ( ) -> info ( "Evaluating expression: " . $ language -> compile ( $ this -> expression ) ) ; try { if ( $ return = $ language -> evaluate ( $ this -> expression ) ) { Container :: getLogger ( ) -> debug ( __CLASS__ . ": Expression PASSED: $return" ) ; return $ return ; } } catch ( \ Exception $ e ) { Container :: getLogger ( ) -> warning ( $ e -> getMessage ( ) ) ; } Container :: getLogger ( ) -> debug ( __CLASS__ . ": Expression FAILED." ) ; throw new DependencyException ( $ this ) ; } | Evaluate the dependency . |
360 | public function process ( ) { if ( empty ( $ this -> batches ) ) { return true ; } if ( $ this -> currentBatch >= count ( $ this -> batches ) ) { return true ; } $ this -> prepareIndexes ( ) ; $ this -> setBatch ( $ this -> currentBatch + 1 ) ; return true ; } | Process the current queue |
361 | protected function segmentBatches ( $ source ) { $ batchSize = static :: config ( ) -> get ( 'batch_size' ) ; if ( $ batchSize === 0 ) { return array ( $ source ) ; } $ softCap = static :: config ( ) -> get ( 'batch_soft_cap' ) ; $ batches = array ( ) ; $ current = array ( ) ; $ currentSize = 0 ; foreach ( $ source as $ base => $ statefulids ) { if ( ! $ statefulids ) { continue ; } foreach ( $ statefulids as $ stateKey => $ statefulid ) { $ state = $ statefulid [ 'state' ] ; $ ids = $ statefulid [ 'ids' ] ; if ( ! $ ids ) { continue ; } while ( $ ids ) { $ take = $ batchSize - $ currentSize ; if ( count ( $ ids ) <= $ take + $ softCap ) { $ take += $ softCap ; } $ items = array_slice ( $ ids , 0 , $ take , true ) ; $ ids = array_slice ( $ ids , count ( $ items ) , null , true ) ; $ currentSize += count ( $ items ) ; $ merge = array ( $ base => array ( $ stateKey => array ( 'state' => $ state , 'ids' => $ items ) ) ) ; $ current = $ current ? array_merge_recursive ( $ current , $ merge ) : $ merge ; if ( $ currentSize >= $ batchSize ) { $ batches [ ] = $ current ; $ current = array ( ) ; $ currentSize = 0 ; } } } } if ( $ currentSize ) { $ batches [ ] = $ current ; } return $ batches ; } | Segments batches acording to the specified rules |
362 | public function triggerReindex ( ) { if ( ! $ this -> owner -> ID ) { return ; } $ id = $ this -> owner -> ID ; $ class = $ this -> owner -> ClassName ; $ state = SearchVariant :: current_state ( $ class ) ; $ base = DataObject :: getSchema ( ) -> baseDataClass ( $ class ) ; $ key = "$id:$base:" . serialize ( $ state ) ; $ statefulids = array ( array ( 'id' => $ id , 'state' => $ state ) ) ; $ writes = array ( $ key => array ( 'base' => $ base , 'class' => $ class , 'id' => $ id , 'statefulids' => $ statefulids , 'fields' => array ( ) ) ) ; SearchUpdater :: process_writes ( $ writes ) ; } | Forces this object to trigger a re - index in the current state |
363 | public static function solr_options ( ) { if ( self :: $ merged_solr_options ) { return self :: $ merged_solr_options ; } $ defaults = array ( 'host' => 'localhost' , 'port' => 8983 , 'path' => '/solr' , 'version' => '4' ) ; $ version = isset ( self :: $ solr_options [ 'version' ] ) ? self :: $ solr_options [ 'version' ] : $ defaults [ 'version' ] ; $ module = ModuleLoader :: getModule ( 'silverstripe/fulltextsearch' ) ; $ modulePath = $ module -> getPath ( ) ; if ( version_compare ( $ version , '4' , '>=' ) ) { $ versionDefaults = [ 'service' => Solr4Service :: class , 'extraspath' => $ modulePath . '/conf/solr/4/extras/' , 'templatespath' => $ modulePath . '/conf/solr/4/templates/' , ] ; } else { $ versionDefaults = [ 'service' => Solr3Service :: class , 'extraspath' => $ modulePath . '/conf/solr/3/extras/' , 'templatespath' => $ modulePath . '/conf/solr/3/templates/' , ] ; } return ( self :: $ merged_solr_options = array_merge ( $ defaults , $ versionDefaults , self :: $ solr_options ) ) ; } | Get the configured Solr options with the defaults all merged in |
364 | public static function service ( $ core = null ) { $ options = self :: solr_options ( ) ; if ( ! self :: $ service_singleton ) { self :: $ service_singleton = Injector :: inst ( ) -> create ( $ options [ 'service' ] , $ options [ 'host' ] , $ options [ 'port' ] , $ options [ 'path' ] ) ; } if ( $ core ) { if ( ! isset ( self :: $ service_core_singletons [ $ core ] ) ) { self :: $ service_core_singletons [ $ core ] = self :: $ service_singleton -> serviceForCore ( singleton ( $ core ) -> getIndexName ( ) ) ; } return self :: $ service_core_singletons [ $ core ] ; } return self :: $ service_singleton ; } | Get a SolrService |
365 | protected function processIndex ( LoggerInterface $ logger , SolrIndex $ indexInstance , $ batchSize , $ taskName , $ classes = null ) { $ indexClasses = $ this -> getClassesForIndex ( $ indexInstance , $ classes ) ; $ logger -> info ( "Clearing obsolete classes from " . $ indexInstance -> getIndexName ( ) ) ; $ indexInstance -> clearObsoleteClasses ( $ indexClasses ) ; foreach ( $ indexClasses as $ class => $ options ) { $ includeSubclasses = $ options [ 'include_children' ] ; foreach ( SearchVariant :: reindex_states ( $ class , $ includeSubclasses ) as $ state ) { $ this -> processVariant ( $ logger , $ indexInstance , $ state , $ class , $ includeSubclasses , $ batchSize , $ taskName ) ; } } } | Process index for a single SolrIndex instance |
366 | protected function getClassesForIndex ( SolrIndex $ index , $ filterClasses = null ) { $ classes = $ index -> getClasses ( ) ; if ( ! $ filterClasses ) { return $ classes ; } if ( ! is_array ( $ filterClasses ) ) { $ filterClasses = explode ( ',' , $ filterClasses ) ; } return array_intersect_key ( $ classes , array_combine ( $ filterClasses , $ filterClasses ) ) ; } | Get valid classes and options for an index with an optional filter |
367 | protected function processVariant ( LoggerInterface $ logger , SolrIndex $ indexInstance , $ state , $ class , $ includeSubclasses , $ batchSize , $ taskName ) { SearchVariant :: activate_state ( $ state ) ; $ query = $ class :: get ( ) ; if ( ! $ includeSubclasses ) { $ query = $ query -> filter ( 'ClassName' , $ class ) ; } $ total = $ query -> count ( ) ; if ( $ total == 0 || $ indexInstance -> variantStateExcluded ( $ state ) ) { $ logger -> info ( "Clearing all records of type {$class} in the current state: " . json_encode ( $ state ) ) ; $ this -> clearRecords ( $ indexInstance , $ class ) ; return ; } $ groups = ( int ) ( ( $ total + $ batchSize - 1 ) / $ batchSize ) ; for ( $ group = 0 ; $ group < $ groups ; $ group ++ ) { $ this -> processGroup ( $ logger , $ indexInstance , $ state , $ class , $ groups , $ group , $ taskName ) ; } } | Process re - index for a given variant state and class |
368 | public function runGroup ( LoggerInterface $ logger , SolrIndex $ indexInstance , $ state , $ class , $ groups , $ group ) { Environment :: increaseTimeLimitTo ( ) ; SearchVariant :: activate_state ( $ state ) ; $ logger -> info ( "Adding $class" ) ; $ this -> clearRecords ( $ indexInstance , $ class , $ groups , $ group ) ; $ items = $ this -> getRecordsInGroup ( $ indexInstance , $ class , $ groups , $ group ) ; $ processed = array ( ) ; foreach ( $ items as $ item ) { $ processed [ ] = $ item -> ID ; $ indexInstance -> add ( $ item ) ; $ item -> destroy ( ) ; } $ logger -> info ( "Updated " . implode ( ',' , $ processed ) ) ; DB :: query ( 'SELECT 1' ) ; $ logger -> info ( "Done" ) ; } | Explicitly invoke the process that performs the group processing . Can be run either by a background task or a queuedjob . |
369 | protected function getRecordsInGroup ( SolrIndex $ indexInstance , $ class , $ groups , $ group ) { $ baseClass = DataObject :: getSchema ( ) -> baseDataClass ( $ class ) ; $ items = DataList :: create ( $ class ) -> where ( sprintf ( '"%s"."ID" %% \'%d\' = \'%d\'' , DataObject :: getSchema ( ) -> tableName ( $ baseClass ) , intval ( $ groups ) , intval ( $ group ) ) ) -> sort ( "ID" ) ; $ classes = $ indexInstance -> getClasses ( ) ; $ options = $ classes [ $ class ] ; if ( ! $ options [ 'include_children' ] ) { $ items = $ items -> filter ( 'ClassName' , $ class ) ; } return $ items ; } | Gets the datalist of records in the given group in the current state |
370 | protected function clearRecords ( SolrIndex $ indexInstance , $ class , $ groups = null , $ group = null ) { $ conditions = array ( "+(ClassHierarchy:{$class})" ) ; if ( $ groups ) { $ conditions [ ] = "+_query_:\"{!frange l={$group} u={$group}}mod(ID, {$groups})\"" ; } $ query = new SearchQuery ( ) ; SearchVariant :: with ( $ class ) -> call ( 'alterQuery' , $ query , $ indexInstance ) ; if ( $ query -> isfiltered ( ) ) { $ conditions = array_merge ( $ conditions , $ indexInstance -> getFiltersComponent ( $ query ) ) ; } $ deleteQuery = implode ( ' ' , $ conditions ) ; $ indexInstance -> getService ( ) -> deleteByQuery ( $ deleteQuery ) ; } | Clear all records of the given class in the current state ONLY . |
371 | protected function cancelExistingJobs ( $ type ) { $ clearable = array ( QueuedJob :: STATUS_PAUSED , QueuedJob :: STATUS_NEW , QueuedJob :: STATUS_WAIT , QueuedJob :: STATUS_INIT , QueuedJob :: STATUS_RUN ) ; DB :: query ( sprintf ( 'UPDATE "%s" ' . ' SET "JobStatus" = \'%s\'' . ' WHERE "JobStatus" IN (\'%s\')' . ' AND "Implementation" = \'%s\'' , Convert :: raw2sql ( DataObject :: getSchema ( ) -> tableName ( QueuedJobDescriptor :: class ) ) , Convert :: raw2sql ( QueuedJob :: STATUS_CANCELLED ) , implode ( "','" , Convert :: raw2sql ( $ clearable ) ) , Convert :: raw2sql ( $ type ) ) ) ; return DB :: affected_rows ( ) ; } | Cancel any cancellable jobs |
372 | protected function getLeftComparison ( SearchCriterion $ searchCriterion ) { switch ( $ searchCriterion -> getComparison ( ) ) { case SearchCriterion :: GREATER_EQUAL : case SearchCriterion :: GREATER_THAN : return $ searchCriterion -> getValue ( ) ; case SearchCriterion :: ISNULL : case SearchCriterion :: ISNOTNULL : case SearchCriterion :: LESS_EQUAL : case SearchCriterion :: LESS_THAN : return '*' ; default : throw new InvalidArgumentException ( 'Invalid comparison for RangeCriterion' ) ; } } | Select the value that we want as our left comparison value . |
373 | protected function getLogger ( ) { if ( $ this -> logger ) { return $ this -> logger ; } $ this -> logger = $ this -> getLoggerFactory ( ) -> getQueuedJobLogger ( $ this ) ; return $ this -> logger ; } | Gets a logger for this job |
374 | protected function processGroup ( LoggerInterface $ logger , SolrIndex $ indexInstance , $ state , $ class , $ groups , $ group , $ taskName ) { $ indexClass = get_class ( $ indexInstance ) ; $ indexClassEscaped = $ indexClass ; $ statevar = json_encode ( $ state ) ; if ( strpos ( PHP_OS , "WIN" ) !== false ) { $ statevar = '"' . str_replace ( '"' , '\\"' , $ statevar ) . '"' ; } else { $ statevar = "'" . $ statevar . "'" ; $ class = addslashes ( $ class ) ; $ indexClassEscaped = addslashes ( $ indexClass ) ; } $ php = Environment :: getEnv ( 'SS_PHP_BIN' ) ? : Config :: inst ( ) -> get ( static :: class , 'php_bin' ) ; $ frameworkPath = ModuleLoader :: getModule ( 'silverstripe/framework' ) -> getPath ( ) ; $ scriptPath = sprintf ( "%s%scli-script.php" , $ frameworkPath , DIRECTORY_SEPARATOR ) ; $ scriptTask = "{$php} {$scriptPath} dev/tasks/{$taskName}" ; $ cmd = "{$scriptTask} index={$indexClassEscaped} class={$class} group={$group} groups={$groups} variantstate={$statevar}" ; $ cmd .= " verbose=1" ; $ logger -> info ( "Running '$cmd'" ) ; $ process = new Process ( $ cmd ) ; $ process -> setTimeout ( $ this -> config ( ) -> get ( 'process_timeout' ) ) ; $ process -> inheritEnvironmentVariables ( ) ; $ process -> run ( ) ; $ res = $ process -> getOutput ( ) ; if ( $ logger ) { $ logger -> info ( preg_replace ( '/\r\n|\n/' , '$0 ' , $ res ) ) ; } if ( Director :: isDev ( ) ) { Solr :: service ( $ indexClass ) -> commit ( ) ; } DB :: query ( 'SELECT 1' ) ; } | Process a single group . |
375 | public function commit ( $ expungeDeletes = false , $ waitFlush = null , $ waitSearcher = true , $ timeout = 3600 ) { if ( $ waitFlush ) { user_error ( 'waitFlush must be false when using Solr 4.0+' . E_USER_ERROR ) ; } $ expungeValue = $ expungeDeletes ? 'true' : 'false' ; $ searcherValue = $ waitSearcher ? 'true' : 'false' ; $ rawPost = '<commit expungeDeletes="' . $ expungeValue . '" waitSearcher="' . $ searcherValue . '" />' ; return $ this -> _sendRawPost ( $ this -> _updateUrl , $ rawPost , $ timeout ) ; } | Replace underlying commit function to remove waitFlush in 4 . 0 + since it s been deprecated and 4 . 4 throws errors if you pass it |
376 | protected function updateIndex ( $ instance , $ store ) { $ index = $ instance -> getIndexName ( ) ; $ this -> getLogger ( ) -> info ( "Configuring $index." ) ; $ this -> getLogger ( ) -> info ( "Uploading configuration ..." ) ; $ instance -> uploadConfig ( $ store ) ; $ service = Solr :: service ( ) ; if ( $ service -> coreIsActive ( $ index ) ) { $ this -> getLogger ( ) -> info ( "Reloading core ..." ) ; $ service -> coreReload ( $ index ) ; } else { $ this -> getLogger ( ) -> info ( "Creating core ..." ) ; $ service -> coreCreate ( $ index , $ store -> instanceDir ( $ index ) ) ; } $ this -> getLogger ( ) -> info ( "Done" ) ; } | Update the index on the given store |
377 | protected function getSolrConfigStore ( ) { $ options = Solr :: solr_options ( ) ; if ( ! isset ( $ options [ 'indexstore' ] ) || ! ( $ indexstore = $ options [ 'indexstore' ] ) ) { throw new Exception ( 'No index configuration for Solr provided' , E_USER_ERROR ) ; } $ mode = $ indexstore [ 'mode' ] ; if ( $ mode === 'file' ) { return new SolrConfigStore_File ( $ indexstore ) ; } if ( $ mode === 'webdav' ) { return new SolrConfigStore_WebDAV ( $ indexstore ) ; } if ( $ mode === 'post' ) { return new SolrConfigStore_Post ( $ indexstore ) ; } if ( ClassInfo :: exists ( $ mode ) && ClassInfo :: classImplements ( $ mode , SolrConfigStore :: class ) ) { return new $ mode ( $ indexstore ) ; } user_error ( 'Unknown Solr index mode ' . $ indexstore [ 'mode' ] , E_USER_ERROR ) ; } | Get config store |
378 | public static function variants ( $ class = null , $ includeSubclasses = true ) { if ( ! $ class ) { if ( self :: $ variants === null ) { $ classes = ClassInfo :: subclassesFor ( static :: class ) ; $ concrete = array ( ) ; foreach ( $ classes as $ variantclass ) { $ ref = new ReflectionClass ( $ variantclass ) ; if ( $ ref -> isInstantiable ( ) ) { $ variant = singleton ( $ variantclass ) ; if ( $ variant -> appliesToEnvironment ( ) ) { $ concrete [ $ variantclass ] = $ variant ; } } } self :: $ variants = $ concrete ; } return self :: $ variants ; } else { $ key = $ class . '!' . $ includeSubclasses ; if ( ! isset ( self :: $ class_variants [ $ key ] ) ) { self :: $ class_variants [ $ key ] = array ( ) ; foreach ( self :: variants ( ) as $ variantclass => $ instance ) { if ( $ instance -> appliesTo ( $ class , $ includeSubclasses ) ) { self :: $ class_variants [ $ key ] [ $ variantclass ] = $ instance ; } } } return self :: $ class_variants [ $ key ] ; } } | Returns an array of variants . |
379 | public static function current_state ( $ class = null , $ includeSubclasses = true ) { $ state = array ( ) ; foreach ( self :: variants ( $ class , $ includeSubclasses ) as $ variant => $ instance ) { $ state [ $ variant ] = $ instance -> currentState ( ) ; } return $ state ; } | Get the current state of every variant |
380 | public static function activate_state ( $ state ) { foreach ( self :: variants ( ) as $ variant => $ instance ) { if ( isset ( $ state [ $ variant ] ) && $ instance -> appliesToEnvironment ( ) ) { $ instance -> activateState ( $ state [ $ variant ] ) ; } } } | Activate all the states in the passed argument |
381 | public static function reindex_states ( $ class = null , $ includeSubclasses = true ) { $ allstates = array ( ) ; foreach ( self :: variants ( $ class , $ includeSubclasses ) as $ variant => $ instance ) { if ( $ states = $ instance -> reindexStates ( ) ) { $ allstates [ $ variant ] = $ states ; } } return $ allstates ? new CombinationsArrayIterator ( $ allstates ) : array ( array ( ) ) ; } | Return an iterator that when used in a for loop activates one combination of reindex states per loop and restores back to the original state at the end |
382 | protected function addFilterField ( $ index , $ name , $ field ) { if ( isset ( $ index -> filterFields [ $ name ] ) ) { $ field [ 'base' ] = $ this -> mergeClasses ( $ index -> filterFields [ $ name ] [ 'base' ] , $ field [ 'base' ] ) ; $ field [ 'origin' ] = $ this -> mergeClasses ( $ index -> filterFields [ $ name ] [ 'origin' ] , $ field [ 'origin' ] ) ; } $ index -> filterFields [ $ name ] = $ field ; } | Add new filter field to index safely . |
383 | public function getResults ( ) { $ request = $ this -> getRequestHandler ( ) -> getRequest ( ) ; $ searchTerms = $ request -> requestVar ( 'Search' ) ; $ query = SearchQuery :: create ( ) -> addSearchTerm ( $ searchTerms ) ; if ( $ start = $ request -> requestVar ( 'start' ) ) { $ query -> setStart ( $ start ) ; } $ params = [ 'spellcheck' => 'true' , 'spellcheck.collate' => 'true' , ] ; $ indexClasses = FullTextSearch :: get_indexes ( SolrIndex :: class ) ; $ indexClass = reset ( $ indexClasses ) ; $ index = $ indexClass :: singleton ( ) ; $ results = $ index -> search ( $ query , - 1 , - 1 , $ params ) ; if ( $ results ) { foreach ( $ results -> Matches as $ match ) { if ( ! $ match -> canView ( ) ) { $ results -> Matches -> remove ( $ match ) ; } } } return $ results ; } | Return dataObjectSet of the results using current request to get info from form . Simplest implementation loops over all Solr indexes |
384 | protected function coreCommand ( $ command , $ core , $ params = array ( ) ) { $ command = strtoupper ( $ command ) ; $ params = array_merge ( $ params , array ( 'action' => $ command , 'wt' => 'json' ) ) ; $ params [ $ command == 'CREATE' ? 'name' : 'core' ] = $ core ; return $ this -> _sendRawGet ( $ this -> _constructUrl ( 'admin/cores' , $ params ) ) ; } | Handle encoding the GET parameters and making the HTTP call to execute a core command |
385 | public function coreIsActive ( $ core ) { $ result = $ this -> coreCommand ( 'STATUS' , $ core ) ; return isset ( $ result -> status -> $ core -> uptime ) ; } | Is the passed core active? |
386 | public function coreCreate ( $ core , $ instancedir , $ config = null , $ schema = null , $ datadir = null ) { $ args = array ( 'instanceDir' => $ instancedir ) ; if ( $ config ) { $ args [ 'config' ] = $ config ; } if ( $ schema ) { $ args [ 'schema' ] = $ schema ; } if ( $ datadir ) { $ args [ 'dataDir' ] = $ datadir ; } return $ this -> coreCommand ( 'CREATE' , $ core , $ args ) ; } | Create a new core |
387 | public function serviceForCore ( $ core ) { $ klass = Config :: inst ( ) -> get ( get_called_class ( ) , 'core_class' ) ; return new $ klass ( $ this -> _host , $ this -> _port , $ this -> _path . $ core , $ this -> _httpTransport ) ; } | Create a new Solr4Service_Core instance for the passed core |
388 | public function getIndexName ( ) { $ name = $ this -> sanitiseClassName ( get_class ( $ this ) , '-' ) ; $ indexParts = [ $ name ] ; if ( $ indexPrefix = Environment :: getEnv ( 'SS_SOLR_INDEX_PREFIX' ) ) { array_unshift ( $ indexParts , $ indexPrefix ) ; } if ( $ indexSuffix = Environment :: getEnv ( 'SS_SOLR_INDEX_SUFFIX' ) ) { $ indexParts [ ] = $ indexSuffix ; } return implode ( $ indexParts ) ; } | Helper for returning the correct index name . Supports prefixing and suffixing |
389 | public function addAnalyzer ( $ field , $ type , $ params ) { $ fullFields = $ this -> fieldData ( $ field ) ; if ( $ fullFields ) { foreach ( $ fullFields as $ fullField => $ spec ) { if ( ! isset ( $ this -> analyzerFields [ $ fullField ] ) ) { $ this -> analyzerFields [ $ fullField ] = array ( ) ; } $ this -> analyzerFields [ $ fullField ] [ $ type ] = $ params ; } } } | Index - time analyzer which is applied to a specific field . Can be used to remove HTML tags apply stemming etc . |
390 | protected function getCopyDestinations ( ) { $ copyFields = $ this -> config ( ) -> copy_fields ; if ( $ copyFields ) { return $ copyFields ; } $ df = $ this -> getDefaultField ( ) ; return array ( $ df ) ; } | Get list of fields each text field should be copied into . This will fallback to the default field if omitted . |
391 | protected function getCollatedSuggestion ( $ collation = '' ) { if ( is_string ( $ collation ) ) { return $ collation ; } if ( is_object ( $ collation ) ) { if ( isset ( $ collation -> misspellingsAndCorrections ) ) { foreach ( $ collation -> misspellingsAndCorrections as $ key => $ value ) { return $ value ; } } } return '' ; } | Extract first suggestion text from collated values |
392 | protected function getNiceSuggestion ( $ collation = '' ) { $ collationParts = explode ( ' ' , $ collation ) ; foreach ( $ collationParts as $ key => & $ part ) { $ part = ltrim ( $ part , '+' ) ; } return implode ( ' ' , $ collationParts ) ; } | Extract a human friendly spelling suggestion from a Solr spellcheck collation string . |
393 | public function addStoredField ( $ field , $ forceType = null , $ extraOptions = array ( ) ) { $ options = array_merge ( $ extraOptions , array ( 'stored' => 'true' ) ) ; $ this -> addFulltextField ( $ field , $ forceType , $ options ) ; } | Add a field that should be stored |
394 | public function addBoostedField ( $ field , $ forceType = null , $ extraOptions = array ( ) , $ boost = 2 ) { $ options = array_merge ( $ extraOptions , array ( 'boost' => $ boost ) ) ; $ this -> addFulltextField ( $ field , $ forceType , $ options ) ; } | Add a fulltext field with a boosted value |
395 | public function getQueryFields ( ) { if ( empty ( $ this -> boostedFields ) ) { return null ; } $ queryFields = array ( ) ; foreach ( $ this -> boostedFields as $ fieldName => $ boost ) { $ queryFields [ ] = $ fieldName . '^' . $ boost ; } $ df = $ this -> getDefaultField ( ) ; if ( $ queryFields && ! isset ( $ this -> boostedFields [ $ df ] ) ) { $ queryFields [ ] = $ df ; } return $ queryFields ; } | Determine the best default value for the qf parameter |
396 | protected function toXmlTag ( $ tag , $ attrs , $ content = null ) { $ xml = "<$tag " ; if ( $ attrs ) { $ attrStrs = array ( ) ; foreach ( $ attrs as $ attrName => $ attrVal ) { $ attrStrs [ ] = "$attrName='$attrVal'" ; } $ xml .= $ attrStrs ? implode ( ' ' , $ attrStrs ) : '' ; } $ xml .= $ content ? ">$content</$tag>" : '/>' ; return $ xml ; } | Convert definition to XML tag |
397 | public function getCopyFieldDefinitions ( ) { $ xml = array ( ) ; foreach ( $ this -> getCopyDestinations ( ) as $ copyTo ) { foreach ( $ this -> fulltextFields as $ name => $ field ) { $ xml [ ] = "<copyField source='{$name}' dest='{$copyTo}' />" ; } } foreach ( $ this -> copyFields as $ source => $ fields ) { foreach ( $ fields as $ fieldAttrs ) { $ xml [ ] = $ this -> toXmlTag ( 'copyField' , $ fieldAttrs ) ; } } return implode ( "\n\t" , $ xml ) ; } | Generate XML for copy field definitions |
398 | protected function classIs ( $ class , $ base ) { if ( is_array ( $ base ) ) { foreach ( $ base as $ nextBase ) { if ( $ this -> classIs ( $ class , $ nextBase ) ) { return true ; } } return false ; } return $ class === $ base || is_subclass_of ( $ class , $ base ) ; } | Determine if the given object is one of the given type |
399 | public function clearObsoleteClasses ( $ classes ) { if ( empty ( $ classes ) ) { return false ; } $ conditions = array ( ) ; foreach ( $ classes as $ class => $ options ) { if ( $ options [ 'include_children' ] ) { $ conditions [ ] = "ClassHierarchy:{$class}" ; } else { $ conditions [ ] = "ClassName:{$class}" ; } } $ deleteQuery = "-(" . implode ( ' ' , $ conditions ) . ")" ; $ this -> getService ( ) -> deleteByQuery ( $ deleteQuery ) ; return true ; } | Clear all records which do not match the given classname whitelist . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.