fixed relative paths
[project/tinymce.git] / tinymce.module
1 <?php
2 // $Id$
3 // A collaborative project by Matt Westgate <drupal at asitis dot org>,
4 // Richard Bennett <richard.b@ at ritechnologies dot com> and Jeff Robbins <robbins at jjeff dot com>
5
6 /**
7 * @file
8 * Integrate the TinyMCE editor (http://tinymce.moxiecode.com/) into Drupal.
9 */
10
11 /**
12 * Implementation of hook_menu().
13 */
14 function tinymce_menu($may_cache) {
15 $items = array();
16 if ($may_cache) {
17 $items[] = array('path' => 'admin/settings/tinymce', 'title' => t('tinymce'),
18 'callback' => 'tinymce_admin',
19 'access' => user_access('administer tinymce'));
20 }
21 return $items;
22 }
23
24 /**
25 * Implementation of hook_help().
26 */
27 function tinymce_help($section) {
28 switch ($section) {
29 case 'admin/modules#description':
30 return t('The TinyMCE Javascript HTML WYSIWYG editor.');
31 case 'admin/settings/tinymce#pages':
32 return "node/*\nuser/*\ncomment/*";
33 case 'admin/settings/tinymce':
34 return t('<p>TinyMCE adds what-you-see-is-what-you-get (WYSIWYG) HTML editing to textareas, enabling users to create rich content.</p><p>TinyMCE Profiles are based on user roles, and defines for example, what pages receive TinyMCE capabilities, what buttons or themes are enabled for the editor, how the editor is displayed, and a few other settings. 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 a role defined in multiple profiles. In this case, the user will receive the profile for the role with the lowest role id they belong to. Did I mention it was confusing?</p><p>lastly, only users with the <code>access tinymce</code> permission will be able to use TinyMCE.</p>');
35 }
36 }
37
38 /**
39 * Implementation of hook_perm().
40 */
41 function tinymce_perm() {
42 return array('administer tinymce', 'access tinymce');
43 }
44
45 /**
46 * Implementation of hook_img_assist_head().
47 */
48 function tinymce_img_assist_head() {
49 global $base_url;
50 // The tinymce docs say to include tiny_mce_popup.js, but this was killing IE!
51 $popup_path = $base_url .'/'. drupal_get_path('module', 'tinymce'). '/tinymce/jscripts/tiny_mce/tiny_mce_popup.js';
52 $img_assist_prop = $img_template = '';
53 if (module_exist('img_assist')) {
54 $img_assist_prop = $base_url .'/'. drupal_get_path('module', 'img_assist'). '/properties.js';
55 $img_assist_prop = '<script type="text/javascript" src="'. $img_assist_prop .'"></script>';
56
57 $img_template = variable_get('img_assist_img_html', img_assist_help('img_assist/template'));
58 $nl = "\n";
59 $img_template = preg_replace('/\n|\r|(\r\n)/m', '\\'. $nl, $img_template);
60 }
61 $clean_url = variable_get('clean_url', 0);
62
63 $output = <<<EOD
64 $img_assist_prop
65 <script type="text/javascript">
66 var clean_url = $clean_url;
67 var img_template = '$img_template';
68
69 function insertImage(form) {
70 if (window.opener) {
71 form['edit[filepath]'].value = window.opener.tinyMCE.convertURL(form['edit[filepath]'].value);
72 form['edit[nodePath]'].value = window.opener.tinyMCE.convertURL(form['edit[nodePath]'].value);
73
74 var img = generate_image_tag(form, 'html');
75 //img = img.replace(/\\r|\\n|\\t/g, '');
76
77 window.opener.tinyMCE.execInstanceCommand(myTextarea.name, 'mceInsertContent', false, img, true);
78 }
79 }
80 </script>
81 EOD;
82
83 return $output;
84 }
85
86 /**
87 * Implementation of hook_img_assist_on_submit().
88 */
89 function tinymce_img_assist_on_submit() {
90 return 'parent.insertImage(this.form);';
91 }
92
93 /**
94 * Implementation of hook_elements().
95 */
96 function tinymce_elements() {
97 $type = array();
98
99 if (user_access('access tinymce')) {
100 // Set resizable to false to avoid drupal.js resizable function from taking control of the textarea
101 $type['textarea'] = array('#process' => array('tinymce_process_textarea' => array()), '#resizable' => FALSE);
102 }
103
104 return $type;
105 }
106
107 /**
108 * Attach tinymce to a textarea
109 */
110 function tinymce_process_textarea($element) {
111 static $is_running = FALSE;
112 global $user;
113 global $base_url;
114 static $profile_name;
115
116 //$element is an array of attributes for the textarea but there is no just 'name' value, so we extract this from the #id field
117 $textarea_name = substr($element['#id'], strpos($element['#id'], '-') + 1);
118
119 // Since tinymce_config() makes a db hit, only call it when we're pretty sure
120 // we're gonna render tinymce.
121 if (!$profile_name) {
122 $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))));
123 }
124 $profile = tinymce_profile_load($profile_name);
125 $init = tinymce_config($profile);
126 $init['elements'] = 'edit['. $textarea_name .']';
127
128 if (_tinymce_page_match($profile)) {
129 // Merge user-defined TinyMCE settings.
130 $init = (array) theme('tinymce_theme', $init, $textarea_name, $init['theme'], $is_running);
131
132 // If $init array is empty no need to execute rest of code since there are no textareas to theme with TinyMCE
133 if (count($init) < 1) {
134 return $element;
135 }
136
137 $settings = array();
138 foreach ($init as $k => $v) {
139 $v = is_array($v) ? implode(',', $v) : $v;
140 // Don't wrap the JS init in quotes for boolean values or functions.
141 if (strtolower($v) != 'true' && strtolower($v) != 'false' && $v[0] != '{') {
142 $v = '"'. $v. '"';
143 }
144 $settings[] = $k. ' : '. $v;
145 }
146 $tinymce_settings = implode(",\n ", $settings);
147
148 if (module_exist('img_assist')) {
149 $img_assist_js_on = $base_url .'/'. url('img_assist/add&editor=tinymce') .'&textarea=';
150 $img_assist_js_off = $base_url .'/'. url('img_assist/add') .'&textarea=';
151 $img_assist_on = $base_url .'/'. url('img_assist/add&editor=tinymce') .'&textarea=edit['. $textarea_name .']';
152 $img_assist_off = $base_url .'/'. url('img_assist/add') .'&textarea=edit['. $textarea_name .']';
153 }
154
155 $enable = t('enable rich-text');
156 $disable = t('disable rich-text');
157
158 $tinymce_invoke = <<<EOD
159 <script type="text/javascript">
160 tinyMCE.init({
161 $tinymce_settings
162 });
163 </script>
164 EOD;
165
166 $js_toggle = <<<EOD
167 <script type="text/javascript">
168 function mceToggle(id, linkid) {
169 element = document.getElementById(id);
170 link = document.getElementById(linkid);
171 img_assist = document.getElementById('img_assist-link-'+ id);
172
173 if (tinyMCE.getEditorId(element.name) == null) {
174 tinyMCE.addMCEControl(element, element.name);
175 element.togg = 'on';
176 link.innerHTML = '$disable';
177 link.href = "javascript:mceToggle('" +id+ "', '" +linkid+ "');";
178 if (img_assist)
179 img_assist.href = "$img_assist_js_on"+ element.name;
180 link.blur();
181 }
182 else {
183 tinyMCE.removeMCEControl(tinyMCE.getEditorId(element.name));
184 element.togg = 'off';
185 link.innerHTML = '$enable';
186 link.href = "javascript:mceToggle('" +id+ "', '" +linkid+ "');";
187 if (img_assist)
188 img_assist.href = "$img_assist_js_off"+ element.name;
189 link.blur();
190 }
191 }
192 </script>
193 EOD;
194
195 $status = isset($user->tinymce_status) ? $user->tinymce_status : variable_get('tinymce_default_state', 0);
196 $link_text = $status == 1 ? $disable : $enable;
197 $no_wysiwyg = t('Your current web browser does not support WYSIWYG editing.');
198 $wysiwyg_link = <<<EOD
199 <script type="text/javascript">
200 img_assist = document.getElementById('img_assist-link-edit-$textarea_name');
201 if (img_assist) {
202 img_assist.href = tinyMCE.getEditorId('edit-$textarea_name') == null ? "$img_assist_on" : "$img_assist_off";
203 }
204 if (typeof(document.execCommand) == 'undefined') {
205 img_assist.href = "$img_assist_off";
206 document.write('<div style="font-size:x-small">$no_wysiwyg</div>');
207 }
208 else {
209 document.write("<div><a href=\"javascript:mceToggle('edit-$textarea_name', 'wysiwyg4$textarea_name');\" id=\"wysiwyg4$textarea_name\">$link_text</a></div>");
210 }
211 </script>
212 EOD;
213
214 // We only load the TinyMCE js file once per request
215 if (!$is_running) {
216 $is_running = TRUE;
217 $tinymce_mod_path = drupal_get_path('module', 'tinymce');
218 if (is_dir($tinymce_mod_path.'/imagemanager/')) {
219 // if tinymce imagemanager is installed
220 drupal_add_js(drupal_get_path('module', 'tinymce') .'/imagemanager/jscripts/mcimagemanager.js');
221 }
222 // TinyMCE Compressor
223 if (file_exists($tinymce_mod_path. '/tinymce/jscripts/tiny_mce/tiny_mce_gzip.php')) {
224 drupal_add_js($base_url. '/'. $tinymce_mod_path .'/tinymce/jscripts/tiny_mce/tiny_mce_gzip.php');
225 }
226 else {
227 // For some crazy reason IE will only load this JS file if the absolute reference is given to it.
228 drupal_add_js($base_url. '/'. $tinymce_mod_path .'/tinymce/jscripts/tiny_mce/tiny_mce.js');
229 }
230 drupal_set_html_head($js_toggle);
231 // We have to do this becuase of some unfocused CSS in certain themes. See http://drupal.org/node/18879 for details
232 drupal_set_html_head('<style type="text/css" media="all">.mceEditor img { display: inline; }</style>');
233 }
234 // Load a TinyMCE init for each textarea.
235 if ($init) drupal_set_html_head($tinymce_invoke);
236
237 // Make sure to append to #suffix so it isn't completely overwritten
238 $element['#suffix'] .= $wysiwyg_link;
239 }
240
241 return $element;
242 }
243
244 /**
245 * Implementation of hook_user().
246 */
247 function tinymce_user($type, &$edit, &$user, $category = NULL) {
248 if ($type == 'form' && $category == 'account' && user_access('access tinymce')) {
249 $user_status = $edit['tinymce_status'] != NULL ? $edit['tinymce_status'] : ($user->tinymce_status != NULL ? $user->tinymce_status : variable_get('tinymce_default_state', 0));
250 $form['tinymce'] = array('#type' => 'fieldset', '#title' => t('Rich-text settings'), '#weight' => 5, '#collapsible' => TRUE, '#collapsed' => TRUE);
251 $form['tinymce']['tinymce_status'] = array('#type' => 'radios', '#title' => t('Default status'), '#default_value' => $user_status, '#options' => array(t('Off'), t('On')), '#description' => t('Should rich-text editing be enabled or disabled by default in textarea fields?'));
252 return array('tinymce' => $form);
253 }
254 if ($type == 'validate') {
255 return array('tinymce_status' => $edit['tinymce_status']);
256 }
257 }
258
259 /**
260 * @addtogroup themeable
261 * @{
262 */
263
264 /**
265 * Customize a TinyMCE theme.
266 *
267 * @param init
268 * An array of settings TinyMCE should invoke a theme. You may override any
269 * of the TinyMCE settings. Details here:
270 *
271 * http://tinymce.moxiecode.com/wrapper.php?url=tinymce/docs/using.htm
272 *
273 * @param textarea_name
274 * The name of the textarea TinyMCE wants to enable.
275 *
276 * @param theme_name
277 * The default tinymce theme name to be enabled for this textarea. The
278 * sitewide default is 'simple', but the user may also override this.
279 *
280 * @param is_running
281 * A boolean flag that identifies id TinyMCE is currently running for this
282 * request life cycle. It can be ignored.
283 */
284 function theme_tinymce_theme($init, $textarea_name, $theme_name, $is_running) {
285 switch ($textarea_name) {
286 // Disable tinymce for these textareas
287 case 'log': // book and page log
288 case 'img_assist_pages':
289 case 'caption': // signature
290 case 'pages':
291 case 'access_pages': //TinyMCE profile settings.
292 case 'user_mail_welcome_body': // user config settings
293 case 'user_mail_approval_body': // user config settings
294 case 'user_mail_pass_body': // user config settings
295 case 'synonyms': // taxonomy terms
296 case 'description': // taxonomy terms
297 unset($init);
298 break;
299
300 // Force the 'simple' theme for some of the smaller textareas.
301 case 'signature':
302 case 'site_mission':
303 case 'site_footer':
304 case 'site_offline_message':
305 case 'page_help':
306 case 'user_registration_help':
307 case 'user_picture_guidelines':
308 $init['theme'] = 'simple';
309 foreach ($init as $k => $v) {
310 if (strstr($k, 'theme_advanced_')) unset($init[$k]);
311 }
312 break;
313 }
314
315 // Add some extra features when using the advanced theme.
316 switch ($theme_name) {
317 case 'advanced':
318 //$init['extended_valid_elements'] = array('a[href|target|name|title|onclick]');
319 break;
320 }
321
322 // Always return $init; !!
323 return $init;
324 }
325
326 /** @} End of addtogroup themeable */
327
328 /**
329 * Grab the themes available to TinyMCE.
330 *
331 * TinyMCE themes control the functionality and buttons that are available to a
332 * user. Themes are only looked for within the default TinyMCE theme directory.
333 *
334 * NOTE: This function is not used in this release. We are only using advanced theme.
335 *
336 * @return
337 * An array of theme names.
338 */
339 function _tinymce_get_themes() {
340 static $themes = array();
341
342 if (!$themes) {
343 $theme_loc = drupal_get_path('module', 'tinymce') .'/tinymce/jscripts/tiny_mce/themes/';
344 if (is_dir($theme_loc) && $dh = opendir($theme_loc)) {
345 while (($file = readdir($dh)) !== false) {
346 if (!in_array($file, array('.', '..', 'CVS')) && is_dir($theme_loc . $file)) {
347 $themes[$file] = $file;
348 }
349 }
350 closedir($dh);
351 asort($themes);
352 }
353 }
354
355 return $themes;
356 }
357
358 /**
359 * Return plugin metadata from the plugin registry.
360 *
361 * We also scrape each plugin's *.js file for the human friendly name and help
362 * text URL of each plugin.
363 *
364 * @return
365 * An array for each plugin.
366 */
367 function _tinymce_get_buttons($skip_metadata = TRUE) {
368 include_once(drupal_get_path('module', 'tinymce'). '/plugin_reg.php');
369 $plugins = _tinymce_plugins();
370 if ($skip_metadata == FALSE && is_array($plugins)) {
371 foreach ($plugins as $name => $plugin) {
372 $file = drupal_get_path('module', 'tinymce'). '/tinymce/jscripts/tiny_mce/plugins/'. $name .'/editor_plugin_src.js';
373 // Grab the plugin metadata by scanning the *.js file.
374 if (file_exists($file)) {
375 $lines = file($file);
376 $has_longname = FALSE;
377 $has_infourl = FALSE;
378 foreach ($lines as $line) {
379 if ($has_longname && $has_infourl) break;
380 if (strstr($line, 'longname')) {
381 $start = strpos($line, "'") + 1;
382 $end = strrpos($line, "'") - $start;
383 $metadata[$name]['longname'] = substr($line, $start, $end);
384 $has_longname = TRUE;
385 }
386 elseif (strstr($line, 'infourl')) {
387 $start = strpos($line, "'") + 1;
388 $end = strrpos($line, "'") - $start;
389 $metadata[$name]['infourl'] = substr($line, $start, $end);
390 $has_infourl = TRUE;
391 }
392 }
393 }
394
395 // Find out the buttons a plugin has.
396 foreach ($plugin as $k => $v) {
397 if (strstr($k, 'theme_advanced_buttons')) {
398 $metadata[$name]['buttons'] = array_merge((array) $metadata[$name]['buttons'], $plugin[$k]);
399 }
400 }
401 }
402 return $metadata;
403 }
404
405 return $plugins;
406 }
407 /********************************************************************
408 * Module Functions :: Public
409 ********************************************************************/
410
411 /**
412 * Controller for tinymce administrative settings.
413 */
414 function tinymce_admin($arg = NULL) {
415
416 $edit = $_POST['edit'];
417 $op = $_POST['op'];
418
419 $op = $arg && !$op ? $arg : $op;
420
421 switch ($op) {
422 case 'add':
423 $breadcrumb[] = array('path' => 'admin', 'title' => t('administer'));
424 $breadcrumb[] = array('path' => 'admin/settings/tinymce', 'title' => t('tinymce'));
425 $breadcrumb[] = array('path' => 'admin/settings/tinymce/add', 'title' => t('Add new tinymce profile'));
426 menu_set_location($breadcrumb);
427 $output = tinymce_profile_form($edit);
428 break;
429
430 case 'edit':
431 drupal_set_title(t('Edit tinymce profile'));
432 $output = tinymce_profile_form(tinymce_profile_load(urldecode(arg(4))));
433 break;
434
435 case 'delete':
436 tinymce_profile_delete(urldecode(arg(4)));
437 drupal_set_message(t('Deleted profile'));
438 drupal_goto('admin/settings/tinymce');
439 break;
440
441 case t('Create profile');
442 case t('Update profile');
443 if (tinymce_profile_validate($edit)) {
444 tinymce_profile_save($edit);
445 $edit['old_name'] ? drupal_set_message(t('Your tinymce profile has been updated.')) : drupal_set_message(t('Your tinymce profile has been created.'));
446 drupal_goto('admin/settings/tinymce');
447 }
448 else {
449 $output = tinymce_profile_form($edit);
450 }
451 break;
452
453 case t('Save settings'):
454 variable_set('tinymce_default_state', $edit['tinymce_default_state']);
455 variable_set('tinymce_safari_message', $edit['tinymce_safari_message']);
456 drupal_set_message(t('Settings updated'));
457 drupal_goto('admin/settings/tinymce');
458 break;
459
460 default:
461 drupal_set_title(t('TinyMCE settings (%revision)', array('%revision' => '$Revision$')));
462 //Check if TinyMCE is installed.
463 $tinymce_loc = drupal_get_path('module', 'tinymce') .'/tinymce/';
464 if (!is_dir($tinymce_loc)) {
465 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');
466 }
467 $output = tinymce_profile_overview();
468 }
469
470 print theme('page', $output);
471 }
472
473 /**
474 * Return an array of initial tinymce config options from the current role.
475 */
476 function tinymce_config($profile) {
477
478 global $base_url;
479 global $user;
480 // Drupal theme path.
481 $themepath = drupal_get_path('theme', init_theme()).'/';
482 $host = $base_url.'/';
483
484 $settings = $profile->settings;
485
486 // Build a default list of TinyMCE settings.
487
488 // Is tinymce on by default?
489 $status = isset($user->tinymce_status) ? $user->tinymce_status : variable_get('tinymce_default_state', 0);
490
491 $init['mode'] = $status == 1 ? 'exact' : 'none';
492 $init['theme'] = $settings['theme'] ? $settings['theme'] : 'simple';
493 $init['document_base_url'] = "base_path()";
494 $init['language'] = $settings['language'] ? $settings['language'] : 'en';
495 $init['safari_warning'] = variable_get('tinymce_safari_message', 0) ? 'true' : 'false';
496 $init['entity_encoding'] = 'raw';
497 $init['verify_html'] = $settings['verify_html'] ? $settings['verify_html'] : 'false';
498 $init['preformatted'] = $settings['preformatted'] ? $settings['preformatted'] : 'false';
499 $init['convert_fonts_to_styles'] = $settings['convert_fonts_to_styles'] ? $settings['convert_fonts_to_styles'] : 'false';
500 if ($init['theme'] == 'advanced') {
501 $init['plugins'] = array();
502 $init['theme_advanced_toolbar_location'] = $settings['toolbar_loc'] ? $settings['toolbar_loc'] : 'bottom';
503 $init['theme_advanced_toolbar_align'] = $settings['toolbar_align'] ? $settings['toolbar_align'] : 'left';
504 $init['theme_advanced_path_location'] = $settings['path_loc'] ? $settings['path_loc'] : 'bottom';
505 $init['theme_advanced_resizing'] = $settings['resizing'] ? $settings['resizing'] : 'true';
506 $init['theme_advanced_blockformats'] = $settings['block_formats'] ? $settings['block_formats'] : 'p,address,pre,h1,h2,h3,h4,h5,h6';
507
508 if (is_array($settings['buttons'])) {
509 // This gives us the $plugins variable.
510 $plugins = _tinymce_get_buttons();
511
512 // Find the enabled buttons and the mce row they belong on. Also map the
513 // plugin metadata for each button.
514 $plugin_tracker = array();
515 foreach ($plugins as $rname => $rplugin) { // Plugin name
516 foreach ($rplugin as $mce_key => $mce_value) { // TinyMCE key
517 foreach ($mce_value as $k => $v) { // Buttons
518 if ($settings['buttons'][$rname . '-' . $v]) {
519 // Font isn't a true plugin, rather it's buttons made available by the advanced theme
520 if (!in_array($rname, $plugin_tracker) && $rname != 'font') $plugin_tracker[] = $rname;
521 $init[$mce_key][] = $v;
522 }
523 }
524 }
525 // Some advanced plugins only have an $rname and no buttons
526 if ($settings['buttons'][$rname]) {
527 if (!in_array($rname, $plugin_tracker)) $plugin_tracker[] = $rname;
528 }
529 }
530
531 // Add the rest of the TinyMCE config options to the $init array for each button.
532 if (is_array($plugin_tracker)) {
533 foreach ($plugin_tracker as $pname) {
534 if ($pname != 'default') $init['plugins'][] = $pname;
535 foreach ($plugins[$pname] as $mce_key => $mce_value) {
536 // Don't overwrite buttons or extended_valid_elements
537 if ($mce_key == 'extended_valid_elements') {
538 // $mce_value is an array for extended_valid_elements so just grab the first element in the array (never more than one)
539 $init[$mce_key][] = $mce_value[0];
540 }
541 else if (!strstr($mce_key, 'theme_advanced_buttons')) {
542 $init[$mce_key] = $mce_value;
543 }
544 }
545 }
546 }
547
548 // Cleanup
549 foreach ($init as $mce_key => $mce_value) {
550 if (is_array($mce_value)) $mce_value = array_unique($mce_value);
551 $init[$mce_key] = $mce_value;
552 }
553
554 // Shuffle buttons around so that row 1 always has the most buttons,
555 // followed by row 2, etc. Note: These rows need to be set to NULL otherwise
556 // TinyMCE loads it's own buttons inherited from the theme.
557 if (!$init['theme_advanced_buttons1']) $init['theme_advanced_buttons1'] = array();
558 if (!$init['theme_advanced_buttons2']) $init['theme_advanced_buttons2'] = array();
559 if (!$init['theme_advanced_buttons3']) $init['theme_advanced_buttons3'] = array();
560
561 $min_btns = 5; // Minimum number of buttons per row.
562 $num1 = count($init['theme_advanced_buttons1']);
563 $num2 = count($init['theme_advanced_buttons2']);
564 $num3 = count($init['theme_advanced_buttons3']);
565
566 if ($num3 < $min_btns) {
567 $init['theme_advanced_buttons2'] = array_merge($init['theme_advanced_buttons2'], $init['theme_advanced_buttons3']);
568 $init['theme_advanced_buttons3'] = array();
569 $num2 = count($init['theme_advanced_buttons2']);
570 }
571 if ($num2 < $min_btns) {
572 $init['theme_advanced_buttons1'] = array_merge($init['theme_advanced_buttons1'], $init['theme_advanced_buttons2']);
573 // Squish the rows together, since row 2 is empty
574 $init['theme_advanced_buttons2'] = $init['theme_advanced_buttons3'];
575 $init['theme_advanced_buttons3'] = array();
576 $num1 = count($init['theme_advanced_buttons1']);
577 }
578 if ($num1 < $min_btns) {
579 $init['theme_advanced_buttons1'] = array_merge($init['theme_advanced_buttons1'], $init['theme_advanced_buttons2']);
580 // Squish the rows together, since row 2 is empty
581 $init['theme_advanced_buttons2'] = $init['theme_advanced_buttons3'];
582 $init['theme_advanced_buttons3'] = array();
583 }
584
585 }
586 }
587
588 if ($settings['css_classes']) $init['theme_advanced_styles'] = $settings['css_classes'];
589
590 if ($settings['css_setting'] == 'theme') {
591 $css = $themepath . 'style.css';
592 if (file_exists($css)) {
593 $init['content_css'] = $host . $css;
594 }
595 }
596 else if ($settings['css_setting'] == 'self') {
597 $init['content_css'] = str_replace(array('%h', '%t'), array($host, $themepath), $settings['css_path']);
598 }
599
600 return $init;
601 }
602
603 /**
604 * Remove a profile from the database.
605 */
606 function tinymce_profile_delete($name) {
607 db_query("DELETE FROM {tinymce_settings} WHERE name = '%s'", $name);
608 db_query("DELETE FROM {tinymce_role} WHERE name = '%s'", $name);
609 }
610
611 /**
612 * Return an HTML form for profile configuration.
613 */
614 function tinymce_profile_form($edit) {
615 $edit = (object) $edit;
616
617 // Only display the roles that currently don't have a tinymce profile. One
618 // profile per role.
619 $orig_roles = user_roles(FALSE, 'access tinymce');
620 $roles = $orig_roles;
621 if (arg(3) == 'add') {
622 $result = db_query('SELECT DISTINCT(rid) FROM {tinymce_role}');
623 while ($data = db_fetch_object($result)) {
624 unset($roles[$data->rid]);
625 }
626 if (!$orig_roles) {
627 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/access'))), 'error');
628 }
629 else if (!$roles) {
630 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');
631 }
632 else if (count($orig_roles) != count($roles)) {
633 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.'));
634 }
635 $btn = t('Create profile');
636 }
637 else {
638 $form['old_name'] = array('#type' => 'hidden', '#value' => $edit->name);
639 $btn = t('Update profile');
640 }
641
642 $form['basic'] = array('#type' => 'fieldset', '#title' => t('Basic setup'), '#collapsible' => TRUE, '#collapsed' => TRUE);
643 $form['basic']['name'] = array('#type' => 'textfield', '#title' => t('Profile name'), '#default_value' => $edit->name, '#size' => 40, '#maxlength' => 128, '#description' => t('Enter a name for this profile. This name is only visible within the tinymce administration page.'), '#required' => TRUE);
644 $form['basic']['rids'] = array('#type' => 'checkboxes', '#title' => t('Roles allowed to use this profile'), '#default_value' => array_keys((array) $edit->rids), '#options' => $roles, '#description' => t('Check at least one role. Only roles with \'access tinymce\' permission will be shown here.'), '#required' => TRUE);
645 // This line upgrades previous versions of TinyMCE for user who previously selected a theme other than advanced.
646 if ($edit->settings['theme'] != 'advanced') $edit->settings['theme'] = 'advanced';
647 $form['basic']['theme'] = array('#type' => 'hidden', '#value' => $edit->settings['theme'] ? $edit->settings['theme'] : 'advanced');
648 $languages = 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', 'sk', 'sv', 'th', 'zh_cn', 'zh_tw', 'zh_tw_utf8'));
649 $form['basic']['language'] = array('#type' => 'select', '#title' => t('Language'), '#default_value' => $edit->settings['language'] ? $edit->settings['language'] : 'en', '#options' => $languages, '#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.'));
650
651 $form['visibility'] = array('#type' => 'fieldset', '#title' => t('Visibility'), '#collapsible' => TRUE, '#collapsed' => TRUE);
652 $access = user_access('use PHP for block visibility');
653
654 // 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
655 if ($edit->settings['access'] == 2 && !$access) {
656 $form['visibility'] = array();
657 $form['visibility']['access'] = array('#type' => 'value', '#value' => 2);
658 $form['visibility']['access_pages'] = array('#type' => 'value', '#value' => $edit->settings['access_pages']);
659 }
660 else {
661 $options = array(t('Show on every page except the listed pages.'), t('Show on only the listed pages.'));
662 $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>')));
663
664 if ($access) {
665 $options[] = t('Show if the following PHP code returns <code>TRUE</code> (PHP-mode, experts only).');
666 $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 ?>')));
667 }
668 $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);
669 $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);
670 }
671
672 $form['buttons'] = array('#type' => 'fieldset', '#title' => t('Buttons and plugins'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#tree' => TRUE, '#theme' => 'tinymce_profile_form_buttons');
673
674 $metadata = _tinymce_get_buttons(FALSE);
675 // Generate the button list.
676 foreach($metadata as $name => $meta) {
677 if (is_array($meta['buttons'])) {
678 foreach ($meta['buttons'] as $button) {
679 if ($name != 'default') {
680 $img_src = drupal_get_path('module', 'tinymce'). "/tinymce/jscripts/tiny_mce/plugins/$name/images/$name.gif";
681
682 //correct for plugins that have more than one button
683 if (!file_exists($img_src)) {
684 $img_src = drupal_get_path('module', 'tinymce'). "/tinymce/jscripts/tiny_mce/plugins/$name/images/$button.gif";
685 }
686 }
687 else {
688 $img_src = drupal_get_path('module', 'tinymce'). "/tinymce/jscripts/tiny_mce/themes/advanced/images/$button.gif";
689 }
690
691 $b = file_exists($img_src) ? '<img src="'. base_path(). $img_src .'" title="'. $button .'" style="border: 1px solid grey; vertical-align: middle;" />' : $button;
692
693 if ($name == 'default') {
694 $title = $b;
695 }
696 else {
697 $title = $metadata[$name]['longname'] ? $metadata[$name]['longname'] : $name;
698 if ($metadata[$name]['infourl']) {
699 $title = '<a href="'. $metadata[$name]['infourl'] .'" target="_blank">'. $title .'</a>';
700 }
701 $title = $b . ' &#8211; '. $title;
702 }
703 $form_value = $edit->settings['buttons'][$name . '-' . $button];
704 $form['buttons'][$name . '-' . $button] = array('#type' => 'checkbox', '#title' => $title, '#default_value' => $form_value);
705 }
706 }
707 else {
708 $title = $metadata[$name]['longname'] ? $metadata[$name]['longname'] : $name;
709 if ($metadata[$name]['infourl']) {
710 $title = '<a href="'. $metadata[$name]['infourl'] .'" target="_blank">'. $title .'</a>';
711 }
712 $form_value = $edit->settings['buttons'][$name];
713 $form['buttons'][$name] = array('#type' => 'checkbox', '#title' => $title, '#default_value' => $form_value);
714 }
715 }
716
717 $form['appearance'] = array('#type' => 'fieldset', '#title' => t('Editor appearance'), '#collapsible' => TRUE, '#collapsed' => TRUE);
718 $form['appearance']['toolbar_loc'] = array('#type' => 'select', '#title' => t('Toolbar location'), '#default_value' => $edit->settings['toolbar_loc'], '#options' => array('bottom' => 'bottom', 'top' => 'top'), '#description' => t('Show toolbar at the top or bottom of the editor area?'));
719 $form['appearance']['toolbar_align'] = array('#type' => 'select', '#title' => t('Toolbar alignment'), '#default_value' => $edit->settings['toolbar_align'], '#options' => array('center' => 'center', 'left' => 'left', 'right' => 'right'), '#description' => t('Align tool icons left, center, or right within the toolbar.'));
720 $form['appearance']['path_loc'] = array('#type' => 'select', '#title' => t('Path location'), '#default_value' => $edit->settings['path_loc'] ? $edit->settings['path_loc'] : 'bottom', '#options' => array('none' => 'none', 'top' => 'top', 'bottom' => 'bottom'), '#description' => t('Path to html elements (i.e. "body>table>tr>td"). Show at top, bottom, or not at all.'));
721 $form['appearance']['resizing'] = array('#type' => 'select', '#title' => t('Enable resizing button'), '#default_value' => isset($edit->settings['resizing']) ? 'false' : 'true', '#options' => array('false' => 'false', 'true' => '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.'));
722 $form['appearance']['block_formats'] = array('#type' => 'textfield', '#title' => t('Block formats'), '#default_value' => $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.'));
723
724 $form['output'] = array('#type' => 'fieldset', '#title' => t('Cleanup and output'), '#collapsible' => TRUE, '#collapsed' => TRUE);
725 $form['output']['verify_html'] = array('#type' => 'select', '#title' => t('Verify HTML'), '#default_value' => $edit->settings['verify_html'], '#options' => array('true' => 'true', 'false' => 'false'), '#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.'));
726 $form['output']['preformatted'] = array('#type' => 'select', '#title' => t('Preformatted'), '#default_value' => $edit->settings['preformatted'], '#options' => array('false' => 'false', 'true' => '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.'));
727 $form['output']['convert_fonts_to_styles'] = array('#type' => 'select', '#title' => t('Convert &lt;font&gt; tags to styles'), '#default_value' => $edit->settings['convert_fonts_to_styles'], '#options' => array('true' => 'true', 'false' => '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.'));
728
729 $form['css'] = array('#type' => 'fieldset', '#title' => t('CSS'), '#collapsible' => TRUE, '#collapsed' => TRUE);
730 $form['css']['css_setting'] = array('#type' => 'select', '#title' => t('Editor CSS'), '#default_value' => $edit->settings['css_setting'] ? $edit->settings['css_setting'] : 'theme', '#options' => array('theme' => 'use theme css', 'self' => 'define css', 'none' => '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.'));
731 $form['css']['css_path'] = array('#type' => 'textfield', '#title' => t('CSS path'), '#default_value' => $edit->settings['css_path'], '#size' => 40, '#maxlength' => 255, '#description' => t('Enter path to CSS file (example: "css/editor.css").<br />Macros: %h (host name: http://www.example.com/), %t (path to theme: theme/yourtheme/)<br />Be sure to select "define css" above.'));
732 $form['css']['css_classes'] = array('#type' => 'textfield', '#title' => t('CSS classes'), '#default_value' => $edit->settings['css_classes'], '#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.'));
733
734 $form['submit'] = array('#type' => 'submit', '#value' => $btn);
735
736 $output .= drupal_get_form('tinymce_profile_form', $form);
737
738 return $output;
739 }
740
741 /**
742 * Layout for the buttons in the tinymce profile form
743 */
744 function theme_tinymce_profile_form_buttons($form) {
745 $buttons = array();
746
747 // Flatten forms array
748 foreach (element_children($form) as $key) {
749 $buttons[] = form_render($form[$key]);
750 }
751
752 //split checkboxes into rows with 3 columns
753 $total = count($buttons);
754 $rows = array();
755 for ($i = 0; $i < $total; $i++) {
756 $row = array();
757 $row[] = array('data' => $buttons[$i]);
758 $row[] = array('data' => $buttons[++$i]);
759 $row[] = array('data' => $buttons[++$i]);
760 $rows[] = $row;
761 }
762
763 $output = theme('table', array(), $rows, array('width' => '100%'));
764
765 return $output;
766 }
767
768 /**
769 * Load all profiles. Just load one profile if $name is passed in.
770 */
771 function tinymce_profile_load($name = '') {
772 static $profiles = array();
773
774 if (!$profiles) {
775 $roles = user_roles();
776 $result = db_query('SELECT * FROM {tinymce_settings}');
777 while ($data = db_fetch_object($result)) {
778 $data->settings = unserialize($data->settings);
779 $result2 = db_query("SELECT rid FROM {tinymce_role} WHERE name = '%s'", $data->name);
780 $role = array();
781 while ($r = db_fetch_object($result2)) {
782 $role[$r->rid] = $roles[$r->rid];
783 }
784 $data->rids = $role;
785
786 $profiles[$data->name] = $data;
787 }
788 }
789
790 return ($name ? $profiles[$name] : $profiles);
791 }
792
793 /**
794 * Controller for tinymce profiles.
795 */
796 function tinymce_profile_overview() {
797 $output = '';
798
799 $profiles = tinymce_profile_load();
800 if ($profiles) {
801 $output .= t('<p><a href="%create-profile-url">Create new profile</a></p>', array('%create-profile-url' => url('admin/settings/tinymce/add')));
802 $roles = user_roles();
803 $header = array(t('Profile'), t('Roles'), t('Operations'));
804 foreach ($profiles as $p) {
805 $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'));
806 }
807 $output .= theme('table', $header, $rows). '<p>&nbsp;</p>';
808 }
809 else {
810 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'))));
811 }
812
813 $form['settings'] = array('#type' => 'fieldset', '#title' => t('Default settings'), '#collapsible' => TRUE);
814 $form['settings']['tinymce_default_state'] = array('#type' => 'radios', '#title' => t('Default tinymce state'), '#default_value' => variable_get('tinymce_default_state', 0), '#options' => array(t('Off'), t('On')), '#description' => 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.'));
815 $form['settings']['tinymce_safari_message'] = array(
816 '#type' => 'radios', '#title' => t('Safari browser warning'), '#default_value' => variable_get('tinymce_safari_message', 0), '#options' => array(t('Disabled'), t('Enabled')),
817 '#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.')
818 );
819 $form['settings']['submit'] = array('#type' => 'submit', '#value' => t('Save settings'));
820
821 $output .= drupal_get_form('settings', $form);
822
823 return $output;
824 }
825
826 /**
827 * Save a profile to the database.
828 */
829 function tinymce_profile_save($edit) {
830 db_query("DELETE FROM {tinymce_settings} WHERE name = '%s' or name = '%s'", $edit['name'], $edit['old_name']);
831 db_query("DELETE FROM {tinymce_role} WHERE name = '%s' or name = '%s'", $edit['name'], $edit['old_name']);
832 db_query("INSERT INTO {tinymce_settings} (name, settings) VALUES ('%s', '%s')", $edit['name'], serialize($edit));
833 foreach ($edit['rids'] as $rid => $value) {
834 db_query("INSERT INTO {tinymce_role} (name, rid) VALUES ('%s', %d)", $edit['name'], $rid);
835 }
836 }
837
838 /**
839 * Profile validation.
840 */
841 function tinymce_profile_validate($edit) {
842 $errors = array();
843
844 if (!$edit['name']) {
845 $errors['name'] = t('You must give a profile name.');
846 }
847
848 if (!$edit['rids']) {
849 $errors['rids'] = t('You must select at least one role.');
850 }
851
852 foreach ($errors as $name => $message) {
853 form_set_error($name, $message);
854 }
855
856 return count($errors) == 0;
857 }
858
859 /********************************************************************
860 * Module Functions :: Private
861 ********************************************************************/
862
863 /**
864 * Determine if TinyMCE has permission to be used on the current page.
865 *
866 * @return
867 * TRUE if can render, FALSE if not allowed.
868 */
869 function _tinymce_page_match($edit) {
870 $page_match = FALSE;
871
872 //Kill TinyMCE if we're editing a textarea with PHP in it!
873 if ($_POST['edit']['format'] == 2) {
874 return FALSE;
875 }
876 else {
877 // PHP input formats are #2 in the filters table.
878 preg_match("|^node/(\d+)(/edit)$|", $_GET['q'], $match);
879 if (intval($match[1]) > 0) {
880 if (db_result(db_query('SELECT format FROM {node_revisions} WHERE nid = %d AND vid = %d AND format = 2', $match[1], $match[1]))) {
881 return FALSE;
882 }
883 }
884 }
885
886 if ($edit->settings['access_pages']) {
887 // If the PHP option wasn't selected
888 if ($edit->settings['access'] < 2) {
889 $path = drupal_get_path_alias($_GET['q']);
890 $regexp = '/^('. preg_replace(array('/(\r\n?|\n)/', '/\\\\\*/', '/(^|\|)\\\\<front\\\\>($|\|)/'), array('|', '.*', '\1'. preg_quote(variable_get('site_frontpage', 'node'), '/') .'\2'), preg_quote($edit->settings['access_pages'], '/')) .')$/';
891 $page_match = !($edit->settings['access'] xor preg_match($regexp, $path));
892 }
893 else {
894 $page_match = drupal_eval($edit->settings['access_pages']);
895 }
896 }
897 // No pages were specified to block so show on all
898 else {
899 $page_match = TRUE;
900 }
901
902 return $page_match;
903 }