Skip to content
wysiwyg_editor.module 42.8 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$
// A collaborative project by Matt Westgate <drupal at asitis dot org>,
// Richard Bennett <richard.b@ at ritechnologies dot com> and Jeff Robbins <robbins at jjeff dot com>

/**
 * @file
 * Integrate the TinyMCE editor (http://tinymce.moxiecode.com/) into Drupal.
 */

/**
 * Implementation of hook_menu().
 */
function tinymce_menu($may_cache) {
  $items = array();
  if ($may_cache) {
    $items[] = array(
      'path' => 'admin/settings/tinymce',
      'title' => t('TinyMCE'),
      'callback' => 'tinymce_admin',
      'description' => t('Configure the rich editor.'),
      'access' => user_access('administer tinymce'),
    );
  }
  return $items;
}

/**
 * Implementation of hook_help().
 */
function tinymce_help($section) {
  switch ($section) {
    case 'admin/settings/tinymce#pages':
      return "node/*\nuser/*\ncomment/*";
    case 'admin/settings/tinymce':
    case 'admin/help#tinymce' :
      return t('<p style="font-size:x-small">$Revision$ $Date$</p>' .
               '<p>TinyMCE adds what-you-see-is-what-you-get (WYSIWYG) html editing to textareas. This editor can be enabled/disabled without reloading the page by clicking a link below each textarea.</p>
                <p>Profiles can be defined based on user roles. A TinyMCE profile can define which pages receive this TinyMCE capability, what buttons or themes are enabled for the editor, how the editor is displayed, and a few other editor functions.</p>
                <p>Lastly, only users with the <code>access tinymce</code> <a href="!url">permission</a> will be able to use TinyMCE.</p>', array('!url' => url('admin/user/access'))
              );
  }
}

/**
 * Implementation of hook_perm().
 */
function tinymce_perm() {
  $array = array('administer tinymce', 'access tinymce');
  $tinymce_mod_path = drupal_get_path('module', 'tinymce');

  if (is_dir($tinymce_mod_path . '/tinymce/jscripts/tiny_mce/plugins/imagemanager/')) {
    $array[] = 'access tinymce imagemanager';
  }
  if (is_dir($tinymce_mod_path . '/tinymce/jscripts/tiny_mce/plugins/filemanager/')) {
    $array[] = 'access tinymce filemanager';
  }

  return $array;
}

/**
 * Implementation of hook_elements().
 */
function tinymce_elements() {
  $type = array();

  if (user_access('access tinymce')) {
    // Let TinyMCE potentially process each textarea.
    $type['textarea'] = array('#process' => array('tinymce_process_textarea' => array()), '#wysiwyg' => TRUE, '#wysiwyg_style' => 'advanced');
  }

  return $type;
}

/**
 * Load tinymce files and send configuration data.
 */
function tinymce_load() {
  global $user;
  static $loaded = FALSE;

  // We only load the TinyMCE js file once per page request.
  if (!$loaded) {
    $profile = tinymce_profile_load(tinymce_current_profile());

    $enable  = t('enable rich-text');
    $disable = t('disable rich-text');

    $status = tinymce_user_get_status($user, $profile);

    $no_wysiwyg = t('Your current web browser does not support WYSIWYG editing.');

    $tinymce_mod_path = drupal_get_path('module', 'tinymce');

    if (is_dir($tinymce_mod_path . '/tinymce/jscripts/tiny_mce/plugins/imagemanager/') && user_access('access tinymce imagemanager') ) {
      // if tinymce imagemanager is installed
      drupal_add_js($tinymce_mod_path . '/tinymce/jscripts/tiny_mce/plugins/imagemanager/jscripts/mcimagemanager.js');
    }

    if (is_dir($tinymce_mod_path . '/tinymce/jscripts/tiny_mce/plugins/filemanager/') && user_access('access tinymce filemanager') ) {
      // if tinymce filemanager is installed
      drupal_add_js($tinymce_mod_path . '/tinymce/jscripts/tiny_mce/plugins/filemanager/jscripts/mcfilemanager.js');
    }

    // TinyMCE Compressor >= 1.0.9
    if (file_exists($tinymce_mod_path . '/tinymce/jscripts/tiny_mce/tiny_mce_gzip.js')) {
      drupal_add_js($tinymce_mod_path . '/tinymce/jscripts/tiny_mce/tiny_mce_gzip.js');
    }
    // TinyMCE Compressor < 1.0.9
    elseif (file_exists($tinymce_mod_path . '/tinymce/jscripts/tiny_mce/tiny_mce_gzip.php')) {
      drupal_add_js($tinymce_mod_path . '/tinymce/jscripts/tiny_mce/tiny_mce_gzip.php');
    }
    else {
      // For some crazy reason IE will only load this JS file if the absolute reference is given to it.
      drupal_add_js($tinymce_mod_path . '/tinymce/jscripts/tiny_mce/tiny_mce.js');
    }
    // Add tinyme.js to the footer to ensure it's executed after the Drupal.settings array has been rendered and populated.
    drupal_add_js($tinymce_mod_path .'/tinymce.js', 'footer');
    drupal_add_js(array('tinymce' => array('configs' => array(), 'showToggle' => ($profile->settings['show_toggle'] == 'true'), 'disable' => $disable, 'enable' => $enable, 'noWysiwyg' => $no_wysiwyg, 'linkText' => $link_text, 'status' => $status)), 'setting');
    // We have to do this because of some unfocused CSS in certain themes. See http://drupal.org/node/18879 for details
    drupal_set_html_head('<style type="text/css" media="all">.mceEditor img { display: inline; }</style>');
    $loaded = TRUE;
  }
}

