scanner.module 44.2 KB
Newer Older
1 2 3 4
<?php
/**
 * @file
 * Search and Replace Scanner - works on all nodes text content.
5 6 7 8 9 10
 *
 * The Search and Replace Scanner can do regular expression matches
 * against the title, body and CCK text content fields on all nodes in your system.
 * This is useful for finding html strings that Drupal's normal search will
 * ignore. And it can replace the matched text. Very handy if you are changing
 * the name of your company, or are changing the URL of a link included
Tao Starbow's avatar
Tao Starbow committed
11
 * multiple times in multiple nodes.
12 13
 *
 * The module allow you to configure which fields and tables to work with,
Tao Starbow's avatar
Tao Starbow committed
14
 * and also to add in custom tables and fields for modules that don't use CCK.
15
 *
Tao Starbow's avatar
Tao Starbow committed
16 17
 * Limitations:
 *  Only works with Mysql
18
 *
Tao Starbow's avatar
Tao Starbow committed
19
 * Warning:
20
 *  This is a very powerful tool, and as such is very dangerous.  You can
Tao Starbow's avatar
Tao Starbow committed
21 22
 *  easy distroy your entire site with it.  Be sure to backup your database
 *  before using it.  No, really.
23
 *
Tao Starbow's avatar
Tao Starbow committed
24
 * Todo:
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
 *  Provide better highlighting for search results
 *   - right now there's a known bug where multiple search terms
 *     on the same line aren't all highlighted. (The hit count
 *     is correct, though, and all items are replaced correctly.)
 *
 * Credits:
 *  Version 5.x-1.0 by:
 *   - Tao Starbow http://www.starbowconsulting.com
 *     Drupal username: starbow
 *  Version 5.x-2.0 by:
 *   - Amit Asaravala http://www.returncontrol.com
 *     Drupal username: aasarava
 *   - Jason Salter jason http://www.fivepaths.com
 *     Drupal username: jpsalter
 *   - Sponsored by Five Paths Consulting http://www.fivepaths.com
40 41 42
 *  Version 7.x-1.0 by:
 *   - Michael Rossetti - http://www.mit.edu
 *     Drupal username: MikeyR
43 44
 */

45 46 47 48 49 50 51 52 53 54 55 56 57

//The special characters to escape if a search string is not a regex string:
define('SCANNER_REGEX_CHARS', '.\/+*?[^]$() {}=!<>|:');

//The modes that the search-and-replace process can be in.
//We need to track the modes to prevent accidentally starting a replacement
// or a long search if a user leaves mid-way through the process
// and comes back again w/ the same session variables.
define('SCANNER_STATUS_GO_SEARCH', 1);
define('SCANNER_STATUS_GO_CONFIRM', 2);
define('SCANNER_STATUS_GO_REPLACE', 3);


58
/**
59
 * Implements hook_menu().
60
 */
