#340195 by sun: Fixed #after_build function not invoked on all forms.
[project/wysiwyg.git] / wysiwyg.module
1 <?php
2 // $Id$
3
4 /**
5 * @file
6 * Integrate client-side editors with Drupal.
7 */
8
9 /**
10 * Implementation of hook_menu().
11 */
12 function wysiwyg_menu() {
13 $items = array();
14 $items['admin/settings/wysiwyg/profile'] = array(
15 'title' => 'Wysiwyg',
16 'page callback' => 'wysiwyg_admin',
17 'description' => 'Configure client-side editor profiles.',
18 'access arguments' => array('administer filters'),
19 'file' => 'wysiwyg.admin.inc',
20 );
21 return $items;
22 }
23
24 /**
25 * Implementation of hook_theme().
26 */
27 function wysiwyg_theme() {
28 return array(
29 'wysiwyg_profile_overview' => array('arguments' => array('form' => NULL)),
30 'wysiwyg_admin_button_table' => array('arguments' => array('form' => NULL)),
31 );
32 }
33
34 /**
35 * Implementation of hook_help().
36 */
37 function wysiwyg_help($path, $arg) {
38 switch ($path) {
39 case 'admin/settings/wysiwyg/profile':
40 if (empty($arg[4])) {
41 $output = '<p>'. t('A Wysiwyg profile can be associated to an input format. A Wysiwyg profile defines, which client-side editor is loaded, can define what buttons or themes are enabled for the editor, how the editor is displayed, and a few other editor-specific functions.') .'</p>';
42 return $output;
43 }
44 break;
45 }
46 }
47
48 /**
49 * Implementation of hook_elements().
50 *
51 * @todo Remove #wysiwyg_style; the GUI for an editor should be solely handled
52 * via profiles, when profiles are attached to an input format. It makes no
53 * sense to display TinyMCE's simple GUI/theme for the user signature, when
54 * the input format allows users to use advanced HTML and hence, editor
55 * plugins. Fix this here, in wysiwyg_process_element(), and lastly
56 * in wysiwyg_get_editor_config().
57 */
58 function wysiwyg_elements() {
59 $type = array();
60 // @todo Derive editor theme from input format.
61 $type['textarea'] = array('#wysiwyg_style' => 'advanced');
62 return $type;
63 }
64
65 /**
66 * Implementation of hook_form_alter().
67 *
68 * Before Drupal 7, there is no way to easily identify form fields that are
69 * input format enabled. As a workaround, we assign a form #after_build
70 * processing callback that is executed on all forms after they have been
71 * completely built, so form elements are in their effective order
72 * and position already.
73 *
74 * @see wysiwyg_process_form()
75 */
76 function wysiwyg_form_alter(&$form, &$form_state) {
77 $form['#after_build'][] = 'wysiwyg_process_form';
78 // Disable 'teaser' textarea.
79 if (isset($form['body_field'])) {
80 unset($form['body_field']['teaser_js']);
81 $form['body_field']['teaser_include'] = array();
82 }
83 }
84
85 /**
86 * Process a textarea for Wysiwyg Editor.
87 *
88 * This way, we can recurse into the form and search for certain, hard-coded
89 * elements that have been added by filter_form(). If an input format selector
90 * or input format guidelines element is found, we assume that the preceding
91 * element is the corresponding textarea and use it's #id for attaching
92 * client-side editors.
93 *
94 * @see wysiwyg_elements(), filter_form()
95 */
96 function wysiwyg_process_form(&$form) {
97 // Iterate over element children; resetting array keys to access last index.
98 if ($children = array_values(element_children($form))) {
99 foreach ($children as $index => $item) {
100 $element = &$form[$item];
101
102 // filter_form() always uses the key 'format'. We need a type-agnostic
103 // match to prevent false positives. Also, there must have been at least
104 // one element on this level.
105 if ($item === 'format' && $index > 0) {
106 // Make sure we either match a input format selector or input format
107 // guidelines (displayed if user has access to one input format only).
108 if ((isset($element['#type']) && $element['#type'] == 'fieldset') || isset($element['format']['guidelines'])) {
109 // The element before this element is the target form field.
110 $field = &$form[$children[$index - 1]];
111
112 // Disable #resizable to avoid resizable behavior to hi-jack the UI,
113 // but load the behavior, so the 'none' editor can attach/detach it.
114 $extra_class = '';
115 if (!empty($field['#resizable'])) {
116 // Due to our CSS class parsing, we can add arbitrary parameters
117 // for each input format.
118 $extra_class = ' wysiwyg-resizable-1';
119 $field['#resizable'] = FALSE;
120 drupal_add_js('misc/textarea.js');
121 }
122
123 // Determine the available input formats. The last child element is a
124 // link to "More information about formatting options". When only one
125 // input format is displayed, we also have to remove formatting
126 // guidelines, stored in the child 'format'.
127 $formats = element_children($element);
128 array_pop($formats);
129 if (($key = array_search('format', $formats)) !== FALSE) {
130 unset($formats[$key]);
131 }
132 foreach ($formats as $format) {
133 // Default to 'none' editor (Drupal's default behaviors).
134 $editor = 'none';
135 $theme = '';
136 // Fetch the profile associated to this input format.
137 $profile = wysiwyg_get_profile($format);
138 if ($profile) {
139 $editor = $profile->editor;
140 // Check editor theme (and reset it if not/no longer available).
141 $theme = wysiwyg_get_editor_themes($profile, (isset($field['#wysiwyg_style']) ? $field['#wysiwyg_style'] : ''));
142
143 // Add profile settings for this input format.
144 wysiwyg_add_editor_settings($profile, $theme);
145 // Add plugin settings for this input format.
146 wysiwyg_add_plugin_settings($profile);
147
148 $theme = ' wysiwyg-theme-'. $theme;
149 }
150
151 // Use a prefix/suffix for a single input format, or attach to input
152 // format selector radio buttons.
153 if (isset($element['format']['guidelines'])) {
154 $element['format']['guidelines']['#prefix'] = '<div class="wysiwyg wysiwyg-editor-'. $editor .' wysiwyg-field-'. $field['#id'] . $theme . $extra_class .'">';
155 $element['format']['guidelines']['#suffix'] = '</div>';
156 // Edge-case: Default format contains no input filters.
157 if (empty($element['format']['guidelines']['#value'])) {
158 $element['format']['guidelines']['#value'] = ' ';
159 }
160 }
161 else {
162 if (isset($element[$format]['#attributes']['class'])) {
163 $element[$format]['#attributes']['class'] .= ' ';
164 }
165 else {
166 $element[$format]['#attributes']['class'] = '';
167 }
168 $element[$format]['#attributes']['class'] .= 'wysiwyg wysiwyg-editor-'. $editor .' wysiwyg-field-'. $field['#id'] . $theme . $extra_class;
169 }
170 }
171 }
172 // If this element is 'format', do not recurse further.
173 continue;
174 }
175 // Recurse into children.
176 wysiwyg_process_form($element);
177 }
178 }
179 return $form;
180 }
181
182 /**
183 * Determine the profile to use for a given input format id.
184 *
185 * This function also performs sanity checks for the configured editor in a
186 * profile to ensure that we do not load a malformed editor.
187 *
188 * @param $format
189 * The internal id of an input format.
190 *
191 * @return
192 * A wysiwyg profile.
193 *
194 * @see wysiwyg_load_editor(), wysiwyg_get_editor()
195 */
196 function wysiwyg_get_profile($format) {
197 if ($profile = wysiwyg_load_profile($format)) {
198 if (wysiwyg_load_editor($profile)) {
199 return $profile;
200 }
201 }
202 return FALSE;
203 }
204
205 /**
206 * Load an editor library and initialize basic Wysiwyg settings.
207 *
208 * @param $profile
209 * A wysiwyg editor profile.
210 *
211 * @return
212 * TRUE if the editor has been loaded, FALSE if not.
213 *
214 * @see wysiwyg_get_profile()
215 */
216 function wysiwyg_load_editor($profile) {
217 static $settings_added;
218 static $loaded = array();
219
220 $name = $profile->editor;
221 // Library files must be loaded only once.
222 if (!isset($loaded[$name])) {
223 // Load editor.
224 $editor = wysiwyg_get_editor($name);
225 if ($editor) {
226 // Determine library files to load.
227 // @todo Allow to configure the library/execMode to use.
228 if (isset($profile->settings['library']) && isset($editor['libraries'][$profile->settings['library']])) {
229 $library = $profile->settings['library'];
230 $files = $editor['libraries'][$profile->settings['library']]['files'];
231 }
232 else {
233 // Fallback to the first by default (external libraries can change).
234 $library = key($editor['libraries']);
235 $files = array_shift($editor['libraries']);
236 $files = $files['files'];
237 }
238 foreach ($files as $file) {
239 drupal_add_js($editor['library path'] . '/' . $file);
240 }
241 // Load JavaScript integration files for this editor.
242 $files = array();
243 if (isset($editor['js files'])) {
244 $files = $editor['js files'];
245 }
246 foreach ($files as $file) {
247 drupal_add_js($editor['js path'] . '/' . $file);
248 }
249 // Load CSS stylesheets for this editor.
250 $files = array();
251 if (isset($editor['css files'])) {
252 $files = $editor['css files'];
253 }
254 foreach ($files as $file) {
255 drupal_add_css($editor['css path'] . '/' . $file, 'module', 'screen');
256 }
257
258 $status = wysiwyg_user_get_status($profile);
259 drupal_add_js(array('wysiwyg' => array(
260 'configs' => array($editor['name'] => array()),
261 // @todo Move into profile settings.
262 'showToggle' => isset($profile->settings['show_toggle']) ? $profile->settings['show_toggle'] : TRUE,
263 // @todo http://drupal.org/node/322433
264 'status' => $status,
265 // @todo Move into (global) editor settings.
266 // If JS compression is enabled, at least TinyMCE is unable to determine
267 // its own base path and exec mode since it can't find the script name.
268 'editorBasePath' => base_path() . $editor['library path'],
269 'execMode' => $library,
270 )), 'setting');
271
272 $loaded[$name] = TRUE;
273 }
274 else {
275 $loaded[$name] = FALSE;
276 }
277 }
278
279 // Add basic Wysiwyg settings if any editor has been added.
280 if (!isset($settings_added) && $loaded[$name]) {
281 drupal_add_js(array('wysiwyg' => array(
282 'configs' => array(),
283 'disable' => t('Disable rich-text'),
284 'enable' => t('Enable rich-text'),
285 )), 'setting');
286
287 // Initialize our namespaces in the *header* to do not force editor
288 // integration scripts to check and define Drupal.wysiwyg on its own.
289 drupal_add_js(wysiwyg_get_path('wysiwyg.init.js'), 'core');
290
291 // The 'none' editor is a special editor implementation, allowing us to
292 // attach and detach regular Drupal behaviors just like any other editor.
293 drupal_add_js(wysiwyg_get_path('editors/js/none.js'));
294
295 // Add wysiwyg.js to the footer to ensure it's executed after the
296 // Drupal.settings array has been rendered and populated. Also, since editor
297 // library initialization functions must be loaded first by the browser,
298 // and Drupal.wysiwygInit() must be executed AFTER editors registered
299 // their callbacks and BEFORE Drupal.behaviors are applied, this must come
300 // last.
301 drupal_add_js(wysiwyg_get_path('wysiwyg.js'), 'module', 'footer');
302
303 $settings_added = TRUE;
304 }
305
306 return $loaded[$name];
307 }
308
309 /**
310 * Register a theme.
311 */
312 function wysiwyg_add_editor_settings($profile, $theme) {
313 static $editors = array();
314
315 if (!isset($editors[$profile->editor][$theme])) {
316 $config = wysiwyg_get_editor_config($profile, $theme);
317 drupal_add_js(array('wysiwyg' => array('configs' => array($profile->editor => array($theme => $config)))), 'setting');
318 $editors[$profile->editor][$theme] = TRUE;
319 }
320 }
321
322 /**
323 * Add settings for external plugins.
324 *
325 * @param $profile
326 * A wysiwyg editor profile.
327 */
328 function wysiwyg_add_plugin_settings($profile) {
329 static $plugins_added = array();
330
331 if (!isset($plugins_added[$profile->editor])) {
332 $plugins = array();
333 $editor = wysiwyg_get_editor($profile->editor);
334 // Collect editor plugins provided via hook_wysiwyg_plugin().
335 $info = module_invoke_all('wysiwyg_plugin', $editor['name'], $editor['installed version']);
336 // Only keep enabled plugins in this profile.
337 foreach ($info as $plugin => $meta) {
338 if (!isset($profile->settings['buttons'][$plugin])) {
339 unset($info[$plugin]);
340 }
341 }
342
343 if (isset($editor['plugin settings callback']) && function_exists($editor['plugin settings callback'])) {
344 $plugins = $editor['plugin settings callback']($editor, $profile, $info);
345 }
346
347 drupal_add_js(array('wysiwyg' => array('plugins' => array($profile->editor => $plugins))), 'setting');
348
349 $plugins_added[$profile->editor] = TRUE;
350 }
351 }
352
353 /**
354 * Grab the themes available to Wysiwyg Editor.
355 *
356 * Wysiwyg Editor themes control the functionality and buttons that are available to a
357 * user. Themes are only looked for within the default Wysiwyg Editor theme directory.
358 *
359 * @param $profile
360 * A wysiwyg editor profile; passed/altered by reference.
361 * @param $selected_theme
362 * An optional theme name that ought to be used.
363 *
364 * @return
365 * An array of theme names, or a single, checked theme name if $selected_theme
366 * was given.
367 */
368 function wysiwyg_get_editor_themes(&$profile, $selected_theme = NULL) {
369 static $themes = array();
370
371 if (!isset($themes[$profile->editor])) {
372 $editor = wysiwyg_get_editor($profile->editor);
373 if (isset($editor['themes callback']) && function_exists($editor['themes callback'])) {
374 $themes[$editor['name']] = $editor['themes callback']($editor, $profile);
375 }
376 // Fallback to 'default' otherwise.
377 else {
378 $themes[$editor['name']] = array('default');
379 }
380 }
381
382 // Check optional $selected_theme argument, if given.
383 if (isset($selected_theme)) {
384 // If the passed theme name does not exist, use the first available.
385 if (!isset($themes[$profile->editor][$selected_theme])) {
386 $selected_theme = $profile->settings['theme'] = $themes[$profile->editor][0];
387 }
388 }
389
390 return isset($selected_theme) ? $selected_theme : $themes[$profile->editor];
391 }
392
393 /**
394 * Return plugin metadata from the plugin registry.
395 *
396 * @param $editor_name
397 * The internal name of an editor to return plugins for.
398 *
399 * @return
400 * An array for each plugin.
401 */
402 function wysiwyg_get_plugins($editor_name) {
403 $plugins = array();
404 if (!empty($editor_name)) {
405 $editor = wysiwyg_get_editor($editor_name);
406 // Add internal editor plugins.
407 if (isset($editor['plugin callback']) && function_exists($editor['plugin callback'])) {
408 $plugins = $editor['plugin callback']($editor);
409 }
410 // Load our own plugins.
411 include_once drupal_get_path('module', 'wysiwyg') .'/wysiwyg.plugins.inc';
412
413 // Add editor plugins provided via hook_wysiwyg_plugin().
414 $plugins = array_merge($plugins, module_invoke_all('wysiwyg_plugin', $editor['name'], $editor['installed version']));
415 }
416 return $plugins;
417 }
418
419 /**
420 * Return an array of initial Wysiwyg Editor config options from the current role.
421 */
422 function wysiwyg_get_editor_config($profile, $theme) {
423 $editor = wysiwyg_get_editor($profile->editor);
424 $settings = array();
425 if (!empty($editor['settings callback']) && function_exists($editor['settings callback'])) {
426 $settings = $editor['settings callback']($editor, $profile->settings, $theme);
427 }
428 return $settings;
429 }
430
431 /**
432 * Load all profiles. Just load one profile if $name is passed in.
433 */
434 function wysiwyg_load_profile($format = '') {
435 static $profiles;
436
437 if (!isset($profiles)) {
438 $profiles = array();
439 $result = db_query('SELECT * FROM {wysiwyg}');
440 while ($profile = db_fetch_object($result)) {
441 $profile->settings = unserialize($profile->settings);
442 $profiles[$profile->format] = $profile;
443 }
444 }
445
446 return ($format && isset($profiles[$format]) ? $profiles[$format] : ($format ? FALSE : $profiles));
447 }
448
449 /**
450 * Implementation of hook_user().
451 */
452 function wysiwyg_user($type, &$edit, &$user, $category = NULL) {
453 if ($type == 'form' && $category == 'account') {
454 // @todo http://drupal.org/node/322433
455 $profile = new stdClass;
456 if (isset($profile->settings['user_choose']) && $profile->settings['user_choose']) {
457 $form['wysiwyg'] = array(
458 '#type' => 'fieldset',
459 '#title' => t('Wysiwyg Editor settings'),
460 '#weight' => 10,
461 '#collapsible' => TRUE,
462 '#collapsed' => TRUE,
463 );
464 $form['wysiwyg']['wysiwyg_status'] = array(
465 '#type' => 'checkbox',
466 '#title' => t('Enable editor by default'),
467 '#default_value' => isset($user->wysiwyg_status) ? $user->wysiwyg_status : (isset($profile->settings['default']) ? $profile->settings['default'] : FALSE),
468 '#return_value' => 1,
469 '#description' => t('If enabled, rich-text editing is enabled by default in textarea fields.'),
470 );
471 return array('wysiwyg' => $form);
472 }
473 }
474 elseif ($type == 'validate' && isset($edit['wysiwyg_status'])) {
475 return array('wysiwyg_status' => $edit['wysiwyg_status']);
476 }
477 }
478
479 function wysiwyg_user_get_status($profile) {
480 global $user;
481
482 if ($profile->settings['user_choose'] && isset($user->wysiwyg_status)) {
483 $status = $user->wysiwyg_status;
484 }
485 else {
486 $status = isset($profile->settings['default']) ? $profile->settings['default'] : TRUE;
487 }
488
489 return $status;
490 }
491
492 /**
493 * @defgroup wysiwyg_api Wysiwyg API
494 * @{
495 *
496 * @todo Forked from Panels; abstract into a separate API module that allows
497 * contrib modules to define supported include/plugin types.
498 */
499
500 /**
501 * Return library information for a given editor.
502 *
503 * @param $name
504 * The internal name of an editor.
505 *
506 * @return
507 * The library information for the editor, or FALSE if $name is unknown or not
508 * installed properly.
509 */
510 function wysiwyg_get_editor($name) {
511 $editors = wysiwyg_get_all_editors();
512 return isset($editors[$name]) && $editors[$name]['installed'] ? $editors[$name] : FALSE;
513 }
514
515 /**
516 * Compile a list holding all supported editors including installed editor version information.
517 */
518 function wysiwyg_get_all_editors() {
519 static $editors;
520
521 if (isset($editors)) {
522 return $editors;
523 }
524
525 $editors = wysiwyg_load_includes('editors', 'editor');
526 foreach ($editors as $editor => $properties) {
527 // Fill in required properties.
528 $editors[$editor] += array(
529 'title' => '',
530 'vendor url' => '',
531 'download url' => '',
532 'editor path' => wysiwyg_get_path($properties['name']),
533 'library path' => wysiwyg_get_path($properties['name']),
534 'libraries' => array(),
535 'version callback' => NULL,
536 'themes callback' => NULL,
537 'settings callback' => NULL,
538 'plugin callback' => NULL,
539 'plugin settings callback' => NULL,
540 'versions' => array(),
541 'js path' => $properties['path'] .'/js',
542 'css path' => $properties['path'] .'/css',
543 );
544 // Check whether library is present.
545 if (!($editors[$editor]['installed'] = file_exists($properties['library path']))) {
546 continue;
547 }
548 // Detect library version.
549 if (function_exists($editors[$editor]['version callback'])) {
550 $editors[$editor]['installed version'] = $editors[$editor]['version callback']($properties);
551 }
552 if (empty($editors[$editor]['installed version'])) {
553 $editors[$editor]['error'] = t('The version of %editor could not be detected.', array('%editor' => $properties['title']));
554 $editors[$editor]['installed'] = FALSE;
555 continue;
556 }
557 // Determine to which supported version the installed version maps.
558 ksort($editors[$editor]['versions']);
559 $version = 0;
560 foreach ($editors[$editor]['versions'] as $supported_version => $version_properties) {
561 if (version_compare($editors[$editor]['installed version'], $supported_version, '>=')) {
562 $version = $supported_version;
563 }
564 }
565 if (!$version) {
566 $editors[$editor]['error'] = t('The installed version %version of %editor is not supported.', array('%version' => $editors[$editor]['installed version'], '%editor' => $properties['title']));
567 $editors[$editor]['installed'] = FALSE;
568 continue;
569 }
570 // Apply library version specific definitions and overrides.
571 $editors[$editor] = array_merge($editors[$editor], $editors[$editor]['versions'][$version]);
572 unset($editors[$editor]['versions']);
573 $editors[$editor]['title'] = $editors[$editor]['title'] . ' ' . $editors[$editor]['installed version'];
574 }
575 return $editors;
576 }
577
578 /**
579 * Load include files for wysiwyg implemented by all modules.
580 *
581 * @param $type
582 * The type of includes to search for, can be 'editors'.
583 * @param $hook
584 * The hook name to invoke.
585 * @param $file
586 * An optional include file name without .inc extension to limit the search to.
587 *
588 * @see wysiwyg_get_directories(), _wysiwyg_process_include()
589 */
590 function wysiwyg_load_includes($type = 'editors', $hook = 'editor', $file = NULL) {
591 // Determine implementations.
592 $directories = wysiwyg_get_directories($type);
593 $directories['wysiwyg_'] = wysiwyg_get_path($type);
594 $file_list = array();
595 foreach ($directories as $module => $path) {
596 $file_list[$module] = drupal_system_listing("$file" . '.inc$', $path, 'name', 0);
597 }
598
599 // Load implementations.
600 $info = array();
601 foreach (array_filter($file_list) as $module => $files) {
602 foreach ($files as $file) {
603 include_once './' . $file->filename;
604 $result = _wysiwyg_process_include('wysiwyg', $module . $file->name, dirname($file->filename), $hook);
605 if (is_array($result)) {
606 $info = array_merge($info, $result);
607 }
608 }
609 }
610 return $info;
611 }
612
613 /**
614 * Helper function to build module/file paths.
615 *
616 * @param $file
617 * A file or directory in a module to return.
618 * @param $base_path
619 * Whether to prefix the resulting path with base_path().
620 * @param $module
621 * The module name to use as prefix.
622 *
623 * @return
624 * The path to the specified file in a module.
625 */
626 function wysiwyg_get_path($file = '', $base_path = FALSE, $module = 'wysiwyg') {
627 $base_path = ($base_path ? base_path() : '');
628 return $base_path . drupal_get_path('module', $module) . '/' . $file;
629 }
630
631 /**
632 * Return a list of directories by modules implementing wysiwyg_include_directory().
633 *
634 * @param $plugintype
635 * The type of a plugin; can be 'editors'.
636 *
637 * @return
638 * An array containing module names suffixed with '_' and their defined
639 * directory.
640 *
641 * @see wysiwyg_load_includes(), _wysiwyg_process_include()
642 */
643 function wysiwyg_get_directories($plugintype) {
644 $directories = array();
645 foreach (module_implements('wysiwyg_include_directory') as $module) {
646 $result = module_invoke($module, 'wysiwyg_include_directory', $plugintype);
647 if (isset($result) && is_string($result)) {
648 $directories[$module .'_'] = drupal_get_path('module', $module) .'/'. $result;
649 }
650 }
651 return $directories;
652 }
653
654 /**
655 * Process a single hook implementation of a wysiwyg editor.
656 *
657 * @param $module
658 * The module that owns the hook.
659 * @param $identifier
660 * Either the module or 'wysiwyg_' . $file->name
661 * @param $hook
662 * The name of the hook being invoked.
663 */
664 function _wysiwyg_process_include($module, $identifier, $path, $hook) {
665 $function = $identifier . '_' . $hook;
666 if (!function_exists($function)) {
667 return NULL;
668 }
669 $result = $function();
670 if (!isset($result) || !is_array($result)) {
671 return NULL;
672 }
673
674 // Fill in defaults.
675 foreach ($result as $editor => $properties) {
676 $result[$editor]['module'] = $module;
677 $result[$editor]['name'] = $editor;
678 $result[$editor]['path'] = $path;
679 }
680 return $result;
681 }
682
683 /**
684 * @} End of "defgroup wysiwyg_api".
685 */
686