/**
 * Process a textarea for tinyMCE.
 */
function tinymce_process_textarea($element) {
  tinymce_filter_elements($element);

  if ($element['#wysiwyg']) {
    $profile = tinymce_profile_load(tinymce_current_profile());
    if (_tinymce_page_match($profile)) {

      // Default to advanced theme if the requested one is not installed.
      $themes = _tinymce_get_themes();
      if (!isset($themes[$element['#wysiwyg_style']])) {
        $element['#wysiwyg_style'] = 'advanced';
      }

      tinymce_load();
      _tinymce_set_config($element['#wysiwyg_style']);
      if (!isset($element['#attributes'])) {
        $element['#attributes'] = array();
      }
      if (!isset($element['#attributes']['class'])) {
        $element['#attributes']['class'] = 'tinymce tinymce-'. $element['#wysiwyg_style'];
      }
      else {
        $element['#attributes']['class'] .= ' tinymce tinymce-'. $element['#wysiwyg_style'];
      }
      // Set resizable to false to avoid drupal.js resizable function from
      // taking control of the textarea
      $element['#resizable'] = FALSE;
    }
  }

  return $element;
}

/**
 * Register a theme.
 */
function _tinymce_set_config($theme) {
  static $themes = array();
  // Only sent a theme's configuration data once.
  if (!in_array($theme, $themes)) {
    $profile = tinymce_profile_load(tinymce_current_profile());
    $config = tinymce_config($profile, $theme);
    // Convert the config values into the form expected by tinyMCE.
    foreach ($config as $key => $value) {
      switch($value) {
        case 'true':
          $config[$key] = TRUE;
          break;
        case 'false':
          $config[$key] = FALSE;
          break;
      }
      if (is_array($value)) {
        $config[$key] = implode(',', $config[$key]);
      }
    }
    drupal_add_js('Drupal.settings.tinymce.configs["'. $theme .'"] = '. drupal_to_js($config) .';', 'inline');
    $themes[] = $theme;
  }
}

/**
 * Implementation of hook_user().
 */
function tinymce_user($type, &$edit, &$user, $category = NULL) {
  if ($type == 'form' && $category == 'account' && user_access('access tinymce')) {
    $profile = tinymce_user_get_profile($user);

    // because the settings are saved as strings we need to test for the string 'true'
    if ($profile->settings['user_choose'] == 'true') {
      $form['tinymce'] = array(
        '#type' => 'fieldset',
        '#title' => t('TinyMCE rich-text settings'),
        '#weight' => 10,
        '#collapsible' => TRUE,
        '#collapsed' => TRUE
      );

      $form['tinymce']['tinymce_status'] = array(
        '#type' => 'select',
        '#title' => t('Default state'),
        '#default_value' => isset($user->tinymce_status) ? $user->tinymce_status : (isset($profile->settings['default']) ? $profile->settings['default'] : 'false'),
        '#options' => array('false' => t('disabled'), 'true' => t('enabled')),
        '#description' => t('Should rich-text editing be enabled or disabled by default in textarea fields?')
      );

      return array('tinymce' => $form);
    }
  }
  if ($type == 'validate') {
    return array('tinymce_status' => $edit['tinymce_status']);
  }
}

/**
 * Filter for core text fields.
 *
 * @param $element
 *   The textarea element to be filtered.
 */
function tinymce_filter_elements(&$element) {
  switch ($element['#name']) {
    // Disable tinymce for these textareas.
    case 'log': // book and page log
    case 'img_assist_pages':
    case 'caption': // signature
    case 'pages':
    case 'access_pages': //TinyMCE profile settings.
    case 'user_mail_welcome_body': // user config settings
    case 'user_mail_approval_body': // user config settings
    case 'user_mail_pass_body': // user config settings
    case 'synonyms': // taxonomy terms
    case 'description': // taxonomy terms
      $element['#wysiwyg'] = FALSE;
      break;

    // Force the 'simple' theme for some of the smaller textareas.
    case 'signature':
    case 'site_mission':
    case 'site_footer':
    case 'site_offline_message':
    case 'page_help':
    case 'user_registration_help':
    case 'user_picture_guidelines':
      $element['#wysiwyg_style'] = 'simple';
      break;
  }
}

/**
 * Grab the themes available to TinyMCE.
 *
 * TinyMCE themes control the functionality and buttons that are available to a
 * user. Themes are only looked for within the default TinyMCE theme directory.
 *
 * @return
 *   An array of theme names.
 */
function _tinymce_get_themes() {
  static $themes = array();

  if (!$themes) {
    $theme_loc = drupal_get_path('module', 'tinymce') .'/tinymce/jscripts/tiny_mce/themes/';
    if (is_dir($theme_loc) && $dh = opendir($theme_loc)) {
      while (($file = readdir($dh)) !== false) {
        if (!in_array($file, array('.', '..', 'CVS')) && is_dir($theme_loc . $file)) {
          $themes[$file] = $file;
        }
      }
      closedir($dh);
      asort($themes);
    }
  }

  return $themes;
}

