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