summaryrefslogtreecommitdiffstats
path: root/tinymce.module
blob: 8f509221f3a4130b0f86fc0aee404af549ddac28 (plain)
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
<?php
// $Id$
// A collaborative project by Matt Westgate <drupal at asitis dot org>
// and Richard Bennett <richard.b@gritechnologies.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',
                     'access' => user_access('administer tinymce'));
  }
  return $items;
}

/**
 * Implementation of hook_help().
 */
function tinymce_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      return t('The TinyMCE Javascript HTML WYSIWYG editor.');

    case 'admin/settings/tinymce#pages':
      return "node/*\nuser/*\ncomment/*";

    case 'admin/settings/tinymce':
      return t('<p>TinyMCE adds what-you-see-is-what-you-get (WYSIWYG) html editing to textareas. Profiles can be defined based on user roles. 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. The default profile setting uses the "simple" TinyMCE theme which just shows the most minimal buttons set (bold, italic, underline, etc), but many other settings are available by switching to "advanced". And by default, textareas on affected pages will be automatically swapped out with the rich text editor. Users may disable the editor for any textarea without reloading the page. This setting can be reversed so that pages load with conventional textarea form fields. A link below each textarea allows TinyMCE to be turned on or off "on the fly".</p><p>Be aware that things can get confusing if a user is a member of roles defined in multiple profiles. In this case, the user will receive the profile for role with lowest role id they belong to. Did I mention it was confusing?</p>');
  }
}

/**
 * Implementation of hook_perm().
 */
function tinymce_perm() {
  return array('administer tinymce', 'access tinymce');
}

/**
 * Implementation of hook_img_assist_head().
 */
function tinymce_img_assist_head() {
  global $base_url;
  // The tinymce docs say to include tiny_mce_popup.js, but this was killing IE!
  $popup_path = $base_url .'/'. drupal_get_path('module', 'tinymce'). '/tinymce/jscripts/tiny_mce/tiny_mce_popup.js';
  $img_assist_prop = $base_url .'/'. drupal_get_path('module', 'img_assist'). '/properties.js';
  $clean_url    = variable_get('clean_url', 0);
  $img_template = variable_get('img_assist_img_html', img_assist_help('img_assist/template'));
  $img_template = str_replace("\r\n", "\n", $img_template);
  $img_template = str_replace("\n", '\n', addslashes($img_template));

$output = <<<EOD
<script language="javascript" src="$img_assist_prop"></script>
<script language="javascript">
  var clean_url    = $clean_url;
  var img_template = "$img_template";

  function insertImage(form) {
    if (window.opener) {
      form['edit[thumbpath]'].value = window.opener.tinyMCE.convertURL(form['edit[thumbpath]'].value);
      form['edit[filepath]'].value = window.opener.tinyMCE.convertURL(form['edit[filepath]'].value);
      form['edit[nodePath]'].value = window.opener.tinyMCE.convertURL(form['edit[nodePath]'].value);

      var img = generate_image_tag(form, 'html');
      //img = img.replace(/\\r|\\n|\\t/g, '');

      window.opener.tinyMCE.execInstanceCommand(myTextarea.name, 'mceInsertContent', false, img, true);
    }
  }
</script>
EOD;

  return $output;
}

/**
 * Implementation of hook_img_assist_on_submit().
 */
function tinymce_img_assist_on_submit() {
  return 'parent.insertImage(this.form);';
}

/**
 * Implementation of hook_textarea().
 */