/**
 * Return plugin metadata from the plugin registry.
 *
 * We also scrape each plugin's *.js file for the human friendly name and help
 * text URL of each plugin.
 *
 * @return
 *   An array for each plugin.
 */
function _tinymce_get_buttons($skip_metadata = TRUE) {
  include_once drupal_get_path('module', 'tinymce'). '/wysiwyg_editor.plugins.inc';
  $plugins = _tinymce_plugins();

  if ($skip_metadata == FALSE && is_array($plugins)) {
    foreach ($plugins as $name => $plugin) {
      $file = drupal_get_path('module', 'tinymce'). '/tinymce/jscripts/tiny_mce/plugins/'. $name .'/editor_plugin_src.js';
      // Grab the plugin metadata by scanning the *.js file.
      if (file_exists($file)) {
        $lines = file($file);
        $has_longname = FALSE;
        $has_infourl = FALSE;
        foreach ($lines as $line) {
          if ($has_longname && $has_infourl) break;
          if (strstr($line, 'longname')) {
            $start = strpos($line, "'") + 1;
            $end = strrpos($line, "'") - $start;
            $metadata[$name]['longname'] = substr($line, $start, $end);
            $has_longname = TRUE;
          }
          elseif (strstr($line, 'infourl')) {
            $start = strpos($line, "'") + 1;
            $end = strrpos($line, "'") - $start;
            $metadata[$name]['infourl'] = substr($line, $start, $end);
            $has_infourl = TRUE;
          }
        }
      }

      // Find out the buttons a plugin has.
      foreach ($plugin as $k => $v) {
        if (strstr($k, 'theme_advanced_buttons')) {
          $metadata[$name]['buttons'] = array_merge((array) $metadata[$name]['buttons'], $plugin[$k]);
        }
      }
    }
    return $metadata;
  }

  return $plugins;
}
/********************************************************************
 * Module Functions :: Public
 ********************************************************************/

/**
 * Controller for tinymce administrative settings.
 */
function tinymce_admin($arg = NULL) {

  $edit = $_POST;
  $op = isset($_POST['op']) ? $_POST['op'] : NULL;

  $op = $arg && !$op ? $arg : $op;

  switch ($op) {
    case 'add':
      $breadcrumb[] = array('path' => 'admin', 'title' => t('administer'));
      $breadcrumb[] = array('path' => 'admin/settings/tinymce', 'title' => t('tinymce'));
      $breadcrumb[] = array('path' => 'admin/settings/tinymce/add', 'title' => t('Add new TinyMCE profile'));
      menu_set_location($breadcrumb);
      $output = tinymce_profile_form($edit);
      break;

    case 'edit':
      drupal_set_title(t('Edit tinymce profile'));
      $output = tinymce_profile_form(tinymce_profile_load(urldecode(arg(4))));
      break;

    case 'delete':
      tinymce_profile_delete(urldecode(arg(4)));
      drupal_set_message(t('Deleted profile'));
      drupal_goto('admin/settings/tinymce');
      break;

    case t('Create profile');
    case t('Update profile');
      if (tinymce_profile_validate($edit)) {
        tinymce_profile_save($edit);
        $edit['old_name'] ? drupal_set_message(t('Your TinyMCE profile has been updated.')) : drupal_set_message(t('Your TinyMCE profile has been created.'));
        drupal_goto('admin/settings/tinymce');
      }
      else {
        $output = tinymce_profile_form($edit);
      }
      break;

    default:
      drupal_set_title(t('TinyMCE settings'));
      //Check if TinyMCE is installed.
      $tinymce_loc = drupal_get_path('module', 'tinymce') .'/tinymce/';
      if (!is_dir($tinymce_loc)) {
        drupal_set_message(t('Could not find the TinyMCE engine installed at <strong>!tinymce-directory</strong>. Please <a href="http://tinymce.moxiecode.com/">download TinyMCE</a>, uncompress it and copy the folder into !tinymce-path.', array('!tinymce-path' => drupal_get_path('module', 'tinymce'), '!tinymce-directory' => $tinymce_loc)), 'error');
      }
      $output = tinymce_profile_overview();
  }

  return $output;
}

/**
 * Return an array of initial tinymce config options from the current role.
 */
