comparison sites/all/modules/custom/solrconnect/drush/apachesolr.drush.inc @ 0:015d06b10d37 default tip

initial
author dwinter
date Wed, 31 Jul 2013 13:49:13 +0200
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:015d06b10d37
1 <?php
2
3 /**
4 * @file
5 * drush integration for apachesolr.
6 */
7
8 /**
9 * Implements hook_drush_command().
10 *
11 * @return array
12 * An associative array describing your command(s).
13 */
14 function apachesolr_drush_command() {
15 $items = array();
16
17 $items['solr-delete-index'] = array(
18 'callback' => 'apachesolr_drush_solr_delete_index',
19 'description' => dt('Deletes the content from the index. Can take content types as parameters.'),
20 'arguments' => array(
21 'types' => dt('Optional. A space delimited list of content types to be deleted from the index.'),
22 ),
23 'options' => array(
24 'environment-id' => 'The environment ID',
25 ),
26 'examples' => array(
27 'drush solr-delete-index node' => 'Delete all node content from the index.',
28 'drush solr-delete-index node:article' => 'Delete all content of the article content type from the index.',
29 'drush solr-delete-index node:article node:blog' => 'Delete all content of the article and blog content types from the index.',
30 ),
31 );
32 $items['solr-mark-all'] = array(
33 'callback' => 'apachesolr_drush_solr_mark_for_reindex',
34 'description' => dt('Marks content for reindexing. Can take content types as parameters.'),
35 'arguments' => array(
36 'types' => dt('Optional. A space delimited list of content types to be marked for reindexing.'),
37 ),
38 'options' => array(
39 'environment-id' => 'The environment ID',
40 ),
41 );
42 $items['solr-index'] = array(
43 'callback' => 'apachesolr_drush_solr_index',
44 'description' => dt('Reindexes content marked for (re)indexing.'),
45 'options' => array(
46 'environment-id' => 'The environment ID',
47 'limit' => 'The total number of documents to index',
48 ),
49 );
50 $items['solr-get-last-indexed'] = array(
51 'callback' => 'apachesolr_drush_solr_get_last_indexed',
52 'description' => dt('Get the ID of the last document indexed.'),
53 'arguments' => array(
54 'environment-id' => dt('Optional. The environment ID, uses the default if not passed.'),
55 'entity-type' => dt('Optional. The machine name of the entity, defaults to "node".'),
56 ),
57 );
58 $items['solr-get-next-indexed'] = array(
59 'callback' => 'apachesolr_drush_solr_get_next_indexed',
60 'description' => dt('Get the ID of the next document to be indexed.'),
61 'arguments' => array(
62 'environment-id' => dt('Optional. The environment ID, uses the default if not passed.'),
63 'entity-type' => dt('Optional. The machine name of the entity, defaults to "node".'),
64 ),
65 );
66 $items['solr-search'] = array(
67 'callback' => 'apachesolr_drush_solr_search',
68 'description' => dt('Search the site for keywords using Apache Solr'),
69 'arguments' => array(
70 'keywords' => dt('One or more keywords, separated by spaces.'),
71 ),
72 );
73 $items['solr-get-env-id'] = array(
74 'callback' => 'apachesolr_drush_solr_get_env_id',
75 'description' => dt('Get the default Apache Solr environment ID, or all IDs and names'),
76 'arguments' => array(),
77 'options' => array(
78 'all' => array(
79 'description' => 'List all environment IDs',
80 ),
81 ),
82 );
83 $items['solr-get-env-name'] = array(
84 'callback' => 'apachesolr_drush_solr_get_env_name',
85 'description' => dt('Get the Apache Solr environment name.'),
86 'options' => array(
87 'id' => array(
88 'description' => 'Apache Solr environment ID to use (uses the default environment if not specified)',
89 ),
90 ),
91 );
92 $items['solr-get-env-url'] = array(
93 'callback' => 'apachesolr_drush_solr_get_env_url',
94 'description' => dt('Get the Apache Solr environment url.'),
95 'options' => array(
96 'id' => array(
97 'description' => 'Apache Solr environment ID to use (uses the default environment if not specified)',
98 ),
99 ),
100 );
101 $items['solr-set-env-url'] = array(
102 'callback' => 'apachesolr_drush_solr_set_env_url',
103 'description' => dt('Set the url for an Apache Solr environment.'),
104 'arguments' => array(
105 'url' => dt('Apache Solr server url string.'),
106 ),
107 'required-arguments' => TRUE,
108 'options' => array(
109 'id' => array(
110 'description' => 'Apache Solr environment ID to use (uses the default environment if not specified)',
111 ),
112 ),
113 );
114 $items['solr-variable-get'] = array(
115 'description' => 'Get a list of Apache Solr environment variable names and values.',
116 'arguments' => array(
117 'name' => 'A string to filter the variables by. Variables that have any part of their name matching the string will b listed.',
118 ),
119 'examples' => array(
120 'drush solr-vget' => 'List all variables and values.',
121 'drush solr-vget user' => 'List all variables containing the string "user".',
122 ),
123 'options' => array(
124 'id' => 'Apache Solr environment ID to use (uses the default environment if not specified)',
125 'format' => 'Format to output the object. Use "print_r" for print_r (default), "export" for var_export, and "json" for JSON.',
126 'pipe' => 'A synonym for --format=export. Useful for pasting into code.',
127 ),
128 'aliases' => array('solr-vget'),
129 );
130 $items['solr-variable-set'] = array(
131 'description' => "Set an Apache Solr environment variable.",
132 'arguments' => array(
133 'name' => 'The name of a variable or the first few letters of its name.',
134 'value' => 'The value to assign to the variable. Use \'-\' to read the object from STDIN.',
135 ),
136 'required-arguments' => TRUE,
137 'options' => array(
138 'id' => 'Apache Solr environment ID to use (uses the default environment if not specified)',
139 'yes' => 'Skip confirmation if only one variable name matches.',
140 'always-set' => 'Always skip confirmation.',
141 'format' => 'Format to parse the object. Use "auto" to detect format from value (default), "string", "integer" or "boolean" for corresponding primitive type, and "json" for JSON.',
142 ),
143 'examples' => array(
144 'drush solr-vset --yes apachesolr_read_only 1' => 'Set the apachesolr_read_only variable to 1. Skip confirmation if variable already exists.',
145 'drush solr-vset pr TRUE' => 'Choose from a list of variables beginning with "pr" to set to (bool)true.',
146 'php -r "print json_encode(array(\'drupal\', \'simpletest\'));" | drush solr-vset --format=json project_dependency_excluded_dependencies -'=> 'Set a variable to a complex value (e.g. array)',
147 ),
148 'aliases' => array('solr-vset'),
149 );
150 $items['solr-variable-delete'] = array(
151 'description' => "Delete an Apache Solr environment variable.",
152 'arguments' => array(
153 'name' => 'The name of a variable or the first few letters of its name.',
154 ),
155 'required-arguments' => TRUE,
156 'options' => array(
157 'id' => array(
158 'description' => 'Apaches Solr environment ID to use (uses the default environment if not specified)',
159 ),
160 'yes' => 'Skip confirmation if only one variable name matches.',
161 'exact' => 'Only delete the one variable that exactly matches the specified name.',
162 ),
163 'examples' => array(
164 'drush solr-vdel apachesolr_read_only --id=solr2' => 'Delete the apachesolr_read_only variable for the solr2 environment.',
165 'drush solr-vdel apa' => 'Choose from a list of variables beginning with "u" to delete.',
166 'drush solr-vdel -y --exact apachesolr_read_only' => 'Delete variable, skipping confirmation.',
167 ),
168 'aliases' => array('solr-vdel'),
169 );
170 return $items;
171 }
172
173 /**
174 * Implements hook_drush_help().
175 *
176 * This function is called whenever a drush user calls
177 * 'drush help <name-of-your-command>'
178 *
179 * @param string $section
180 * A string with the help section (prepend with 'drush:')
181 *
182 * @return string
183 * A string with the help text for your command.
184 */
185 function apachesolr_drush_help($section) {
186 switch ($section) {
187 case 'drush:solr-delete-index':
188 return dt("Used without parameters, this command deletes the entire Solr index.
189 Used with parameters for content type, it deletes just the content types that are specified.
190 After the index has been deleted, all content will be indexed again on future cron runs.");
191 case 'drush:solr-mark-all':
192 return dt("Used without parameters, this command marks all of the content in the Solr index for
193 reindexing. Used with parameters for content type, it marks just the content types that are specified.
194 Reindexing is different than deleting as the content is still searchable while it is in queue to be reindexed.
195 Reindexing is done on future cron runs.");
196 case 'drush:solr-index':
197 return dt("Reindexes content marked for (re)indexing. If you want to reindex all content or content
198 of a specific type, use solr-reindex first to mark that content.");
199 case 'drush:solr-search':
200 return dt('Executes a search against the site\'s Apache Solr search index and returns the results.');
201 case 'error:APACHESOLR_ENV_ID_ERROR':
202 return dt('Not a valid environment ID.');
203 }
204 return '';
205 }
206
207 /**
208 * Selectively delete content from the apachesolr index.
209 *
210 * Each argument is a filter on what to delete from the index.
211 * They are of the form entity (to delete all content of that
212 * entity) or entity:bundle (to delete all content of that
213 * bundle).
214 */
215 function apachesolr_drush_solr_delete_index() {
216 module_load_include('inc', 'apachesolr', 'apachesolr.index');
217 $args = func_get_args();
218 $env_id = drush_get_option('environment-id');
219 if (empty($env_id)) {
220 $env_id = apachesolr_default_environment();
221 }
222
223 if (count($args) > 0) {
224 foreach ($args as $type) {
225 $parts = explode(':', $type);
226 if (count($parts) === 1) {
227 apachesolr_index_delete_index($env_id, $type);
228 }
229 elseif (count($parts) == 2) {
230 apachesolr_index_delete_index($env_id, $parts[0], $parts[1]);
231 }
232 else {
233 drush_set_error('The syntax for each type is either entity or entity:bundle');
234 }
235 }
236 }
237 else {
238 apachesolr_index_delete_index($env_id);
239 }
240
241 drush_print(t('Deleted the Solr index'));
242 }
243
244 /**
245 * Mark all of a specific environment id for reindexing
246 */
247 function apachesolr_drush_solr_mark_for_reindex() {
248 module_load_include('inc', 'apachesolr', 'apachesolr.index');
249 $args = func_get_args();
250 $env_id = drush_get_option('environment-id');
251 if (empty($env_id)) {
252 $env_id = apachesolr_default_environment();
253 }
254 if (count($args) > 0) {
255 foreach ($args as $type) {
256 apachesolr_index_mark_for_reindex($env_id, $type);
257 }
258 }
259 else {
260 apachesolr_index_mark_for_reindex($env_id);
261 }
262 drush_print(t('Marked content for reindexing'));
263 }
264
265 /**
266 * Index all the items in the queue using a batch command
267 */
268 function apachesolr_drush_solr_index() {
269 module_load_include('inc', 'apachesolr', 'apachesolr.admin');
270 module_load_include('inc', 'apachesolr', 'apachesolr.index');
271 $env_id = drush_get_option('environment-id');
272 if (empty($env_id)) {
273 $env_id = apachesolr_default_environment();
274 }
275 $total_limit = intval(drush_get_option('limit'));
276 apachesolr_index_batch_index_remaining($env_id, $total_limit);
277 drush_backend_batch_process();
278 }
279
280 /**
281 * Get the last indexed document
282 *
283 * @param string $env_id
284 * @param string $entity_type
285 */
286 function apachesolr_drush_solr_get_last_indexed($env_id = NULL, $entity_type = 'node') {
287 if (NULL === $env_id) {
288 $env_id = apachesolr_default_environment();
289 }
290 $return = apachesolr_get_last_index_position($env_id, $entity_type);
291 drush_print($return['last_entity_id']);
292 }
293
294 function apachesolr_drush_solr_get_next_indexed($env_id = NULL, $entity_type = 'node') {
295 module_load_include('inc', 'apachesolr', 'apachesolr.index');
296 if (NULL === $env_id) {
297 $env_id = apachesolr_default_environment();
298 }
299 $return = apachesolr_index_get_entities_to_index($env_id, $entity_type, 1);
300 $output = (isset($return[0]->entity_id)) ? $return[0]->entity_id : '0';
301 drush_print($output);
302 }
303
304 /**
305 * Search the solr index using Drush
306 */
307 function apachesolr_drush_solr_search() {
308 $args = func_get_args();
309 $keys = implode(' ', $args);
310 foreach (apachesolr_search_search_execute($keys) as $result) {
311 $output = $result['fields']['path'];
312 if(isset($result['user']) && isset($result['node']->is_uid)) {
313 $output .= ' ' . dt('by @name (user/@uid)', array('@name' => strip_tags($result['user']), '@uid' => $result['node']->is_uid));
314 }
315 $output .= "\n";
316 $output .= dt('title: ') . $result['title'] . "\n";
317 $output .= trim(preg_replace('/\s+/', ' ', strip_tags($result['snippet']))) . "\n\n";
318 drush_print($output);
319 }
320 }
321
322 /**
323 * Get all the environments (using option all) or get the default environment id
324 */
325 function apachesolr_drush_solr_get_env_id() {
326 $all = drush_get_option('all');
327
328 if ($all) {
329 foreach (apachesolr_load_all_environments() as $id => $env) {
330 drush_print(drush_format($env['name'], $id));
331 }
332 }
333 else {
334 $solr_env_id = apachesolr_default_environment();
335 drush_print($solr_env_id);
336 }
337 }
338
339 /**
340 * Get the environment name based on the environment ID
341 *
342 * @print The environment name
343 *
344 * @return mixed APACHESOLR_ENV_ID_ERROR
345 * Only return error if the environment can't be found
346 */
347 function apachesolr_drush_solr_get_env_name() {
348 $env_id = drush_get_option('id', apachesolr_default_environment());
349 try {
350 $environment = _apachesolr_drush_environment_load_and_validate($env_id);
351 }
352 catch (Exception $e) {
353 return drush_set_error('APACHESOLR_ENV_ID_ERROR', $e->getMessage());
354 }
355 drush_print($environment['name']);
356 }
357
358 /**
359 * Get the environment url based on the environment ID
360 *
361 * @print The environment url
362 *
363 * @return mixed APACHESOLR_ENV_ID_ERROR
364 * Only return error if the environment can't be found
365 */
366 function apachesolr_drush_solr_get_env_url() {
367 $env_id = drush_get_option('id', apachesolr_default_environment());
368 try {
369 $environment = _apachesolr_drush_environment_load_and_validate($env_id);
370 }
371 catch (Exception $e) {
372 return drush_set_error('APACHESOLR_ENV_ID_ERROR', $e->getMessage());
373 }
374 drush_print($environment['url']);
375 }
376
377 /**
378 * Set the environment url based on the environment ID
379 *
380 * @param $url
381 *
382 * @return mixed APACHESOLR_ENV_ID_ERROR
383 * Only return error if the environment can't be found
384 */
385 function apachesolr_drush_solr_set_env_url($url) {
386 $env_id = drush_get_option('id', apachesolr_default_environment());
387 try {
388 $environment = _apachesolr_drush_environment_load_and_validate($env_id);
389 }
390 catch (Exception $e) {
391 return drush_set_error('APACHESOLR_ENV_ID_ERROR', $e->getMessage());
392 }
393 $environment['url'] = $url;
394 apachesolr_environment_save($environment);
395 }
396
397 /**
398 * Command callback.
399 *
400 * List your site's variables.
401 * much of it copied from drush core
402 *
403 * @param string $arg_name
404 *
405 * @return array|mixed Could be the variable or a drush error
406 */
407 function drush_apachesolr_solr_variable_get($arg_name = NULL) {
408 $output = NULL;
409
410 $found = array();
411
412 $env_id = drush_get_option('id', apachesolr_default_environment());
413 try {
414 $found = _apachesolr_drush_variable_like($env_id, $arg_name);
415 }
416 catch (Exception $e) {
417 return drush_set_error('APACHESOLR_ENV_ID_ERROR', $e->getMessage());
418 }
419
420 foreach ($found as $name => $value) {
421 drush_print_pipe(drush_format($value, $name, 'export'));
422 drush_print(drush_format($value, $name));
423 }
424
425 if (empty($found)) {
426 return drush_set_error('DRUSH_VARIABLE_ERROR', 'No matching variable found.');
427 }
428 else {
429 return $found;
430 }
431 }
432
433 /**
434 * Command callback.
435 * Set a variable.
436 *
437 * @param string $arg_name
438 * @param mixed $value
439 *
440 * @return mixed
441 */
442 function drush_apachesolr_solr_variable_set($arg_name, $value) {
443 $args = func_get_args();
444
445 if (!isset($value)) {
446 return drush_set_error('DRUSH_VARIABLE_ERROR', dt('No value specified.'));
447 }
448
449 $env_id = drush_get_option('id', apachesolr_default_environment());
450 try {
451 $found = _apachesolr_drush_variable_like($env_id, $arg_name, TRUE);
452 }
453 catch (Exception $e) {
454 return drush_set_error('APACHESOLR_ENV_ID_ERROR', $e->getMessage());
455 }
456
457 $options[] = "$arg_name ". dt('(new variable)');
458 $match = isset($found[$arg_name]);
459 if (!$match && $found) {
460 $options = array_merge($options, array_keys($found));
461 }
462
463 if ($value == '-') {
464 $value = stream_get_contents(STDIN);
465 }
466
467 // If the value is a string (usual case, unless we are called from code),
468 // then format the input
469 if (is_string($value)) {
470 $value = _apachesolr_drush_variable_format($value, drush_get_option('format', 'auto'));
471 }
472
473 // Format the output for display
474 if (is_array($value)) {
475 $display = "\n" . var_export($value, TRUE);
476 }
477 elseif (is_integer($value)) {
478 $display = $value;
479 }
480 elseif (is_bool($value)) {
481 $display = $value ? "TRUE" : "FALSE";
482 }
483 else {
484 $display = '"' . $value . '"';
485 }
486
487 $name = NULL;
488 if (drush_get_option('always-set', FALSE) || $match) {
489 $name = $arg_name;
490 }
491 else {
492 $choice = drush_choice($options, 'Enter a number to choose which variable to set.');
493 if ($choice !== FALSE) {
494 $name = ($choice == 0) ? $arg_name : $options[$choice];
495 }
496 }
497 if ($name) {
498 drush_op('apachesolr_environment_variable_set', $env_id, $name, $value);
499 drush_log(dt('!name was set to !value', array('!name' => $name, '!value' => $display)), 'success');
500 }
501 }
502
503 /**
504 *
505 * Format a specific variable
506 *
507 * @param $value
508 * @param $format
509 *
510 * @return bool|int|string
511 */
512 function _apachesolr_drush_variable_format($value, $format) {
513 if ($format == 'auto') {
514 if (is_numeric($value)) {
515 $format = 'integer';
516 }
517 elseif (($value == 'TRUE') || ($value == 'FALSE')) {
518 $format = 'bool';
519 }
520 }
521
522 // Now, we parse the object.
523 switch ($format) {
524 case 'integer':
525 $value = (integer)$value;
526 break;
527
528 case 'bool':
529 case 'boolean':
530 if ($value == 'TRUE') {
531 $value = TRUE;
532 }
533 elseif ($value == 'FALSE') {
534 $value = FALSE;
535 }
536 else {
537 $value = (bool)$value;
538 }
539 break;
540
541 case 'json':
542 $value = drush_json_decode($value);
543 break;
544 }
545 return $value;
546 }
547
548 /**
549 * Command callback.
550 * Delete a variable.
551 * @param $arg_name
552 *
553 * @return string
554 */
555 function drush_apachesolr_solr_variable_delete($arg_name) {
556
557 $env_id = drush_get_option('id', apachesolr_default_environment());
558 // Look for similar variable names.
559 try {
560 $found = _apachesolr_drush_variable_like($env_id, $arg_name, TRUE);
561 }
562 catch (Exception $e) {
563 return drush_set_error('APACHESOLR_ENV_ID_ERROR', $e->getMessage());
564 }
565 drush_log(dt('Using environment ID "!env_id"', array('!env_id' => $env_id)), 'success');
566 $options = array_keys($found);
567
568 if (drush_get_option('exact', FALSE)) {
569 $options = isset($found[$arg_name]) ? array($arg_name) : array();
570 }
571
572 if (empty($options)) {
573 drush_print(dt('!name not found.', array('!name' => $arg_name)));
574 return '';
575 }
576
577 $name = NULL;
578 if ((count($options) == 1) && drush_get_context('DRUSH_AFFIRMATIVE')) {
579 $name = $arg_name;
580 }
581 else {
582 $choice = drush_choice($options, 'Enter a number to choose which variable to delete.');
583 if ($choice !== FALSE) {
584 $name = $options[$choice];
585 }
586 }
587 if ($name) {
588 drush_op('apachesolr_environment_variable_del', $env_id, $name);
589 drush_log(dt('!choice was deleted.', array('!choice' => $name)), 'success');
590 }
591 }
592
593 /**
594 * Load an environment from an id and validate the result.
595 *
596 * @param string $env_id
597 *
598 * @return array $environment
599 * @throws Exception
600 */
601 function _apachesolr_drush_environment_load_and_validate($env_id) {
602 $environment = apachesolr_environment_load($env_id);
603 if (!$environment) {
604 throw new Exception(dt('!env_id is not a valid environment ID.', array('!env_id' => $env_id)));
605 }
606 drush_log(dt('Using environment ID: "!env_id"', array('!env_id' => $env_id)), 'success');
607 return $environment;
608 }
609
610 /**
611 * Search for similar variable names.
612 *
613 * @param string $env_id
614 * @param string $arg
615 * @param bool|string $starts_with
616 *
617 * @throws Exception
618 *
619 * @return array $variable
620 * Only return it if found
621 */
622 function _apachesolr_drush_variable_like($env_id, $arg = NULL, $starts_with = FALSE) {
623 $found = array();
624 $environment = _apachesolr_drush_environment_load_and_validate($env_id);
625 if (!isset($arg)) {
626 return $environment['conf'];
627 }
628 if ($starts_with) {
629 $pattern = "/^{$arg}/i";
630 }
631 else {
632 $pattern = "/{$arg}/i";
633 }
634 foreach ($environment['conf'] as $name => $value) {
635 // Find all variable that start with $arg.
636 if (preg_match($pattern, $name)) {
637 $found[$name] = $value;
638 }
639 }
640 return $found;
641 }
642