61
function scanner_menu() {
62

63 64 65 66
  $items['admin/content/scanner'] = array(
    'title' => 'Search and Replace Scanner',
    'description' => 'Find (and replace) keywords in all your content.',
    'page callback' => 'scanner_view',
67
    'type' => MENU_LOCAL_TASK,
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
    'access arguments' => array('perform search and replace'),
  );
  $items['admin/content/scanner/scan'] = array(
    'title' => 'Search',
    'access arguments' => array('perform search and replace'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['admin/content/scanner/scan/confirm'] = array(
    'title' => 'Confirm Replace',
    'access arguments' => array('perform search and replace'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('scanner_confirm_form'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/content/scanner/undo/confirm'] = array(
    'title' => 'Confirm Undo',
    'access arguments' => array('perform search and replace'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('scanner_undo_confirm_form'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/content/scanner/settings'] = array(// Shows up on scanner page as tab.
    'title' => 'Settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('scanner_admin_form'),
    'access arguments' => array('administer scanner settings'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 1,
  );
  $items['admin/content/scanner/undo'] = array(// Shows up on scanner page as tab.
    'title' => 'Undo',
    'page callback' => 'scanner_undo_page',
    'access arguments' => array('perform search and replace'),
    'type' => MENU_LOCAL_TASK,
  );
  $items['admin/config/scanner'] = array(// Shows up on admin page.
    'title' => 'Search and Replace Scanner',
    'description' => 'Configure defaults and what fields can be searched and replaced.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('scanner_admin_form'),
    'access arguments' => array('administer scanner settings'),
  );
110 111 112
  return $items;
}

113 114 115 116
/**
 * @todo Please document this function.
 * @see http://drupal.org/node/1354
 */
117 118 119 120
function scanner_theme() {
  return array(
    'scanner_results' => array(
      'file' => 'scanner.module',
121
      'variables' => array(
122 123 124 125 126
        'results' => NULL,
      ),
    ),
    'scanner_item' => array(
      'file' => 'scanner.module',
127
      'variables' => array(
128 129 130 131 132
        'item' => NULL,
      ),
    ),
    'scanner_replace_results' => array(
      'file' => 'scanner.module',
133
      'variables' => array(
134 135 136 137 138
        'results' => NULL,
      ),
    ),
    'scanner_replace_item' => array(
      'file' => 'scanner.module',
139
      'variables' => array(
140 141 142 143 144 145 146
        'item' => NULL,
      ),
    ),
  );
}


147
/**
148
 * Implements hook_permission().
149
 */
150 151 152 153 154 155 156 157 158 159 160
function scanner_permission() {
  return array(
    'administer scanner settings' => array(
      'title' => t('administer scanner settings'),
      'description' => t('TODO Add a description for \'administer scanner settings\''),
    ),
    'perform search and replace' => array(
      'title' => t('perform search and replace'),
      'description' => t('TODO Add a description for \'perform search and replace\''),
    ),
  );
161 162
}

163 164 165 166
/**
 * Menu callback; presents the scan form and results.
 */
function scanner_view() {
167 168 169
    
  $output='';
  
170 171
  //using set_html_head because it seems unecessary to load a separate css
  // file for just two simple declarations:
172
  drupal_add_css('
173 174
      #scanner-form .form-submit { margin-top:0; }
      #scanner-form .form-item { margin-bottom:0; }
175
    ', array('type' => 'inline'));
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

  //javascript checks to make sure user has entered some search text:
  drupal_add_js("
    $(document).ready(function() {
      $('input[@type=submit][@value=Search]').click(function() {
        var searchfield = $('#edit-search');
        var chars = searchfield.val().length;
        if (chars == 0) {
          alert('Please provide some search text and try again.');
          searchfield.addClass('error');
          searchfield[0].focus();
          return FALSE;
        } else if (chars < 3) {
          return confirm('Searching for a keyword that has fewer than three characters could take a long time. Are you sure you want to continue?');
        }
        return TRUE;
      });
    });
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
  ", array('type' => 'inline', 'scope' => JS_DEFAULT));
  
  if (isset($_SESSION['scanner_search'])) {
    $search = $_SESSION['scanner_search'];
  }
  else{
    $search = NULL;
  }
  
  if (isset($_SESSION['scanner_status'])) {
    $status = $_SESSION['scanner_status'];
  }
  else{
      $status = NULL;
  }
  
210 211 212 213 214 215
  if (!is_NULL($search) && $status >= SCANNER_STATUS_GO_SEARCH) {

    if ($status == SCANNER_STATUS_GO_CONFIRM) {
      drupal_goto('admin/content/scanner/scan/confirm');

    }
216 217
    elseif ($status == SCANNER_STATUS_GO_REPLACE) {
      $resulttxt = '<a name="results"></a>' . t('Replacement Results');
218 219
      $results = scanner_execute('replace');

220 221
    }
    else {
222 223
      $resulttxt = t('Search Results');
      $results = scanner_execute('search');
224
    }
225

226
    if ($results) {
227 228
      // TODO Please change this theme call to use an associative array for the $variables parameter.
      $results = '<a name="results"></a><div><h2>' . $resulttxt . '</h2>' . $results;
229 230
    }
    else {
231 232
      // TODO Please change this theme call to use an associative array for the $variables parameter.
      $results = t('Your search yielded no results.');
233
    }
234 235
    
    $output = drupal_render(drupal_get_form('scanner_form'));
236 237
    $output .= $results;

238 239 240 241 242 243 244 245 246 247 248 249 250
    //clear any old search form input:
    unset($_SESSION['scanner_search']);
    unset($_SESSION['scanner_replace']);
    unset($_SESSION['scanner_preceded']);
    unset($_SESSION['scanner_followed']);
    unset($_SESSION['scanner_mode']);
    unset($_SESSION['scanner_wholeword']);
    unset($_SESSION['scanner_published']);
    unset($_SESSION['scanner_regex']);
    unset($_SESSION['scanner_terms']);
    //clear old status:
    unset($_SESSION['scanner_status']);

251 252
    return $output;
  }
253 254 255 256
   
  $output .= drupal_render(drupal_get_form('scanner_form'));
  
  return $output;
257 258 259 260 261 262 263 264 265
}

/**
 * The search and replace form.
 *
 * @param str $search - regex to search for.
 * @param str $replace - string to substitute.
 * @return $form
 */
266 267
function scanner_form($node, &$form_state) {
    
268
  $form = array();
269

270
  if (isset($_SESSION['scanner_search'])) {
271
  $search = $_SESSION['scanner_search'];
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
  }
  else{
      $search = NULL;
  }
  
  if (isset($_SESSION['scanner_replace'])) {
  $replace = $_SESSION['scanner_replace'];   
  }
  else{
      $replace = NULL;
  }
  if (isset($_SESSION['scanner_preceded'])) {
    $preceded = $_SESSION['scanner_preceded'];
  }
  else{
      $preceded = NULL;
  }
  
  if (isset($_SESSION['scanner_followed'])) {
    $followed = $_SESSION['scanner_followed'];
  }
  else{
      $followed = NULL;
  }
  
297 298 299 300
  $mode = isset($_SESSION['scanner_mode']) ? $_SESSION['scanner_mode'] : variable_get('scanner_mode', 0);
  $wholeword = isset($_SESSION['scanner_wholeword']) ? $_SESSION['scanner_wholeword'] : variable_get('scanner_wholeword', 0);
  $published = isset($_SESSION['scanner_published']) ? $_SESSION['scanner_published'] : variable_get('scanner_published', 1);
  $regex = isset($_SESSION['scanner_regex']) ? $_SESSION['scanner_regex'] : variable_get('scanner_regex', 0);
301 302 303 304 305 306 307 308
  
  if (isset($_SESSION['scanner_terms'])) {
    $terms = $_SESSION['scanner_terms'];
  }
  else{
      $terms = NULL;
  }
  
309
  $form['search'] = array(
310 311
    '#type' => 'textfield',
    '#default_value' => $search,
312 313
    '#title' => t('Step 1: Search for'),
    '#maxlength' => 256,
314
  );
315 316 317
  $form['submit_search'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
318 319
  );

320 321 322 323 324
  $form['replace'] = array(
    '#type' => 'textfield',
    '#default_value' => $replace,
    '#title' => t('Step 2: Replace with'),
    '#maxlength' => 256,
325 326 327 328
  );
  $form['submit_replace'] = array(
    '#type' => 'submit',
    '#value' => t('Replace'),
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
  );

  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Search Options'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $form['options']['surrounding'] = array(
    '#type' => 'fieldset',
    '#title' => t('Surrounding Text'),
    '#collapsible' => FALSE,
    '#description' => t('You can limit matches by providing the text that should appear immediately before or after the search text. Remember to account for spaces.  Note: Case sensitivity and regular expression options will all apply here, too. Whole word is not recommended.'),
  );

  $form['options']['surrounding']['preceded'] = array(
    '#type' => 'textfield',
    '#title' => t('Preceded by'),
    '#default_value' => $preceded,
    '#maxlength' => 256,
  );

  /* TODO: for possible future implementation...
   * Depends on whether negative lookahead and negative lookbehind
   *  can accurately be approximated in MySQL...
355 356 357 358 359 360
   $form['options']['surrounding']['notpreceded'] = array(
   '#type' => 'checkbox',
   '#title' => t('NOT preceded by the text above'),
   '#default_value' => $notpreceded,
   );
   */
361 362 363 364 365 366 367 368 369 370 371

  $form['options']['surrounding']['followed'] = array(
    '#type' => 'textfield',
    '#title' => t('Followed by'),
    '#default_value' => $followed,
    '#maxlength' => 256,
  );

  /* TODO: for possible future implementation...
   * Depends on whether negative lookahead and negative lookbehind
   *  can accurately be approximated in MySQL...
372 373 374 375 376 377
   $form['options']['surrounding']['notfollowed'] = array(
   '#type' => 'checkbox',
   '#title' => t('NOT followed by the text above'),
   '#default_value' => $notfollowed,
   );
   */
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407

  $form['options']['mode'] = array(
    '#type' => 'checkbox',
    '#title' => t('Case sensitive search'),
    '#default_value' => $mode,
    '#description' => t("Check this if the search should only return results that exactly match the capitalization of your search terms."),
  );

  $form['options']['wholeword'] = array(
    '#type' => 'checkbox',
    '#title' => t('Match whole word'),
    '#default_value' => $wholeword,
    '#description' => t("Check this if you don't want the search to match any partial words. For instance, if you search for 'run', a whole word search will <em>not</em> match 'running'."),
  );

  $form['options']['regex'] = array(
    '#type' => 'checkbox',
    '#title' => t('Use regular expressions in search'),
    '#default_value' => $regex,
    '#description' => t('Check this if you want to use regular expressions in your search terms.'),
  );

  $form['options']['published'] = array(
    '#type' => 'checkbox',
    '#title' => t('Published nodes only'),
    '#default_value' => $published,
    '#description' => t('Check this if you only want your search and replace to affect fields in nodes that are published.'),
  );

  $scanner_vocabularies = array_filter(variable_get('scanner_vocabulary', array()));
408
  
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434

  if (count($scanner_vocabularies)) {

    $vocabularies = taxonomy_get_vocabularies();
    $options = array();

    foreach ($vocabularies as $vid => $vocabulary) {
      if (in_array($vid, $scanner_vocabularies) ) {
        $tree = taxonomy_get_tree($vid);
        if ($tree && (count($tree) > 0)) {
          $options[$vocabulary->name] = array();
          foreach ($tree as $term) {
            $options[$vocabulary->name][$term->tid] = str_repeat('-', $term->depth) . $term->name;
          }
        }
      }
    }

    $form['options']['terms'] = array(
      '#type' => 'select',
      '#title' => t('Only match nodes with these terms'),
      '#options' => $options,
      '#default_value' => $terms,
      '#multiple' => TRUE,
    );
  }
435
  
436 437 438 439
  return $form;
}

/**
440 441
 * Validate form input.
 */
442 443
function scanner_form_validate($form, &$form_state) {
  $search = trim($form_state['values']['search']);
444 445 446 447 448 449 450
  if ($search == '') {
    form_set_error('search', t('Please enter some keywords.'));
  }
}

/**
 * Handles submission of the search and replace form.
451
 *
452 453
 * @param $form
 * @param $form_state
454 455
 * @return the new path that will be goto'ed.
 */
456
function scanner_form_submit($form, &$form_state) {
457
  //save form input:
458

459 460 461 462 463 464 465 466 467
  $_SESSION['scanner_search']    = $form_state['values']['search'];
  $_SESSION['scanner_preceded']  = $form_state['values']['preceded'];
  //$_SESSION['scanner_notpreceded'] = $form_state['values']['notpreceded'];
  $_SESSION['scanner_followed']  = $form_state['values']['followed'];
  //$_SESSION['scanner_notfollowed'] = $form_state['values']['notfollowed'];
  $_SESSION['scanner_mode']      = $form_state['values']['mode'];
  $_SESSION['scanner_wholeword'] = $form_state['values']['wholeword'];
  $_SESSION['scanner_published'] = $form_state['values']['published'];
  $_SESSION['scanner_regex']     = $form_state['values']['regex'];
468
  if (isset($form_state['values']['terms'])) {
469
  $_SESSION['scanner_terms']     = $form_state['values']['terms'];
470
  }
471 472
  $_SESSION['scanner_replace']   = $form_state['values']['replace'];

473
  /* TODO The 'op' element in the form values is deprecated.
474 475 476 477 478 479
   Each button can have #validate and #submit functions associated with it.
   Thus, there should be one button that submits the form and which invokes
   the normal form_id_validate and form_id_submit handlers. Any additional
   buttons which need to invoke different validate or submit functionality
   should have button-specific functions. */
  if ($form_state['values']['op'] == 'Replace') {
480 481 482 483
    $_SESSION['scanner_status'] = SCANNER_STATUS_GO_CONFIRM;
  }
  else {
    $_SESSION['scanner_status'] = SCANNER_STATUS_GO_SEARCH;
484
  }
485
  $form_state['redirect'] = 'admin/content/scanner';
486 487 488 489 490 491 492
}


/**
 * Scanner confirmation form to prevent people from accidentally
 * replacing things they don't intend to.
 */
493
function scanner_confirm_form($form, &$form_state) {
494 495 496 497
  //using set_html_head because it seems unecessary to load a separate css
  // file for just one declaration:
  //you can override the styles by declaring with something "higher up"
  // the chain, like:  #wrapper #scanner-confirm-form .scanner-buttons .scanner-button-msg {...}
498
  drupal_add_css('
499 500 501 502 503 504 505 506 507 508
      #scanner-confirm-form .scanner-buttons .scanner-button-msg {
        position:absolute;
        top:0; left:0; z-index:100;
        width:100%; height:100%;
        background-color:#000; opacity:0.75;
        font-size:1.2em;
      }
      #scanner-confirm-form .scanner-buttons .scanner-button-msg p {
        color:#fff;
      }
509
    ', array('type' => 'inline'));
510 511 512 513 514 515 516 517 518 519 520 521 522

  //javascript to prevent further clicks on confirmation button after it's clicked once.
  //unfortunately we can't just use css disable to disable the button because then
  // the op values aren't sent to drupal correctly.
  drupal_add_js("
    $(document).ready(function() {
      $('input[@type=submit][@value=Yes, Continue]').click(function() {
        $('.scanner-buttons').css('position','relative')
          .append('<div class=\"scanner-button-msg\"><p>Replacing items... please wait...</p></div>')
        $('.scanner-button-msg').click(function() { return false; });
        return true;
      });
    });
523
  ", array('type' => 'inline', 'scope' => JS_DEFAULT));
524

525 526 527 528 529 530 531 532 533 534 535 536 537
  $form = array();

  $search    = $_SESSION['scanner_search'];
  $replace   = $_SESSION['scanner_replace'];
  $preceded  = $_SESSION['scanner_preceded'];
  $followed  = $_SESSION['scanner_followed'];
  $wholeword = $_SESSION['scanner_wholeword'];
  $regex     = $_SESSION['scanner_regex'];
  $mode      = $_SESSION['scanner_mode'];

  $modetxt = ($mode) ? t('Case sensitive') : t('Not case sensitive: will replace any matches regardless of capitalization.');

  $msg = (
538 539 540
    '<p>' . t('Are you sure you want to make the following replacement?') . '</p>' .
    '<div class="scanner-confirm">' .
    '  <label>' . t('Search for') . ':</label> [' . check_plain($search) . ']' .
541 542 543 544
    '</div>'
  );
  if ($preceded) {
    $msg .= (
545 546
      '<div class="scanner-confirm">' .
      '  <label>' . t('Preceded by') . ':</label> [' . check_plain($preceded) . ']' .
547 548 549 550 551
      '</div>'
    );
  }
  if ($followed) {
    $msg .= (
552 553
      '<div class="scanner-confirm">' .
      '  <label>' . t('Followed by') . ':</label> [' . check_plain($followed) . ']' .
554 555 556 557
      '</div>'
    );
  }
  $msg .= (
558 559
    '<div class="scanner-confirm">' .
    '  <label>' . t('Replace with') . ':</label> [' . check_plain($replace) . ']'
560 561 562 563 564
  );
  if ($replace === '') {
    $msg .= ' <span class="warning">This will delete any occurences of the search terms!</span>';
  }
  $msg .= (
565 566 567
    '</div>' .
    '<div class="scanner-confirm">' .
    '  <label>' . t('Mode') . ':</label> ' . $modetxt .
568 569 570 571
    '</div>'
  );
  if ($wholeword) {
    $msg .= (
572 573
      '<div class="scanner-confirm">' .
      '  <label>' . t('Match whole word') . ':</label> ' . t('Yes') .
574 575 576 577 578
      '</div>'
    );
  }
  if ($regex) {
    $msg .= (
579 580
      '<div class="scanner-confirm">' .
      '  <label>' . t('Use regular expressions') . ':</label> ' . t('Yes') .
581 582 583 584 585
      '</div>'
    );
  }

  $form['warning'] = array(
586 587
    '#type' => 'item',
    '#markup' => $msg,
588 589 590 591 592
  );

  $form['confirm'] = array(
    '#type' => 'submit',
    '#value' => t('Yes, Continue'),
593
    '#prefix' => '<div class="scanner-buttons">', //see suffix in cancel button element
594 595 596 597
  );
  $form['cancel'] = array(
    '#type' => 'submit',
    '#value' => t('No, Cancel'),
598
    '#suffix' => '</div>', //see prefix in confirm button element
599
  );
600
  
601 602 603 604 605 606 607
  return $form;
}


/**
 * Submission handling for scanner confirmation form.
 */
608
function scanner_confirm_form_submit($form, &$form_state) {
609
  /* TODO The 'op' element in the form values is deprecated.
610 611 612 613 614 615
   Each button can have #validate and #submit functions associated with it.
   Thus, there should be one button that submits the form and which invokes
   the normal form_id_validate and form_id_submit handlers. Any additional
   buttons which need to invoke different validate or submit functionality
   should have button-specific functions. */
  if ($form_state['values']['op'] == t('Yes, Continue')) {
616 617 618 619 620 621
    $_SESSION['scanner_status'] = SCANNER_STATUS_GO_REPLACE;
  }
  else {
    unset($_SESSION['scanner_status']);
  }

622
  $form_state['redirect'] = 'admin/content/scanner';
623 624
}

625 626 627 628
/**
 * @todo Please document this function.
 * @see http://drupal.org/node/1354
 */
629 630 631
function scanner_undo_page() {
  $header = array(t('Date'), t('Searched'), t('Replaced'), t('Count'), t('Operation'));

632 633 634 635 636
  $undoQuery = db_select('scanner', 's');
  $undoQuery->fields('s', array('undo_id', 'time', 'searched', 'replaced', 'count', 'undone'))
            ->orderBy('undo_id', 'DESC');
  
  $sandrs = $undoQuery->execute();
637

638 639 640
  $rows = array();
  
  foreach ($sandrs as $sandr) {
641 642

    if ($sandr->undone) {
643
      $operation = l(t('Redo'), 'admin/content/scanner/undo/confirm', array('query' => array('undo_id' => $sandr->undo_id)));
644 645
    }
    else {
646
      $operation = l(t('Undo'), 'admin/content/scanner/undo/confirm', array('query' => array('undo_id' => $sandr->undo_id)));
647
    }
648 649 650 651 652 653 654 655

    $rows[] = array(
      format_date($sandr->time),
      check_plain($sandr->searched),
      check_plain($sandr->replaced),
      $sandr->count,
      $operation,
    );
656
  }
657 658
 
  return theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => NULL, 'caption' => 'Prior Search and Replace Events'));
659 660
}

661 662 663 664 665 666
/**
 * @todo Please document this function.
 * @see http://drupal.org/node/1354
 */
function scanner_undo_confirm_form($form, &$form_state) {
       
667 668 669
  $undo_id = $_GET['undo_id'];

  if ($undo_id > 0) {
670 671 672 673 674 675 676 677 678 679 680
    
    $query = db_select('scanner', 's');
    $query->fields('s', array('undo_id', 'searched', 'replaced'))
          ->condition('undo_id', $undo_id, '=');
    
    $result = $query->execute();
    
    foreach ($result as $undo) {
        $undo = $undo;
    }
    
681 682 683 684
  }

  if ($undo->undo_id > 0) {
    $form['info'] = array(
685 686 687 688 689
      '#markup' => '<h2>' . t('Do you want to undo:') . '</h2>' .
                  '<h3>' . t('Searched for:') . '</h3>' .
                  '<p>[<em>' . check_plain($undo->searched) . '</em>]</p>' .
                  '<h3>' . t('Replaced with:') . '</h3>' .
                  '<p>[<em>' . check_plain($undo->replaced) . '</em>]</p>',
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
    );

    $form['undo_id'] = array(
      '#type' => 'hidden',
      '#value' => $undo->undo_id,
    );

    $form['confirm'] = array(
      '#type' => 'submit',
      '#value' => t('Yes, Continue'),
    );

    $form['cancel'] = array(
      '#type' => 'submit',
      '#value' => t('No, Cancel'),
    );

  }
  else {
    $form['info'] = array(
710
      '#value' => '<h2>' . t('No undo event was found') . '</h2>',
711 712 713 714 715 716
    );
  }

  return $form;
}

717 718 719 720
/**
 * @todo Please document this function.
 * @see http://drupal.org/node/1354
 */
721
function scanner_undo_confirm_form_submit($form, &$form_state) {
722

723
  /* TODO The 'op' element in the form values is deprecated.
724 725 726 727 728 729
   Each button can have #validate and #submit functions associated with it.
   Thus, there should be one button that submits the form and which invokes
   the normal form_id_validate and form_id_submit handlers. Any additional
   buttons which need to invoke different validate or submit functionality
   should have button-specific functions. */
  if ($form_state['values']['op'] == t('Yes, Continue')) {
730 731 732 733 734 735 736 737 738 739 740
    
    $query = db_select('scanner', 's');
    $query->fields('s', array('undo_data', 'undone'))
          ->condition('undo_id', $form_state['values']['undo_id'], '=');
    
    $results = $query->execute();
    
    foreach ($results as $undo) {
          $undo = $undo;
    }
    
741
    $undos = unserialize($undo->undo_data);
742 743 744
    
    $count = NULL;
    
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
    foreach ($undos as $nid => $sandr_event) {

      if ($undo->undone == 0) {
        $vid = $sandr_event['old_vid'];
        $undone = 1;
      }
      else {
        $vid = $sandr_event['new_vid'];
        $undone = 0;
      }

      $node = node_load($nid, $vid);

      $node->revision = TRUE;
      $node->log = t('Copy of the revision from %date via Search and Replace Undo', array('%date' => format_date($node->revision_timestamp)));

      node_save($node);
      ++$count;

    }

766 767 768 769 770 771 772 773 774
    drupal_set_message($count . ' ' . t('Nodes reverted'));
    // TODO Please review the conversion of this statement to the D7 database API syntax.

    db_update('scanner')
    ->fields(array(
      'undone' => $undone,
    ))
    ->condition('undo_id', $form_state['values']['undo_id'])
    ->execute();
775 776 777 778 779 780

  }
  else {
    drupal_set_message(t('Undo / Redo canceled'));
  }

781 782
  $form_state['redirect'] = 'admin/content/scanner/undo';
  $form_state['nid'] = $node->nid;
783 784 785
}

/**
786
 * Handles the actual search and replace.
787
 *
788
 * @param str $searchtype - either 'search', or 'replace'
789 790
 * @return The themed results.
 */
791 792
function scanner_execute($searchtype = 'search') {
  global $user;
793

794 795
  // variables to monitor possible timeout
  $max_execution_time = ini_get('max_execution_time');
796
  $start_time = REQUEST_TIME;
797 798 799
  $expanded = FALSE;

  // get process and undo data if saved from timeout
800 801
  $processed = variable_get('scanner_partially_processed_' . $user->uid, array());
  $undo_data = variable_get('scanner_partial_undo_' . $user->uid, array());
802

803 804
  unset($_SESSION['scanner_status']);
  $results = NULL;
805 806 807 808 809 810 811 812 813 814
  $search      = $_SESSION['scanner_search'];
  $replace     = $_SESSION['scanner_replace'];
  $preceded    = $_SESSION['scanner_preceded'];
  //$notpreceded = $_SESSION['scanner_notpreceded'];
  $followed    = $_SESSION['scanner_followed'];
  //$notfollowed = $_SESSION['scanner_notfollowed'];
  $mode        = $_SESSION['scanner_mode'];
  $wholeword   = $_SESSION['scanner_wholeword'];
  $published   = $_SESSION['scanner_published'];
  $regex       = $_SESSION['scanner_regex'];
815
  if (isset($_SESSION['scanner_terms'])) {
816
  $terms       = $_SESSION['scanner_terms'];
817 818 819 820 821
  }
  else{
      $terms = NULL;
  }
  
822 823 824 825 826 827 828 829 830 831 832 833 834 835
  if ($searchtype == 'search') {
    drupal_set_message(t('Scanning for: [%search] ...', array('%search' => $search)));
  }
  else { //searchtype == 'replace'
    drupal_set_message(t('Replacing [%search] with [%replace] ...', array('%search' => $search, '%replace' => $replace)));
  }

  if ($mode) { // Case Sensitive
    $flag = NULL;
  }
  else { // Case Insensitive
    $flag = 'i'; //ci flag for use in php preg_search and preg_replace
  }

836
  
837 838 839 840 841
  $preceded_php = '';
  if (!empty($preceded)) {
    if (!$regex) {
      $preceded = addcslashes($preceded, SCANNER_REGEX_CHARS);
    }
842
    $preceded_php = '(?<=' . $preceded . ')';
843 844 845 846 847 848
  }
  $followed_php = '';
  if (!empty($followed)) {
    if (!$regex) {
      $followed = addcslashes($followed, SCANNER_REGEX_CHARS);
    }
849
    $followed_php = '(?=' . $followed . ')';
850 851 852 853
  }

  //Case 1:
  if ($wholeword && $regex) {
854
    $where = "[[:<:]]" . $search . "[[:>:]]";
855
    $search_db = $preceded . $search . $followed;
856
    $search_php = '\b' . $preceded_php . $search . $followed_php . '\b';
857 858
  }
  //Case 2:
859 860
  elseif ($wholeword && !$regex) {
    $where = "[[:<:]]" . $search . "[[:>:]]";
861
    $search_db = $preceded . addcslashes($search, SCANNER_REGEX_CHARS) . $followed;
862
    $search_php = '\b' . $preceded_php . addcslashes($search, SCANNER_REGEX_CHARS) . $followed_php . '\b';
863 864
  }
  //Case 3:
865 866
  elseif (!$wholeword && $regex) {
    $where = $search;
867 868 869 870 871
    $search_db = $preceded . $search . $followed;
    $search_php = $preceded_php . $search . $followed_php;
  }
  //Case 4:
  else { //!wholeword and !regex:
872
    $where = $search;
873 874 875 876 877 878 879 880 881 882 883 884 885
    $search_db = $preceded . addcslashes($search, SCANNER_REGEX_CHARS) . $followed;
    $search_php = $preceded_php . addcslashes($search, SCANNER_REGEX_CHARS) . $followed_php;
  }

  //if terms selected, then put together extra join and where clause:
  $join = '';
  if (is_array($terms) && count($terms)) {
    $terms_where = array();
    $terms_params = array();
    foreach ($terms as $term) {
      $terms_where[] = 'tn.tid = %d';
      $terms_params[] = $term;
    }
886 887
    $join = 'INNER JOIN {taxonomy_term_node} tn ON t.nid = tn.nid';
    $where .= ' AND (' . implode(' OR ', $terms_where) . ')';
888 889 890 891 892
  }

  $tables_map = _scanner_get_selected_tables_map();

  foreach ( $tables_map as $map ) {
893 894
    $table = $map['table'];
    $field = $map['field'];
895 896
    $type  = $map['type'];

897
    $query_params = array($field, $table, $type, $field, $search_db);
898 899 900 901
    if (!empty($join)) {
      $query_params = array_merge($query_params, $terms_params);
    }

902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
    // TODO Please convert this statement to the D7 database API syntax.
    
    $query = db_select($table, 't');
    if ($table == 'node_revision') {
        $nid = 'nid';
        $vid = 'vid';
    }
    else{
        $field = $field . '_value';
        $nid = 'entity_id';
        $vid = 'revision_id';
    }
    $query->join('node', 'n', 't.' . $vid . ' = n.vid'); //Must use vid and revision_id here.  Make sure it saves as new revision.
    if (is_array($terms) && count($terms)) {
        $db_or = db_or();
        $query->join('taxonomy_index', 'tx', 't.' . $nid . ' = tx.nid');
        foreach ($terms as $term) {
            $db_or->condition('tx.tid', $term);
        }
        $query->condition($db_or);
    }
    $query->addField('t', $field, 'content');
    $query->fields('n', array('nid', 'title'));
    $query->condition('n.type', $type, '=');
    if ($mode) {
        $query->condition('t.' . $field, $search_db, 'REGEXP BINARY');
    }
    else{
        $query->condition('t.' . $field, $search_db, 'REGEXP');    
    }
    if ($published) {
        $query->condition('n.status', '1', '=');
    }
    $result = $query->execute();
936

937 938 939
    $shutting_down = FALSE;
    
    foreach ($result as $row) {
940
      $content = $row->content;
941 942
      $matches = array();
      $text = '';
943
      
944 945
      // checking for possible timeout
      // if within 5 seconds of timeout - attempt to expand environment
946 947 948

      
      if (REQUEST_TIME >= ($start_time + $max_execution_time - 5)) {
949
        if (!$expanded) {
950 951 952 953 954
          if ($user->uid > 0) {
            $verbose = TRUE;
          }
          else {
            $verbose = FALSE;
955
          }
956 957 958
          if (_scanner_change_env('max_execution_time', '600', $verbose)) {
            drupal_set_message(t('Default max_execution_time too small and changed to 10 minutes.'), 'error');
            $max_execution_time = 600;
959
          }
960 961 962 963 964
          $expanded = TRUE;
        }
        // if expanded environment still running out of time - shutdown process
        else {
          $shutting_down = TRUE;
965 966
          variable_set('scanner_partially_processed_' . $user->uid, $processed);
          variable_set('scanner_partial_undo_' . $user->uid, $undo_data);
967 968
          if ($searchtype == 'search') {
            drupal_set_message(t('Did not have enough time to complete search.'), 'error');
969 970
          }
          else {
971
            drupal_set_message(t('Did not have enough time to complete. Please re-submit replace'), 'error');
972 973
          }
          break 2;
974 975
        }
      }
976 977 978 979 980 981 982 983 984 985 986

      /*
       * SEARCH
       */
      if ($searchtype == 'search') {
        //pull out the terms and highlight them for display in search results:
        $regexstr = "/(.{0,130}?)($search_php)(.{0,130})/$flag";
        $hits = preg_match_all($regexstr, $content, $matches, PREG_SET_ORDER);
        if ($hits > 0) {
          foreach ( $matches as $match ) {
            if ( $match[1] ) {
987
              $text .= '...' . htmlentities($match[1], ENT_COMPAT, 'UTF-8');
988
            }
989
            $text .= '<strong>' . htmlentities($match[2], ENT_COMPAT, 'UTF-8') . '</strong>';
990
            if ( $match[3] ) {
991
              $text .= htmlentities($match[3], ENT_COMPAT, 'UTF-8') . '...';
992 993 994 995
            }
          }
        }
        else {
996
          $text = "<div class='warning'>" . t("Can't display search result due to conflict between search term and internal preg_match_all function.") . '</div>';
997 998 999 1000 1001 1002 1003 1004 1005 1006
        }

        $results[] = array(
          'title' => $row->title,
          'type' => $type,
          'count' => $hits,
          'field' => $field,
          'nid' => $row->nid,
          'text' => $text,
        );
1007 1008
      }

1009 1010 1011 1012
      /*
       * REPLACE
       * + check to see if already processed
       */
1013
      elseif (!isset($processed[$field][$row->nid])) {
1014 1015 1016
        $hits = 0;
        $newcontent = preg_replace("/$search_php/$flag", $replace, $content, -1, $hits);

1017 1018
        $thenode = node_load($row->nid);
 
1019 1020 1021 1022 1023 1024 1025 1026
        //see if we're dealing with a CCK text field and therefore need to strip the
        // "_value" off the end:
        preg_match('/(.+)_value$/', $field, $matches);
        if (empty($matches[0])) { //if not CCK text field:
          $thenode->$field = $newcontent;
        }
        else {
          //Is this the best way to copy the new content back into the node's CCK field???
1027 1028 1029 1030 1031 1032
          //$tmpstr = ('$thenode->' . $matches[1] . '[$thenode->language][0]["value"] = $newcontent;');
          //eval($tmpstr);
          
          //This is a better way
          $thenode->{$matches[1]}[$thenode->language][0]["value"] = $newcontent;
          
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
        }

        // NOTE: a revision only created for the first change of the node.
        // subsequent changes of the same node do not generate additional revisions:
        if (!isset($undo_data[$thenode->nid]['new_vid'])) {
          $thenode->revision = TRUE;
          $thenode->log = t('@name replaced %search with %replace via Scanner Search and Replace module.', array('@name' => $user->name, '%search' => $search, '%replace' => $replace));
          $undo_data[$thenode->nid]['old_vid'] = $thenode->vid;
        }

1043
        /* TODO MAKE THIS WORK WITH SUMMARY, TEASERS DON'T EXIST 
1044 1045 1046
        if (variable_get('scanner_rebuild_teasers', 1)) {
          $thenode->teaser = node_teaser($thenode->body, $thenode->format);
        }
1047 1048
        */
        
1049 1050 1051 1052
        node_save($thenode);

        // array to log completed fields in case of shutdown
        $processed[$field][$row->nid] = TRUE;
1053

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
        // undo data construction
        $undo_data[$thenode->nid]['new_vid'] = $thenode->vid; //now set to updated vid after node_save()
        $results[] = array(
          'title' => $thenode->title,
          'type' => $thenode->type,
          'count' => $hits,
          'field' => $field,
          'nid' => $thenode->nid,
        );

Tao Starbow's avatar
Tao Starbow committed
1064
      }
1065

1066
    } //end foreach
1067
  } //end foreach
1068

1069
  // if completed
1070
  if (!$shutting_down) {
1071 1072
    variable_del('scanner_partially_processed_' . $user->uid);
    variable_del('scanner_partial_undo_' . $user->uid);
1073 1074 1075
  }

  if ($searchtype == 'search') {
1076
    return theme('scanner_results', array('results' => $results));
1077 1078 1079
  }
  else { //searchtype == 'replace'
    if (count($undo_data) && !$shutting_down) {
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
      // TODO Please review the conversion of this statement to the D7 database API syntax.
      $id = db_insert('scanner')
            ->fields(array(
                'undo_data' => serialize($undo_data),
                'undone' => 0,
                'searched' => $search,
                'replaced' => $replace,
                'count' => count($undo_data),
                'time' => REQUEST_TIME,
              ))
            ->execute();
Tao Starbow's avatar
Tao Starbow committed
1091
    }
1092

1093
    return theme('scanner_replace_results', array('results' => $results));
1094 1095 1096
  }
}

1097

Tao Starbow's avatar
Tao Starbow committed
1098 1099 1100 1101
// ***************************************************************************
// Settings ******************************************************************
// ***************************************************************************

1102 1103 1104 1105 1106
/**
 * Search and Replace Settings form.
 *
 * @return $form
 */
1107 1108 1109 1110 1111
function scanner_admin_form($node, &$form_state) {
  drupal_set_title(t('Scanner Settings'));
  
  $output= '';
  
1112
  $table_map = _scanner_get_selected_tables_map();
1113 1114 1115 1116 1117 1118
  if ($table_map) {
      $output = '<p>Fields that will be searched (in [nodetype: fieldname] order):</p><ul>' . $output . '</ul>';
      sort($table_map);
      foreach ($table_map as $item) {
        $output .= '<li><b>' . $item['type'] . ':</b> ' . $item['field'] . '</li>';
      }
1119
  }
1120 1121 1122 1123
  else{
      $output = '<p>There are currently no selected elements to be scanned</p>';
  }
  
1124 1125 1126 1127
  $form['selected'] = array(
    '#type' => 'fieldset',
    '#title' => t('Current Settings'),
    '#collapsible' => TRUE,
1128
    '#description' => filter_xss($output, $allowed_tags = array('b', 'ul', 'li', 'p')),
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
  );



  $form['settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Scanner Options'),
    '#collapsible' => TRUE,
  );

Tao Starbow's avatar
Tao Starbow committed
1139
  $form['settings']['scanner_mode'] = array(
1140 1141 1142
    '#type' => 'checkbox',
    '#title' => t('Default: Case Sensitive Search Mode'),
    '#default_value' => variable_get('scanner_mode', 0),
Tao Starbow's avatar
Tao Starbow committed
1143
  );
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161

  $form['settings']['scanner_wholeword'] = array(
    '#type' => 'checkbox',
    '#title' => t('Default: Match Whole Word'),
    '#default_value' => variable_get('scanner_wholeword', 0),
  );

  $form['settings']['scanner_regex'] = array(
    '#type' => 'checkbox',
    '#title' => t('Default: Regular Expression Search'),
    '#default_value' => variable_get('scanner_regex', 0),
  );

  $form['settings']['scanner_published'] = array(
    '#type' => 'checkbox',
    '#title' => t('Default: Search Published Nodes Only'),
    '#default_value' => variable_get('scanner_published', 1),
  );
1162
  /* TURN OFF TEASER (SUMMARY) REBUILD FOR NOW
1163 1164 1165 1166