function tinymce_textarea($op, $textarea_name) {
  static $is_running = FALSE;
  if (!user_access('access tinymce')) return NULL;

  global $user;
  global $base_url;
  static $profile_name;

  // Since tinymce_config() makes a db hit, only call it when we're pretty sure
  // we're gonna render tinymce.
  $valid_so_far = FALSE;
  if ($op == 'post') {
    if (!$profile_name) {
      $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))));
    }
    $profile = tinymce_profile_load($profile_name);
    $init = tinymce_config($profile);
    $init['elements'] = 'edit['. $textarea_name .']';
    $valid_so_far = TRUE;
  }

  if ($valid_so_far && _tinymce_page_match($profile)) {
    // Merge user-defined TinyMCE settings.
    $init = (array) theme('tinymce_theme', $init, $textarea_name, $init['theme'], $is_running);
    $settings = array();
    foreach ($init as $k => $v) {
      if (strtolower($v) != 'true' && strtolower($v) != 'false') {
        $v = '"'. $v. '"';
      }
      $settings[] = $k. ' : '. $v;
    }
    $tinymce_settings = implode(",\n    ", $settings);

    if (function_exists('img_assist_help')) {
      $img_assist_js_on = $base_url .'/'. url('img_assist/add&editor=tinymce') .'&textarea=';
      $img_assist_js_off = $base_url .'/'. url('img_assist/add') .'&textarea=';
      $img_assist_on = $base_url .'/'. url('img_assist/add&editor=tinymce') .'&textarea=edit['. $textarea_name .']';
      $img_assist_off = $base_url .'/'. url('img_assist/add') .'&textarea=edit['. $textarea_name .']';
    }

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

$tinymce_invoke = <<<EOD
<script language="javascript" type="text/javascript">
  tinyMCE.init({
    $tinymce_settings
  });
</script>
EOD;

$js_toggle = <<<EOD
<script language="javascript" type="text/javascript">
  function mceToggle(id, linkid) {
    element = document.getElementById(id);
    link = document.getElementById(linkid);
    img_assist = document.getElementById('img_assist-link-'+ id);

    if (tinyMCE.getEditorId(element.name) == null) {
      tinyMCE.addMCEControl(element, element.name);
      element.togg = 'on';
      link.innerHTML = '$disable';
      link.href = "javascript:mceToggle('" +id+ "', '" +linkid+ "');";
      if (img_assist)
        img_assist.href = "$img_assist_js_on"+ element.name;
      link.blur();
    }
    else {
      tinyMCE.removeMCEControl(tinyMCE.getEditorId(element.name));
      element.togg = 'off';
      link.innerHTML = '$enable';
      link.href = "javascript:mceToggle('" +id+ "', '" +linkid+ "');";
      if (img_assist)
        img_assist.href = "$img_assist_js_off"+ element.name;
      link.blur();
    }
  }
</script>
EOD;

$status = isset($user->tinymce_status) ? $user->tinymce_status : variable_get('tinymce_default_state', 0);
$link_text = $status == 1 ? $disable : $enable;
$no_wysiwyg = t('Your current web browser does not support WYSIWYG editing.');
$wysiwyg_link = <<<EOD
<script language="javascript" type="text/javascript">
  img_assist = document.getElementById('img_assist-link-edit-$textarea_name');
  if (img_assist) {
    img_assist.href = tinyMCE.getEditorId('edit-$textarea_name') == null ? "$img_assist_on" : "$img_assist_off";
  }
  if (typeof(document.execCommand) == 'undefined') {
    img_assist.href = "$img_assist_off";
    document.write('<div style="font-size:x-small">$no_wysiwyg</div>');
  }
  else {
    document.write("<div><a href=\"javascript:mceToggle('edit-$textarea_name', 'wysiwyg4$textarea_name');\" id=\"wysiwyg4$textarea_name\">$link_text</div></a>");
  }
</script>
EOD;

    // We only load the TinyMCE js file once per request
    if (!$is_running && !empty($init)) {
      $is_running = TRUE;
      // For some crazy reason IE will only load this JS file if the absolute reference is given to it.
      drupal_set_html_head('<script language="javascript" type="text/javascript" src="'. $base_url .'/'. drupal_get_path('module', 'tinymce') .'/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>');
      drupal_set_html_head($js_toggle);
      // We have to do this becuase 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>');
    }
    // Load a TinyMCE init for each textarea.
    drupal_set_html_head($tinymce_invoke);

  return $wysiwyg_link;
  }
}

/**
 * Implementation of hook_user().
 */
function tinymce_user($type, &$edit, &$user, $category = NULL) {
  if ($type == 'form' && $category == 'account' && user_access('access tinymce')) {
    $user_status = $edit['tinymce_status'] != NULL ? $edit['tinymce_status'] : ($user->tinymce_status != NULL ? $user->tinymce_status : variable_get('tinymce_default_state', 0));
    $form = form_radios(t('Default status'), 'tinymce_status', $user_status, array(t('Off'), t('On')), t('Should rich-text editing be enabled or disabled by default in textarea fields?'));
    return array(array('title' => t('TinyMCE settings'), 'data' => $form));
  }
  if ($type == 'validate') {
    return array('tinymce_status' => $edit['tinymce_status']);
  }
}


/**
 * @addtogroup themeable
 * @{
 */