function tinymce_config($profile, $theme) {
  global $user;

  // Drupal theme path.
  $themepath = path_to_theme() . '/';
  $host = base_path();

  $settings = $profile->settings;

  // Build a default list of TinyMCE settings.

  $init = array();
  $init['mode']               = 'none';
  $init['theme']              = $theme;
  $init['relative_urls']      = 'false';
  $init['document_base_url']  = "$host";
  $init['language']           = $settings['language'] ? $settings['language'] : 'en';
  $init['safari_warning']     = $settings['safari_message'] ?  $settings['safari_message'] : 'false';
  $init['entity_encoding']    = 'raw';
  $init['verify_html']        = $settings['verify_html'] ? $settings['verify_html'] : 'false';
  $init['preformatted']       = $settings['preformatted'] ? $settings['preformatted'] : 'false';
  $init['convert_fonts_to_spans'] = $settings['convert_fonts_to_spans'] ? $settings['convert_fonts_to_spans'] : 'false';
  $init['remove_linebreaks'] = $settings['remove_linebreaks'] ? $settings['remove_linebreaks'] : 'true';
  $init['apply_source_formatting'] = $settings['apply_source_formatting'] ? $settings['apply_source_formatting'] : 'true';
  $init['theme_advanced_resize_horizontal'] = 'false';
  $init['theme_advanced_resizing_use_cookie'] = 'false';


  $tinymce_mod_path = drupal_get_path('module', 'tinymce');
  if (is_dir($tinymce_mod_path . '/tinymce/jscripts/tiny_mce/plugins/imagemanager/') && user_access('access tinymce imagemanager')) {
    // we probably need more security than this
    $init['file_browser_callback'] = "mcImageManager.filebrowserCallBack";
  }
  if (is_dir($tinymce_mod_path . '/tinymce/jscripts/tiny_mce/plugins/filemanager/') && user_access('access tinymce filemanager')) {
    // we probably need more security than this
    $init['file_browser_callback'] = "mcImageManager.filebrowserCallBack";
  }

  if ($settings['css_classes']) $init['theme_advanced_styles'] = $settings['css_classes'];

  if ($settings['css_setting'] == 'theme') {
    $css = $themepath .'style.css';
    if (file_exists($css)) {
      $init['content_css'] = $host . $css;
    }
  }
  else if ($settings['css_setting'] == 'self') {
    $init['content_css'] = str_replace(array('%h', '%t'), array($host, $themepath), $settings['css_path']);
  }

  // Add theme-specific settings.
  switch ($theme) {
    case 'advanced':

      $init['theme_advanced_resize_horizontal'] = 'false';
      $init['theme_advanced_resizing_use_cookie'] = 'false';
      $init['plugins'] = array();
      $init['theme_advanced_toolbar_location']  = $settings['toolbar_loc'] ? $settings['toolbar_loc'] : 'bottom';
      $init['theme_advanced_toolbar_align']     = $settings['toolbar_align'] ? $settings['toolbar_align'] : 'left';
      $init['theme_advanced_path_location']     = $settings['path_loc'] ? $settings['path_loc'] : 'bottom';
      $init['theme_advanced_resizing']          = $settings['resizing'] ? $settings['resizing'] : 'true';
      $init['theme_advanced_blockformats']      = $settings['block_formats'] ? $settings['block_formats'] : 'p,address,pre,h1,h2,h3,h4,h5,h6';

      if (is_array($settings['buttons'])) {
        // This gives us the $plugins variable.
        $plugins = _tinymce_get_buttons();

        // Find the enabled buttons and the mce row they belong on. Also map the
        // plugin metadata for each button.
        $plugin_tracker = array();
        foreach ($plugins as $rname => $rplugin) { // Plugin name
          foreach ($rplugin as $mce_key => $mce_value) { // TinyMCE key
            foreach ($mce_value as $k => $v) { // Buttons
              if (isset($settings['buttons'][$rname .'-'. $v])) {
                // Font isn't a true plugin, rather it's buttons made available by the advanced theme
                if (!in_array($rname, $plugin_tracker) && $rname != 'font') $plugin_tracker[] = $rname;
                $init[$mce_key][] = $v;
              }
            }
          }
          // Some advanced plugins only have an $rname and no buttons
          if (isset($settings['buttons'][$rname])) {
            if (!in_array($rname, $plugin_tracker)) $plugin_tracker[] = $rname;
          }
        }

        // Add the rest of the TinyMCE config options to the $init array for each button.
        if (is_array($plugin_tracker)) {
          foreach ($plugin_tracker as $pname) {
            if ($pname != 'default') $init['plugins'][] = $pname;
            foreach ($plugins[$pname] as $mce_key => $mce_value) {
              // Don't overwrite buttons or extended_valid_elements
              if ($mce_key == 'extended_valid_elements') {
                // $mce_value is an array for extended_valid_elements so just grab the first element in the array (never more than one)
                $init[$mce_key][] = $mce_value[0];
              }
              else if (!strstr($mce_key, 'theme_advanced_buttons')) {
                $init[$mce_key] = $mce_value;
              }
            }
          }
        }

        // Cleanup
        foreach ($init as $mce_key => $mce_value) {
          if (is_array($mce_value)) $mce_value = array_unique($mce_value);
          $init[$mce_key] = $mce_value;
        }

        // Shuffle buttons around so that row 1 always has the most buttons,
        // followed by row 2, etc. Note: These rows need to be set to NULL otherwise
        // TinyMCE loads its own buttons inherited from the theme.
        if (!isset($init['theme_advanced_buttons1'])) $init['theme_advanced_buttons1'] = array();
        if (!isset($init['theme_advanced_buttons2'])) $init['theme_advanced_buttons2'] = array();
        if (!isset($init['theme_advanced_buttons3'])) $init['theme_advanced_buttons3'] = array();

        $min_btns = 5; // Minimum number of buttons per row.
        $num1 = count($init['theme_advanced_buttons1']);
        $num2 = count($init['theme_advanced_buttons2']);
        $num3 = count($init['theme_advanced_buttons3']);

        if ($num3 < $min_btns) {
          $init['theme_advanced_buttons2'] = array_merge($init['theme_advanced_buttons2'], $init['theme_advanced_buttons3']);
          $init['theme_advanced_buttons3'] = array();
          $num2 = count($init['theme_advanced_buttons2']);
        }
        if ($num2 < $min_btns) {
          $init['theme_advanced_buttons1'] = array_merge($init['theme_advanced_buttons1'], $init['theme_advanced_buttons2']);
          // Squish the rows together, since row 2 is empty
          $init['theme_advanced_buttons2'] = $init['theme_advanced_buttons3'];
          $init['theme_advanced_buttons3'] = array();
          $num1 = count($init['theme_advanced_buttons1']);
        }
        if ($num1 < $min_btns) {
          $init['theme_advanced_buttons1'] = array_merge($init['theme_advanced_buttons1'], $init['theme_advanced_buttons2']);
          // Squish the rows together, since row 2 is empty
          $init['theme_advanced_buttons2'] = $init['theme_advanced_buttons3'];
          $init['theme_advanced_buttons3'] = array();
        }

      }

      break;
  }
  return $init;
}

