_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q258000
Package_Command.browse
test
public function browse( $_, $assoc_args ) { $this->set_composer_auth_env_var(); if ( empty( $assoc_args['format'] ) || 'table' === $assoc_args['format'] ) { WP_CLI::line( WP_CLI::colorize( '%CAlthough the package index will remain in place for backward compatibility reasons, it has been deprecated and will not be updated further. Please refer to https://github.com/wp-cli/ideas/issues/51 to read about its potential replacement.%n' ) ); } $this->show_packages( 'browse', $this->get_community_packages(), $assoc_args ); }
php
{ "resource": "" }
q258001
Package_Command.list_
test
public function list_( $args, $assoc_args ) { $this->set_composer_auth_env_var(); $this->show_packages( 'list', $this->get_installed_packages(), $assoc_args ); }
php
{ "resource": "" }
q258002
Package_Command.path
test
public function path( $args ) { $packages_dir = WP_CLI::get_runner()->get_packages_dir_path(); if ( ! empty( $args ) ) { $packages_dir .= 'vendor/' . $args[0]; if ( ! is_dir( $packages_dir ) ) { WP_CLI::error( 'Invalid package name.' ); } } WP_CLI::line( $packages_dir ); }
php
{ "resource": "" }
q258003
Package_Command.update
test
public function update() { $this->set_composer_auth_env_var(); $composer = $this->get_composer(); // Set up the EventSubscriber $event_subscriber = new PackageManagerEventSubscriber(); $composer->getEventDispatcher()->addSubscriber( $event_subscriber ); // Set up the installer $install = Installer::create( new ComposerIO(), $composer ); $install->setUpdate( true ); // Installer class will only override composer.lock with this flag $install->setPreferSource( true ); // Use VCS when VCS for easier contributions. WP_CLI::log( 'Using Composer to update packages...' ); WP_CLI::log( '---' ); $res = false; try { $res = $install->run(); } catch ( Exception $e ) { WP_CLI::warning( $e->getMessage() ); } WP_CLI::log( '---' ); if ( 0 === $res ) { WP_CLI::success( 'Packages updated.' ); } else { $res_msg = $res ? " (Composer return code {$res})" : ''; // $res may be null apparently. WP_CLI::error( "Failed to update packages{$res_msg}." ); } }
php
{ "resource": "" }
q258004
Package_Command.uninstall
test
public function uninstall( $args ) { list( $package_name ) = $args; $this->set_composer_auth_env_var(); $package = $this->get_installed_package_by_name( $package_name ); if ( false === $package ) { WP_CLI::error( 'Package not installed.' ); } $package_name = $package->getPrettyName(); // Make sure package name is what's in composer.json. // Read the WP-CLI packages composer.json and do some initial error checking. list( $json_path, $composer_backup, $composer_backup_decoded ) = $this->get_composer_json_path_backup_decoded(); // Revert on shutdown if `$revert` is true (set to false on success). $revert = true; $this->register_revert_shutdown_function( $json_path, $composer_backup, $revert ); // Remove the 'require' from composer.json. WP_CLI::log( sprintf( 'Removing require statement from %s', $json_path ) ); $manipulator = new JsonManipulator( $composer_backup ); $manipulator->removeSubNode( 'require', $package_name, true /*caseInsensitive*/ ); // Remove the 'repository' details from composer.json. WP_CLI::log( sprintf( 'Removing repository details from %s', $json_path ) ); $manipulator->removeSubNode( 'repositories', $package_name, true /*caseInsensitive*/ ); file_put_contents( $json_path, $manipulator->getContents() ); $composer = $this->get_composer(); // Set up the installer. $install = Installer::create( new NullIO(), $composer ); $install->setUpdate( true ); // Installer class will only override composer.lock with this flag $install->setPreferSource( true ); // Use VCS when VCS for easier contributions. WP_CLI::log( 'Removing package directories and regenerating autoloader...' ); $res = false; try { $res = $install->run(); } catch ( Exception $e ) { WP_CLI::warning( $e->getMessage() ); } if ( 0 === $res ) { $revert = false; WP_CLI::success( 'Uninstalled package.' ); } else { $res_msg = $res ? " (Composer return code {$res})" : ''; // $res may be null apparently. WP_CLI::error( "Package removal failed{$res_msg}." ); } }
php
{ "resource": "" }
q258005
Package_Command.get_composer
test
private function get_composer() { $this->avoid_composer_ca_bundle(); try { $composer_path = $this->get_composer_json_path(); // Composer's auto-load generating code makes some assumptions about where // the 'vendor-dir' is, and where Composer is running from. // Best to just pretend we're installing a package from ~/.wp-cli or similar chdir( pathinfo( $composer_path, PATHINFO_DIRNAME ) ); // Prevent DateTime error/warning when no timezone set. // Note: The package is loaded before WordPress load, For environments that don't have set time in php.ini. // phpcs:ignore WordPress.WP.TimezoneChange.timezone_change_date_default_timezone_set,WordPress.PHP.NoSilencedErrors.Discouraged date_default_timezone_set( @date_default_timezone_get() ); $composer = Factory::create( new NullIO(), $composer_path ); } catch ( Exception $e ) { WP_CLI::error( sprintf( 'Failed to get composer instance: %s', $e->getMessage() ) ); } return $composer; }
php
{ "resource": "" }
q258006
Package_Command.get_community_packages
test
private function get_community_packages() { static $community_packages; if ( null === $community_packages ) { $this->avoid_composer_ca_bundle(); try { $community_packages = $this->package_index()->getPackages(); } catch ( Exception $e ) { WP_CLI::error( $e->getMessage() ); } } return $community_packages; }
php
{ "resource": "" }
q258007
Package_Command.package_index
test
private function package_index() { static $package_index; if ( ! $package_index ) { $config_args = [ 'config' => [ 'secure-http' => true, 'home' => dirname( $this->get_composer_json_path() ), ], ]; $config = new Config(); $config->merge( $config_args ); $config->setConfigSource( new JsonConfigSource( $this->get_composer_json() ) ); try { $package_index = new ComposerRepository( [ 'url' => self::PACKAGE_INDEX_URL ], new NullIO(), $config ); } catch ( Exception $e ) { WP_CLI::error( $e->getMessage() ); } } return $package_index; }
php
{ "resource": "" }
q258008
Package_Command.show_packages
test
private function show_packages( $context, $packages, $assoc_args ) { if ( 'list' === $context ) { $default_fields = [ 'name', 'authors', 'version', 'update', 'update_version', ]; } elseif ( 'browse' === $context ) { $default_fields = [ 'name', 'description', 'authors', 'version', ]; } $defaults = [ 'fields' => implode( ',', $default_fields ), 'format' => 'table', ]; $assoc_args = array_merge( $defaults, $assoc_args ); $composer = $this->get_composer(); $list = []; foreach ( $packages as $package ) { $name = $package->getPrettyName(); if ( isset( $list[ $name ] ) ) { $list[ $name ]['version'][] = $package->getPrettyVersion(); } else { $package_output = []; $package_output['name'] = $package->getPrettyName(); $package_output['description'] = $package->getDescription(); $package_output['authors'] = implode( ', ', array_column( (array) $package->getAuthors(), 'name' ) ); $package_output['version'] = [ $package->getPrettyVersion() ]; $update = 'none'; $update_version = ''; if ( 'list' === $context ) { try { $latest = $this->find_latest_package( $package, $composer, null ); if ( $latest && $latest->getFullPrettyVersion() !== $package->getFullPrettyVersion() ) { $update = 'available'; $update_version = $latest->getPrettyVersion(); } } catch ( Exception $e ) { WP_CLI::warning( $e->getMessage() ); $update = 'error'; $update_version = $update; } } $package_output['update'] = $update; $package_output['update_version'] = $update_version; $package_output['pretty_name'] = $package->getPrettyName(); // Deprecated but kept for BC with package-command 1.0.8. $list[ $package_output['name'] ] = $package_output; } } $list = array_map( function( $package ) { $package['version'] = implode( ', ', $package['version'] ); return $package; }, $list ); ksort( $list ); if ( 'ids' === $assoc_args['format'] ) { $list = array_keys( $list ); } Utils\format_items( $assoc_args['format'], $list, $assoc_args['fields'] ); }
php
{ "resource": "" }
q258009
Package_Command.get_package_by_shortened_identifier
test
private function get_package_by_shortened_identifier( $package_name ) { // Check the package index first, so we don't break existing behavior. $lc_package_name = strtolower( $package_name ); // For BC check. foreach ( $this->get_community_packages() as $package ) { if ( $package_name === $package->getPrettyName() ) { return $package; } // For BC allow getting by lowercase name. if ( $lc_package_name === $package->getName() ) { return $package; } } // Check if the package exists on Packagist. $url = "https://repo.packagist.org/p/{$package_name}.json"; $response = Utils\http_request( 'GET', $url ); if ( 20 === (int) substr( $response->status_code, 0, 2 ) ) { return $package_name; } // Fall back to GitHub URL if we had no match yet. $url = "https://github.com/{$package_name}.git"; $github_token = getenv( 'GITHUB_TOKEN' ); // Use GITHUB_TOKEN if available to avoid authorization failures or rate-limiting. $headers = $github_token ? [ 'Authorization' => 'token ' . $github_token ] : []; $response = Utils\http_request( 'GET', $url, null /*data*/, $headers ); if ( 20 === (int) substr( $response->status_code, 0, 2 ) ) { return $url; } return false; }
php
{ "resource": "" }
q258010
Package_Command.get_installed_packages
test
private function get_installed_packages() { $composer = $this->get_composer(); $repo = $composer->getRepositoryManager()->getLocalRepository(); $existing = json_decode( file_get_contents( $this->get_composer_json_path() ), true ); $installed_package_keys = ! empty( $existing['require'] ) ? array_keys( $existing['require'] ) : []; if ( empty( $installed_package_keys ) ) { return []; } // For use by legacy incorrect name check. $lc_installed_package_keys = array_map( 'strtolower', $installed_package_keys ); $installed_packages = []; foreach ( $repo->getCanonicalPackages() as $package ) { $idx = array_search( $package->getName(), $lc_installed_package_keys, true ); // Use pretty name as it's case sensitive and what's in composer.json (or at least should be). if ( in_array( $package->getPrettyName(), $installed_package_keys, true ) ) { $installed_packages[] = $package; } elseif ( false !== $idx ) { // Legacy incorrect name check. WP_CLI::warning( sprintf( "Found package '%s' misnamed '%s' in '%s'.", $package->getPrettyName(), $installed_package_keys[ $idx ], $this->get_composer_json_path() ) ); $installed_packages[] = $package; } } return $installed_packages; }
php
{ "resource": "" }
q258011
Package_Command.get_installed_package_by_name
test
private function get_installed_package_by_name( $package_name ) { foreach ( $this->get_installed_packages() as $package ) { if ( $package_name === $package->getPrettyName() ) { return $package; } // Also check non-pretty (lowercase) name in case of legacy incorrect name. if ( $package_name === $package->getName() ) { return $package; } } return false; }
php
{ "resource": "" }
q258012
Package_Command.get_package_name_and_version_from_dir_package
test
private static function get_package_name_and_version_from_dir_package( $dir_package ) { $composer_file = $dir_package . '/composer.json'; if ( ! file_exists( $composer_file ) ) { WP_CLI::error( sprintf( "Invalid package: composer.json file '%s' not found.", $composer_file ) ); } $composer_data = json_decode( file_get_contents( $composer_file ), true ); if ( null === $composer_data ) { WP_CLI::error( sprintf( "Invalid package: failed to parse composer.json file '%s' as json.", $composer_file ) ); } if ( empty( $composer_data['name'] ) ) { WP_CLI::error( sprintf( "Invalid package: no name in composer.json file '%s'.", $composer_file ) ); } $package_name = $composer_data['name']; $version = 'dev-master'; if ( ! empty( $composer_data['version'] ) ) { $version = $composer_data['version']; } return [ $package_name, $version ]; }
php
{ "resource": "" }
q258013
Package_Command.get_composer_json_path
test
private function get_composer_json_path() { static $composer_path; if ( null === $composer_path || getenv( 'WP_CLI_TEST_PACKAGE_GET_COMPOSER_JSON_PATH' ) ) { if ( getenv( 'WP_CLI_PACKAGES_DIR' ) ) { $composer_path = Utils\trailingslashit( getenv( 'WP_CLI_PACKAGES_DIR' ) ) . 'composer.json'; } else { $composer_path = Utils\trailingslashit( Utils\get_home_dir() ) . '.wp-cli/packages/composer.json'; } // `composer.json` and its directory might need to be created if ( ! file_exists( $composer_path ) ) { $composer_path = $this->create_default_composer_json( $composer_path ); } else { $composer_path = realpath( $composer_path ); if ( false === $composer_path ) { $error = error_get_last(); WP_CLI::error( sprintf( "Composer path '%s' for packages/composer.json not found: %s", $composer_path, $error['message'] ) ); } } } return $composer_path; }
php
{ "resource": "" }
q258014
Package_Command.create_default_composer_json
test
private function create_default_composer_json( $composer_path ) { $composer_dir = pathinfo( $composer_path, PATHINFO_DIRNAME ); if ( ! is_dir( $composer_dir ) ) { if ( ! @mkdir( $composer_dir, 0777, true ) ) { // @codingStandardsIgnoreLine $error = error_get_last(); WP_CLI::error( sprintf( "Composer directory '%s' for packages couldn't be created: %s", $composer_dir, $error['message'] ) ); } } $composer_dir = realpath( $composer_dir ); if ( false === $composer_dir ) { $error = error_get_last(); WP_CLI::error( sprintf( "Composer directory '%s' for packages not found: %s", $composer_dir, $error['message'] ) ); } $composer_path = Utils\trailingslashit( $composer_dir ) . Utils\basename( $composer_path ); $json_file = new JsonFile( $composer_path ); $repositories = (object) [ 'wp-cli' => (object) $this->composer_type_package, ]; $options = [ 'name' => 'wp-cli/wp-cli', 'description' => 'Installed community packages used by WP-CLI', 'version' => self::get_wp_cli_version_composer(), 'authors' => [ (object) $this->author_data ], 'homepage' => self::PACKAGE_INDEX_URL, 'require' => new stdClass(), 'require-dev' => new stdClass(), 'minimum-stability' => 'dev', 'prefer-stable' => true, 'license' => 'MIT', 'repositories' => $repositories, ]; try { $json_file->write( $options ); } catch ( Exception $e ) { WP_CLI::error( $e->getMessage() ); } return $composer_path; }
php
{ "resource": "" }
q258015
Package_Command.get_raw_git_version
test
private function get_raw_git_version( $version ) { if ( '' === $version ) { return 'master'; } // If Composer hash given then just use whatever's after it. $hash_pos = strpos( $version, '#' ); if ( false !== $hash_pos ) { return substr( $version, $hash_pos + 1 ); } // Strip any Composer 'dev-' prefix. if ( 0 === strncmp( $version, 'dev-', 4 ) ) { $version = substr( $version, 4 ); } // Ignore/strip any relative suffixes. return str_replace( [ '^', '~' ], '', $version ); }
php
{ "resource": "" }
q258016
Package_Command.guess_version_constraint_from_tag
test
private function guess_version_constraint_from_tag( $tag ) { $matches = []; if ( 1 !== preg_match( '/(?:version|v)\s*((?:[0-9]+\.?)+)(?:-.*)/i', $tag, $matches ) ) { return $tag; } $constraint = "^{$matches[1]}"; WP_CLI::debug( "Guessing version constraint to use: {$constraint}", 'packages' ); return $constraint; }
php
{ "resource": "" }
q258017
Package_Command.get_composer_json_path_backup_decoded
test
private function get_composer_json_path_backup_decoded() { $composer_json_obj = $this->get_composer_json(); $json_path = $composer_json_obj->getPath(); $composer_backup = file_get_contents( $json_path ); if ( false === $composer_backup ) { $error = error_get_last(); WP_CLI::error( sprintf( "Failed to read '%s': %s", $json_path, $error['message'] ) ); } try { $composer_backup_decoded = $composer_json_obj->read(); } catch ( Exception $e ) { WP_CLI::error( sprintf( "Failed to parse '%s' as json: %s", $json_path, $e->getMessage() ) ); } return [ $json_path, $composer_backup, $composer_backup_decoded ]; }
php
{ "resource": "" }
q258018
AbstractQueuedJob.setObject
test
protected function setObject(DataObject $object, $name = 'Object') { $this->{$name . 'ID'} = $object->ID; $this->{$name . 'Type'} = $object->ClassName; }
php
{ "resource": "" }
q258019
AbstractQueuedJob.loadCustomConfig
test
private function loadCustomConfig() { $custom = $this->getCustomConfig(); if (!is_array($custom)) { return; } foreach ($custom as $class => $settings) { foreach ($settings as $setting => $value) { Config::modify()->set($class, $setting, $value); } } }
php
{ "resource": "" }
q258020
DeleteAllJobsTask.run
test
public function run($request) { $confirm = $request->getVar('confirm'); $jobs = DataObject::get(QueuedJobDescriptor::class); if (!$confirm) { echo "Really delete " . $jobs->count() . " jobs? Please add ?confirm=1 to the URL to confirm."; return; } echo "Deleting " . $jobs->count() . " jobs...<br>\n"; $jobs->removeAll(); echo "Done."; }
php
{ "resource": "" }
q258021
CleanupJob.process
test
public function process() { // construct limit statement if query_limit is valid int value $limit = ''; $query_limit = $this->config()->get('query_limit'); if (is_numeric($query_limit) && $query_limit >= 0) { $limit = ' LIMIT ' . ((int)$query_limit); } $statusList = implode('\', \'', $this->config()->get('cleanup_statuses')); switch ($this->config()->get('cleanup_method')) { // If Age, we need to get jobs that are at least n days old case "age": $cutOff = date( "Y-m-d H:i:s", strtotime(DBDatetime::now() . " - " . $this->config()->cleanup_value . " days") ); $stale = DB::query( 'SELECT "ID" FROM "QueuedJobDescriptor" WHERE "JobStatus" IN (\'' . $statusList . '\') AND "LastEdited" < \'' . $cutOff . '\'' . $limit ); $staleJobs = $stale->column("ID"); break; // If Number, we need to save n records, then delete from the rest case "number": $fresh = DB::query( 'SELECT "ID" FROM "QueuedJobDescriptor" ORDER BY "LastEdited" ASC LIMIT ' . $this->config()->cleanup_value ); $freshJobIDs = implode('\', \'', $fresh->column("ID")); $stale = DB::query( 'SELECT "ID" FROM "QueuedJobDescriptor" WHERE "ID" NOT IN (\'' . $freshJobIDs . '\') AND "JobStatus" IN (\'' . $statusList . '\')' . $limit ); $staleJobs = $stale->column("ID"); break; default: $this->addMessage("Incorrect configuration values set. Cleanup ignored"); $this->isComplete = true; return; } if (empty($staleJobs)) { $this->addMessage("No jobs to clean up."); $this->isComplete = true; $this->reenqueue(); return; } $numJobs = count($staleJobs); $staleJobs = implode('\', \'', $staleJobs); DB::query('DELETE FROM "QueuedJobDescriptor" WHERE "ID" IN (\'' . $staleJobs . '\')'); $this->addMessage($numJobs . " jobs cleaned up."); // let's make sure there is a cleanupJob in the queue $this->reenqueue(); $this->isComplete = true; }
php
{ "resource": "" }
q258022
QueuedJobService.queueJob
test
public function queueJob(QueuedJob $job, $startAfter = null, $userId = null, $queueName = null) { $signature = $job->getSignature(); // see if we already have this job in a queue $filter = [ 'Signature' => $signature, 'JobStatus' => [ QueuedJob::STATUS_NEW, QueuedJob::STATUS_INIT, ], ]; $existing = QueuedJobDescriptor::get() ->filter($filter) ->first(); if ($existing && $existing->ID) { return $existing->ID; } $jobDescriptor = new QueuedJobDescriptor(); $jobDescriptor->JobTitle = $job->getTitle(); $jobDescriptor->JobType = $queueName ? $queueName : $job->getJobType(); $jobDescriptor->Signature = $signature; $jobDescriptor->Implementation = get_class($job); $jobDescriptor->StartAfter = $startAfter; $runAsID = 0; if ($userId) { $runAsID = $userId; } elseif (Security::getCurrentUser() && Security::getCurrentUser()->exists()) { $runAsID = Security::getCurrentUser()->ID; } $jobDescriptor->RunAsID = $runAsID; // copy data $this->copyJobToDescriptor($job, $jobDescriptor); $jobDescriptor->write(); $this->startJob($jobDescriptor, $startAfter); return $jobDescriptor->ID; }
php
{ "resource": "" }
q258023
QueuedJobService.copyJobToDescriptor
test
protected function copyJobToDescriptor($job, $jobDescriptor) { $data = $job->getJobData(); $jobDescriptor->TotalSteps = $data->totalSteps; $jobDescriptor->StepsProcessed = $data->currentStep; if ($data->isComplete) { $jobDescriptor->JobStatus = QueuedJob::STATUS_COMPLETE; $jobDescriptor->JobFinished = DBDatetime::now()->Rfc2822(); } $jobDescriptor->SavedJobData = serialize($data->jobData); $jobDescriptor->SavedJobMessages = serialize($data->messages); }
php
{ "resource": "" }
q258024
QueuedJobService.getNextPendingJob
test
public function getNextPendingJob($type = null) { // Filter jobs by type $type = $type ?: QueuedJob::QUEUED; $list = QueuedJobDescriptor::get() ->filter('JobType', $type) ->sort('ID', 'ASC'); // see if there's any blocked jobs that need to be resumed /** @var QueuedJobDescriptor $waitingJob */ $waitingJob = $list ->filter('JobStatus', QueuedJob::STATUS_WAIT) ->first(); if ($waitingJob) { return $waitingJob; } // If there's an existing job either running or pending, the lets just return false to indicate // that we're still executing $runningJob = $list ->filter('JobStatus', [QueuedJob::STATUS_INIT, QueuedJob::STATUS_RUN]) ->first(); if ($runningJob) { return false; } // Otherwise, lets find any 'new' jobs that are waiting to execute /** @var QueuedJobDescriptor $newJob */ $newJob = $list ->filter('JobStatus', QueuedJob::STATUS_NEW) ->where(sprintf( '"StartAfter" < \'%s\' OR "StartAfter" IS NULL', DBDatetime::now()->getValue() )) ->first(); return $newJob; }
php
{ "resource": "" }
q258025
QueuedJobService.checkJobHealth
test
public function checkJobHealth($queue = null) { $queue = $queue ?: QueuedJob::QUEUED; // Select all jobs currently marked as running $runningJobs = QueuedJobDescriptor::get() ->filter([ 'JobStatus' => [ QueuedJob::STATUS_RUN, QueuedJob::STATUS_INIT, ], 'JobType' => $queue, ]); // If no steps have been processed since the last run, consider it a broken job // Only check jobs that have been viewed before. LastProcessedCount defaults to -1 on new jobs. $stalledJobs = $runningJobs ->filter('LastProcessedCount:GreaterThanOrEqual', 0) ->where('"StepsProcessed" = "LastProcessedCount"'); foreach ($stalledJobs as $stalledJob) { $this->restartStalledJob($stalledJob); } // now, find those that need to be marked before the next check // foreach job, mark it as having been incremented foreach ($runningJobs as $job) { $job->LastProcessedCount = $job->StepsProcessed; $job->write(); } // finally, find the list of broken jobs and send an email if there's some found $brokenJobs = QueuedJobDescriptor::get()->filter('JobStatus', QueuedJob::STATUS_BROKEN); if ($brokenJobs && $brokenJobs->count()) { $this->getLogger()->error( print_r( [ 'errno' => 0, 'errstr' => 'Broken jobs were found in the job queue', 'errfile' => __FILE__, 'errline' => __LINE__, 'errcontext' => [], ], true ), [ 'file' => __FILE__, 'line' => __LINE__, ] ); } return $stalledJobs->count(); }
php
{ "resource": "" }
q258026
QueuedJobService.checkDefaultJobs
test
public function checkDefaultJobs($queue = null) { $queue = $queue ?: QueuedJob::QUEUED; if (count($this->defaultJobs)) { $activeJobs = QueuedJobDescriptor::get()->filter( 'JobStatus', [ QueuedJob::STATUS_NEW, QueuedJob::STATUS_INIT, QueuedJob::STATUS_RUN, QueuedJob::STATUS_WAIT, QueuedJob::STATUS_PAUSED, ] ); foreach ($this->defaultJobs as $title => $jobConfig) { if (!isset($jobConfig['filter']) || !isset($jobConfig['type'])) { $this->getLogger()->error( "Default Job config: $title incorrectly set up. Please check the readme for examples", [ 'file' => __FILE__, 'line' => __LINE__, ] ); continue; } $job = $activeJobs->filter(array_merge( ['Implementation' => $jobConfig['type']], $jobConfig['filter'] )); if (!$job->count()) { $this->getLogger()->error( "Default Job config: $title was missing from Queue", [ 'file' => __FILE__, 'line' => __LINE__, ] ); Email::create() ->setTo( isset($jobConfig['email']) ? $jobConfig['email'] : Config::inst()->get(Email::class, 'queued_job_admin_email') ) ->setFrom(Config::inst()->get(Email::class, 'admin_email')) ->setSubject('Default Job "' . $title . '" missing') ->setData($jobConfig) ->addData('Title', $title) ->addData('Site', Director::absoluteBaseURL()) ->setHTMLTemplate('QueuedJobsDefaultJob') ->send(); if (isset($jobConfig['recreate']) && $jobConfig['recreate']) { if (!array_key_exists('construct', $jobConfig) || !isset($jobConfig['startDateFormat']) || !isset($jobConfig['startTimeString']) ) { $this->getLogger()->error( "Default Job config: $title incorrectly set up. Please check the readme for examples", [ 'file' => __FILE__, 'line' => __LINE__, ] ); continue; } QueuedJobService::singleton()->queueJob( Injector::inst()->createWithArgs($jobConfig['type'], $jobConfig['construct']), date($jobConfig['startDateFormat'], strtotime($jobConfig['startTimeString'])) ); $this->getLogger()->info( "Default Job config: $title has been re-added to the Queue", [ 'file' => __FILE__, 'line' => __LINE__, ] ); } } } } }
php
{ "resource": "" }
q258027
QueuedJobService.restartStalledJob
test
protected function restartStalledJob($stalledJob) { if ($stalledJob->ResumeCounts < static::config()->get('stall_threshold')) { $stalledJob->restart(); $logLevel = 'warning'; $message = _t( __CLASS__ . '.STALLED_JOB_RESTART_MSG', 'A job named {name} (#{id}) appears to have stalled. It will be stopped and restarted, please ' . 'login to make sure it has continued', ['name' => $stalledJob->JobTitle, 'id' => $stalledJob->ID] ); } else { $stalledJob->pause(); $logLevel = 'error'; $message = _t( __CLASS__ . '.STALLED_JOB_MSG', 'A job named {name} (#{id}) appears to have stalled. It has been paused, please login to check it', ['name' => $stalledJob->JobTitle, 'id' => $stalledJob->ID] ); } $this->getLogger()->log( $logLevel, $message, [ 'file' => __FILE__, 'line' => __LINE__, ] ); $from = Config::inst()->get(Email::class, 'admin_email'); $to = Config::inst()->get(Email::class, 'queued_job_admin_email'); $subject = _t(__CLASS__ . '.STALLED_JOB', 'Stalled job'); if ($to) { $mail = Email::create($from, $to, $subject) ->setData([ 'JobID' => $stalledJob->ID, 'Message' => $message, 'Site' => Director::absoluteBaseURL(), ]) ->setHTMLTemplate('QueuedJobsStalledJob'); $mail->send(); } }
php
{ "resource": "" }
q258028
QueuedJobService.initialiseJob
test
protected function initialiseJob(QueuedJobDescriptor $jobDescriptor) { // create the job class $impl = $jobDescriptor->Implementation; /** @var QueuedJob $job */ $job = Injector::inst()->create($impl); /* @var $job QueuedJob */ if (!$job) { throw new Exception("Implementation $impl no longer exists"); } $jobDescriptor->JobStatus = QueuedJob::STATUS_INIT; $jobDescriptor->write(); // make sure the data is there $this->copyDescriptorToJob($jobDescriptor, $job); // see if it needs 'setup' or 'restart' called if ($jobDescriptor->StepsProcessed <= 0) { $job->setup(); } else { $job->prepareForRestart(); } // make sure the descriptor is up to date with anything changed $this->copyJobToDescriptor($job, $jobDescriptor); $jobDescriptor->write(); return $job; }
php
{ "resource": "" }
q258029
QueuedJobService.hasPassedTimeLimit
test
protected function hasPassedTimeLimit() { // Ensure a limit exists $limit = static::config()->get('time_limit'); if (!$limit) { return false; } // Ensure started date is set $this->markStarted(); // Check duration $now = DBDatetime::now()->getTimestamp(); return $now > $this->startedAt + $limit; }
php
{ "resource": "" }
q258030
QueuedJobService.isMemoryTooHigh
test
protected function isMemoryTooHigh() { $used = $this->getMemoryUsage(); $limit = $this->getMemoryLimit(); return $limit && ($used > $limit); }
php
{ "resource": "" }
q258031
QueuedJobService.parseMemory
test
protected function parseMemory($memString) { switch (strtolower(substr($memString, -1))) { case "b": return round(substr($memString, 0, -1)); case "k": return round(substr($memString, 0, -1) * 1024); case "m": return round(substr($memString, 0, -1) * 1024 * 1024); case "g": return round(substr($memString, 0, -1) * 1024 * 1024 * 1024); default: return round($memString); } }
php
{ "resource": "" }
q258032
QueuedJobService.getJobListFilter
test
public function getJobListFilter($type = null, $includeUpUntil = 0) { $util = singleton(QJUtils::class); $filter = ['JobStatus <>' => QueuedJob::STATUS_COMPLETE]; if ($includeUpUntil) { $filter['JobFinished > '] = DBDatetime::create()->setValue( DBDatetime::now()->getTimestamp() - $includeUpUntil )->Rfc2822(); } $filter = $util->dbQuote($filter, ' OR '); if ($type) { $filter = $util->dbQuote(['JobType =' => (string)$type]) . ' AND (' . $filter . ')'; } return $filter; }
php
{ "resource": "" }
q258033
QueuedJobService.runQueue
test
public function runQueue($queue) { if (!self::config()->get('disable_health_check')) { $this->checkJobHealth($queue); } $this->checkdefaultJobs($queue); $this->queueRunner->runQueue($queue); }
php
{ "resource": "" }
q258034
QueuedJobService.processJobQueue
test
public function processJobQueue($name) { // Start timer to measure lifetime $this->markStarted(); // Begin main loop do { if (class_exists(Subsite::class)) { // clear subsite back to default to prevent any subsite changes from leaking to // subsequent actions Subsite::changeSubsite(0); } $job = $this->getNextPendingJob($name); if ($job) { $success = $this->runJob($job->ID); if (!$success) { // make sure job is null so it doesn't continue the current // processing loop. Next queue executor can pick up where // things left off $job = null; } } } while ($job); }
php
{ "resource": "" }
q258035
QueuedTaskRunner.queueTask
test
public function queueTask($request) { $name = $request->param('TaskName'); $tasks = $this->getTasks(); $variables = $request->getVars(); unset($variables['url']); unset($variables['flush']); unset($variables['flushtoken']); unset($variables['isDev']); $querystring = http_build_query($variables); $title = function ($content) { printf(Director::is_cli() ? "%s\n\n" : '<h1>%s</h1>', $content); }; $message = function ($content) { printf(Director::is_cli() ? "%s\n" : '<p>%s</p>', $content); }; foreach ($tasks as $task) { if ($task['segment'] == $name) { /** @var BuildTask $inst */ $inst = Injector::inst()->create($task['class']); if (!$inst->isEnabled()) { $message('The task is disabled'); return; } $title(sprintf('Queuing Task %s', $inst->getTitle())); $job = new RunBuildTaskJob($task['class'], $querystring); $jobID = Injector::inst()->get(QueuedJobService::class)->queueJob($job); $message('Done: queued with job ID ' . $jobID); $adminUrl = Director::baseURL() . AdminRootController::config()->get('url_base'); $adminLink = $adminUrl . "/queuedjobs/" . str_replace('\\', '-', QueuedJobDescriptor::class); $message("Visit <a href=\"$adminLink\">queued jobs admin</a> to see job status"); return; } } $message(sprintf('The build task "%s" could not be found', Convert::raw2xml($name))); }
php
{ "resource": "" }
q258036
BaseRunner.logDescriptorStatus
test
protected function logDescriptorStatus($descriptor, $queue) { if (is_null($descriptor)) { $this->writeLogLine('No new jobs on queue ' . $queue); } if ($descriptor === false) { $this->writeLogLine('Job is still running on queue ' . $queue); } if ($descriptor instanceof QueuedJobDescriptor) { $this->writeLogLine('Running ' . $descriptor->JobTitle . ' and others from queue ' . $queue . '.'); } }
php
{ "resource": "" }
q258037
BaseRunner.listJobs
test
public function listJobs() { $service = $this->getService(); for ($i = 1; $i <= 3; $i++) { $jobs = $service->getJobList($i); $num = $jobs ? $jobs->Count() : 0; $this->writeLogLine('Found ' . $num . ' jobs for mode ' . $i . '.'); } }
php
{ "resource": "" }
q258038
DoormanQueuedJobTask.refreshDescriptor
test
protected function refreshDescriptor() { if ($this->descriptor) { $this->descriptor = QueuedJobDescriptor::get()->byID($this->descriptor->ID); } }
php
{ "resource": "" }
q258039
CheckJobHealthTask.run
test
public function run($request) { $queue = $request->requestVar('queue') ?: QueuedJob::QUEUED; $stalledJobCount = $this->getService()->checkJobHealth($queue); echo $stalledJobCount === 0 ? 'All jobs are healthy' : 'Detected and attempted restart on ' . $stalledJobCount . ' stalled jobs'; }
php
{ "resource": "" }
q258040
QueuedJobDescriptor.pause
test
public function pause($force = false) { if ($force || in_array( $this->JobStatus, [QueuedJob::STATUS_WAIT, QueuedJob::STATUS_RUN, QueuedJob::STATUS_INIT] )) { $this->JobStatus = QueuedJob::STATUS_PAUSED; $this->write(); return true; } return false; }
php
{ "resource": "" }
q258041
QueuedJobDescriptor.resume
test
public function resume($force = false) { if ($force || in_array($this->JobStatus, [QueuedJob::STATUS_PAUSED, QueuedJob::STATUS_BROKEN])) { $this->JobStatus = QueuedJob::STATUS_WAIT; $this->ResumeCounts++; $this->write(); QueuedJobService::singleton()->startJob($this); return true; } return false; }
php
{ "resource": "" }
q258042
QueuedJobDescriptor.activateOnQueue
test
public function activateOnQueue() { // if it's an immediate job, lets cache it to disk to be picked up later if ($this->JobType == QueuedJob::IMMEDIATE && !Config::inst()->get(QueuedJobService::class, 'use_shutdown_function') ) { touch($this->getJobDir() . '/queuedjob-' . $this->ID); } }
php
{ "resource": "" }
q258043
QueuedJobDescriptor.getJobDir
test
protected function getJobDir() { // make sure our temp dir is in place. This is what will be inotify watched $jobDir = Config::inst()->get(QueuedJobService::class, 'cache_dir'); if ($jobDir{0} !== '/') { $jobDir = TEMP_FOLDER . '/' . $jobDir; } if (!is_dir($jobDir)) { Filesystem::makeFolder($jobDir); } return $jobDir; }
php
{ "resource": "" }
q258044
QueuedJobDescriptor.cleanupJob
test
public function cleanupJob() { // remove the job's temp file if it exists $tmpFile = $this->getJobDir() . '/queuedjob-' . $this->ID; if (file_exists($tmpFile)) { unlink($tmpFile); } }
php
{ "resource": "" }
q258045
QueuedJobDescriptor.getMessages
test
public function getMessages() { if (strlen($this->SavedJobMessages)) { $messages = @unserialize($this->SavedJobMessages); if (!empty($messages)) { return DBField::create_field( 'HTMLText', '<ul><li>' . nl2br(implode('</li><li>', Convert::raw2xml($messages))) . '</li></ul>' ); } return ''; } }
php
{ "resource": "" }
q258046
QueuedJobDescriptor.getLastMessage
test
public function getLastMessage() { if (strlen($this->SavedJobMessages)) { $msgs = @unserialize($this->SavedJobMessages); if (is_array($msgs) && sizeof($msgs)) { return array_pop($msgs); } } }
php
{ "resource": "" }
q258047
QueuedJobDescriptor.getJobTypeString
test
public function getJobTypeString() { $map = $this->getJobTypeValues(); return isset($map[$this->JobType]) ? $map[$this->JobType] : '(Unknown)'; }
php
{ "resource": "" }
q258048
QueuedJobDescriptor.getJobTypeValues
test
public function getJobTypeValues() { return [ QueuedJob::IMMEDIATE => _t(__CLASS__ . '.TYPE_IMMEDIATE', 'Immediate'), QueuedJob::QUEUED => _t(__CLASS__ . '.TYPE_QUEUED', 'Queued'), QueuedJob::LARGE => _t(__CLASS__ . '.TYPE_LARGE', 'Large'), ]; }
php
{ "resource": "" }
q258049
GenerateGoogleSitemapJob.setup
test
public function setup() { parent::setup(); Environment::increaseTimeLimitTo(); $restart = $this->currentStep == 0; if (!$this->tempFile || !file_exists($this->tempFile)) { $tmpfile = tempnam(TempFolder::getTempFolder(BASE_PATH), 'sitemap'); if (file_exists($tmpfile)) { $this->tempFile = $tmpfile; } $restart = true; } if ($restart) { $this->pagesToProcess = DB::query('SELECT ID FROM SiteTree_Live WHERE ShowInSearch=1')->column(); } }
php
{ "resource": "" }
q258050
GenerateGoogleSitemapJob.prepareForRestart
test
public function prepareForRestart() { parent::prepareForRestart(); // if the file we've been building is missing, lets fix it up if (!$this->tempFile || !file_exists($this->tempFile)) { $tmpfile = tempnam(TempFolder::getTempFolder(BASE_PATH), 'sitemap'); if (file_exists($tmpfile)) { $this->tempFile = $tmpfile; } $this->currentStep = 0; $this->pagesToProcess = DB::query('SELECT ID FROM SiteTree_Live WHERE ShowInSearch=1')->column(); } }
php
{ "resource": "" }
q258051
GenerateGoogleSitemapJob.completeJob
test
protected function completeJob() { $content = '<?xml version="1.0" encoding="UTF-8"?>' . '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'; $content .= file_get_contents($this->tempFile); $content .= '</urlset>'; $sitemap = Director::baseFolder() . '/sitemap.xml'; file_put_contents($sitemap, $content); if (file_exists($this->tempFile)) { unlink($this->tempFile); } $nextgeneration = Injector::inst()->create(GenerateGoogleSitemapJob::class); QueuedJobService::singleton()->queueJob( $nextgeneration, DBDatetime::create()->setValue( DBDatetime::now()->getTimestamp() + $this->config()->get('regenerate_time') )->Rfc2822() ); }
php
{ "resource": "" }
q258052
DoormanRunner.runQueue
test
public function runQueue($queue) { // split jobs out into multiple tasks... /** @var ProcessManager $manager */ $manager = Injector::inst()->create(ProcessManager::class); $manager->setWorker( BASE_PATH . "/vendor/silverstripe/framework/cli-script.php dev/tasks/ProcessJobQueueChildTask" ); $logPath = Environment::getEnv('SS_DOORMAN_LOGPATH'); if ($logPath) { $manager->setLogPath($logPath); } // Assign default rules $defaultRules = $this->getDefaultRules(); if ($defaultRules) { foreach ($defaultRules as $rule) { $manager->addRule($rule); } } $descriptor = $this->getNextJobDescriptorWithoutMutex($queue); while ($manager->tick() || $descriptor) { $this->logDescriptorStatus($descriptor, $queue); if ($descriptor instanceof QueuedJobDescriptor) { $descriptor->JobStatus = QueuedJob::STATUS_INIT; $descriptor->write(); $manager->addTask(new DoormanQueuedJobTask($descriptor)); } sleep(1); $descriptor = $this->getNextJobDescriptorWithoutMutex($queue); } }
php
{ "resource": "" }
q258053
GridFieldQueuedJobExecute.handleAction
test
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { $actions = $this->getActions(null); if (in_array($actionName, $actions)) { $item = $gridField->getList()->byID($arguments['RecordID']); if (!$item) { return; } $item->$actionName(); Requirements::clear(); } }
php
{ "resource": "" }
q258054
PublishItemsJob.getTitle
test
public function getTitle() { $title = 'Unknown'; if ($root = $this->getRoot()) { $title = $root->Title; } return _t( __CLASS__ . '.Title', "Publish items beneath {title}", ['title' => $title] ); }
php
{ "resource": "" }
q258055
PublishItemsJob.setup
test
public function setup() { if (!$this->getRoot()) { // we're missing for some reason! $this->isComplete = true; $this->remainingChildren = array(); return; } $remainingChildren = array(); $remainingChildren[] = $this->getRoot()->ID; $this->remainingChildren = $remainingChildren; // we reset this to 1; this is because we only know for sure about 1 item remaining // as time goes by, this will increase as we discover more items that need processing $this->totalSteps = 1; }
php
{ "resource": "" }
q258056
PublishItemsJob.process
test
public function process() { $remainingChildren = $this->remainingChildren; // if there's no more, we're done! if (!count($remainingChildren)) { $this->isComplete = true; return; } // we need to always increment! This is important, because if we don't then our container // that executes around us thinks that the job has died, and will stop it running. $this->currentStep++; // lets process our first item - note that we take it off the list of things left to do $ID = array_shift($remainingChildren); // get the page $page = DataObject::get_by_id(Page::class, $ID); if ($page) { // publish it $page->doPublish(); // and add its children to the list to be published foreach ($page->Children() as $child) { $remainingChildren[] = $child->ID; // we increase how many steps we need to do - this means our total steps constantly rises, // but it gives users an idea of exactly how many more we know about $this->totalSteps++; } $page->destroy(); unset($page); } // and now we store the new list of remaining children $this->remainingChildren = $remainingChildren; if (!count($remainingChildren)) { $this->isComplete = true; return; } }
php
{ "resource": "" }
q258057
ProcessJobQueueTask.getQueue
test
protected function getQueue($request) { $queue = $request->getVar('queue'); if (!$queue) { $queue = 'Queued'; } switch (strtolower($queue)) { case 'immediate': $queue = QueuedJob::IMMEDIATE; break; case 'queued': $queue = QueuedJob::QUEUED; break; case 'large': $queue = QueuedJob::LARGE; break; default: break; } return $queue; }
php
{ "resource": "" }
q258058
YiiCaster.castModel
test
public static function castModel(ActiveRecord $model) { $attributes = array_merge( $model->getAttributes(), $model->getRelatedRecords() ); $results = []; foreach ($attributes as $key => $value) { $results[Caster::PREFIX_VIRTUAL.$key] = $value; } return $results; }
php
{ "resource": "" }
q258059
ShellController.actionIndex
test
public function actionIndex() { $config = new Configuration; $config->getPresenter()->addCasters( $this->getCasters() ); $shell = new Shell($config); $shell->setIncludes($this->include); $shell->run(); }
php
{ "resource": "" }
q258060
SourceMapGenerator.saveMap
test
public function saveMap($content) { $asset_handler = Requirements::backend()->getAssetHandler(); $css_file = $this->options['sourceMapWriteTo']; $asset_handler->setContent($css_file, $content); $url = $asset_handler->getContentURL($css_file); $this->options['sourceMapURL'] = $url; return $this->options['sourceMapURL']; }
php
{ "resource": "" }
q258061
Block.write
test
public function write($data) { $size = mb_strlen($data, 'UTF-8'); if($this->exists($this->id)) { shmop_delete($this->shmid); shmop_close($this->shmid); $this->shmid = shmop_open($this->id, "c", $this->perms, $size); shmop_write($this->shmid, $data, 0); } else { $this->shmid = shmop_open($this->id, "c", $this->perms, $size); shmop_write($this->shmid, $data, 0); } }
php
{ "resource": "" }
q258062
Block.read
test
public function read() { $size = shmop_size($this->shmid); $data = shmop_read($this->shmid, 0, $size); return $data; }
php
{ "resource": "" }
q258063
Sidebar_Command.list_
test
public function list_( $args, $assoc_args ) { global $wp_registered_sidebars; Utils\wp_register_unused_sidebar(); if ( ! empty( $assoc_args['format'] ) && 'ids' === $assoc_args['format'] ) { $sidebars = wp_list_pluck( $wp_registered_sidebars, 'id' ); } else { $sidebars = $wp_registered_sidebars; } $formatter = new Formatter( $assoc_args, $this->fields ); $formatter->display_items( $sidebars ); }
php
{ "resource": "" }
q258064
Widget_Command.list_
test
public function list_( $args, $assoc_args ) { list( $sidebar_id ) = $args; $this->validate_sidebar( $sidebar_id ); $output_widgets = $this->get_sidebar_widgets( $sidebar_id ); if ( ! empty( $assoc_args['format'] ) && 'ids' === $assoc_args['format'] ) { $output_widgets = wp_list_pluck( $output_widgets, 'id' ); } $formatter = new Formatter( $assoc_args, $this->fields ); $formatter->display_items( $output_widgets ); }
php
{ "resource": "" }
q258065
Widget_Command.add
test
public function add( $args, $assoc_args ) { list( $name, $sidebar_id ) = $args; $position = Utils\get_flag_value( $args, 2, 1 ) - 1; $this->validate_sidebar( $sidebar_id ); $widget = $this->get_widget_obj( $name ); if ( false === $widget ) { WP_CLI::error( 'Invalid widget type.' ); } /* * Adding a widget is as easy as: * 1. Creating a new widget option * 2. Adding the widget to the sidebar * 3. Positioning appropriately */ $widget_options = $this->get_widget_options( $name ); $option_keys = $widget_options; if ( ! isset( $widget_options['_multiwidget'] ) ) { $widget_options['_multiwidget'] = 1; } unset( $option_keys['_multiwidget'] ); $option_keys = array_keys( $option_keys ); $last_key = array_pop( $option_keys ); $option_index = $last_key + 1; $widget_options[ $option_index ] = $this->sanitize_widget_options( $name, $assoc_args, array() ); $this->update_widget_options( $name, $widget_options ); $widget_id = $name . '-' . $option_index; $this->move_sidebar_widget( $widget_id, null, $sidebar_id, null, $position ); WP_CLI::success( 'Added widget to sidebar.' ); }
php
{ "resource": "" }
q258066
Widget_Command.update
test
public function update( $args, $assoc_args ) { list( $widget_id ) = $args; if ( ! $this->validate_sidebar_widget( $widget_id ) ) { WP_CLI::error( "Widget doesn't exist." ); } if ( empty( $assoc_args ) ) { WP_CLI::error( 'No options specified to update.' ); } list( $name, $option_index ) = $this->get_widget_data( $widget_id ); $widget_options = $this->get_widget_options( $name ); $clean_options = $this->sanitize_widget_options( $name, $assoc_args, $widget_options[ $option_index ] ); $widget_options[ $option_index ] = array_merge( (array) $widget_options[ $option_index ], $clean_options ); $this->update_widget_options( $name, $widget_options ); WP_CLI::success( 'Widget updated.' ); }
php
{ "resource": "" }
q258067
Widget_Command.move
test
public function move( $args, $assoc_args ) { list( $widget_id ) = $args; if ( ! $this->validate_sidebar_widget( $widget_id ) ) { WP_CLI::error( "Widget doesn't exist." ); } if ( empty( $assoc_args['position'] ) && empty( $assoc_args['sidebar-id'] ) ) { WP_CLI::error( 'A new position or new sidebar must be specified.' ); } list( $name, $option_index, $current_sidebar_id, $current_sidebar_index ) = $this->get_widget_data( $widget_id ); $new_sidebar_id = ! empty( $assoc_args['sidebar-id'] ) ? $assoc_args['sidebar-id'] : $current_sidebar_id; $this->validate_sidebar( $new_sidebar_id ); $new_sidebar_index = ! empty( $assoc_args['position'] ) ? $assoc_args['position'] - 1 : $current_sidebar_index; // Moving between sidebars adds to the top if ( $new_sidebar_id !== $current_sidebar_id && $new_sidebar_index === $current_sidebar_index ) { // Human-readable positions are different than numerically indexed array $new_sidebar_index = 0; } $this->move_sidebar_widget( $widget_id, $current_sidebar_id, $new_sidebar_id, $current_sidebar_index, $new_sidebar_index ); WP_CLI::success( 'Widget moved.' ); }
php
{ "resource": "" }
q258068
Widget_Command.deactivate
test
public function deactivate( $args, $assoc_args ) { $count = 0; $errors = 0; foreach ( $args as $widget_id ) { if ( ! $this->validate_sidebar_widget( $widget_id ) ) { WP_CLI::warning( "Widget '{$widget_id}' doesn't exist." ); $errors++; continue; } list( $name, $option_index, $sidebar_id, $sidebar_index ) = $this->get_widget_data( $widget_id ); if ( 'wp_inactive_widgets' === $sidebar_id ) { WP_CLI::warning( sprintf( "'%s' is already deactivated.", $widget_id ) ); continue; } $this->move_sidebar_widget( $widget_id, $sidebar_id, 'wp_inactive_widgets', $sidebar_index, 0 ); $count++; } Utils\report_batch_operation_results( 'widget', 'deactivate', count( $args ), $count, $errors ); }
php
{ "resource": "" }
q258069
Widget_Command.delete
test
public function delete( $args, $assoc_args ) { $count = 0; $errors = 0; foreach ( $args as $widget_id ) { if ( ! $this->validate_sidebar_widget( $widget_id ) ) { WP_CLI::warning( "Widget '{$widget_id}' doesn't exist." ); $errors++; continue; } // Remove the widget's settings. list( $name, $option_index, $sidebar_id, $sidebar_index ) = $this->get_widget_data( $widget_id ); $widget_options = $this->get_widget_options( $name ); unset( $widget_options[ $option_index ] ); $this->update_widget_options( $name, $widget_options ); // Remove the widget from the sidebar. $all_widgets = $this->wp_get_sidebars_widgets(); unset( $all_widgets[ $sidebar_id ][ $sidebar_index ] ); $all_widgets[ $sidebar_id ] = array_values( $all_widgets[ $sidebar_id ] ); update_option( 'sidebars_widgets', $all_widgets ); $count++; } Utils\report_batch_operation_results( 'widget', 'delete', count( $args ), $count, $errors ); }
php
{ "resource": "" }
q258070
Widget_Command.reset
test
public function reset( $args, $assoc_args ) { global $wp_registered_sidebars; $all = Utils\get_flag_value( $assoc_args, 'all', false ); // Bail if no arguments and no all flag. if ( ! $all && empty( $args ) ) { WP_CLI::error( 'Please specify one or more sidebars, or use --all.' ); } // Fetch all sidebars if all flag is set. if ( $all ) { $args = array_keys( $wp_registered_sidebars ); } // Sidebar ID wp_inactive_widgets is reserved by WP core for inactive widgets. if ( isset( $args['wp_inactive_widgets'] ) ) { unset( $args['wp_inactive_widgets'] ); } // Check if no registered sidebar. if ( empty( $args ) ) { WP_CLI::error( 'No sidebar registered.' ); } $count = 0; $errors = 0; foreach ( $args as $sidebar_id ) { if ( ! array_key_exists( $sidebar_id, $wp_registered_sidebars ) ) { WP_CLI::warning( sprintf( 'Invalid sidebar: %s', $sidebar_id ) ); $errors++; continue; } $widgets = $this->get_sidebar_widgets( $sidebar_id ); if ( empty( $widgets ) ) { WP_CLI::warning( sprintf( "Sidebar '%s' is already empty.", $sidebar_id ) ); } else { foreach ( $widgets as $widget ) { $widget_id = $widget->id; list( $name, $option_index, $new_sidebar_id, $sidebar_index ) = $this->get_widget_data( $widget_id ); $this->move_sidebar_widget( $widget_id, $new_sidebar_id, 'wp_inactive_widgets', $sidebar_index, 0 ); } WP_CLI::log( sprintf( "Sidebar '%s' reset.", $sidebar_id ) ); $count++; } } Utils\report_batch_operation_results( 'sidebar', 'reset', count( $args ), $count, $errors ); }
php
{ "resource": "" }
q258071
Widget_Command.validate_sidebar
test
private function validate_sidebar( $sidebar_id ) { global $wp_registered_sidebars; Utils\wp_register_unused_sidebar(); if ( ! array_key_exists( $sidebar_id, $wp_registered_sidebars ) ) { WP_CLI::error( 'Invalid sidebar.' ); } }
php
{ "resource": "" }
q258072
Widget_Command.validate_sidebar_widget
test
private function validate_sidebar_widget( $widget_id ) { $sidebars_widgets = $this->wp_get_sidebars_widgets(); $widget_exists = false; foreach ( $sidebars_widgets as $sidebar_id => $widgets ) { if ( in_array( $widget_id, $widgets, true ) ) { $widget_exists = true; break; } } return $widget_exists; }
php
{ "resource": "" }
q258073
Widget_Command.get_widget_data
test
private function get_widget_data( $widget_id ) { $parts = explode( '-', $widget_id ); $option_index = array_pop( $parts ); $name = implode( '-', $parts ); $sidebar_id = false; $sidebar_index = false; $all_widgets = $this->wp_get_sidebars_widgets(); foreach ( $all_widgets as $s_id => &$widgets ) { $key = array_search( $widget_id, $widgets, true ); if ( false !== $key ) { $sidebar_id = $s_id; $sidebar_index = $key; break; } } return array( $name, $option_index, $sidebar_id, $sidebar_index ); }
php
{ "resource": "" }
q258074
Widget_Command.move_sidebar_widget
test
private function move_sidebar_widget( $widget_id, $current_sidebar_id, $new_sidebar_id, $current_index, $new_index ) { $all_widgets = $this->wp_get_sidebars_widgets(); $needs_placement = true; // Existing widget if ( $current_sidebar_id && ! is_null( $current_index ) ) { $widgets = $all_widgets[ $current_sidebar_id ]; if ( $current_sidebar_id !== $new_sidebar_id ) { unset( $widgets[ $current_index ] ); } else { $part = array_splice( $widgets, $current_index, 1 ); array_splice( $widgets, $new_index, 0, $part ); $needs_placement = false; } $all_widgets[ $current_sidebar_id ] = array_values( $widgets ); } if ( $needs_placement ) { $widgets = ! empty( $all_widgets[ $new_sidebar_id ] ) ? $all_widgets[ $new_sidebar_id ] : array(); $before = array_slice( $widgets, 0, $new_index, true ); $after = array_slice( $widgets, $new_index, count( $widgets ), true ); $widgets = array_merge( $before, array( $widget_id ), $after ); $all_widgets[ $new_sidebar_id ] = array_values( $widgets ); } update_option( 'sidebars_widgets', $all_widgets ); }
php
{ "resource": "" }
q258075
Widget_Command.get_widget_obj
test
private function get_widget_obj( $id_base ) { global $wp_widget_factory; $widget = wp_filter_object_list( $wp_widget_factory->widgets, array( 'id_base' => $id_base ) ); if ( empty( $widget ) ) { return false; } return array_pop( $widget ); }
php
{ "resource": "" }
q258076
Widget_Command.sanitize_widget_options
test
private function sanitize_widget_options( $id_base, $dirty_options, $old_options ) { $widget = $this->get_widget_obj( $id_base ); if ( empty( $widget ) ) { return array(); } // No easy way to determine expected array keys for $dirty_options // because Widget API dependent on the form fields // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Whitelisting due to above reason. return @$widget->update( $dirty_options, $old_options ); }
php
{ "resource": "" }
q258077
Random.getRandomInteger
test
public function getRandomInteger($min = 0, $max = PHP_INT_MAX) { $min = (int) $min; $max = (int) $max; $range = $max - $min; $bits = $this->getBitsInInteger($range); $bytes = $this->getBytesInBits($bits); $mask = (int) ((1 << $bits) - 1); do { $byteString = $this->generator->generate($bytes); $result = hexdec(bin2hex($byteString)) & $mask; } while ($result > $range); return (int) $result + $min; }
php
{ "resource": "" }
q258078
Random.getRandomString
test
public function getRandomString($length, $charset = null) { $length = (int) $length; if (!$charset) { $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./'; } $charsetLength = strlen($charset); $neededBytes = $this->getBytesInBits($length * ($this->getBitsInInteger($charsetLength) + 1)); $string = ''; do { $byteString = $this->generator->generate($neededBytes); for ($i = 0; $i < $neededBytes; ++$i) { if (ord($byteString[$i]) > (255 - (255 % $charsetLength))) { continue; } $string .= $charset[ord($byteString[$i]) % $charsetLength]; } } while (strlen($string) < $length); return substr($string, 0, $length); }
php
{ "resource": "" }
q258079
Base32Encoder.encode
test
public function encode($string) { $encoded = ''; if ($string) { $binString = ''; // Build a binary string representation of the input string foreach (str_split($string) as $char) { $binString .= str_pad(decbin(ord($char)), 8, 0, STR_PAD_LEFT); } // Encode the data in 5-bit chunks foreach (str_split($binString, 5) as $chunk) { $chunk = str_pad($chunk, 5, 0, STR_PAD_RIGHT); $encoded .= $this->charset[bindec($chunk)]; } // Add padding to the encoded string as required if (strlen($encoded) % 8) { $encoded .= str_repeat($this->charset[32], 8 - (strlen($encoded) % 8)); } } return $encoded; }
php
{ "resource": "" }
q258080
Base32Encoder.decode
test
public function decode($string) { $decoded = ''; $string = preg_replace("/[^{$this->charset}]/", '', rtrim(strtoupper($string), $this->charset[32])); if ($string) { $binString = ''; foreach (str_split($string) as $char) { $binString .= str_pad(decbin(strpos($this->charset, $char)), 5, 0, STR_PAD_LEFT); } $binString = substr($binString, 0, (floor(strlen($binString) / 8) * 8)); foreach (str_split($binString, 8) as $chunk) { $chunk = str_pad($chunk, 8, 0, STR_PAD_RIGHT); $decoded .= chr(bindec($chunk)); } } return $decoded; }
php
{ "resource": "" }
q258081
GeneratorFactory.addGeneratorPath
test
public function addGeneratorPath($prefix, $path) { $path = realpath($path); $success = false; if ($path && !array_key_exists($prefix, $this->generatorPaths)) { $this->generatorPaths[$prefix] = $path; $success = true; } return $success; }
php
{ "resource": "" }
q258082
GeneratorFactory.removeGeneratorPath
test
public function removeGeneratorPath($prefixOrPath) { if (array_key_exists($prefixOrPath, $this->generatorPaths)) { $prefix = $prefixOrPath; unset($this->generatorPaths[$prefix]); } elseif (($prefixOrPath = realpath($prefixOrPath)) && in_array($prefixOrPath, $this->generatorPaths)) { $path = $prefixOrPath; $generatorPaths = $this->generatorPaths; $this->generatorPaths = array_filter($generatorPaths, function ($value) use ($path) { return ($value != $path); }); } return $this; }
php
{ "resource": "" }
q258083
GeneratorFactory.getGenerator
test
public function getGenerator() { if (!$this->generators) { $this->loadGenerators(); } $generators = $this->generators; usort($generators, function ($a, $b) { return ($b::getPriority() - $a::getPriority()); }); $generator = null; if (isset ($generators[0])) { $class = $generators[0]; $generator = new $class; } return $generator; }
php
{ "resource": "" }
q258084
GeneratorFactory.loadGenerators
test
public function loadGenerators() { // Reset the list of loaded classes $this->generators = array (); // Loop through each registered path foreach ($this->generatorPaths as $generatorPrefix => $generatorPath) { // Build the iterators to search the path $dirIterator = new \RecursiveDirectoryIterator($generatorPath); $iteratorIterator = new \RecursiveIteratorIterator($dirIterator); $generatorIterator = new \RegexIterator($iteratorIterator, '/^.+\.php$/i'); // Loop through the iterator looking for GeneratorInterface // instances foreach ($generatorIterator as $generatorFile) { // Determine additional namespace from file path $pathName = $generatorFile->getPath(); if (substr($pathName, 0, strlen($generatorPath)) == $generatorPath) { $pathName = substr($pathName, strlen($generatorPath), strlen($pathName)); } // Best guess for class name is Prefix\Path\File $class = $generatorPrefix . '\\' . $pathName . $generatorFile->getBasename('.php'); $class = str_replace('/', '\\', $class); // If the class doesn't exists and isn't autoloaded, try to // load it from the discovered file. if (!class_exists($class, true) && !in_array($generatorFile->getPathName(), get_included_files())) { include $generatorFile->getPathname(); } // If the class exists and implements GeneratorInterface, // append it to our list. if (class_exists($class, false) && in_array(__NAMESPACE__ . '\\GeneratorInterface', class_implements($class))) { if ($class::isSupported()) { $this->generators[] = $class; } } } } }
php
{ "resource": "" }
q258085
FormGroup.showAsRow
test
public function showAsRow($rowConfig = 'default') { $rowConfig = app('config')->get("bs4.form_rows.$rowConfig", null); if ($rowConfig === null) { throw new \InvalidArgumentException("Unknown configuration entry: bs4.form_rows.$rowConfig"); } $element = clone $this; // Add a class to ourselves, to the control wrapper and to the label $element = $element->addClass('row'); $element->controlWrapper = $element->controlWrapper ?? Div::create(); $element->controlWrapper = $element->controlWrapper->addClass($rowConfig['control_wrapper'] ?? []); $element->label = $element->label ?? $element->label('', true)->label; $element->label = $element->label->addClass($rowConfig['label'] ?? []); return $element; }
php
{ "resource": "" }
q258086
Input.readOnly
test
public function readOnly($showAsPlainText = false) { $element = clone $this; $element->plainText = $showAsPlainText; return $element->attribute('readonly', 'readonly'); }
php
{ "resource": "" }
q258087
BuildsForms.openForm
test
public function openForm($method, $action, array $options = []): Htmlable { // Initialize the form state if ($this->formState !== null || $this->currentForm !== null) { throw new RuntimeException('You cannot open another form before closing the previous one'); } $this->formState = app()->make(FormState::class); $this->formState->setModel($options['model'] ?? null); $this->formState->setHideErrors($options['hideErrors'] ?? false); // Create a form element with sane defaults $this->currentForm = Form::create(); // Handle form method consequences (token / hidden method field) // // If Laravel needs to spoof the form's method, we'll append a hidden // field containing the actual method // // On any other method that get, the form needs a CSRF token $method = strtoupper($method); if (\in_array($method, ['DELETE', 'PATCH', 'PUT'], true)) { $this->currentForm = $this->currentForm->addChild($this->hidden('_method', $method)); $method = 'POST'; } if ($method !== 'GET') { $this->currentForm = $this->currentForm->addChild($this->token()); } if ($options['files'] ?? false) { $this->currentForm = $this->currentForm->acceptsFiles(); } return $this->currentForm ->method($method) ->action($action) ->addClassIf($options['inline'] ?? false, 'form-inline') ->attributesIf($options['attributes'] ?? false, $options['attributes'] ?? []) ->open(); }
php
{ "resource": "" }
q258088
InputGroup.prefix
test
public function prefix($prefix, $isPlainText = true) { if ($prefix === null) { return $this; } $element = clone $this; $element->prefixes[] = [ 'content' => $prefix, 'plaintext' => $isPlainText, ]; return $element; }
php
{ "resource": "" }
q258089
InputGroup.suffix
test
public function suffix($suffix, $isPlainText = true) { if ($suffix === null) { return $this; } $element = clone $this; $element->suffixes[] = [ 'content' => $suffix, 'plaintext' => $isPlainText, ]; return $element; }
php
{ "resource": "" }
q258090
InputGroup.assembleAddons
test
private function assembleAddons($addons, $addonContainerClass) { if (0 === \count($addons)) { return $this; } $div = Div::create() ->addClass($addonContainerClass) ->addChildren($addons, function ($token) { $content = $token['content'] ?? ''; $plainText = $token['plaintext'] ?? true; // When not instructed to treat as plain text, use it directly if (!$plainText) { return $content; } // When instructed to use as plain text, we wrap inside a span $span = Span::create()->addClass('input-group-text'); return \is_string($content) ? $span->text($content) : $span->addChild($content); }); return $this->addChild($div); }
php
{ "resource": "" }
q258091
SizableComponent.size
test
public function size($size) { if (!property_exists($this, 'sizableClass')) { throw new RuntimeException('You must specify the sizable CSS class'); } $size = strtolower($size); if (!\in_array($size, ['lg', 'sm'], true)) { throw new RuntimeException('Invalid size'); } return $this->addClass("{$this->sizableClass}-$size"); }
php
{ "resource": "" }
q258092
Session.unscrub
test
private function unscrub($msg) { $args = $msg->arguments; $session = $this; foreach ($msg->callbacks as $id => $path) { if (!isset($this->wrapped[$id])) { $this->wrapped[$id] = function() use ($session, $id) { $session->request((int) $id, func_get_args()); }; } $location =& $args; foreach ($path as $part) { if (is_array($location)) { $location =& $location[$part]; continue; } $location =& $location->$part; } $location = $this->wrapped[$id]; } return $args; }
php
{ "resource": "" }
q258093
Converter.clientTempF
test
public function clientTempF($cb) { $this->remote->temperature(function($degC) use ($cb) { $degF = round($degC * 9 / 5 + 32); $cb($degF); }); }
php
{ "resource": "" }
q258094
SimpleRemoteRepository.getNodes
test
public function getNodes($sessionName, $path, $cb) { if (!$this->validateSessionName($sessionName, $cb)) return false; $exception = null; $msg = null; $names = array (); try { $parent = $this->sessions[$sessionName]->getNode($path); $nodes = $parent->getNodes(); $names = array_keys ($nodes->getArrayCopy()); } catch (\Exception $e) { $exception = get_class($e); $msg = $e->getMessage(); } $cb($names, $exception, $msg); }
php
{ "resource": "" }
q258095
SimpleRemoteRepository.getProperties
test
public function getProperties($sessionName, $path, $cb) { if (!$this->validateSessionName($sessionName, $cb)) return false; $exception = null; $msg = null; $names = array (); try { $parent = $this->sessions[$sessionName]->getNode($path); $properties = $parent->getProperties (); $names = array_keys ($properties); } catch (\Exception $e) { $exception = get_class($e); $msg = $e->getMessage(); } $cb($names, $exception, $msg); }
php
{ "resource": "" }
q258096
SmartyEngine.evaluatePath
test
protected function evaluatePath(string $path, array $data = []) { extract($data, EXTR_SKIP); try { if (!$this->smarty->isCached($path)) { foreach ($data as $var => $val) { $this->smarty->assign($var, $val); } } // render $cacheId = isset($data['smarty.cache_id']) ? $data['smarty.cache_id'] : null; $compileId = isset($data['smarty.compile_id']) ? $data['smarty.compile_id'] : null; return $this->smarty->fetch($path, $cacheId, $compileId); // @codeCoverageIgnoreStart } catch (\SmartyException $e) { $this->handleViewException($e); } catch (Throwable $e) { $this->handleViewException(new FatalThrowableError($e)); } }
php
{ "resource": "" }
q258097
Redis.write
test
protected function write(array $keys, $expire = 1) { foreach ($keys as $k => $v) { $k = sha1($k); $this->redis->setex($k, $expire, $v); } return true; }
php
{ "resource": "" }
q258098
Selenium.getWebdriver
test
public function getWebdriver() { $browser = $this->browser; $config = parse_ini_file(__DIR__ . '/config.dist.ini', true); if (file_exists(__DIR__ . '/config.ini')) { $config = parse_ini_file(__DIR__ . '/config.ini', true); } if ($browser == 'chrome') { $driver['type'] = 'webdriver.chrome.driver'; } elseif ($browser == 'firefox') { $driver['type'] = 'webdriver.gecko.driver'; } elseif ($browser == 'MicrosoftEdge') { $driver['type'] = 'webdriver.edge.driver'; } elseif ($browser == 'edg') { $driver['type'] = 'webdriver.edg.driver'; } elseif ($browser == 'internet explorer') { $driver['type'] = 'webdriver.ie.driver'; } // All the exceptions in the world... if (isset($config[$browser][$this->getOs()])) { $driver['path'] = __DIR__ . '/' . $config[$browser][$this->getOs()]; } else { print('No driver for your browser. Check your browser configuration in config.ini'); // We can't do anything without a driver, exit exit(1); } return '-D' . implode('=', $driver); }
php
{ "resource": "" }
q258099
Exif.getAperture
test
public function getAperture() { if (!isset($this->data[self::APERTURE])) { return false; } return $this->data[self::APERTURE]; }
php
{ "resource": "" }