/**
 * Customize a TinyMCE theme.
 *
 * @param init
 *   An array of settings TinyMCE should invoke a theme. You may override any
 *   of the TinyMCE settings. Details here:
 *
 *    http://tinymce.moxiecode.com/wrapper.php?url=tinymce/docs/using.htm
 *
 * @param textarea_name
 *   The name of the textarea TinyMCE wants to enable.
 *
 * @param theme_name
 *   The default tinymce theme name to be enabled for this textarea. The
 *   sitewide default is 'simple', but the user may also override this.
 *
 * @param is_running
 *   A boolean flag that identifies id TinyMCE is currently running for this
 *   request life cycle. It can be ignored.
 */
function theme_tinymce_theme($init, $textarea_name, $theme_name, $is_running) {
  switch ($textarea_name) {
    // Disable tinymce for these textareas
    case 'log':
    case 'img_assist_pages':
    case 'caption':
      unset($init);
      break;

    // Force the 'simple' theme for some of the smaller textareas.
    case 'signature':
    case 'site_mission':
    case 'site_footer':
    case 'settings][access_pages':
      $init['theme'] = 'simple';
      unset($init['theme_advanced_toolbar_location']);
      unset($init['theme_advanced_toolbar_align']);
      unset($init['theme_advanced_path_location']);
      unset($init['theme_advanced_blockformats']);
      unset($init['theme_advanced_styles']);
      break;
  }

  // Add some extra features when using the advanced theme.
  switch ($theme_name) {
    case 'advanced':
      $init['extended_valid_elements'] = 'a[href|target|name|title|onclick]';
      $init['theme_advanced_buttons3_add_before'] = 'tablecontrols,separator';
      $init['plugins'] = file_exists(drupal_get_path('module', 'tinymce'). '/tinymce/jscripts/tiny_mce/plugins/drupalimage') ? 'drupalimage,table,emotions,print' : 'table,emotions,print';
      $init['theme_advanced_buttons3_add'] = 'drupalimage,emotions,separator,print';
      break;
  }

  // Always return $init; !!
  return $init;
}

/** @} End of addtogroup themeable */

/**
 * 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;
}

/********************************************************************
 * Module Functions :: Public
 ********************************************************************/

/**
 * Controller for tinymce administrative settings.
 */
