Skip to content
gallery_install.inc 41.5 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 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 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 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 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 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 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 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 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 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
<?php
// $Id$

/**
 * gallery.module : gallery_install.inc
 * Configure embedded Gallery install (directory options, etc.)
 */

define(GALLERY_INSTALL_STEP_PHPMEMORY,  1);
define(GALLERY_INSTALL_STEP_LOCATIONS,  2);
define(GALLERY_INSTALL_STEP_PLUGINS,    3);
define(GALLERY_INSTALL_STEP_URLREWRITE, 4);
define(GALLERY_INSTALL_STEP_USERSYNC,   5);

/**
 * Function _gallery_install().
 */
function _gallery_install($form_values = NULL) {
  $form['#multistep'] = TRUE;
  $form['#redirect'] = FALSE;
  $form['#submit']['_gallery_install_submit'] = array();
  
  $install_status = array(
    'phpmemory' => array(
      'title' => 'PHP Memory Limit',
      'severity' => GALLERY_SEVERITY_ERROR,
    ),
    'locations' => array(
      'title' => 'Gallery2 locations',
      'severity' => GALLERY_SEVERITY_ERROR,
    ),
    'plugins' => array(
      'title' => 'Drupal Modules / Gallery2 Plugins',
      'severity' => GALLERY_SEVERITY_WARNING,
    ),
    'cleanurls' => array(
      'title' => 'Clean URL / URL Rewrite',
      'severity' => GALLERY_SEVERITY_WARNING,
    ),
    'usersync' => array(
      'title' => 'Initial User Synchronization',
      'severity' => GALLERY_SEVERITY_ERROR,
    ),
  );

  if (!isset($form_values)) {
    $form_values = array();
    $form_values['step'] = GALLERY_INSTALL_STEP_PHPMEMORY;
    $form_values['gallery_valid'] = FALSE;
    $form_values['initial_check'] = TRUE;
    if (variable_get('gallery_config_reset', FALSE)) {
      $form_values['initial_check'] = FALSE;
      variable_del('gallery_config_reset');
    }
  }
  else {
    // Work around a D5 design flaw
    // manage $form_values to allow the same form to be submitted more than once
    $form_values = unserialize(variable_get('gallery_wizard_data', array()));
    $form_values['initial_check'] = FALSE;
  }
  
  $form['install_status'] = array(
    '#type' => 'fieldset',
    '#title' => t('Install status'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
    '#description' => t('Correct configuration of the following items is essential for the embedded gallery to function properly.'),
  );
  
  // Step 1: Check PHP Memory
  if ($form_values['step'] >= GALLERY_INSTALL_STEP_PHPMEMORY) {
    _gallery_install_step_php_memory($form, $form_values, $install_status);
  }

  // Step 2 : Gallery2 Locations
  if ($form_values['step'] >= GALLERY_INSTALL_STEP_LOCATIONS) {
    _gallery_install_step_locations($form, $form_values, $install_status);
  }
  
  // Step 3: Drupal Modules and Gallery2 Plugins check
  if ($form_values['step'] >= GALLERY_INSTALL_STEP_PLUGINS) {
    _gallery_install_step_plugins($form, $form_values, $install_status);
  }

  // Step 4: Clean URL configuration
  if ($form_values['step'] >= GALLERY_INSTALL_STEP_URLREWRITE) {
    _gallery_install_step_urlrewrite($form, $form_values, $install_status);
  }
  
  // Step 5: User Synchronization
  if ($form_values['step'] >= GALLERY_INSTALL_STEP_USERSYNC) {
    _gallery_install_step_usersync($form, $form_values, $install_status);
  }
  
  $form['initial_check'] = array(
    '#type' => 'hidden',
    '#value' => $form_values['initial_check'],
  );
  $form['gallery_valid'] = array(
    '#type' => 'hidden',
    '#value' => $form_values['gallery_valid'],
  );
  $form['plugins_valid'] = array(
    '#type' => 'hidden',
    '#value' => $form_values['plugins_valid'],
  );
  $form['step'] = array(
    '#type' => 'hidden',
    '#value' => $form_values['step'],
  );
  
  $form['buttons']['reset'] = array('#type' => 'submit', '#value' => t('Reset & Restart'));

  // Set the global status variable 'gallery_valid'
  gallery_set_status(array(
    'gallery_valid' => array(
      'title' => t('Overall Status (Installation)'),
      'severity' => $form_values['gallery_valid'] ? GALLERY_SEVERITY_SUCCESS : GALLERY_SEVERITY_ERROR,
    ),
  ));
  
  // Create install status table
  $error = FALSE;
  $rows = array();
  foreach ($install_status as $key => $step_status) {
    // Find the combination of status and severity of the plugin
    $severity = ($step_status['status'] <= 0) ? $step_status['severity'] : GALLERY_SEVERITY_SUCCESS; 
    if (!$step_status['status']) {
      $error = TRUE;
    }   
    $row = array();
    $row[] = array('data' => $step_status['title'], 'align' => 'left', 'width' => '20%');
    $row[] = array('data' => theme('gallery_severity_message', $severity), 'align' => 'center');
    $row[] = array('data' => $step_status['info'], 'class' => 'description', 'id' => $key);
    $rows[] = $row;
  }
  if ($error && !$form_values['initial_check']) {
    $rows[] = array(array(
      'data' => t('Critical errors are present. Your Gallery is not available.'), 
      'colspan' => '3', 
      'align' => 'center', 
      'class' => 'message')
    );
  }
  $header = array('Step', 'Status', 'Description');
  $form['install_status']['status']['#value'] = theme('table', $header, $rows, array('class' => 'package'));
  
  return $form;
}

/**
 * Function _gallery_install_step_php_memory().
 * Step 1: Check PHP Memory
 */ 
function _gallery_install_step_php_memory(&$form, &$form_values, &$install_status) {
  $phpmemory_info = _gallery_php_mem_check();
  $desc = $phpmemory_info['info'];
  if (!$phpmemory_info['status']) {
    $desc .= ' '. t('Until this is fixed your Gallery2 cannot be installed.');
    $form_values['step'] = GALLERY_INSTALL_STEP_PHPMEMORY;
  }
  else {
    $form_values['step']++;
  }
  
  $form['phpmemory'] = array(
    '#type' => 'fieldset',
    '#title' => t('Step 1: PHP Memory Test') . ($phpmemory_info['status'] ? ' '. t('(OK)') : ''),
    '#description' => $desc,
    '#collapsible' => ($form_values['step'] > GALLERY_INSTALL_STEP_PHPMEMORY),
    '#collapsed' => $phpmemory_info['status'],
  );
  if (!$phpmemory_info['status']) {
    $form['phpmemory']['check'] = array('#type' => 'submit', '#value' => t('Check PHP memory again'));      
  }
  
  $install_status['phpmemory']['status'] = $phpmemory_info['status'];
  $install_status['phpmemory']['info'] = $phpmemory_info['info'];
}

/**
 * Function _gallery_install_step_locations().
 * Step 2: Gallery2 Locations
 */ 
function _gallery_install_step_locations(&$form, &$form_values, &$install_status) {
  if ($form_values['step'] > GALLERY_INSTALL_STEP_LOCATIONS || $form_values['initial_check']) {
    _gallery_install_locations($form, $form_values, $install_status);
  }
  // Check was not successful. Don't proceed with step 3
  if (!$form_values['gallery_valid']) {
    $form_values['step'] = GALLERY_INSTALL_STEP_LOCATIONS;
  }
  else {
    $form_values['step']++;
  }

  $autodetect_dir = variable_get('gallery_autodetect_dir', 1);
  $extra = $autodetect_dir ? t('- Auto Configuration') : t('- Manual Configuration');
  // If 'initial_check' = True then this is the first time the user has come through this
  // step (or the wizard has been restarted). Allow the field to be edited EVEN IF VALID.
  // If 'initial_check' = False then this step has been completed already, so make read-only.
  if (!$form_values['gallery_valid']) {
    $desc = $autodetect_dir ?
      t('Enter the \'Gallery2 URL or URI\' and click \'Test location settings\'
        to automatically configure the settings needed for embedding Gallery2 into Drupal. Note that
        the auto-config will not work for all host configurations. If you have tried it with a value 
        you know is correct and it did not work then just use the manual configuration instead.') :
      t('Enter the \'Gallery2 URL or URI\' and \'Gallery2 filesystem path\' and then click 
        \'Test location settings\'. This will check and configure the settings needed for embedding
        Gallery2 into Drupal.');
  }
  else {
    $desc = '';
  }
  
  $form['install'] = array(
    '#type' => 'fieldset',
    '#title' => t('Step 2: Gallery2 location settings') .' '. $extra . ($form_values['gallery_valid'] ? ' '. t('(OK)') : ''),
    '#description' => isset($form['install']['#description']) ? ($desc .'<p>'. $form['install']['#description'] .'</p>') : $desc,
    '#collapsible' => ($form_values['step'] > GALLERY_INSTALL_STEP_LOCATIONS),
    '#collapsed' => $form_values['gallery_valid'],
  ); 
  
  // Only provide these values when autoconfig has been set. Otherwise the user might think
  // that these had been automatically figured out even though manual config was done.
  if ($autodetect_dir) {
    $gallery_uri = isset($form_values['gallery_uri_auto']) ? 
      $form_values['gallery_uri_auto'] : ($form_values['gallery_valid'] ? 
      variable_get('gallery_uri', '/gallery2/') : '');

    $gallery_dir = isset($form_values['gallery_dir_auto']) ? 
      $form_values['gallery_dir_auto'] : ($form_values['gallery_valid'] ? 
      variable_get('gallery_dir', './gallery2/') : '');
      
    $embed_uri = isset($form_values['gallery_embed_uri_auto']) ? 
      $form_values['gallery_embed_uri_auto'] : ($form_values['gallery_valid'] ? 
      variable_get('gallery_embed_uri', '?q=gallery') : '');
    $form['install']['gallery_uri_auto'] = array(
      '#type' => 'textfield',
      '#title' => t('Gallery2 URL or URI'),
      '#default_value' => $gallery_uri,
      '#size' => 64,
      '#maxlength' => 128,
      '#description' => t('URL or URI of the G2 standalone location. This can be either the full
        URL to Gallery2 (e.g. http://www.example.com/gallery2) or the path from docroot to the
        Gallery2 directory (e.g. /gallery2). If using a URI the protocol/hostname are both
        optional.'),
      '#disabled' => $form_values['gallery_valid'],
    );

    if (!empty($gallery_dir)) {
      $form['install']['gallery_dir_auto_item'] = array(
        '#title' => t('Gallery2 filesystem path'),
        '#type' => 'item',
        '#value' => $gallery_dir,
      );
    }
    $form['install']['gallery_dir_auto'] = array(
      '#type' => 'value',
      '#value' => $gallery_dir,
    );
    
    if (!empty($gallery_dir)) {
      $form['install']['gallery_embed_uri_auto_item'] = array(
        '#title' => t('Embed URI'),
        '#type' => 'item',
        '#value' => $embed_uri,
      );
    }
    $form['install']['gallery_embed_uri_auto'] = array(
      '#type' => 'value',
      '#value' => $embed_uri,
    );
  }
  else {
    $gallery_uri = isset($form_values['gallery_uri_man']) ? 
      $form_values['gallery_uri_man'] : ($form_values['gallery_valid'] ? 
      variable_get('gallery_uri', '/gallery2/') : '');
      
    $gallery_dir = isset($form_values['gallery_dir_man']) ? 
      $form_values['gallery_dir_man'] : ($form_values['gallery_valid'] ? 
      variable_get('gallery_dir', './gallery2/') : '');
      
    $embed_uri = isset($form_values['gallery_embed_uri_man']) ? 
      $form_values['gallery_embed_uri_man'] : ($form_values['gallery_valid'] ? 
      variable_get('gallery_embed_uri', '?q=gallery') : '');
      
    $form['install']['gallery_uri_man'] = array(
      '#type' => 'textfield',
      '#title' => t('Gallery2 URL or URI'),
      '#default_value' => $gallery_uri,
      '#size' => 64,
      '#maxlength' => 128,
      '#description' => t('URL or URI of the G2 standalone location. This can be either the full
        URL to Gallery2 (e.g. http://www.example.com/gallery2) or the path from docroot to the
        Gallery2 directory (e.g. /gallery2). If using a URI the protocol/hostname are both
        optional.'),
      '#disabled' => $form_values['gallery_valid'],
    );
    
    $form['install']['gallery_dir_man'] = array(
      '#type' => 'textfield',
      '#title' => t('Gallery2 filesystem path'),
      '#default_value' => $gallery_dir,
      '#size' => 64,
      '#maxlength' => 128,
      '#description' => t('The filesystem path of your Gallery2 directory. This can be either an
        absolute path (e.g. /home/mysite/htdocs/gallery2) or relative to the root directory of your
        Drupal installation (e.g. ../gallery2).'),
      '#disabled' => $form_values['gallery_valid'],
    );
  
    $form['install']['gallery_embed_uri_man'] = array(
      '#type' => 'textfield',
      '#title' => t('Embed URI'),
      '#default_value' => $embed_uri,
      '#size' => 64,
      '#maxlength' => 128,
      '#description' => t('URI to access G2 via Drupal. Don\'t worry if you are using clean urls in Drupal and this still ends in \'index.php?q=gallery\'. This is needed to get the Gallery2 URL rewrite module to work correctly and will not be visible.'),
      '#disabled' => $form_values['gallery_valid'],
    );
  }
  
  if (!$form_values['gallery_valid']) {
    $form['install']['location_button'] = array(
      '#type' => 'submit',
      '#value' => t('Test location settings'),
    );
    if ($autodetect_dir) {
      $form['install']['manual_config_button'] = array(
        '#type' => 'submit',
        '#value' => t('Use Manual Configuration'),
      );
    }
    else {
      $form['install']['auto_config_button'] = array(
        '#type' => 'submit',
        '#value' => t('Use Auto Configuration'),
      );
    }
  }
}

/**
 * Function _gallery_install_step_plugins().
 * Step 3: Drupal Modules / Gallery2 Plugins
 */ 
function _gallery_install_step_plugins(&$form, &$form_values, &$install_status) {  
  $form['plugins'] = array(
    '#type' => 'fieldset',
    '#title' => t('Step 3: Drupal Modules / Gallery2 Plugins'),
    '#collapsible' => ($form_values['step'] > GALLERY_INSTALL_STEP_PLUGINS),
    '#collapsed' => FALSE,
  );
  
  $header = array('Name', 'Status', 'Description');
  $overall_plugin_severity = GALLERY_SEVERITY_UNKNOWN - 1;
  $overall_plugin_status = GALLERY_PLUGIN_ENABLED;
  // Wanted (required) G2 plugins 
  $wanted_g2_plugins = gallery_wanted_plugin_info();
  $rows = array();
  foreach ($wanted_g2_plugins as $key => $module) {
    // Find the combination of status and severity of the plugin
    $severity = ($module['status'] != GALLERY_PLUGIN_ENABLED) ? $module['severity'] : GALLERY_SEVERITY_SUCCESS;
    $row = array();
    $row[] = array('data' => $module['title'], 'align' => 'left', 'width' => '15%');
    $row[] = array('data' => theme('gallery_severity_status_message', $severity, $module['status']), 'align' => 'center');
    $row[] = array('data' => $module['info'], 'class' => 'description', 'id' => $key);
    $rows[] = $row;
    if ($module['status'] != GALLERY_PLUGIN_ENABLED && $severity > $overall_plugin_severity) {
      $overall_plugin_severity = $severity;
      $overall_plugin_status = $module['status'];
    }
  }
  $form['plugins']['wanted_g2_plugins'] = array(
    '#type' => 'fieldset',
    '#title' => t('Recommended Gallery2 plugins'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
    '#value' => theme('table', $header, $rows, array('class' => 'package')),
    '#description' => t('These Gallery2 plugins support much of the functionality that the Drupal Gallery module provides.
                         None of them are strictly required, but you will almost certainly want to activate at least some
                         of them (particularly the Image Block plugin).'),
  );  
     
  // Unwanted (interfering) G2 plugins  
  $unwanted_g2_plugins = gallery_unwanted_plugin_info();
  $rows = array();
  foreach ($unwanted_g2_plugins as $key => $module) {
    // Find the combination of status and severity of the plugin
    $severity = ($module['status'] == GALLERY_PLUGIN_ENABLED) ? 
      $module['severity'] : GALLERY_SEVERITY_SUCCESS;    
    $row = array();
    $row[] = array('data' => $module['title'], 'align' => 'left', 'width' => '15%');
    $row[] = array('data' => theme('gallery_severity_status_message', $severity, $module['status'], TRUE, TRUE), 'align' => 'center');
    $row[] = array('data' => $module['info'], 'class' => 'description', 'id' => $key);
    $rows[] = $row;
    if ($module['status'] == GALLERY_PLUGIN_ENABLED && $severity > $overall_plugin_severity) {
      $overall_plugin_severity = $severity;
      $overall_plugin_status = $module['status'];
    }
  }
  $form['plugins']['unwanted_g2_plugins'] = array(
    '#type' => 'fieldset',
    '#title' =>  t('Gallery2 plugins which should not be installed'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
    '#value' => theme('table', $header, $rows, array('class' => 'package')),
    '#description' => t('These Gallery2 plugins should not be used when Gallery2 is
                         embedded into Drupal as they may cause problems.'),
  );  
    
  // Wanted (optional) Drupal modules
  $wanted_modules = gallery_wanted_module_info();
  $rows = array();
  foreach ($wanted_modules as $key => $module) {
    // Find the combination of status and severity of the plugin
    $severity = (!$module['status']) ? $module['severity'] : GALLERY_SEVERITY_SUCCESS;    
    $row = array();
    $row[] = array('data' => $module['title'], 'align' => 'left', 'width' => '15%');
    $row[] = array('data' => theme('gallery_severity_status_message', $severity, $module['status']), 'align' => 'center');
    $row[] = array('data' => $module['info'], 'class' => 'description', 'id' => $key);
    $rows[] = $row;
    if ($module['status'] != GALLERY_PLUGIN_ENABLED && $severity > $overall_plugin_severity) {
      $overall_plugin_severity = $severity;
      $overall_plugin_status = $module['status'];
    }
  }
  $form['plugins']['wanted_modules'] = array(
    '#type' => 'fieldset',
    '#title' =>  t('Optional Drupal modules'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
    '#value' => theme('table', $header, $rows, array('class' => 'package')),
    '#description' => t('These Drupal modules can optionally be used to enhance the functionality of the Gallery module.'),
  );

  // Check if no issue was found.
  if ($overall_plugin_severity < GALLERY_SEVERITY_UNKNOWN) {
    $overall_plugin_severity = GALLERY_SEVERITY_SUCCESS;
  }

  $install_status['plugins']['status'] = $overall_plugin_status;
  $install_status['plugins']['severity'] = $overall_plugin_severity;
  
  if ($overall_plugin_status <= 0) {
    // There is a problem with at least one module/plugin
    $form_values['plugins_valid'] = FALSE;   
    $form['plugins']['#title'] .= ' ('. strip_tags(theme('gallery_severity_message', $overall_plugin_severity)) .')';       
    $install_status['plugins']['info'] = t('You may have some loss in functionality in your embedded Gallery2 (see below
                                            for details). You should check the details and if the functionality is not
                                            important for your site you can just ignore this.');
    $form['plugins']['#collapsed'] = !$form_values['initial_check'];
    if ($form_values['initial_check']) {
      $form_values['step']++;
    }
  }
  else {
    $form_values['step']++;
    $form_values['plugins_valid'] = TRUE;
    $form['plugins']['#collapsible'] = TRUE;
    $form['plugins']['#collapsed'] = TRUE;
    $form['plugins']['#title'] .= ' '. t('(OK)');       
    $install_status['plugins']['info'] = t('The status of all Drupal modules and Gallery2 plugins
                                            is optimal for your embedded Gallery2.');
  }
}

/**
 * Function _gallery_install_step_urlrewrite().
 * Step 4: Clean URL configuration
 */
function _gallery_install_step_urlrewrite(&$form, &$form_values, &$install_status) {
  $form['rewrite'] = array('#type' => 'fieldset');
  
  $clean_urls_status = variable_get('clean_url', 0);
  $rewrite_status = gallery_single_plugin_status('rewrite');

  if ($clean_urls_status) {
    if ($rewrite_status == GALLERY_PLUGIN_ENABLED) {
      _gallery_install_urlrewrite($public_path, $htaccess_path, TRUE);
      $public_path = isset($form_values['htaccess_public_path']) ? $form_values['htaccess_public_path'] : $public_path;
      $htaccess_path = isset($form_values['htaccess_filesystem_path']) ? $form_values['htaccess_filesystem_path'] : $htaccess_path;
      // Check for writable .htaccess file
      if (file_exists($htaccess_path .'.htaccess')) {
        if (is_writable($htaccess_path .'.htaccess')) {
          $form_values['rewrite_valid'] = ($form_values['initial_check'] || $form_values['step'] > GALLERY_INSTALL_STEP_URLREWRITE);
          $result = t('There is a writable .htaccess file in your defined Drupal directory (@dir).',
                        array('@dir' => $htaccess_path));
          // Check syntax of the 'Show Item' rule (must start with 'gallery/')
          list ($ret, $rules) = GalleryCoreApi::getPluginParameter('module', 'rewrite', 'activeRules');
          if (!$ret) {
            $rules = unserialize($rules);
            if (isset($rules['rewrite'][0]['pattern']) && substr($rules['rewrite'][0]['pattern'], 0, 7) != 'gallery') {
              $result .= ' <strong>'. t('Your \'Show Item\' rule should start with \'gallery/\'.
                                         Make sure to change the URL Rewrite rule(s) accordingly.') .'</strong>';
            }
          }
        }
        else {
          $form_values['rewrite_valid'] = FALSE;
          $result = t('The .htaccess file in your defined Drupal directory (@dir) is not writable. Please CHMOD it to 644
                       (or 666 if 644 does not work).', array('@dir' => $htaccess_path));
        }
      }
      else {
        $form_values['rewrite_valid'] = FALSE;
        $result = t('There is no .htaccess file in your defined Drupal directory (@dir) or the directory does not exist.',
                      array('@dir' => $htaccess_path));
      }
    }
    else {
      $form_values['rewrite_valid'] = FALSE;
      $result = t('Clean URLs are enabled in Drupal, but the Gallery2 URL Rewrite plugin is unavailable.');
    }
  }
  else {
    $form_values['rewrite_valid'] = TRUE;
    $result = t('Clean URLs are disabled in Drupal and the URL Rewrite plugin will not be configured.');
    $form['rewrite']['#description'] = t('Clean URLs are disabled in Drupal and the URL Rewrite plugin will not be configured.
                                          If you want to use the URL Rewrite plugin please enable clean URLs in Drupal and
                                          install and activate the plugin in Gallery2.');
  }
  
  // User selected to skip the URLRewrite step
  if (variable_get('gallery_rewrite_disable', 0)) {
    $form_values['rewrite_valid'] = TRUE;
    $clean_urls_status = FALSE;
    $result = $form['rewrite']['#description'] = t('URL Rewrite has been disabled manually.');
    $form['rewrite']['#description'] .= ' '. t('\'Reset & Restart\' your configuration to change these settings.');
  }
  
  if ($form_values['rewrite_valid']) {
    $form_values['step']++;
  }
  
  $form['rewrite']['#title'] = t('Step 4: Clean URLs / URL Rewrite settings') . ($form_values['rewrite_valid'] ? ' '. t('(OK)') : '');
  $form['rewrite']['#collapsible'] = ($form_values['step'] > GALLERY_INSTALL_STEP_URLREWRITE);
  $form['rewrite']['#collapsed'] = $form_values['rewrite_valid'];

  if ($clean_urls_status) {
    if ($rewrite_status < GALLERY_PLUGIN_ENABLED) {
      $form['rewrite']['#description'] = t('Clean URLs are enabled in Drupal, but the Gallery2 URL Rewrite plugin is unavailable
                                            (!status).', array('!status' => theme('gallery_plugin_status_message', $rewrite_status)));
      if (!$form_values['initial_check'] && !$form_values['rewrite_valid']) {
        $form_values['step'] = GALLERY_INSTALL_STEP_URLREWRITE;
        $form['rewrite']['check'] = array('#type' => 'submit', '#value' => t('Check URL Rewrite status again'));
      }
    }
    else {
      // CleanURL and URLRewrite are both enabled
      $form['rewrite']['#description'] = t('Clean URLs are !clean_url_status in Drupal and the Gallery2 URL Rewrite plugin is
                                            !rewrite_status. It is possible to automatically configure the URL Rewrite plugin.
                                            The configuration assumes that the rules should be placed in your Drupal .htaccess
                                            file (it will add them to the beginning) which works in most applications. If you
                                            need a special configuration, enter the desired values manually.',
        array(
          '!clean_url_status' => theme('gallery_module_status_message', $clean_urls_status),
          '!rewrite_status' => theme('gallery_plugin_status_message', $rewrite_status)
        )
      );
      $form['rewrite']['#description'] .= $form_values['rewrite_valid'] ? '' : ('<p>'. $result .'</p>');
      
      $form['rewrite']['htaccess_public_path'] = array(
        '#type' => 'textfield',
        '#title' => t('Public path to your .htaccess file'),
        '#size' => 64,
        '#maxlength' => 255,
        '#default_value' => $public_path,
        '#description' => t('This is the location of your Drupal .htaccess file relative to your webserver document root.'),
        '#disabled' => $form_values['rewrite_valid'],
      );
      $form['rewrite']['htaccess_filesystem_path'] = array(
        '#type' => 'textfield',
        '#title' => t('Filesystem path to your .htaccess file'),
        '#size' => 100,
        '#maxlength' => 255,
        '#default_value' => $htaccess_path,
        '#description' => t('This is the absolute directory path of your Drupal .htaccess file.'),
        '#disabled' => $form_values['rewrite_valid'],
      );
      if (!$form_values['initial_check'] && !$form_values['rewrite_valid']) {
        $form['rewrite']['config'] = array('#type' => 'submit', '#value' => t('Configure URL Rewrite plugin'));
      }
    }
    
    if (!$form_values['initial_check'] && !$form_values['rewrite_valid']) {
      $form['rewrite']['skip'] = array('#type' => 'submit', '#value' => t('Skip URL Rewrite Config'));
    }
  }

  $install_status['cleanurls']['status'] = $form_values['rewrite_valid'];
  $install_status['cleanurls']['info'] = $result;
}

/**
 * Function _gallery_install_step_usersync().
 * Step 5: User Synchronization
 */ 
function _gallery_install_step_usersync(&$form, &$form_values, &$install_status) {
  $form_values['gallery_valid'] = variable_get('gallery_valid', 0);
  
  if ($form_values['gallery_valid']) {
    $form_values['step']++;
  }
  
  $form['usersync'] = array(
    '#type' => 'fieldset',
    '#title' => t('Step 5: Initial User Synchronization') . ($form_values['gallery_valid'] ? ' '. t('(OK)') : ''),
    '#collapsible' => ($form_values['step'] > GALLERY_INSTALL_STEP_USERSYNC),
    '#collapsed' => ($form_values['gallery_valid']),
  );
  
  $install_status['usersync']['status'] = $form_values['gallery_valid'];
  if ($form_values['gallery_valid']) {
    $install_status['usersync']['info'] = $form['usersync']['#description'] = t('Your initial user synchronization has been
        completed already.<br />If you want to resync all your users or you want to import users from an existing Gallery2
        setup, you can always use the <a href= "@gallery-usersync">Advanced Sync</a> options in the Gallery user administration.',
        array('@gallery-usersync' => url('admin/user/gallery/advanced')));
  }
  else {
    $install_status['usersync']['info'] = $form['usersync']['#description'] = t('User synchronization is essential for the
        embedded Gallery to work correctly. Drupal users/groups are usually synced with their Gallery counterparts when a
        user/group is modified in Drupal. Missing user mappings will cause errors in your embedded Gallery.');
    $form['usersync']['#description'] .= '<br /><br />'. t('It is recommended that you sync your users now. However there
        can be reasons to skip this step, e.g. if you have a working Gallery with many users and a fresh Drupal installation.
        Note that the current user and the Drupal superuser (uid=1) will always be sync.');
    
    $form['usersync']['sync'] = array('#type' => 'submit', '#value' => t('Sync users/groups'));
    $form['usersync']['skip'] = array('#type' => 'submit', '#value' => t('Skip sync'));
  }
}

/**
 * Function _gallery_install_submit().
 */
function _gallery_install_submit($form_id, $form_values) {
  switch ($form_values['op']) {
    case t('Sync users/groups'):
    case t('Skip sync'):
      $autodetect = variable_get('gallery_autodetect_dir', 1);
      if ($autodetect) {
        variable_set('gallery_uri', $form_values['gallery_uri_auto']);
        variable_set('gallery_dir', $form_values['gallery_dir_auto']);
        variable_set('gallery_embed_uri', $form_values['gallery_embed_uri_auto']);
      }
      else {
        variable_set('gallery_uri', $form_values['gallery_uri_man']);
        variable_set('gallery_dir', $form_values['gallery_dir_man']);
        variable_set('gallery_embed_uri', $form_values['gallery_embed_uri_man']);
      }
      variable_del('gallery_wizard_data');
      
      // This is the last step: gallery_valid will be TRUE even
      // if the admin decides to skip the user/group sync step
      $form_values['gallery_valid'] = TRUE;
      
      // Set gallery_valid variable and rebuild the menu so that
      // the user sync callback is available for the next step
      variable_set('gallery_valid', $form_values['gallery_valid']);
      // Clear cache and rebuild menu
      cache_clear_all('gallery', 'cache', TRUE);
      menu_rebuild();
      
      // Always sync (at least) the current user to avoid
      // errors (unknown user) during GalleryEmbed::init()
      require_once(drupal_get_path('module', 'gallery') .'/gallery_user.inc');
      global $user;
      gallery_user_modify($user, 'update', TRUE, $form_values);
      // Make sure the Drupal superuser (uid=1) always gets admin right
      if ($user->uid != 1) {
        gallery_user_modify(user_load(array('uid' => 1)), 'update', FALSE, $form_values);
      }
      // Trigger bulk user/group sync
      if ($form_values['op'] != t('Skip sync')) {
        require_once(drupal_get_path('module', 'gallery') .'/gallery_user_admin.inc');
        _gallery_user_advanced_start(array('sync'), 'admin/settings/gallery/install');
      }
      drupal_get_messages();
      drupal_goto('admin/settings/gallery/install');
      break;
    case t('Use Manual Configuration'):
      variable_set('gallery_autodetect_dir', 0);
      $form_values['step'] = GALLERY_INSTALL_STEP_LOCATIONS;
      break;
    case t('Use Auto Configuration'):
      variable_set('gallery_autodetect_dir', 1);
      $form_values['step'] = GALLERY_INSTALL_STEP_LOCATIONS;
      break;
    case t('Configure URL Rewrite plugin'):
      if (!_gallery_install_urlrewrite($form_values['htaccess_public_path'], $form_values['htaccess_filesystem_path'])) {
        $form_values['step'] = GALLERY_INSTALL_STEP_URLREWRITE;
      }
      break;
    case t('Skip URL Rewrite Config'):
      variable_set('gallery_rewrite_disable', 1);
      break;
    case t('Reset & Restart'):
      // Reset configuration
      variable_del('gallery_autodetect_dir');
      variable_del('gallery_uri');
      variable_del('gallery_dir');
      variable_del('gallery_embed_uri');
      variable_del('gallery_valid');
      variable_del('gallery_rewrite_disable');
      variable_del('gallery_wizard_data');
      menu_rebuild();
      variable_set('gallery_config_reset', TRUE);
      drupal_get_messages();
      drupal_goto('admin/settings/gallery/install');
      break;
  }
  
  variable_set('gallery_wizard_data', serialize($form_values));
}

/**
 * Function _gallery_install_locations().
 */
function _gallery_install_locations(&$form, &$form_values, &$install_status) {
  include_once(drupal_get_path('module', 'gallery') .'/G2EmbedDiscoveryUtilities.class');

  $autodetect = variable_get('gallery_autodetect_dir', 1);
  if ($form_values['initial_check']) {
    $orig_values['g2_uri'] = variable_get('gallery_uri', '/gallery2/');
    $orig_values['g2_embed_path'] = variable_get('gallery_dir', './gallery2/');
    $orig_values['embed_uri'] = variable_get('gallery_embed_uri', '?q=gallery');
  }
  else {
    if ($autodetect) {
      $orig_values['g2_uri'] = $form_values['gallery_uri_auto'];
    }
    else {
      $orig_values['g2_uri'] = $form_values['gallery_uri_man'];
      $orig_values['g2_embed_path'] = $form_values['gallery_dir_man'];
      $orig_values['embed_uri'] = $form_values['gallery_embed_uri_man'];
    }
  }

  list($gallery_valid, $detect_values, $result) = _gallery_install_locations_check($orig_values, $autodetect);
  if (!$gallery_valid) {
    $form['install']['#description'] = gallery_format_status($result, t('Errors in your current Gallery2 location settings:'));
  }

  if ($autodetect) {
    $form_values['gallery_uri_auto'] = $detect_values['g2_uri'];
    $form_values['gallery_dir_auto'] = $detect_values['g2_embed_path'];
    $form_values['gallery_embed_uri_auto'] = $detect_values['embed_uri'];
  }
  else {
    $form_values['gallery_uri_man'] = $detect_values['g2_uri'];
    $form_values['gallery_dir_man'] = $detect_values['g2_embed_path'];
    $form_values['gallery_embed_uri_man'] = $detect_values['embed_uri'];
  }
  $form_values['gallery_valid'] = $gallery_valid;

  $install_status['locations']['status'] = $gallery_valid;
  $install_status['locations']['info'] = $gallery_valid ?
    t('The Gallery2 location settings appear to be correct.') :
    t('There is a problem with the Gallery2 location settings. Please check below and retest.
       Remember that the auto-config will not work for all hosts.');
}

/**
 * Function _gallery_install_locations_check().
 */
function _gallery_install_locations_check($orig, $autodetect) {
  // Set up the result status array. The rest gets filled in later.
  $result = array(
    'g2_uri' => array(
          'title' => t('URI of Gallery2'),
          'severity' => GALLERY_SEVERITY_ERROR,
    ),
    'g2_embed_path' => array(
          'title' => t('Location of Gallery2'),
          'severity' => GALLERY_SEVERITY_ERROR,
    ),
    'init' => array(
          'title' => t('Gallery Init'),
          'severity' => GALLERY_SEVERITY_ERROR,
    ),
  );
  
  $vars = array();
  $vars['gallery_valid'] = TRUE;
  
  // Strip the end /gallery if present and replace with index.php?q=gallery to avoid any 
  // url rewrite issues. See http://gallery.menalto.com/node/46181
  // Note the use of index.php in all cases. Not needed for Apache, but for IIS
  
  $embed_uri = $orig['embed_uri'];
  if ($autodetect || empty($embed_uri)) {
    $embed_uri = url('gallery', NULL, NULL, FALSE);
    // i18n overrides the link to gallery to include a ?q=en or something
    if (module_exists('i18n')) {
      i18n_get_lang_prefix($embed_uri, TRUE);
    }
    if (substr($embed_uri, -8) == '/gallery') {
      $embed_uri = substr($embed_uri, 0, -7) .'index.php?q=gallery';
    }
  }
  
  // Normalise the Embed Application URI
  $embed_uri = G2EmbedDiscoveryUtilities::normalizeEmbedUri($embed_uri); 
  $vars['embed_uri'] = $embed_uri;     
     
  // Normalise the G2 URI 
  $g2_uri = G2EmbedDiscoveryUtilities::normalizeG2Uri($orig['g2_uri']);
  $vars['g2_uri'] = $g2_uri;

    // Find the Gallery Directory and Embed URI
  if ($autodetect) {
    // Auto-Detect the G2 embed path 
    list($success, $embed_php_path, $error_string) = 
      G2EmbedDiscoveryUtilities::getG2EmbedPathByG2Uri($g2_uri); 
    if ($success) {
      // G2 Embed Path is found OK
      $vars['g2_embed_path'] = rtrim($embed_php_path, 'embed.php'); 
    }
    else {
      // Something is wrong with the G2 URI given as the G2 embed path is not found
      // Try getG2EmbedPathByG2UriEmbedUriAndLocation instead
      $drupal_path = realpath(".") .'/';  
      list($success, $embed_php_path, $error_string) =
        G2EmbedDiscoveryUtilities::getG2EmbedPathByG2UriEmbedUriAndLocation($g2_uri, $embed_uri, $drupal_path);
      if ($success) {
        // G2 Embed Path is found OK
        $vars['g2_embed_path'] = rtrim($embed_php_path, 'embed.php'); 
      }
      else {
        $result['g2_uri']['status'] = FALSE;
        $result['g2_uri']['info'] = $error_string;
        $vars['g2_embed_path'] = '';
        $vars['gallery_valid'] = FALSE;
      } 
    }
    // Check for config.php in the embed_path (not existing => invalid path)
    //  e.g. this is the path to the G2 codebase, but we have a multisite configuration
    if (!empty($vars['g2_embed_path'])) {
      list($ok, $error_string) = G2EmbedDiscoveryUtilities::isFileReadable($vars['g2_embed_path'] .'config.php');
      if (!$ok) {
        $result['g2_embed_path']['status'] = FALSE;
        $result['g2_embed_path']['info'] = $error_string;
        $vars['g2_embed_path'] = '';
        $vars['gallery_valid'] = FALSE;
      }
    }
  } 
  else {
    // Do not autodetect the variables, but check the manually entered ones.
    $embed_php_path = $orig['g2_embed_path'];
    $embed_php_path .= (substr($embed_php_path, -1) != '/') ? '/' : '';
    // Check path can be read, adding embed.php if needed
    list($ok, $error_string) = G2EmbedDiscoveryUtilities::isFileReadable($embed_php_path .'embed.php');
    $vars['g2_embed_path'] = $embed_php_path;
    if (!$ok) {
      $result['g2_embed_path']['status'] = FALSE;
      $result['g2_embed_path']['info'] = $error_string;
      $vars['gallery_valid'] = FALSE;
    }
    else {
      // Check for config.php in the embed_path (not existing => invalid path)
      //  e.g. this is the path to the G2 codebase, but we have a multisite configuration
      list($ok, $error_string) = G2EmbedDiscoveryUtilities::isFileReadable($embed_php_path .'config.php');
      if (!$ok) {
        $result['g2_embed_path']['status'] = FALSE;
        $result['g2_embed_path']['info'] = $error_string;
        $vars['gallery_valid'] = FALSE;
      }
    }
  }
  
  // If the filepaths seem correct then check Gallery2 works and has the correct module configs
  if ($vars['gallery_valid']) {
    // Gallery install is thought valid, so init it.
    $vars['gallery_dir'] = $vars['g2_embed_path'];
    if (!_gallery_init(TRUE, $vars, FALSE)) {
      // Gallery install was supposed to be valid, but it still failed. Something is wrong.
      $result['init']['status'] = FALSE;
      $result['init']['info'] = t('Everything seemed OK, but the Gallery could still not be initialised.
                                   Perhaps a manually entered value is incorrect.');
      $vars['gallery_valid'] = FALSE;
    }
    else {
      // Is Gallery2 installed inside the Drupal root directory?
      _gallery_install_in_drupal_folder($vars['g2_embed_path']);
      // Update version info
      gallery_version();       
      GalleryEmbed::done();
    }
  }

  // Only return items where status has been set
  foreach ($result as $key => $value) {
    if (!isset($value['status'])) {
      unset($result[$key]);
    }
  }
  
  return array($vars['gallery_valid'], $vars, $result);
}

/**
 * Function _gallery_install_in_drupal_folder().
 */
function _gallery_install_in_drupal_folder($embed_path) {
  global $base_url;
  static $warn = TRUE;
  
  // Dont proceed if G2 was not initialized
  if (!isset($GLOBALS['gallery'])) {
    return;
  }
  
  if (!empty($embed_path)) {
    // Reset 'gallery_outside' state
    variable_del('gallery_outside');
    // Get location of Drupal, Gallery2, etc.
    $docroot = strtolower(str_replace('/', '\\' , $_SERVER['DOCUMENT_ROOT']));
    $base_path = strtolower(str_replace('/', '\\' , base_path()));
    $g2_base = strtolower($GLOBALS['gallery']->getConfig('galleryBaseUrl'));
    if ((strpos(strtolower($embed_path), $base_path) === FALSE && strpos(strtolower($embed_path), $docroot) !== FALSE)
        || (!empty($g2_base) && strpos($g2_base, $base_url) === FALSE) || strpos(strtolower($embed_path), '../') !== FALSE) {
      // G2 is installed outside the Drupal root directory
      variable_set('gallery_outside', TRUE);
      if ($warn) {
        // Avoid duplicate warning
        $warn = FALSE;
        drupal_set_message(t('Your location settings are valid, but your Gallery2 is installed outside the Drupal
                              root directory. It is highly advisable to move G2 into the Drupal folder or to create
                              a symbolic link in the Drupal directory pointing to your G2 installation (see
                              instructions on <a href="@codex">codex.gallery2.org</a>).',
                              array('@codex' => url('http://codex.gallery2.org/Integration:Drupal:Installation'))), 'error');
      }
    }
  }
}

/**
 * Function _gallery_install_urlrewrite().
 */
function _gallery_install_urlrewrite(&$public_path, &$htaccess_path, $load_config = FALSE) {
  list($ret, $rewrite_api) = GalleryCoreApi::newFactoryInstance('RewriteApi');
  if ($ret || !isset($rewrite_api)) {
    gallery_error(t('Error trying to create URL Rewrite plugin instance.'), $ret);
    return FALSE;
  }
  
  list($ret, $params) = $rewrite_api->fetchEmbedConfig();
  if ($ret) {
    gallery_error(t('Error trying to fetch Embedded URL Rewrite configuration.'), $ret);
    return FALSE;
  }
  
  // Load the configuration from G2 (or derive from Drupal path)
  if ($load_config) {
    if (empty($params['embeddedHtaccess'])) {
      $http = 'http'. (isset($_SERVER['HTTPS']) ? (($_SERVER['HTTPS'] == 'on') ? 's' : '') : '');
      $public_path = str_replace($http .'://'. $_SERVER['HTTP_HOST'], '', base_path());
      $htaccess_path = realpath(".") .'/';
    }
    else {
      $public_path = $params['embeddedLocation'];
      $htaccess_path = $params['embeddedHtaccess'];
    }
  }
  
  // Check for trailing slash
  $public_path .= (substr($public_path, -1) != '/') ? '/' : '';
  $htaccess_path .= (substr($htaccess_path, -1) != '/') ? '/' : '';
  
  if (!$load_config) {
    if (!file_exists($htaccess_path .'.htaccess')) {
      // File .htaccess does not exist
      if (is_writable($htaccess_path .'.htaccess')) {
        // Directory exists and is writable => try to create .htaccess
        $f = fopen($htaccess_path .'.htaccess', 'w');
        fclose($f);
      }
      else {
        return FALSE;
      }
    }
    // Save the G2 rewrite values
    $params['embeddedLocation'] = $public_path;
    $params['embeddedHtaccess'] = $htaccess_path;
    list($ret, $code, $errstr) = $rewrite_api->saveEmbedConfig($params);
    if ($ret) {
      gallery_error(t('Error trying to save Embedded URL Rewrite configuration.'), $ret);
      return FALSE;
    }
    if ($code) {
      $errstr =  $code .' - '. $errstr;
      drupal_set_message(t('The Gallery2 URL Rewrite plugin returned the following error:') .'<br /><pre>'. $errstr .'</pre>', 'error');
      return FALSE;
    }
  }
  
  return TRUE;