/** * Implements AcsfEventHandler::handle(). */ public function handle() { drush_print(dt('Entered @class', array('@class' => get_class($this)))); // Clear the theme field so all users will use the default theme. db_update('users')->fields(array('theme' => 0))->execute(); // Clear any in-progress multistep forms that are not normally wiped during // cache-clear. The other caches are expected to be cleared externally from // this process. cache_clear_all('*', 'cache_form', TRUE); // Clean up ACSF variables. $acsf_variables = acsf_vget_group('acsf_duplication_scrub'); foreach ($acsf_variables as $name => $value) { acsf_vdel($name); } // Begin the site without any watchdog records. This should happen right at // the end of the scubbing process to remove any log entries added by the // scrubbing process itself. if (db_table_exists('watchdog')) { db_delete('watchdog')->execute(); } // Mark the entire scrubbing process as complete. variable_set('acsf_duplication_scrub_status', 'complete'); }
/** * Implements AcsfEventHandler::handle(). */ public function handle() { drush_print(dt('Entered @class', array('@class' => get_class($this)))); $tables = array(); // Invalidate search indexes. If the search module has never been enabled, // then it's not enabled now and this block is skipped. if (module_exists('search')) { // Call this function to ensure that the necessary search hooks get // called. search_reindex(); // Calling search_reindex globally (with no parameters) invokes hooks, but // does not truncate the following tables: $tables[] = 'search_dataset'; $tables[] = 'search_index'; $tables[] = 'search_node_links'; $tables[] = 'search_total'; } $tables[] = 'accesslog'; $tables[] = 'node_counter'; $tables[] = 'batch'; $tables[] = 'queue'; $tables[] = 'semaphore'; $tables[] = 'sessions'; $tables[] = 'themebuilder_session'; $this->truncateTables($tables); }
/** * Rolls back the configured migrations. */ public function rollback() { $log = new DrushLogMigrateMessage(); $query = \Drupal::entityQuery('migration'); $names = $query->execute(); // Order the migrations according to their dependencies. /** @var MigrationInterface[] $migrations */ $migrations = \Drupal::entityManager()->getStorage('migration')->loadMultiple($names); // Assume we want all those tagged 'Drupal %'. foreach ($migrations as $migration_id => $migration) { $keep = FALSE; $tags = $migration->get('migration_tags'); foreach ($tags as $tag) { if (strpos($tag, 'Drupal ') === 0) { $keep = TRUE; break; } } if (!$keep) { unset($migrations[$migration_id]); } } // Roll back in reverse order. $this->migrationList = array_reverse($migrations); foreach ($this->migrationList as $migration_id => $migration) { drush_print(dt('Rolling back @migration', ['@migration' => $migration_id])); $executable = new MigrateExecutable($migration, $log); // drush_op() provides --simulate support. drush_op([$executable, 'rollback']); $migration->delete(); } }
/** * Print druplicon as post-command output. * * @hook post-command * * @option druplicon Shows the druplicon as glorious ASCII art. * @todo hidden is not yet part of annotated-command project. It is recognized by Drush's annotation_adapter.inc * @hidden-option druplicon */ public function druplicon($result, CommandData $commandData) { // If one command does a drush_invoke to another command, // then this hook will be called multiple times. Only print // once. (n.b. If drush_invoke_process passes along the // --druplicon option, then we will still get mulitple output) if ($this->printed) { return; } $this->printed = true; $annotationData = $commandData->annotationData(); $commandName = $annotationData['command']; // For some reason, Drush help uses drush_invoke_process to call helpsingle if ($commandName == 'helpsingle') { return; } if ($commandData->input()->getOption('druplicon')) { $this->logger()->debug(dt('Displaying Druplicon for "!command" command.', array('!command' => $commandName))); $misc_dir = DRUSH_BASE_PATH . '/misc'; if (drush_get_context('DRUSH_NOCOLOR')) { $content = file_get_contents($misc_dir . '/druplicon-no_color.txt'); } else { $content = file_get_contents($misc_dir . '/druplicon-color.txt'); } // @todo: `$commandData->output->writeln($content)` after $output hooked up to backend invoke drush_print($content); } }
/** * Implements AcsfEventHandler::handle(). */ public function handle() { drush_print(dt('Entered @class', array('@class' => get_class($this)))); $options = $this->event->context['scrub_options']; $limit = $options['batch_comment']; if ($options['retain_content'] || !module_exists('comment')) { return; } if ($options['avoid_oom']) { // Orphaned comments, that is comments by an authenticated user or // attached to a node that no longer exists, cannot be deleted by // comment_delete_multiple. Handle these items first. if ($cids = $this->getOrphanedItems($limit)) { $orphaned = TRUE; } elseif ($cids = $this->getItems($limit)) { $orphaned = FALSE; } if (!empty($cids)) { $this->deleteItems($cids, $orphaned); $this->event->dispatcher->interrupt(); } } else { do { if ($cids = $this->getOrphanedItems($limit)) { $orphaned = TRUE; } elseif ($cids = $this->getItems($limit)) { $orphaned = FALSE; } else { break; } $this->deleteItems($cids, $orphaned); } while (TRUE); } }
/** * @param string $source * @param string $destination * @param array $options * * @return string */ public function process($source, $destination, $options = array()) { $command = $this->buildCommandLine($source, $destination, $options); if (!empty($options['debug'])) { drush_print('$> ' . $command); } passthru($command); }
function show_options(array $commands = array()) { drush_print(t('Please type one of the following options to continue:')); show_help($commands); $handle = fopen("php://stdin", "r"); $line = fgets($handle); run(trim($line), $commands); }
/** * Print druplicon as post-command output. * * @hook post-command * * @option $druplicon Shows the druplicon as glorious ASCII art. */ public function druplicon() { if (drush_get_option('druplicon')) { $misc_dir = DRUSH_BASE_PATH . '/misc'; if (drush_get_context('DRUSH_NOCOLOR')) { $content = file_get_contents($misc_dir . '/druplicon-no_color.txt'); } else { $content = file_get_contents($misc_dir . '/druplicon-color.txt'); } drush_print($content); } }
/** * Run the configured migrations. */ public function import() { $log = new DrushLogMigrateMessage(); foreach ($this->migrationList as $migration_id) { /** @var MigrationInterface $migration */ $migration = Migration::load($migration_id); drush_print(dt('Upgrading !migration', ['!migration' => $migration_id])); $executable = new MigrateExecutable($migration, $log); // drush_op() provides --simulate support. drush_op([$executable, 'import']); } }
/** * @todo document */ public function printAsset($asset) { if (is_string($asset)) { $asset = isset($this->assets[$asset]) ? $this->assets[$asset] : FALSE; } if ($asset instanceof Asset) { $width = drush_get_context('DRUSH_COLUMNS', 80); if ($width > 80) { $width = 80; } drush_print(dt("@name\n!separator\n!table", array('@name' => $asset->getName(), '!separator' => str_repeat('_', $width), '!table' => $asset->table()))); } }
/** * Implements AcsfEventHandler::handle(). */ public function handle() { drush_print(dt('Entered @class', array('@class' => get_class($this)))); $enable_for_scrub = acsf_vget('acsf_duplication_enable_for_scrub', array()); if (!empty($enable_for_scrub)) { require_once DRUPAL_ROOT . '/includes/install.inc'; // Re-disable modules that were disabled prior to starting the scrubbing // process, and enabled only for scrubbing. module_disable($enable_for_scrub); // Uninstall these modules. Drupal will drop their tables and any orphaned // data remaining in them. drupal_uninstall_modules($enable_for_scrub); } }
/** * Implements AcsfEventHandler::handle(). */ public function handle() { drush_print(dt('Entered @class', array('@class' => get_class($this)))); if (!$this->isComplete()) { $site = acsf_get_acsf_site(); $site->clean(); variable_del('acsf_duplication_scrub_status'); variable_set('site_name', $this->event->context['site_name']); variable_set('install_time', time()); // As a preparatory step, remove any corrupt file entries that may prevent // duplication from succeeding. Specifically, remove any file with an // empty URI string. db_delete('file_managed')->condition('uri', '')->execute(); $this->setComplete(); } }
/** * Implements AcsfEventHandler::handle(). */ public function handle() { drush_print(dt('Entered @class', array('@class' => get_class($this)))); // Remove all temporary files. This code is copied from system_cron() so see // that function for more details. Some highlights: // - It's unclear if the status field can ever be anything other than 0 // (temporary) or 1 (permanenet), but system_cron() uses the bitwise & // operator, so apparently, it thinks additional status bit fields are // possible. // - It's unclear why <> is used instead of != for ("not equal"). // - Separate placeholders are used instead of a single ":permanent" due to // a bug in some PHP versions (see system_cron() for the d.o. issue link). $fids = db_query('SELECT fid FROM {file_managed} WHERE status & :permanent1 <> :permanent2 LIMIT 1000', array(':permanent1' => FILE_STATUS_PERMANENT, ':permanent2' => FILE_STATUS_PERMANENT))->fetchCol(); foreach ($fids as $fid) { if ($file = file_load($fid)) { file_delete($file); } } }
public function render() { $reporters = module_implements('prod_monitor_summary'); $lines = array(); // D7 hooks foreach ($reporters as $i => $module) { $new_lines = module_invoke($module, 'prod_monitor_summary'); if (!is_array($new_lines)) { throw new MonitoringException($module . ' has invalid output format'); } $lines = array_merge($lines, new_lines); } // Listeners should call AddOutputLine() on ourself $this->notify(ProdObservable::SIGNAL_MONITOR_SUMMARY); $lines = array_merge($lines, $this->_lines); foreach ($lines as $line) { drush_print($line, 0, NULL, TRUE); } }
/** * Implements AcsfEventHandler::handle(). */ public function handle() { drush_print(dt('Entered @class', array('@class' => get_class($this)))); // Enable any modules that are currently disabled, but were once enabled, so // that their data cleanup hooks (e.g. hook_user_delete) and functions // (e.g. search_reindex) can be invoked. // // Note: These modules will all be uninstalled. Uninstalling them should // really take care of all the cleanup these modules should be doing. But // enable them here for good measure just incase there's some cleanup // depending on these hooks. require_once DRUPAL_ROOT . '/includes/install.inc'; $modules = system_rebuild_module_data(); $enable_for_scrub = array(); foreach ($modules as $module) { // Disabled modules with schema_version > -1 have not been uninstalled. if (empty($module->status) && $module->schema_version > SCHEMA_UNINSTALLED) { $enable_for_scrub[] = $module->name; } } // Get a list of disabled dependencies. These will get automatically enabled // during module_enable(), but we want to be able to disable and uninstall // them explicitly later. foreach ($enable_for_scrub as $dependent) { foreach (array_keys($modules[$dependent]->requires) as $dependency) { // Use isset() to make sure the module is still in the filesystem before // trying to enable it. (Historically there have been modules in Gardens // which were disabled but then removed from the codebase without ever // uninstalling them, and we don't want to try to enable those now, // because it will fail.) if (isset($modules[$dependency]) && empty($modules[$dependency]->status)) { $enable_for_scrub[] = $dependency; } } } module_enable($enable_for_scrub); acsf_vset('acsf_duplication_enable_for_scrub', $enable_for_scrub, 'acsf_duplication_scrub'); }
/** * Implements AcsfEventHandler::handle(). */ public function handle() { drush_print(dt('Entered @class', array('@class' => get_class($this)))); $options = $this->event->context['scrub_options']; $limit = $options['batch_node']; if ($options['retain_content']) { return; } if ($options['avoid_oom']) { if ($nids = $this->getItems($limit)) { node_delete_multiple($nids); $this->event->dispatcher->interrupt(); } } else { do { $nids = $this->getItems($limit); if (empty($nids)) { break; } node_delete_multiple($nids); } while (TRUE); } }
/** * Implements AcsfEventHandler::handle(). */ public function handle() { drush_print(dt('Entered @class', array('@class' => get_class($this)))); $options = $this->event->context['scrub_options']; variable_del('cron_last'); variable_del('cron_semaphore'); variable_del('node_cron_last'); variable_del('drupal_private_key'); variable_set('cron_key', drupal_hash_base64(drupal_random_bytes(55))); // Ensure Drupal filesystem related configuration variables are correct for // the new site. Consider the following variables: // - file_directory_path // - file_directory_temp // - file_private_path // - file_temporary_path // Given the AH environment for Gardens, we want to leave the temp paths // alone, and we want to delete the other variables, to ensure they reset to // their defaults (because of scarecrow, these shouldn't exist in the // variable table anyway). $file_path_variables = array('file_directory_path', 'file_private_path'); foreach ($file_path_variables as $variable) { variable_del($variable); } }
/** * Log message * * @param string $message * @param int $level */ public function log($message, $level = E_USER_NOTICE, $willBreak = false) { if ($willBreak) { trigger_error($message, $level); return; } $prefix = ''; $type = null; switch ($level) { case E_USER_NOTICE: $type = 'notice'; break; case E_USER_WARNING: $type = 'warning'; $prefix = 'WARN: '; break; case E_USER_ERROR: $type = 'error'; $prefix = 'ERR: '; break; } // drush_log($message, $type); drush_print($prefix . $message); }
// require_once(drupal_get_path('module', 'islandora').'/includes/derivatives.inc'); // repository connection parameters $url = 'localhost:8080/fedora'; $username = '******'; $password = '******'; // set up connection and repository variables $connection = new RepositoryConnection($url, $username, $password); $api = new FedoraApi($connection); $repository = new FedoraRepository($api, new SimpleCache()); // try to fetch PID from repo try { // drush_print("Attempting to access $objectPID from repository"); $object = $repository->getObject($objectPID); } catch (Exception $e) { drush_print("\n\n**********####### ERROR #######**********"); drush_print("***Could not get object {$objectPID} from repo***\n\n"); return; } /** * Copy/Paste from the islandora_oai module */ $last_modified_before = $object->lastModifiedDate; islandora_do_derivatives($object, array('force' => TRUE, 'source_dsid' => 'MODS', 'destination_dsid' => 'DC')); $last_modified_after = $object->lastModifiedDate; $success = TRUE; if ($last_modified_before == $last_modified_after) { $success = FALSE; } if ($success) { drush_log(dt("Dublin Core record updated for @pid.", array('@pid' => $object->id)), 'success'); } else {
$namePartNode->parentNode->removeChild($namePartNode); // set flag to re-ingest the datastream and regen the DC record $updateThisRecord = TRUE; } } if ($updateThisRecord) { // write the new updated info back into the datastream $modsDS->setContentFromString($modsDOMDoc->saveXML($modsDOMDoc->documentElement)); # ingest edited datastream into the repository $object->ingestDatastream($modsDS); //drush_print("MODS record updated for object pid: $objectPID\n"); /*************MODS RECORD COMPLETE*****************/ /******************DUBLIN CORE ********************/ //drush_print("Re-generating Dublin Core"); // update the DC based on the MODS record $document = new DOMDocument(); $document->loadXML($modsDS->content); $transform = 'mods_to_dc.xsl'; // the magic call xml_form_builder_update_dc_datastream($object, $transform, $document); //drush_print("Dublin core regenerated"); /*************DUBLIN CORE COMPLETE*****************/ // keep track of how many objects we edited $objectsChanged++; } else { //drush_print("No update necessary"); } } drush_print("Main processing loop complete"); drush_print("{$objectsChanged} objects were updated"); echo "\n\nAll operations complete\n";
$password = '******'; # set up connection and repository variables $connection = new RepositoryConnection($url, $username, $password); $api = new FedoraApi($connection); $repository = new FedoraRepository($api, new SimpleCache()); # what is the pid you want? $pid = 'islandora:3'; # what to change the name to? $givenName = "Mickey"; $familyName = "Mouse"; $wholeName = $givenName . ' ' . $familyName; # try to fetch PID from repo try { $object = $repository->getObject($pid); } catch (Exception $e) { drush_print('****************ERROR***************'); exit; } # grab the data streams $dublinCoreDS = $object['DC']; $modsDS = $object['MODS']; // drush_print('******Dublin Core********'); // drush_print(@$dublinCoreDS->getContent()); // drush_print(); # parse the datastreams into simplexml objects $modsXML = simplexml_load_string(@$modsDS->getContent()); $dcXML = simplexml_load_string(@$dublinCoreDS->getContent()); //print_r($dcXML->getDocNamespaces()); // foreach ($dcXML->children("dc", TRUE) as $entry) // { // if ($entry->contributor)
$connection = new RepositoryConnection($url, $username, $password); $api = new FedoraApi($connection); $repository = new FedoraRepository($api, new SimpleCache()); // query to grab all pdf collection objects from the repository $sparqlQuery = "SELECT ?s\n FROM <#ri>\n WHERE {\n ?s <info:fedora/fedora-system:def/relations-external#isMemberOfCollection>\n <info:fedora/{$collection}> .\n }"; // run query drush_print("\nQuerying repository for all objects in the {$collection} collection..."); $allPDFObjects = $repository->ri->sparqlQuery($sparqlQuery); drush_print("Query complete\n"); // check number of objects in the collection to make sure we have some $totalNumObjects = count($allPDFObjects); if ($totalNumObjects <= 0) { drush_print("***Error: no objects found in the given collection. Check the collection name."); drush_print("***No processing was completed. Exiting."); return; } else { drush_print("There are {$totalNumObjects} objects to be processed"); } drush_print("\nBeginning main processing loop\n"); for ($counter = 0; $counter < $totalNumObjects; $counter++) { // grab the next object from the result set $theObject = $allPDFObjects[$counter]; // increment the counter shown to the user $realCount = $counter + 1; // drush_print("Processing record $realCount of $totalNumObjects"); // grab the PID value from the object array $objectPID = $theObject['s']['value']; drush_print($objectPID); } drush_print("\nMain processing loop complete\n"); echo "\n\nAll operations complete\n";
/** * Collect data about plugin types. */ protected function collectPlugins() { // Get the IDs of all services from the container. $service_ids = \Drupal::getContainer()->getServiceIds(); //drush_print_r($service_ids); // Filter them down to the ones that are plugin managers. // TODO: this omits some that don't conform to this pattern! Deal with // these! See https://www.drupal.org/node/2086181 $plugin_manager_service_ids = array_filter($service_ids, function ($element) { if (strpos($element, 'plugin.manager.') === 0) { return TRUE; } }); //drush_print_r($plugin_manager_service_ids); // Developer trapdoor: just process the block plugin type, to make terminal // debug output easier to read through. //$plugin_manager_service_ids = array('plugin.manager.block'); // Assemble data from each one. $plugin_type_data = array(); foreach ($plugin_manager_service_ids as $plugin_manager_service_id) { // Get the class for the service. $plugin_manager = \Drupal::service($plugin_manager_service_id); $plugin_manager_class = get_class($plugin_manager); //drush_print_r("$plugin_manager_service_id -> $plugin_manager_class"); // Get a reflection class for the plugin manager class. $plugin_manager_reflection = new \ReflectionClass($plugin_manager_class); // Get the lines of code body for the constructor method. $constructor = $plugin_manager_reflection->getConstructor(); $filename = $constructor->getFileName(); $start_line = $constructor->getStartLine(); $end_line = $constructor->getEndLine(); $length = $end_line - $start_line; $source = file($filename); $lines = array_slice($source, $start_line, $length); // Find the call to the parent constructor. This should be the first line. // WARNING! This will BREAK if the call has a linebreak in it! // TODO: Consider allowing for that! $parent_constructor_call = NULL; foreach ($lines as $line) { if (preg_match('@\\s*parent::__construct@', $line)) { $parent_constructor_call = $line; break; } } if (empty($parent_constructor_call)) { // We can't find the parent constructor call -- this plugin manager is // doing something different. drush_print("Unable to find call to parent constructor in plugin manager class constructor method for service {$plugin_manager_service_id}, class {$plugin_manager}."); continue; } // The call to the constructor's parent method should be in this form: // parent::__construct('Plugin/Block', $namespaces, $module_handler, 'Drupal\Core\Block\BlockPluginInterface', 'Drupal\Core\Block\Annotation\Block'); // See Drupal\Core\Plugin\DefaultPluginManager for detail on these. // Use PHP's tokenizer to get the string parameters. // We need to add a PHP open tag for that to work. $tokens = token_get_all('<?php ' . $parent_constructor_call); // Go through the tokens and get the constant strings: these are the // parameters to the call that we want. $constant_string_parameters = array(); foreach ($tokens as $token) { // For some reason, commas are not turned into tokens but appear as raw // strings! WTF?! if (!is_array($token)) { continue; } $token_name = token_name($token[0]); if ($token_name == 'T_CONSTANT_ENCAPSED_STRING') { // These come with the quotation marks, so we have to trim those. $constant_string_parameters[] = substr($token[1], 1, -1); } } // We identify plugin types by the part of the plugin manager service name // that comes after 'plugin.manager.'. $plugin_type_id = substr($plugin_manager_service_id, strlen('plugin.manager.')); $data = array('type_id' => $plugin_type_id, 'service_id' => $plugin_manager_service_id, 'subdir' => $constant_string_parameters[0], 'plugin_interface' => isset($constant_string_parameters[1]) ? $constant_string_parameters[1] : NULL, 'plugin_definition_annotation_name' => isset($constant_string_parameters[2]) ? $constant_string_parameters[2] : 'Drupal\\Component\\Annotation\\Plugin'); // Analyze the interface, if there is one. if (empty($data['plugin_interface'])) { $data['plugin_interface_methods'] = array(); } else { // Get a reflection class for the interface. $plugin_interface_reflection = new \ReflectionClass($data['plugin_interface']); $methods = $plugin_interface_reflection->getMethods(); foreach ($methods as $method) { $interface_method_data = array(); $interface_method_data['name'] = $method->getName(); // Methods may be in parent interfaces, so not all in the same file. $filename = $method->getFileName(); $source = file($filename); $start_line = $method->getStartLine(); // Trim whitespace from the front, as this will be indented. $interface_method_data['declaration'] = trim($source[$start_line - 1]); // Get the docblock for the method. $method_docblock_lines = explode("\n", $method->getDocComment()); foreach ($method_docblock_lines as $line) { // Take the first actual docblock line to be the description. if (substr($line, 0, 5) == ' * ') { $interface_method_data['description'] = substr($line, 5); break; } } $data['plugin_interface_methods'][$method->getName()] = $interface_method_data; } } // Now analyze the anotation. // Get a reflection class for the annotation class. // Each property of the annotation class describes a property for the // plugin annotation. $annotation_reflection = new \ReflectionClass($data['plugin_definition_annotation_name']); $properties_reflection = $annotation_reflection->getProperties(\ReflectionProperty::IS_PUBLIC); $plugin_properties = array(); foreach ($properties_reflection as $property_reflection) { // Assemble data about this annotation property. $annotation_property_data = array(); $annotation_property_data['name'] = $property_reflection->name; // Get the docblock for the property, so we can figure out whether the // annotation property requires translation, and also add detail to the // annotation code. $property_docblock = $property_reflection->getDocComment(); $property_docblock_lines = explode("\n", $property_docblock); foreach ($property_docblock_lines as $line) { if (substr($line, 0, 3) == '/**') { continue; } // Take the first actual docblock line to be the description. if (!isset($annotation_property_data['description']) && substr($line, 0, 5) == ' * ') { $annotation_property_data['description'] = substr($line, 5); } // Look for a @var token, to tell us the type of the property. if (substr($line, 0, 10) == ' * @var ') { $annotation_property_data['type'] = substr($line, 10); } } $plugin_properties[$property_reflection->name] = $annotation_property_data; } $data['plugin_properties'] = $plugin_properties; $plugin_type_data[$plugin_type_id] = $data; } //drush_print_r($plugin_type_data); // Write the processed data to a file. $directory = $this->environment->getHooksDirectory(); $serialized = serialize($plugin_type_data); file_put_contents("{$directory}/plugins_processed.php", $serialized); }
public function log($level, $message, array $context = array()) { // Convert to old $entry array for b/c calls $entry = $context; $entry['type'] = $level; $entry['message'] = $message; // Drush\Log\Logger should take over all of the responsibilities // of drush_log, including caching the log messages and sending // log messages along to backend invoke. // TODO: move these implementations inside this class. $log =& drush_get_context('DRUSH_LOG', array()); $log[] = $entry; drush_backend_packet('log', $entry); if (drush_get_context('DRUSH_NOCOLOR')) { $red = "[%s]"; $yellow = "[%s]"; $green = "[%s]"; } else { $red = "[31;40m[1m[%s][0m"; $yellow = "[1;33;40m[1m[%s][0m"; $green = "[1;32;40m[1m[%s][0m"; } $verbose = drush_get_context('DRUSH_VERBOSE'); $debug = drush_get_context('DRUSH_DEBUG'); switch ($level) { case LogLevel::WARNING: case 'cancel': $type_msg = sprintf($yellow, $level); break; case 'failed': // Obsolete; only here in case contrib is using it. // Obsolete; only here in case contrib is using it. case 'error': $type_msg = sprintf($red, $level); break; case 'ok': case 'completed': // Obsolete; only here in case contrib is using it. // Obsolete; only here in case contrib is using it. case 'success': case 'status': // Obsolete; only here in case contrib is using it. // In quiet mode, suppress progress messages if (drush_get_context('DRUSH_QUIET')) { return TRUE; } $type_msg = sprintf($green, $level); break; case 'notice': case 'message': // Obsolete; only here in case contrib is using it. // Obsolete; only here in case contrib is using it. case 'info': if (!$verbose) { // print nothing. exit cleanly. return TRUE; } $type_msg = sprintf("[%s]", $level); break; default: if (!$debug) { // print nothing. exit cleanly. return TRUE; } $type_msg = sprintf("[%s]", $level); break; } // When running in backend mode, log messages are not displayed, as they will // be returned in the JSON encoded associative array. if (drush_get_context('DRUSH_BACKEND')) { return; } $columns = drush_get_context('DRUSH_COLUMNS', 80); $width[1] = 11; // Append timer and memory values. if ($debug) { $timer = sprintf('[%s sec, %s]', round($entry['timestamp'] - DRUSH_REQUEST_TIME, 2), drush_format_size($entry['memory'])); $entry['message'] = $entry['message'] . ' ' . $timer; } $width[0] = $columns - 11; $format = sprintf("%%-%ds%%%ds", $width[0], $width[1]); // Place the status message right aligned with the top line of the error message. $message = wordwrap($entry['message'], $width[0]); $lines = explode("\n", $message); $lines[0] = sprintf($format, $lines[0], $type_msg); $message = implode("\n", $lines); drush_print($message, 0, STDERR); }
/** * Implements AcsfEventHandler::handle(). */ public function handle() { drush_print(dt('Entered @class', array('@class' => get_class($this)))); db_query('TRUNCATE {acsf_theme_notifications}'); }
function drush_bootstrap($argc, $argv) { global $args, $override, $conf; // Parse command line options and arguments. $args = drush_parse_args($argv, array('h', 'u', 'r', 'l')); // We use PWD if available because getcwd() resolves symlinks, which // could take us outside of the Drupal root, making it impossible to find. $path = $_SERVER['PWD']; if (empty($path)) { $path = getcwd(); } // Convert windows paths. $path = drush_convert_path($path); // Try and locate the Drupal root directory $root = _drush_locate_root($path); // Load .drushrc file if available. Allows you to provide defaults for options and variables. drush_load_rc($root); $uri = FALSE; // If the current directory contains a settings.php we assume that is the desired site URI. if (file_exists('./settings.php')) { // Export the following settings.php variables to the global namespace. global $db_url, $db_prefix, $cookie_domain, $conf, $installed_profile, $update_free_access; // If the settings.php has a defined path we use the URI from that. include_once './settings.php'; if (isset($base_url)) { $uri = $base_url; } else { // Alternatively we default to the name of the current directory, if it is not 'default'. $elements = explode('/', $path); $current = array_pop($elements); if ($current != 'default') { $uri = 'http://' . $current; } } } // Define basic options as constants. define('DRUSH_URI', drush_get_option(array('l', 'uri'), $uri)); define('DRUSH_VERBOSE', drush_get_option(array('v', 'verbose'), FALSE)); define('DRUSH_AFFIRMATIVE', drush_get_option(array('y', 'yes'), FALSE)); define('DRUSH_SIMULATE', drush_get_option(array('s', 'simulate'), FALSE)); // TODO: Make use of this as soon as the external define('DRUSH_USER', drush_get_option(array('u', 'user'), 0)); // If no root is defined, we try to guess from the current directory. define('DRUSH_DRUPAL_ROOT', drush_get_option(array('r', 'root'), $root)); // If the Drupal directory can't be found, and no -r option was specified, // or the path specified in -r does not point to a Drupal directory, // we have no alternative but to give up the ghost at this point. // (NOTE: t() is not available yet.) if (!DRUSH_DRUPAL_ROOT || !is_dir(DRUSH_DRUPAL_ROOT) || !file_exists(DRUSH_DRUPAL_ROOT . '/' . DRUSH_DRUPAL_BOOTSTRAP)) { $dir = ''; if (DRUSH_DRUPAL_ROOT) { $dir = ' in ' . DRUSH_DRUPAL_ROOT; } // Provide a helpful exit message, letting the user know where we looked // (if we looked at all) and a hint on how to specify the directory manually. $message = "E: Could not locate a Drupal installation directory{$dir}. Aborting.\n"; $message .= "Hint: You can specify your Drupal installation directory with the --root\n"; $message .= "parameter on the command line or \$options['root'] in your drushrc.php file.\n"; die($message); } // Fake the necessary HTTP headers that Drupal needs: if (DRUSH_URI) { $drupal_base_url = parse_url(DRUSH_URI); $_SERVER['HTTP_HOST'] = $drupal_base_url['host']; $_SERVER['PHP_SELF'] = $drupal_base_url['path'] . '/index.php'; } else { $_SERVER['HTTP_HOST'] = NULL; $_SERVER['PHP_SELF'] = NULL; } $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF']; $_SERVER['REMOTE_ADDR'] = ''; $_SERVER['REQUEST_METHOD'] = NULL; $_SERVER['SERVER_SOFTWARE'] = NULL; // Change to Drupal root dir. chdir(DRUSH_DRUPAL_ROOT); // Bootstrap Drupal. _drush_bootstrap_drupal(); /** * Allow the drushrc.php file to override $conf settings. * This is a separate variable because the $conf array gets initialized to an empty array, * in the drupal bootstrap process, and changes in settings.php would wipe out the drushrc.php * settings */ if (is_array($override)) { $conf = array_merge($conf, $override); } // Login the specified user (if given). if (DRUSH_USER) { _drush_login(DRUSH_USER); } // Now we can use all of Drupal. if (DRUSH_SIMULATE) { drush_print(t('SIMULATION MODE IS ENABLED. NO ACTUAL ACTION WILL BE TAKEN. SYSTEM WILL REMAIN UNCHANGED.')); } // Dispatch the command. $output = drush_dispatch($args['commands']); // prevent a '1' at the end of the outputs if ($output === true) { $output = ''; } // TODO: Terminate with the correct exit status. return $output; }
try { /******************DUBLIN CORE ********************/ // drush_print("Re-generating Dublin Core"); // update the DC based on the MODS record $document = new DOMDocument(); $document->loadXML($modsDS->content); $transform = 'mods_to_dc.xsl'; // the magic call xml_form_builder_update_dc_datastream($object, $transform, $document); // drush_print("Dublin core regenerated"); /*************DUBLIN CORE COMPLETE*****************/ // keep track of how many objects we edited $objectsChanged++; } catch (Exception $e) { drush_print("\n\n**********####### ERROR #######*********"); drush_print("***Could not update {$objectPID} DC record ****\n\n"); $skippedObjects[] = $objectPID; continue; } } } drush_print("Main processing loop complete"); drush_print("{$objectsChanged} out of {$totalNumObjects} were updated"); if (!empty($skippedObjects)) { $skippedObjects = array_unique($skippedObjects); drush_print("The script had problems with the following PID's"); foreach ($skippedObjects as $skipped) { drush_print($skipped); } } echo "\n\nAll operations complete\n";
public function clearScreen() { if (drush_verify_cli()) { drush_print("c"); } }
/** * Render response using Drush. * * @return string * Report using Drush native output functions. */ public function toDrush() { if ($this->percent == SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_INFO) { drush_print(dt('!label: Info', array('!label' => $this->getLabel()))); } else { drush_print(dt('!label: @percent%', array('!label' => $this->getLabel(), '@percent' => $this->percent))); } if ($this->percent == 100) { if (drush_get_option('gist')) { drush_print(str_repeat(' ', 2) . dt('No action required.')); } else { drush_log(str_repeat(' ', 2) . dt('No action required.'), 'success'); } } if (drush_get_option('detail') || $this->percent != 100) { foreach ($this->checks as $check) { if (drush_get_option('detail') || $check->getScore() != SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_PASS || $this->percent == SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_INFO) { if (drush_get_option('detail')) { drush_print(str_repeat(' ', 2) . dt('!label: !description', array('!label' => $check->getLabel(), '!description' => $check->getDescription()))); } else { if ($check->getScore() != SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_INFO) { drush_print(str_repeat(' ', 2) . dt('!label', array('!label' => $check->getLabel()))); } } if ($this->percent == SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_INFO || drush_get_option('detail')) { if ($check->getScore() != SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_INFO || drush_get_option('detail')) { drush_print(str_repeat(' ', 4) . dt('!result', array('!result' => $check->getResult()))); } else { drush_print(str_repeat(' ', 2) . dt('!result', array('!result' => $check->getResult()))); } } else { if (drush_get_option('gist')) { drush_log(str_repeat(' ', 4) . dt('!result', array('!result' => $check->getResult()))); } else { drush_log(str_repeat(' ', 4) . dt('!result', array('!result' => $check->getResult())), $check->getScoreDrushLevel()); } } if ($check->renderAction()) { drush_print(str_repeat(' ', 6) . dt('!action', array('!action' => $check->renderAction()))); } } } } }
$dslabel = drush_shift(); if (!$dslabel) { drush_print("***Error: please provide the DS name as the second argument"); drush_print("Example: drush php-script printDSInfo.php RULA:193 OBJ.0"); return; } # include all Tuque php files $tuquePath = libraries_get_path('tuque') . '/*.php'; foreach (glob($tuquePath) as $filename) { require_once $filename; } // repository connection parameters $url = 'localhost:8080/fedora'; $username = '******'; $password = '******'; // set up connection and repository variables $connection = new RepositoryConnection($url, $username, $password); $api = new FedoraApi($connection); $repository = new FedoraRepository($api, new SimpleCache()); $api_m = $repository->api->m; $api_a = $repository->api->a; drush_print("Datastream history for the {$dslabel} datastream:"); $info = array_reverse($api_m->getDatastreamHistory($PID, $dslabel)); print_r($info); $history = $api_a->getObjectHistory($PID); $profile = $api_a->getObjectProfile($PID, new DateTime()); drush_print("Object History:"); print_r($history); drush_print("Object Profile:"); print_r($profile); echo "\n\nAll operations complete\n";