function tinymce_admin($arg = NULL) {
  $edit = $_POST['edit'];
  $op = $_POST['op'];

  $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;

    case t('Save settings'):
      variable_set('tinymce_default_state', $edit['tinymce_default_state']);
      drupal_set_message(t('Settings updated'));
      drupal_goto('admin/settings/tinymce');
      break;

    default:
      drupal_set_title(t('TinyMCE settings (%revision)', array('%revision' => '$Revision$')));
      //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();
  }

  print theme('page', $output);
}

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

  $settings = $profile->settings;

  // Build a default list of TinyMCE settings.

  // Is tinymce on by default?
  $status = isset($user->tinymce_status) ? $user->tinymce_status : variable_get('tinymce_default_state', 0);
  $init['mode'] = $status == 1 ? 'exact' : 'none';
  $init['theme'] = $settings['theme'] ? $settings['theme'] : 'simple';
  $init['document_base_url'] = "$base_url/";

  $init['verify_html'] = $settings['verify_html'] ? $settings['verify_html'] : 'false';
  $init['auto_cleanup_word'] = $settings['msword'] ? $settings['msword'] : 'false';
  $init['preformatted'] = $settings['preformatted'] ? $settings['preformatted'] : 'false';
  $init['force_br_newlines'] = $settings['force_br'] ? $settings['force_br'] : 'false';
  $init['force_p_newlines'] = $settings['force_p'] ? $settings['force_p'] : 'false';
  if ($init['theme'] == 'advanced') {
    $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'] : 'none';
    $init['theme_advanced_blockformats'] = $settings['block_formats'] ? $settings['block_formats'] : 'p,address,pre,h1,h2,h3,h4,h5,h6';
  }

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

  if ($settings['css_setting'] == 'theme') {
    $css = drupal_get_path('theme', init_theme()) . '/style.css';
    if (file_exists($css)) {
      $init['content_css'] = $base_url .'/'. $css;
    }
    else if ($settings['css_setting'] == 'self') {
      $init['content_css'] = $edit['css_path'];
    }
  }

  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($edit) {
  $edit = array2object($edit);

  // Only display the roles that currently don't have a tinymce profile. One
  // profile per role.
  $orig_roles = user_roles();
  $roles = $orig_roles;
  if (arg(3) == 'add') {
    $result = db_query('SELECT DISTINCT(rid) FROM {tinymce_role}');
    while ($data = db_fetch_object($result)) {
      unset($roles[$data->rid]);
    }
    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. First remove an existing tinymce profile from at least one role in order to create a new profile.'), '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 {
    $output = form_hidden('old_name', $edit->name);
    $btn = t('Update profile');
  }

  $group = form_textfield(t('Profile name'), 'name', $edit->name, 40, 128, t('Enter an unique name for this profile. This name is only visible in the tinymce administration page.'), NULL, TRUE);
  $group .= form_checkboxes(t('Roles allowed to use this profile'), 'rids', array_keys((array) $edit->rids), $roles, t('Select at least one role.'), NULL, TRUE);
  $group .= form_radios(t('Theme'), 'settings][theme', $edit->settings['theme'] ? $edit->settings['theme'] : 'simple',  _tinymce_get_themes(), t('Select the tinymce theme. The <em>advanced</em> theme will display advanced options below.'), FALSE ,array('onclick'=>'tinymceThemeOptions(this.value);'));
  $group .= form_radios(t('Make tinymce visible on'), 'settings][access', $edit->settings['access'], array(t('specific pages'), t('all textareas')));
  $group .= form_textarea(t('Specific pages'), 'settings][access_pages', $edit->settings['access_pages'] ? $edit->settings['access_pages'] : tinymce_help('admin/settings/tinymce#pages'), 40, 5, t("Enter one page per line as Drupal paths. The '*' character is a wildcard. Example paths are '<em>blog</em>' for the blog page and '<em>blog/*</em>' for every personal blog. '<em>&lt;front&gt;</em>' is the front page."));
  $output .= form_group(t('Basic setup'), $group);

  $output .= t('<h3>Options</h3>');

  $group = '';
  $group .= form_select(t('Toolbar location'), 'settings][toolbar_loc', $edit->settings['toolbar_loc'], array('bottom' => 'bottom', 'top' => 'top'), t('Show toolbar at the top or bottom of the editor area?'));
  $group .= form_select(t('Toolbar alignment'), 'settings][toolbar_align', $edit->settings['toolbar_align'], array('center' => 'center', 'left' => 'left', 'right' => 'right'), t('Align tool icons left, center, or right within the toolbar.'));
  $group .= form_select(t('Path location'), 'settings][path_loc', $edit->settings['path_loc'], array('none' => 'none', 'top' => 'top', 'bottom' => 'bottom'), t('Path to html elements (i.e. "body>table>tr>td"). Show at top, bottom, or not at all.'));
  $group .= form_textfield(t('Block formats'), 'settings][block_formats', $edit->settings['block_formats'] ? $edit->settings['block_formats'] : 'p,address,pre,h1,h2,h3,h4,h5,h6', 40, 250, t('Comma separated list of HTML block formats. You can only remove elements, not add.'));
  $dsp    = $edit->settings['theme'] == 'advanced' ? 'block' : 'none';
  $output .= '<div id="advancedThemeSettings" style="display:'. $dsp .';">'. form_group(('Advanced theme options'), $group).'</div>';

  $group = form_textfield(t('Editor width'), 'settings][width', $edit->settings['width'], 3, 5, t('Set width of editor. Leave blank to use size of textarea being replaced.'));
  $group .= form_textfield(t('Editor height'), 'settings][height', $edit->settings['height'], 3, 5, t('Set height of editor. Leave blank to use size of textarea being replaced.'));
  $output .= form_group(t('Editor display'), $group);

  $group = form_select(t('Auto cleanup Word'), 'settings][msword', $edit->settings['msword'], array('true' => 'true', 'false' => 'false'), t('Automatically cleanup MS Office/Word HTML will be executed automatically on paste operations. (Only works in Internet Explorer)'));
  $group .= form_select(t('Verify HTML'), 'settings][verify_html', $edit->settings['verify_html'], array('true' => 'true', 'false' => 'false'), 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.'));
  $group .= form_select(t('Preformatted'), 'settings][preformatted', $edit->settings['preformatted'], array('false' => 'false', 'true' => 'true'), 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.'));
  $output .= form_group(t('On save'), $group);

  $group = form_select(t('Editor CSS'), 'settings][css_setting', $edit->settings['css_setting'] ? $edit->settings['css_setting'] : 'theme', array('theme' => 'use theme css', 'self' => 'define css', 'none' => 'tinyMCE default'), t('Defines the CSS to be used in the editor area.<br />use theme css - get css from current Drupal theme.<br/>define css - enter path for css file below.<br />tinyMCE default - uses default CSS from editor.'));
  $group .= form_textfield(t('CSS path'), 'settings][css_path', $edit->settings['css_path'], 40, 255, t('Enter path to CSS file (example: "/css/editor.css"). Select "define css" above.'));
  $group .= form_textfield(t('CSS classes'), 'settings][css_classes', $edit->settings['css_classes'], 40, 255, 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;"<br />Leave blank to automatically import list of CSS classes from style sheet.'));
  $output .= form_group(t('CSS'), $group);

  $group .= form_select(t('Force BR new lines'), 'settings][force_br', $edit->settings['force_br'] ? $edit->settings['force_br'] : 'false', array('true' => 'true', 'false' => 'false'), t('Use BR tags for new lines rather than P.'));
  $group .= form_select(t('Force P new lines'), 'settings][force_p', $edit->settings['force_p'] ? $edit->settings['force_p'] : 'true', array('true' => 'true', 'false' => 'false'), t('When enabled, Mozilla/Firefox will generate P elements on Enter/Return key and BR elements on Shift+Enter/Return..'));
  $output .= form_group(t('Formatting'), $group);
  $output .= form_submit($btn);

  $js = <<<EOD
<script type='text/javascript'>
  function tinymceThemeOptions(theme) {
    document.getElementById('advancedThemeSettings').style.display = theme == 'advanced' ? 'block' : 'none';
  }
</script>
EOD;
  drupal_set_html_head($js);

  return form($output);
}

/**
 * Load all profiles.
 */
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 = '';
  $output .= t('<p><a href="%create-profile-url">Create new profile</a></p>', array('%create-profile-url' => url('admin/settings/tinymce/add')));

  $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). '<p>&nbsp;</p>';
  }
  else {
    $output .= t('<p>No profiles found.</p>');
  }

  $group = form_radios(t('Default tinymce state'), 'tinymce_default_state', variable_get('tinymce_default_state', 0), array(t('Off'), t('On')), t('Should tinymce be enabled or disabled by default when it\'s first loaded from a textarea? Note: The user may override this setting in their profile.'));
  $output .= form_group(t('Default settings'), $group);
  $output .= form_submit(t('Save settings'));

  return form($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['settings']));
  foreach ($edit['rids'] as $rid) {
    db_query("INSERT INTO {tinymce_role} (name, rid) VALUES ('%s', %d)", $edit['name'], $rid);
  }
}