/**
 * Remove a profile from the database.
 */
function tinymce_profile_delete($name) {
  db_query("DELETE FROM {tinymce_settings} WHERE name = '%s'", $name);
  db_query("DELETE FROM {tinymce_role} WHERE name = '%s'", $name);
}

/**
 * Return an HTML form for profile configuration.
 */
function tinymce_profile_form_build($edit) {
  $edit = (object) $edit;

  // Only display the roles that currently don't have a tinymce profile. One
  // profile per role.
  $orig_roles = user_roles(FALSE, 'access tinymce');
  $roles = $orig_roles;
  if (arg(3) == 'add') {
    $result = db_query('SELECT DISTINCT(rid) FROM {tinymce_role}');
    while ($data = db_fetch_object($result)) {
      if (!in_array($data->rid, array_keys((array) $edit->rids)) && !form_get_errors()) {
        unset($roles[$data->rid]);
      }
    }
    if (!$orig_roles) {
      drupal_set_message(t('You must <a href="!access-control-url">assign</a> at least one role with the \'access tinymce\' permission before creating a profile.', array('!access-control-url' => url('admin/user/access'))), 'error');
    }
    else if (!$roles) {
      drupal_set_message(t('You will not be allowed to create a new profile since all user roles have already been assigned profiles. Either remove an existing tinymce profile from at least one role or assign another role the \'access tinymce\' permission.'), 'error');
    }
    else if (count($orig_roles) != count($roles)) {
      drupal_set_message(t('Not all user roles are shown since they already have tinymce profiles. You must first unassign profiles in order to add them to a new one.'));
    }
    $btn = t('Create profile');
  }
  else {
    $form['old_name'] = array('#type' => 'hidden', '#value' => $edit->name);
    $btn = t('Update profile');
  }

  $form['basic'] = array(
    '#type' => 'fieldset',
    '#title' => t('Basic setup'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE
  );

  $form['basic']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Profile name'),
    '#default_value' => isset($edit->name) ? $edit->name : NULL,
    '#size' => 40,
    '#maxlength' => 128,
    '#description' => t('Enter a name for this profile. This name is only visible within the tinymce administration page.'),
    '#required' => TRUE
  );

  $form['basic']['rids'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Roles allowed to use this profile'),
    '#default_value' => isset($edit->rids) ? array_keys((array)$edit->rids) : NULL,
    '#options' => $roles,
    '#description' =>  t('Check at least one role. Only roles with \'access tinymce\' permission will be shown here.'),
    '#required' => TRUE
  );

  $form['basic']['default'] = array(
    '#type' => 'select',
    '#title' => t('Default state'),
    '#default_value' => isset($edit->settings['default']) ? $edit->settings['default'] : 'false',
    '#options' => array('false' => t('disabled'), 'true' => t('enabled')),
    '#description' => t('Default editor state for users in this profile. Users will be able to override this state if the next option is enabled.'),
  );

  $form['basic']['user_choose'] = array(
    '#type' => 'select',
    '#title' => t('Allow users to choose default'),
    '#default_value' => isset($edit->settings['user_choose']) ? $edit->settings['user_choose'] : 'false',
    '#options' => array('false' => t('false'), 'true' => t('true')),
    '#description' => t('If allowed, users will be able to choose their own TinyMCE default state by visiting their profile page.'),
  );

  $form['basic']['show_toggle'] = array(
    '#type' => 'select',
    '#title' => t('Show disable/enable rich text editor toggle'),
    '#default_value' => isset($edit->settings['show_toggle']) ? $edit->settings['show_toggle'] : 'true',
    '#options' => array('false' => t('false'), 'true' => t('true')),
    '#description' => t('Whether or not to show the disable/enable rich text editor toggle below the textarea. If false, editor defaults to the global default or user default (see above).'),
  );

  // This line upgrades previous versions of TinyMCE for user who previously selected a theme other than advanced.
  if (isset($edit->settings['theme']) && $edit->settings['theme'] != 'advanced')
    $edit->settings['theme'] = 'advanced';

  $form['basic']['theme'] = array(
    '#type' => 'hidden',
    '#value' => isset($edit->settings['theme']) ? $edit->settings['theme'] : 'advanced'
  );

  $form['basic']['language'] = array(
    '#type' => 'select',
    '#title' => t('Language'),
    '#default_value' => isset($edit->settings['language']) ? $edit->settings['language'] : 'en',
    '#options' => drupal_map_assoc(array('ar', 'ca', 'cs', 'cy', 'da', 'de', 'el', 'en', 'es', 'fa', 'fi', 'fr', 'fr_ca', 'he', 'hu', 'is', 'it', 'ja', 'ko', 'nb', 'nl', 'nn', 'pl', 'pt', 'pt_br', 'ru', 'ru_KOI8-R', 'ru_UTF-8', 'si', 'sk', 'sv', 'th', 'zh_cn', 'zh_tw', 'zh_tw_utf8')),
    '#description' => t('The language for the TinyMCE interface. Language codes based on the <a href="http://www.loc.gov/standards/iso639-2/englangn.html">ISO-639-2</a> format.')
  );

  $form['basic']['safari_message'] = array(
    '#type' => 'select',
    '#title' => t('Safari browser warning'),
    '#default_value' => isset($edit->settings['safari_message']) ? $edit->settings['safari_message'] : 'false',
    '#options' => array('false' => t('false'), 'true' => t('true')),
    '#description' => t('TinyMCE support for the Safari web browser is experimental and a warning message is displayed when that browser is detected. You can disable this message here.')
  );

  $form['visibility'] = array(
    '#type' => 'fieldset',
    '#title' => t('Visibility'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE
  );

  $access = user_access('use PHP for block visibility');

  // If the visibility is set to PHP mode but the user doesn't have this block permission, don't allow them to edit nor see this PHP code
  if (isset($edit->settings['access']) && $edit->settings['access'] == 2 && !$access) {
    $form['visibility'] = array();
    $form['visibility']['access'] = array(
      '#type' => 'value',
      '#value' => 2
    );
    $form['visibility']['access_pages'] = array(
      '#type' => 'value',
      '#value' => (isset($edit->settings['access_pages']) ? $edit->settings['access_pages'] : NULL),
      '#wysiwyg' => FALSE,
    );
  }
  else {
    $options = array(t('Show on every page except the listed pages.'), t('Show on only the listed pages.'));
    $description = t("Enter one page per line as Drupal paths. The '*' character is a wildcard. Example paths are '!blog' for the blog page and !blog-wildcard for every personal blog. !front is the front page.", array('!blog' => theme('placeholder', 'blog'), '!blog-wildcard' =>  theme('placeholder', 'blog/*'), '!front' => theme('placeholder', '<front>')));

    if ($access) {
      $options[] = t('Show if the following PHP code returns <code>TRUE</code> (PHP-mode, experts only).');
      $description .= t('If the PHP-mode is chosen, enter PHP code between !php. Note that executing incorrect PHP-code can break your Drupal site.', array('!php' => theme('placeholder', '<?php ?>')));
    }
    $form['visibility']['access'] = array(
      '#type' => 'radios',
      '#title' => t('Show tinymce on specific pages'),
      '#default_value' => isset($edit->settings['access']) ? $edit->settings['access'] : 1,
      '#options' => $options
    );
    $form['visibility']['access_pages'] = array(
      '#type' => 'textarea',
      '#title' => t('Pages'),
      '#default_value' => isset($edit->settings['access_pages']) ? $edit->settings['access_pages'] : tinymce_help('admin/settings/tinymce#pages'),
      '#description' => $description
    );
  }

  $form['buttons'] = array(
    '#type' => 'fieldset',
    '#title' => t('Buttons and plugins'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#tree' => TRUE,
    '#theme' => 'tinymce_admin_button_table'
  );

  $metadata = _tinymce_get_buttons(FALSE);
  // Generate the button list.
  foreach ($metadata as $name => $meta) {
    if (isset($meta['buttons']) && is_array($meta['buttons'])) {
      foreach ($meta['buttons'] as $button) {
        if ($name != 'default') {
          $img_src = drupal_get_path('module', 'tinymce') ."/tinymce/jscripts/tiny_mce/plugins/$name/images/$name.gif";

          //correct for plugins that have more than one button
          if (!file_exists($img_src)) {
            $img_src = drupal_get_path('module', 'tinymce') ."/tinymce/jscripts/tiny_mce/plugins/$name/images/$button.gif";
          }
        }
        else {
          $img_src = drupal_get_path('module', 'tinymce') ."/tinymce/jscripts/tiny_mce/themes/advanced/images/$button.gif";
        }

        $b = file_exists($img_src) ? '<img src="'. base_path() . $img_src .'" title="'. $button .'" style="border: 1px solid grey; vertical-align: middle;" />' : $button;

        if ($name == 'default') {
          $title = $b;
        }
        else {
          $title = isset($metadata[$name]['longname']) ? $metadata[$name]['longname'] : $name;
          if (isset($metadata[$name]['infourl'])) {
            $title = '<a href="'. $metadata[$name]['infourl'] .'" target="_blank">'. $title .'</a>';
          }
          $title = $b .' &#8211; '. $title;
        }
        $form_value = isset($edit->settings['buttons'][$name .'-'. $button]) ? $edit->settings['buttons'][$name .'-'. $button] : NULL;
        $form['buttons'][$name .'-'. $button] = array('#type' => 'checkbox', '#title' => $title, '#default_value' => $form_value);
      }
    }
    else {
      $title = $metadata[$name]['longname'] ? $metadata[$name]['longname'] : $name;
      if ($metadata[$name]['infourl']) {
        $title = '<a href="'. $metadata[$name]['infourl'] .'" target="_blank">'. $title .'</a>';
      }
      $form_value = isset($edit->settings['buttons'][$name]) ? $edit->settings['buttons'][$name] : NULL;
      $form['buttons'][$name] = array('#type' => 'checkbox', '#title' => $title, '#default_value' => $form_value);
    }
  }

  $form['appearance'] = array(
    '#type' => 'fieldset',
    '#title' => t('Editor appearance'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE
  );

  $form['appearance']['toolbar_loc'] = array(
    '#type' => 'select',
    '#title' => t('Toolbar location'),
    '#default_value' => isset($edit->settings['toolbar_loc']) ? $edit->settings['toolbar_loc'] : NULL,
    '#options' => array('bottom' => t('bottom'), 'top' => t('top')),
    '#description' => t('Show toolbar at the top or bottom of the editor area?')
  );

  $form['appearance']['toolbar_align'] = array(
    '#type' => 'select',
    '#title' => t('Toolbar alignment'),
    '#default_value' => isset($edit->settings['toolbar_align']) ? $edit->settings['toolbar_align'] : NULL,
    '#options' => array('center' => t('center'), 'left' => t('left'), 'right' => t('right')),
    '#description' => t('Align tool icons left, center, or right within the toolbar.')
  );

  $form['appearance']['path_loc'] = array(
    '#type' => 'select',
    '#title' => t('Path location'),
    '#default_value' => isset($edit->settings['path_loc']) ? $edit->settings['path_loc'] : 'bottom',
    '#options' => array('none' => t('none'), 'top' => t('top'), 'bottom' => t('bottom')),
    '#description' => t('Path to html elements (i.e. "body>table>tr>td"). Show at top, bottom, or not at all.')
  );

  $form['appearance']['resizing'] = array(
    '#type' => 'select',
    '#title' => t('Enable resizing button'),
    '#default_value' => isset($edit->settings['resizing']) ? $edit->settings['resizing'] : 'true',
    '#options' => array('false' => t('false'), 'true' => t('true')),
    '#description' => t(' This option gives you the ability to enable/disable the resizing button. If enabled the <strong>Path location toolbar</strong> must be set to "top" or "bottom" in order to display the resize icon.')
  );

  $form['appearance']['block_formats'] = array(
    '#type' => 'textfield',
    '#title' => t('Block formats'),
    '#default_value' => isset($edit->settings['block_formats']) ? $edit->settings['block_formats'] : 'p,address,pre,h1,h2,h3,h4,h5,h6',
    '#size' => 40,
    '#maxlength' => 250,
    '#description' => t('Comma separated list of HTML block formats. You can only remove elements, not add.')
  );

  $form['output'] = array(
    '#type' => 'fieldset',
    '#title' => t('Cleanup and output'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE
  );

  $form['output']['verify_html'] = array(
    '#type' => 'select',
    '#title' => t('Verify HTML'),
    '#default_value' => isset($edit->settings['verify_html']) ? $edit->settings['verify_html'] : NULL,
    '#options' => array('false' => t('false'), 'true' => t('true')),
    '#description' => t('Should the HTML contents be verified or not? Verifying will strip &lt;head&gt tags, so choose false if you will be editing full page HTML.')
  );

  $form['output']['preformatted'] = array(
    '#type' => 'select',
    '#title' => t('Preformatted'),
    '#default_value' => isset($edit->settings['preformatted']) ? $edit->settings['preformatted'] : NULL,
    '#options' => array('false' => t('false'), 'true' => t('true')),
    '#description' => t('If this option is set to true, the editor will insert TAB characters on tab and preserve other whitespace characters just like a PRE HTML element does.')
  );

  $form['output']['convert_fonts_to_spans'] = array(
    '#type' => 'select',
    '#title' => t('Convert &lt;font&gt; tags to styles'),
    '#default_value' => isset($edit->settings['convert_fonts_to_spans']) ? $edit->settings['convert_fonts_to_spans'] : NULL,
    '#options' => array('true' => t('true'), 'false' => t('false')),
    '#description' => t('If you set this option to true, font size, font family, font color and font background color will be replaced by inline styles.')
  );

  $form['output']['remove_linebreaks'] = array(
     '#type' => 'select',
     '#title' => t('Remove linebreaks'),
     '#default_value' => isset($edit->settings['remove_linebreaks']) ? $edit->settings['remove_linebreaks'] : NULL,
     '#options' => array('true' => 'true', 'false' => 'false'),
     '#description' => t('Set this option to false to prevent TinyMCE from removing linebreaks from existing nodes.  True avoids conflicts with some filters.')
  );

  $form['output']['apply_source_formatting'] = array(
     '#type' => 'select',
     '#title' => t('Apply source formatting'),
     '#default_value' => isset($edit->settings['apply_source_formatting']) ? $edit->settings['apply_source_formatting'] : NULL,
     '#options' => array('true' => 'true', 'false' => 'false'),
     '#description' => t('This option makes TinyMCE apply source formatting.  Set this to true for a cleaner HTML source.  Choose false to avoid conflicts with some filters.')
  );

  $form['css'] = array(
    '#type' => 'fieldset',
    '#title' => t('CSS'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE
  );

  $form['css']['css_setting'] = array(
    '#type' => 'select',
    '#title' => t('Editor CSS'),
    '#default_value' => isset($edit->settings['css_setting']) ? $edit->settings['css_setting'] : 'theme',
    '#options' => array('theme' => t('use theme css'), 'self' => t('define css'), 'none' => t('tinyMCE default')),
    '#description' => t('Defines the CSS to be used in the editor area.<br />use theme css - load style.css from current site theme.<br/>define css - enter path for css file below.<br />tinyMCE default - uses default CSS from editor.')
  );

  $form['css']['css_path'] = array(
    '#type' => 'textfield',
    '#title' => t('CSS path'),
    '#default_value' => isset($edit->settings['css_path']) ? $edit->settings['css_path'] : NULL,
    '#size' => 40,
    '#maxlength' => 255,
    '#description' => t('Enter path to CSS file (<em>example: "css/editor.css"</em>) or a list of css files seperated by a comma (<em>example: /themes/garland/style.css,http://domain.com/customMCE.css</em>).<br />Macros: %h (host name: http://www.example.com/), %t (path to theme: theme/yourtheme/)<br />Be sure to select "define css" above.')
  );

  $form['css']['css_classes'] = array(
    '#type' => 'textfield',
    '#title' => t('CSS classes'),
    '#default_value' => isset($edit->settings['css_classes']) ? $edit->settings['css_classes'] : NULL,
    '#size' => 40,
    '#maxlength' => 255,
    '#description' => t('Adds CSS classes to the "styles" droplist. Format is: &lt;title&gt;=&lt;class&gt;;<br/> Example: Header 1=header1;Header 2=header2;Header 3=header3 (note: no trailing \';\')<br />Leave blank to automatically import list of CSS classes from style sheet.')
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $btn
  );

  return $form;
}

/**
 * Return an HTML form for profile configuration.
 */
function tinymce_profile_form($edit) {

  $output .= drupal_get_form('tinymce_profile_form_build', $edit);

  return $output;
}

/**
 * Layout for the buttons in the tinymce profile form
 */
function theme_tinymce_admin_button_table($form) {
  $buttons = array();

  // Flatten forms array
  foreach (element_children($form) as $key) {
    $buttons[] = drupal_render($form[$key]);
  }

  //split checkboxes into rows with 3 columns
  $total = count($buttons);
  $rows = array();
  for ($i = 0; $i < $total; $i++) {
    $row = array();
    $row[] = array('data' => $buttons[$i]);
    $row[] = array('data' => $buttons[++$i]);
    $row[] = array('data' => $buttons[++$i]);
    $rows[] = $row;
  }

  $output = theme('table', array(), $rows, array('width' => '100%'));

  return $output;
}

/**
 * Return the name of the current user's default profile.
 */
function tinymce_current_profile() {
  static $profile_name;
  if (!$profile_name) {
    global $user;
    $profile_name = db_result(db_query('SELECT s.name FROM {tinymce_settings} s INNER JOIN {tinymce_role} r ON r.name = s.name WHERE r.rid IN (%s)', implode(',', array_keys($user->roles))));
  }
  return $profile_name;
}

/**
 * Load all profiles. Just load one profile if $name is passed in.
 */
function tinymce_profile_load($name = '') {
  static $profiles = array();

  if (!$profiles) {
    $roles = user_roles();
    $result = db_query('SELECT * FROM {tinymce_settings}');
    while ($data = db_fetch_object($result)) {
      $data->settings = unserialize($data->settings);
      $result2 = db_query("SELECT rid FROM {tinymce_role} WHERE name = '%s'", $data->name);
      $role = array();
      while ($r = db_fetch_object($result2)) {
        $role[$r->rid] = $roles[$r->rid];
      }
      $data->rids = $role;

      $profiles[$data->name] = $data;
    }
  }

  return ($name ? $profiles[$name] : $profiles);
}

/**
 * Controller for tinymce profiles.
 */
function tinymce_profile_overview() {
  $output = '';

  $profiles = tinymce_profile_load();
  if ($profiles) {
    $roles = user_roles();
    $header = array(t('Profile'), t('Roles'), t('Operations'));
    foreach ($profiles as $p) {
      $rows[] = array(array('data' => $p->name, 'valign' => 'top'), array('data' => implode("<br />\n", $p->rids)), array('data' => l(t('edit'), 'admin/settings/tinymce/edit/'. urlencode($p->name)) .' '. l(t('delete'), 'admin/settings/tinymce/delete/'. urlencode($p->name)), 'valign' => 'top'));
    }
    $output .= theme('table', $header, $rows);
    $output .= t('<p><a href="!create-profile-url">Create new profile</a></p>', array('!create-profile-url' => url('admin/settings/tinymce/add')));
  }
  else {
    drupal_set_message(t('No profiles found. Click here to <a href="!create-profile-url">create a new profile</a>.', array('!create-profile-url' => url('admin/settings/tinymce/add'))));
  }

  return $output;
}

/**
 * Save a profile to the database.
 */
function tinymce_profile_save($edit) {
  db_query("DELETE FROM {tinymce_settings} WHERE name = '%s' or name = '%s'", $edit['name'], $edit['old_name']);
  db_query("DELETE FROM {tinymce_role} WHERE name = '%s' or name = '%s'", $edit['name'], $edit['old_name']);
  db_query("INSERT INTO {tinymce_settings} (name, settings) VALUES ('%s', '%s')", $edit['name'], serialize($edit));
  foreach ($edit['rids'] as $rid => $value) {
    db_query("INSERT INTO {tinymce_role} (name, rid) VALUES ('%s', %d)", $edit['name'], $rid);
  }