/**
 * Profile validation.
 */
function tinymce_profile_validate($edit) {
  $errors = array();

  if (!$edit['name']) {
    $errors['name'] = t('You must give a profile name.');
  }

  if (!$edit['rids']) {
    $errors['rids'] = t('You must select at least one role.');
  }

  foreach ($errors as $name => $message) {
    form_set_error($name, $message);
  }

  return count($errors) == 0;
}

/********************************************************************
 * Module Functions :: Private
 ********************************************************************/

/**
 * Determine if TinyMCE has permission to be used on the current page.
 *
 * @return
 *   TRUE if can render, FALSE if not allowed.
 */
function _tinymce_page_match($edit) {
  //Kill TinyMCE if we're editing a textarea with PHP in it!
  if ($_POST['edit']['format'] == 2) {
    return FALSE;
  }
  else {
    // PHP input formats are #2 in the filters table.
    preg_match("|^node/(\d+)(/edit)$|", $_GET['q'], $match);
    if (intval($match[1]) > 0) {
      if (db_result(db_query('SELECT format FROM {node} WHERE nid = %d AND format = 2', $match[1]))) {
        return FALSE;
      }
    }
  }

  if ($edit->settings['access'] == 1) {
    return TRUE;
  }
  else {
    $page_match = FALSE;
    $pages = $edit->settings['access_pages'] ? $edit->settings['access_pages'] : tinymce_help('admin/settings/tinymce#pages');
    if ($pages) {
      $path = drupal_get_path_alias($_GET['q']);
      $regexp = '/^('. preg_replace(array('/(\r\n?|\n)/', '/\\\\\*/', '/(^|\|)\\\\<front\\\\>($|\|)/'), array('|', '.*', '\1'. variable_get('site_frontpage', 'node') .'\2'), preg_quote($pages, '/')) .')$/';
      $page_match = preg_match($regexp, $path);
    }
    return $page_match;
  }
}
?>