Issue #1078834 by sun: Fixed coding standards errors.
[project/wysiwyg.git] / wysiwyg.module
1 <?php
2
3 /**
4 * @file
5 * Integrates client-side editors with Drupal.
6 */
7
8 /**
9 * Implements hook_entity_info().
10 */
11 function wysiwyg_entity_info() {
12 $types['wysiwyg_profile'] = array(
13 'label' => t('Wysiwyg profile'),
14 'base table' => 'wysiwyg',
15 'controller class' => 'WysiwygProfileController',
16 'fieldable' => FALSE,
17 // When loading all entities, DrupalDefaultEntityController::load() ignores
18 // its static cache. Therefore, wysiwyg_profile_load_all() implements a
19 // custom static cache.
20 'static cache' => FALSE,
21 'entity keys' => array(
22 'id' => 'format',
23 ),
24 );
25 return $types;
26 }
27
28 /**
29 * Controller class for Wysiwyg profiles.
30 */
31 class WysiwygProfileController extends DrupalDefaultEntityController {
32 /**
33 * Overrides DrupalDefaultEntityController::attachLoad().
34 */
35 function attachLoad(&$queried_entities, $revision_id = FALSE) {
36 // Unserialize the profile settings.
37 foreach ($queried_entities as $key => $record) {
38 $queried_entities[$key]->settings = unserialize($record->settings);
39 }
40 // Call the default attachLoad() method.
41 parent::attachLoad($queried_entities, $revision_id);
42 }
43 }
44
45 /**
46 * Implementation of hook_menu().
47 */
48 function wysiwyg_menu() {
49 $items['admin/config/content/wysiwyg'] = array(
50 'title' => 'Wysiwyg profiles',
51 'page callback' => 'drupal_get_form',
52 'page arguments' => array('wysiwyg_profile_overview'),
53 'description' => 'Configure client-side editors.',
54 'access arguments' => array('administer filters'),
55 'file' => 'wysiwyg.admin.inc',
56 );
57 $items['admin/config/content/wysiwyg/profile'] = array(
58 'title' => 'List',
59 'type' => MENU_DEFAULT_LOCAL_TASK,
60 );
61 $items['admin/config/content/wysiwyg/profile/%wysiwyg_profile/edit'] = array(
62 'title' => 'Edit',
63 'page callback' => 'drupal_get_form',
64 'page arguments' => array('wysiwyg_profile_form', 5),
65 'access arguments' => array('administer filters'),
66 'file' => 'wysiwyg.admin.inc',
67 'tab_root' => 'admin/config/content/wysiwyg/profile',
68 'tab_parent' => 'admin/config/content/wysiwyg/profile/%wysiwyg_profile',
69 'type' => MENU_LOCAL_TASK,
70 );
71 $items['admin/config/content/wysiwyg/profile/%wysiwyg_profile/delete'] = array(
72 'title' => 'Remove',
73 'page callback' => 'drupal_get_form',
74 'page arguments' => array('wysiwyg_profile_delete_confirm', 5),
75 'access arguments' => array('administer filters'),
76 'file' => 'wysiwyg.admin.inc',
77 'tab_root' => 'admin/config/content/wysiwyg/profile',
78 'tab_parent' => 'admin/config/content/wysiwyg/profile/%wysiwyg_profile',
79 'type' => MENU_LOCAL_TASK,
80 'weight' => 10,
81 );
82 $items['wysiwyg/%'] = array(
83 'page callback' => 'wysiwyg_dialog',
84 'page arguments' => array(1),
85 'access arguments' => array('access content'),
86 'type' => MENU_CALLBACK,
87 'file' => 'wysiwyg.dialog.inc',
88 );
89 return $items;
90 }
91
92 /**
93 * Implementation of hook_theme().
94 *
95 * @see drupal_common_theme(), common.inc
96 * @see template_preprocess_page(), theme.inc
97 */
98 function wysiwyg_theme() {
99 return array(
100 'wysiwyg_profile_overview' => array(
101 'render element' => 'form',
102 ),
103 'wysiwyg_admin_button_table' => array(
104 'render element' => 'form',
105 ),
106 'wysiwyg_dialog_page' => array(
107 'variables' => array('content' => NULL, 'show_messages' => TRUE),
108 'file' => 'wysiwyg.dialog.inc',
109 'template' => 'wysiwyg-dialog-page',
110 ),
111 );
112 }
113
114 /**
115 * Implementation of hook_help().
116 */
117 function wysiwyg_help($path, $arg) {
118 switch ($path) {
119 case 'admin/config/content/wysiwyg':
120 $output = '<p>' . t('A Wysiwyg profile is associated with an input format. A Wysiwyg profile defines which client-side editor is loaded with a particular input format, what buttons or themes are enabled for the editor, how the editor is displayed, and a few other editor-specific functions.') . '</p>';
121 return $output;
122 }
123 }
124
125 /**
126 * Implementation of hook_form_alter().
127 */
128 function wysiwyg_form_alter(&$form, &$form_state) {
129 // Teaser splitter is unconditionally removed and NOT supported.
130 if (isset($form['body_field'])) {
131 unset($form['body_field']['teaser_js']);
132 }
133 }
134
135 /**
136 * Implements hook_element_info_alter().
137 */
138 function wysiwyg_element_info_alter(&$types) {
139 $types['text_format']['#pre_render'][] = 'wysiwyg_pre_render_text_format';
140 }
141
142 /**
143 * Process a text format widget to load and attach editors.
144 *
145 * The element's #id is used as reference to attach client-side editors.
146 */
147 function wysiwyg_pre_render_text_format($element) {
148 // filter_process_format() copies properties to the expanded 'value' child
149 // element. Skip this text format widget, if it contains no 'format' or when
150 // the current user does not have access to edit the value.
151 if (!isset($element['format']) || !empty($element['value']['#disabled'])) {
152 return $element;
153 }
154 // Allow modules to programmatically enforce no client-side editor by setting
155 // the #wysiwyg property to FALSE.
156 if (isset($element['#wysiwyg']) && !$element['#wysiwyg']) {
157 return $element;
158 }
159
160 $format_field = &$element['format'];
161 $field = &$element['value'];
162 $settings = array(
163 'field' => $field['#id'],
164 );
165
166 // If this textarea is #resizable and we will load at least one
167 // editor, then only load the behavior and let the 'none' editor
168 // attach/detach it to avoid hi-jacking the UI. Due to our CSS class
169 // parsing, we can add arbitrary parameters for each input format.
170 // The #resizable property will be removed below, if at least one
171 // profile has been loaded.
172 $resizable = 0;
173 if (!empty($field['#resizable'])) {
174 $resizable = 1;
175 drupal_add_js('misc/textarea.js');
176 }
177 // Determine the available text formats.
178 foreach ($format_field['format']['#options'] as $format_id => $format_name) {
179 $format = 'format' . $format_id;
180 // Initialize default settings, defaulting to 'none' editor.
181 $settings[$format] = array(
182 'editor' => 'none',
183 'status' => 1,
184 'toggle' => 1,
185 'resizable' => $resizable,
186 );
187
188 // Fetch the profile associated to this text format.
189 $profile = wysiwyg_get_profile($format_id);
190 if ($profile) {
191 $loaded = TRUE;
192 $settings[$format]['editor'] = $profile->editor;
193 $settings[$format]['status'] = (int) wysiwyg_user_get_status($profile);
194 if (isset($profile->settings['show_toggle'])) {
195 $settings[$format]['toggle'] = (int) $profile->settings['show_toggle'];
196 }
197 // Check editor theme (and reset it if not/no longer available).
198 $theme = wysiwyg_get_editor_themes($profile, (isset($profile->settings['theme']) ? $profile->settings['theme'] : ''));
199
200 // Add plugin settings (first) for this text format.
201 wysiwyg_add_plugin_settings($profile);
202 // Add profile settings for this text format.
203 wysiwyg_add_editor_settings($profile, $theme);
204 }
205 }
206 // Use a hidden element for a single text format.
207 if (!$format_field['format']['#access']) {
208 $format_field['wysiwyg'] = array(
209 '#type' => 'hidden',
210 '#name' => $format_field['format']['#name'],
211 '#value' => $format_id,
212 '#attributes' => array(
213 'id' => $format_field['format']['#id'],
214 'class' => array('wysiwyg'),
215 ),
216 );
217 $format_field['wysiwyg']['#attached']['js'][] = array(
218 'data' => array(
219 'wysiwyg' => array(
220 'triggers' => array(
221 $format_field['format']['#id'] => $settings,
222 ),
223 ),
224 ),
225 'type' => 'setting',
226 );
227 }
228 // Otherwise, attach to text format selector.
229 else {
230 $format_field['format']['#attributes']['class'][] = 'wysiwyg';
231 $format_field['format']['#attached']['js'][] = array(
232 'data' => array(
233 'wysiwyg' => array(
234 'triggers' => array(
235 $format_field['format']['#id'] => $settings,
236 ),
237 ),
238 ),
239 'type' => 'setting',
240 );
241 }
242
243 // If we loaded at least one editor, then the 'none' editor will
244 // handle resizable textareas instead of core.
245 if (isset($loaded) && $resizable) {
246 $field['#resizable'] = FALSE;
247 }
248
249 return $element;
250 }
251
252 /**
253 * Determine the profile to use for a given input format id.
254 *
255 * This function also performs sanity checks for the configured editor in a
256 * profile to ensure that we do not load a malformed editor.
257 *
258 * @param $format
259 * The internal id of an input format.
260 *
261 * @return
262 * A wysiwyg profile.
263 *
264 * @see wysiwyg_load_editor(), wysiwyg_get_editor()
265 */
266 function wysiwyg_get_profile($format) {
267 if ($profile = wysiwyg_profile_load($format)) {
268 if (wysiwyg_load_editor($profile)) {
269 return $profile;
270 }
271 }
272 return FALSE;
273 }
274
275 /**
276 * Load an editor library and initialize basic Wysiwyg settings.
277 *
278 * @param $profile
279 * A wysiwyg editor profile.
280 *
281 * @return
282 * TRUE if the editor has been loaded, FALSE if not.
283 *
284 * @see wysiwyg_get_profile()
285 */
286 function wysiwyg_load_editor($profile) {
287 static $settings_added;
288 static $loaded = array();
289
290 $name = $profile->editor;
291 // Library files must be loaded only once.
292 if (!isset($loaded[$name])) {
293 // Load editor.
294 $editor = wysiwyg_get_editor($name);
295 if ($editor) {
296 // Determine library files to load.
297 // @todo Allow to configure the library/execMode to use.
298 if (isset($profile->settings['library']) && isset($editor['libraries'][$profile->settings['library']])) {
299 $library = $profile->settings['library'];
300 $files = $editor['libraries'][$library]['files'];
301 }
302 else {
303 // Fallback to the first defined library by default (external libraries can change).
304 $library = key($editor['libraries']);
305 $files = array_shift($editor['libraries']);
306 $files = $files['files'];
307 }
308 foreach ($files as $file => $options) {
309 if (is_array($options)) {
310 $options += array('type' => 'file', 'scope' => 'header', 'defer' => FALSE, 'cache' => TRUE, 'preprocess' => TRUE);
311 drupal_add_js($editor['library path'] . '/' . $file, $options);
312 }
313 else {
314 drupal_add_js($editor['library path'] . '/' . $options);
315 }
316 }
317 // If editor defines an additional load callback, invoke it.
318 // @todo Isn't the settings callback sufficient?
319 if (isset($editor['load callback']) && function_exists($editor['load callback'])) {
320 $editor['load callback']($editor, $library);
321 }
322 // Load JavaScript integration files for this editor.
323 $files = array();
324 if (isset($editor['js files'])) {
325 $files = $editor['js files'];
326 }
327 foreach ($files as $file) {
328 drupal_add_js($editor['js path'] . '/' . $file);
329 }
330 // Load CSS stylesheets for this editor.
331 $files = array();
332 if (isset($editor['css files'])) {
333 $files = $editor['css files'];
334 }
335 foreach ($files as $file) {
336 drupal_add_css($editor['css path'] . '/' . $file);
337 }
338
339 drupal_add_js(array('wysiwyg' => array(
340 'configs' => array($editor['name'] => array('global' => array(
341 // @todo Move into (global) editor settings.
342 // If JS compression is enabled, at least TinyMCE is unable to determine
343 // its own base path and exec mode since it can't find the script name.
344 'editorBasePath' => base_path() . $editor['library path'],
345 'execMode' => $library,
346 ))),
347 )), 'setting');
348
349 $loaded[$name] = TRUE;
350 }
351 else {
352 $loaded[$name] = FALSE;
353 }
354 }
355
356 // Add basic Wysiwyg settings if any editor has been added.
357 if (!isset($settings_added) && $loaded[$name]) {
358 drupal_add_js(array('wysiwyg' => array(
359 'configs' => array(),
360 'plugins' => array(),
361 'disable' => t('Disable rich-text'),
362 'enable' => t('Enable rich-text'),
363 )), 'setting');
364
365 $path = drupal_get_path('module', 'wysiwyg');
366 // Initialize our namespaces in the *header* to do not force editor
367 // integration scripts to check and define Drupal.wysiwyg on its own.
368 drupal_add_js($path . '/wysiwyg.init.js', array('group' => JS_LIBRARY));
369
370 // The 'none' editor is a special editor implementation, allowing us to
371 // attach and detach regular Drupal behaviors just like any other editor.
372 drupal_add_js($path . '/editors/js/none.js');
373
374 // Add wysiwyg.js to the footer to ensure it's executed after the
375 // Drupal.settings array has been rendered and populated. Also, since editor
376 // library initialization functions must be loaded first by the browser,
377 // and Drupal.wysiwygInit() must be executed AFTER editors registered
378 // their callbacks and BEFORE Drupal.behaviors are applied, this must come
379 // last.
380 drupal_add_js($path . '/wysiwyg.js', array('scope' => 'footer'));
381
382 $settings_added = TRUE;
383 }
384
385 return $loaded[$name];
386 }
387
388 /**
389 * Add editor settings for a given input format.
390 */
391 function wysiwyg_add_editor_settings($profile, $theme) {
392 static $formats = array();
393
394 if (!isset($formats[$profile->format])) {
395 $config = wysiwyg_get_editor_config($profile, $theme);
396 // drupal_to_js() does not properly convert numeric array keys, so we need
397 // to use a string instead of the format id.
398 if ($config) {
399 drupal_add_js(array('wysiwyg' => array('configs' => array($profile->editor => array('format' . $profile->format => $config)))), 'setting');
400 }
401 $formats[$profile->format] = TRUE;
402 }
403 }
404
405 /**
406 * Add settings for external plugins.
407 *
408 * Plugins can be used in multiple profiles, but not necessarily in all. Because
409 * of that, we need to process plugins for each profile, even if most of their
410 * settings are not stored per profile.
411 *
412 * Implementations of hook_wysiwyg_plugin() may execute different code for each
413 * editor. Therefore, we have to invoke those implementations for each editor,
414 * but process the resulting plugins separately for each profile.
415 *
416 * Drupal plugins differ to native plugins in that they have plugin-specific
417 * definitions and settings, which need to be processed only once. But they are
418 * also passed to the editor to prepare settings specific to the editor.
419 * Therefore, we load and process the Drupal plugins only once, and hand off the
420 * effective definitions for each profile to the editor.
421 *
422 * @param $profile
423 * A wysiwyg editor profile.
424 *
425 * @todo Rewrite wysiwyg_process_form() to build a registry of effective
426 * profiles in use, so we can process plugins in multiple profiles in one shot
427 * and simplify this entire function.
428 */
429 function wysiwyg_add_plugin_settings($profile) {
430 static $plugins = array();
431 static $processed_plugins = array();
432 static $processed_formats = array();
433
434 // Each input format must only processed once.
435 // @todo ...as long as we do not have multiple profiles per format.
436 if (isset($processed_formats[$profile->format])) {
437 return;
438 }
439 $processed_formats[$profile->format] = TRUE;
440
441 $editor = wysiwyg_get_editor($profile->editor);
442
443 // Collect native plugins for this editor provided via hook_wysiwyg_plugin()
444 // and Drupal plugins provided via hook_wysiwyg_include_directory().
445 if (!array_key_exists($editor['name'], $plugins)) {
446 $plugins[$editor['name']] = wysiwyg_get_plugins($editor['name']);
447 }
448
449 // Nothing to do, if there are no plugins.
450 if (empty($plugins[$editor['name']])) {
451 return;
452 }
453
454 // Determine name of proxy plugin for Drupal plugins.
455 $proxy = (isset($editor['proxy plugin']) ? key($editor['proxy plugin']) : '');
456
457 // Process native editor plugins.
458 if (isset($editor['plugin settings callback'])) {
459 // @todo Require PHP 5.1 in 3.x and use array_intersect_key().
460 $profile_plugins_native = array();
461 foreach ($plugins[$editor['name']] as $plugin => $meta) {
462 // Skip Drupal plugins (handled below).
463 if ($plugin === $proxy) {
464 continue;
465 }
466 // Only keep native plugins that are enabled in this profile.
467 if (isset($profile->settings['buttons'][$plugin])) {
468 $profile_plugins_native[$plugin] = $meta;
469 }
470 }
471 // Invoke the editor's plugin settings callback, so it can populate the
472 // settings for native external plugins with required values.
473 $settings_native = call_user_func($editor['plugin settings callback'], $editor, $profile, $profile_plugins_native);
474
475 if ($settings_native) {
476 drupal_add_js(array('wysiwyg' => array('plugins' => array('format' . $profile->format => array('native' => $settings_native)))), 'setting');
477 }
478 }
479
480 // Process Drupal plugins.
481 if ($proxy && isset($editor['proxy plugin settings callback'])) {
482 $profile_plugins_drupal = array();
483 foreach (wysiwyg_get_all_plugins() as $plugin => $meta) {
484 if (isset($profile->settings['buttons'][$proxy][$plugin])) {
485 // JavaScript and plugin-specific settings for Drupal plugins must be
486 // loaded and processed only once. Plugin information is cached
487 // statically to pass it to the editor's proxy plugin settings callback.
488 if (!isset($processed_plugins[$proxy][$plugin])) {
489 $profile_plugins_drupal[$plugin] = $processed_plugins[$proxy][$plugin] = $meta;
490 // Load the Drupal plugin's JavaScript.
491 drupal_add_js($meta['js path'] . '/' . $meta['js file']);
492 // Add plugin-specific settings.
493 if (isset($meta['settings'])) {
494 drupal_add_js(array('wysiwyg' => array('plugins' => array('drupal' => array($plugin => $meta['settings'])))), 'setting');
495 }
496 }
497 else {
498 $profile_plugins_drupal[$plugin] = $processed_plugins[$proxy][$plugin];
499 }
500 }
501 }
502 // Invoke the editor's proxy plugin settings callback, so it can populate
503 // the settings for Drupal plugins with custom, required values.
504 $settings_drupal = call_user_func($editor['proxy plugin settings callback'], $editor, $profile, $profile_plugins_drupal);
505
506 if ($settings_drupal) {
507 drupal_add_js(array('wysiwyg' => array('plugins' => array('format' . $profile->format => array('drupal' => $settings_drupal)))), 'setting');
508 }
509 }
510 }
511
512 /**
513 * Retrieve available themes for an editor.
514 *
515 * Editor themes control the visual presentation of an editor.
516 *
517 * @param $profile
518 * A wysiwyg editor profile; passed/altered by reference.
519 * @param $selected_theme
520 * An optional theme name that ought to be used.
521 *
522 * @return
523 * An array of theme names, or a single, checked theme name if $selected_theme
524 * was given.
525 */
526 function wysiwyg_get_editor_themes(&$profile, $selected_theme = NULL) {
527 static $themes = array();
528
529 if (!isset($themes[$profile->editor])) {
530 $editor = wysiwyg_get_editor($profile->editor);
531 if (isset($editor['themes callback']) && function_exists($editor['themes callback'])) {
532 $themes[$editor['name']] = $editor['themes callback']($editor, $profile);
533 }
534 // Fallback to 'default' otherwise.
535 else {
536 $themes[$editor['name']] = array('default');
537 }
538 }
539
540 // Check optional $selected_theme argument, if given.
541 if (isset($selected_theme)) {
542 // If the passed theme name does not exist, use the first available.
543 if (!in_array($selected_theme, $themes[$profile->editor])) {
544 $selected_theme = $profile->settings['theme'] = $themes[$profile->editor][0];
545 }
546 }
547
548 return isset($selected_theme) ? $selected_theme : $themes[$profile->editor];
549 }
550
551 /**
552 * Return plugin metadata from the plugin registry.
553 *
554 * @param $editor_name
555 * The internal name of an editor to return plugins for.
556 *
557 * @return
558 * An array for each plugin.
559 */
560 function wysiwyg_get_plugins($editor_name) {
561 $plugins = array();
562 if (!empty($editor_name)) {
563 $editor = wysiwyg_get_editor($editor_name);
564 // Add internal editor plugins.
565 if (isset($editor['plugin callback']) && function_exists($editor['plugin callback'])) {
566 $plugins = $editor['plugin callback']($editor);
567 }
568 // Add editor plugins provided via hook_wysiwyg_plugin().
569 $plugins = array_merge($plugins, module_invoke_all('wysiwyg_plugin', $editor['name'], $editor['installed version']));
570 // Add API plugins provided by Drupal modules.
571 // @todo We need to pass the filepath to the plugin icon for Drupal plugins.
572 if (isset($editor['proxy plugin'])) {
573 $plugins += $editor['proxy plugin'];
574 $proxy = key($editor['proxy plugin']);
575 foreach (wysiwyg_get_all_plugins() as $plugin_name => $info) {
576 $plugins[$proxy]['buttons'][$plugin_name] = $info['title'];
577 }
578 }
579 }
580 return $plugins;
581 }
582
583 /**
584 * Return an array of initial editor settings for a Wysiwyg profile.
585 */
586 function wysiwyg_get_editor_config($profile, $theme) {
587 $editor = wysiwyg_get_editor($profile->editor);
588 $settings = array();
589 if (!empty($editor['settings callback']) && function_exists($editor['settings callback'])) {
590 $settings = $editor['settings callback']($editor, $profile->settings, $theme);
591
592 // Allow other modules to alter the editor settings for this format.
593 $context = array('editor' => $editor, 'profile' => $profile, 'theme' => $theme);
594 drupal_alter('wysiwyg_editor_settings', $settings, $context);
595 }
596 return $settings;
597 }
598
599 /**
600 * Retrieve stylesheets for HTML/IFRAME-based editors.
601 *
602 * This assumes that the content editing area only needs stylesheets defined
603 * for the scope 'theme'.
604 *
605 * @return
606 * An array containing CSS files, including proper base path.
607 */
608 function wysiwyg_get_css() {
609 static $files;
610
611 if (isset($files)) {
612 return $files;
613 }
614 // In node form previews, the theme has not been initialized yet.
615 if (!empty($_POST)) {
616 drupal_theme_initialize();
617 }
618
619 $files = array();
620 foreach (drupal_add_css() as $filepath => $info) {
621 if ($info['group'] >= CSS_THEME && $info['media'] != 'print') {
622 if (file_exists($filepath)) {
623 $files[] = base_path() . $filepath;
624 }
625 }
626 }
627 return $files;
628 }
629
630 /**
631 * Loads a profile for a given text format.
632 *
633 * Since there are commonly not many text formats, and each text format-enabled
634 * form element will possibly have to load every single profile, all existing
635 * profiles are loaded and cached once to reduce the amount of database queries.
636 */
637 function wysiwyg_profile_load($format) {
638 $profiles = wysiwyg_profile_load_all();
639 return (isset($profiles[$format]) ? $profiles[$format] : FALSE);
640 }
641
642 /**
643 * Loads all profiles.
644 */
645 function wysiwyg_profile_load_all() {
646 // entity_load(..., FALSE) does not re-use its own static cache upon
647 // repetitive calls, so a custom static cache is required.
648 // @see wysiwyg_entity_info()
649 $profiles = &drupal_static(__FUNCTION__);
650
651 if (!isset($profiles)) {
652 // Additional database cache to support alternative caches like memcache.
653 if ($cached = cache_get('wysiwyg_profiles')) {
654 $profiles = $cached->data;
655 }
656 else {
657 $profiles = entity_load('wysiwyg_profile', FALSE);
658 cache_set('wysiwyg_profiles', $profiles);
659 }
660 }
661
662 return $profiles;
663 }
664
665 /**
666 * Deletes a profile from the database.
667 */
668 function wysiwyg_profile_delete($format) {
669 db_delete('wysiwyg')
670 ->condition('format', $format)
671 ->execute();
672 }
673
674 /**
675 * Clear all Wysiwyg profile caches.
676 */
677 function wysiwyg_profile_cache_clear() {
678 entity_get_controller('wysiwyg_profile')->resetCache();
679 drupal_static_reset('wysiwyg_profile_load_all');
680 cache_clear_all('wysiwyg_profiles', 'cache');
681 }
682
683 /**
684 * Implements hook_form_FORM_ID_alter().
685 */
686 function wysiwyg_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
687 $account = $form['#user'];
688 $user_formats = filter_formats($account);
689 $options = array();
690 $options_default = array();
691 foreach (wysiwyg_profile_load_all() as $format => $profile) {
692 // Only show profiles that have user_choose enabled.
693 if (!empty($profile->settings['user_choose']) && isset($user_formats[$format])) {
694 $options[$format] = check_plain($user_formats[$format]->name);
695 if (wysiwyg_user_get_status($profile, $account)) {
696 $options_default[] = $format;
697 }
698 }
699 }
700 if (!empty($options)) {
701 $form['wysiwyg']['wysiwyg_status'] = array(
702 '#type' => 'checkboxes',
703 '#title' => t('Text formats enabled for rich-text editing'),
704 '#options' => $options,
705 '#default_value' => $options_default,
706 );
707 }
708 }
709
710 /**
711 * Implements hook_user_insert().
712 *
713 * Wysiwyg's user preferences are normally not exposed on the user registration
714 * form, but in case they are manually altered in, we invoke
715 * wysiwyg_user_update() accordingly.
716 */
717 function wysiwyg_user_insert(&$edit, $account, $category) {
718 wysiwyg_user_update($edit, $account, $category);
719 }
720
721 /**
722 * Implements hook_user_update().
723 */
724 function wysiwyg_user_update(&$edit, $account, $category) {
725 if (isset($edit['wysiwyg_status'])) {
726 db_delete('wysiwyg_user')
727 ->condition('uid', $account->uid)
728 ->execute();
729 $query = db_insert('wysiwyg_user')
730 ->fields(array('uid', 'format', 'status'));
731 foreach ($edit['wysiwyg_status'] as $format => $status) {
732 $query->values(array(
733 'uid' => $account->uid,
734 'format' => $format,
735 'status' => (int) (bool) $status,
736 ));
737 }
738 $query->execute();
739 }
740 }
741
742 function wysiwyg_user_get_status($profile, $account = NULL) {
743 global $user;
744
745 if (!isset($account)) {
746 $account = $user;
747 }
748
749 // Default wysiwyg editor status information is only required on forms, so we
750 // do not pre-emptively load and attach this information on every user_load().
751 if (!isset($account->wysiwyg_status)) {
752 $account->wysiwyg_status = db_query("SELECT format, status FROM {wysiwyg_user} WHERE uid = :uid", array(
753 ':uid' => $account->uid,
754 ))->fetchAllKeyed();
755 }
756
757 if (!empty($profile->settings['user_choose']) && isset($account->wysiwyg_status[$profile->format])) {
758 $status = $account->wysiwyg_status[$profile->format];
759 }
760 else {
761 $status = isset($profile->settings['default']) ? $profile->settings['default'] : TRUE;
762 }
763
764 return (bool) $status;
765 }
766
767 /**
768 * @defgroup wysiwyg_api Wysiwyg API
769 * @{
770 *
771 * @todo Forked from Panels; abstract into a separate API module that allows
772 * contrib modules to define supported include/plugin types.
773 */
774
775 /**
776 * Return library information for a given editor.
777 *
778 * @param $name
779 * The internal name of an editor.
780 *
781 * @return
782 * The library information for the editor, or FALSE if $name is unknown or not
783 * installed properly.
784 */
785 function wysiwyg_get_editor($name) {
786 $editors = wysiwyg_get_all_editors();
787 return isset($editors[$name]) && $editors[$name]['installed'] ? $editors[$name] : FALSE;
788 }
789
790 /**
791 * Compile a list holding all supported editors including installed editor version information.
792 */
793 function wysiwyg_get_all_editors() {
794 static $editors;
795
796 if (isset($editors)) {
797 return $editors;
798 }
799
800 $editors = wysiwyg_load_includes('editors', 'editor');
801 foreach ($editors as $editor => $properties) {
802 // Fill in required properties.
803 $editors[$editor] += array(
804 'title' => '',
805 'vendor url' => '',
806 'download url' => '',
807 'editor path' => wysiwyg_get_path($editors[$editor]['name']),
808 'library path' => wysiwyg_get_path($editors[$editor]['name']),
809 'libraries' => array(),
810 'version callback' => NULL,
811 'themes callback' => NULL,
812 'settings callback' => NULL,
813 'plugin callback' => NULL,
814 'plugin settings callback' => NULL,
815 'versions' => array(),
816 'js path' => $editors[$editor]['path'] . '/js',
817 'css path' => $editors[$editor]['path'] . '/css',
818 );
819 // Check whether library is present.
820 if (!($editors[$editor]['installed'] = file_exists($editors[$editor]['library path']))) {
821 continue;
822 }
823 // Detect library version.
824 if (function_exists($editors[$editor]['version callback'])) {
825 $editors[$editor]['installed version'] = $editors[$editor]['version callback']($editors[$editor]);
826 }
827 if (empty($editors[$editor]['installed version'])) {
828 $editors[$editor]['error'] = t('The version of %editor could not be detected.', array('%editor' => $properties['title']));
829 $editors[$editor]['installed'] = FALSE;
830 continue;
831 }
832 // Determine to which supported version the installed version maps.
833 ksort($editors[$editor]['versions']);
834 $version = 0;
835 foreach ($editors[$editor]['versions'] as $supported_version => $version_properties) {
836 if (version_compare($editors[$editor]['installed version'], $supported_version, '>=')) {
837 $version = $supported_version;
838 }
839 }
840 if (!$version) {
841 $editors[$editor]['error'] = t('The installed version %version of %editor is not supported.', array('%version' => $editors[$editor]['installed version'], '%editor' => $editors[$editor]['title']));
842 $editors[$editor]['installed'] = FALSE;
843 continue;
844 }
845 // Apply library version specific definitions and overrides.
846 $editors[$editor] = array_merge($editors[$editor], $editors[$editor]['versions'][$version]);
847 unset($editors[$editor]['versions']);
848 }
849 return $editors;
850 }
851
852 /**
853 * Invoke hook_wysiwyg_plugin() in all modules.
854 */
855 function wysiwyg_get_all_plugins() {
856 static $plugins;
857
858 if (isset($plugins)) {
859 return $plugins;
860 }
861
862 $plugins = wysiwyg_load_includes('plugins', 'plugin');
863 foreach ($plugins as $name => $properties) {
864 $plugin = &$plugins[$name];
865 // Fill in required/default properties.
866 $plugin += array(
867 'title' => $plugin['name'],
868 'vendor url' => '',
869 'js path' => $plugin['path'] . '/' . $plugin['name'],
870 'js file' => $plugin['name'] . '.js',
871 'css path' => $plugin['path'] . '/' . $plugin['name'],
872 'css file' => $plugin['name'] . '.css',
873 'icon path' => $plugin['path'] . '/' . $plugin['name'] . '/images',
874 'icon file' => $plugin['name'] . '.png',
875 'dialog path' => $plugin['name'],
876 'dialog settings' => array(),
877 'settings callback' => NULL,
878 'settings form callback' => NULL,
879 );
880 // Fill in default settings.
881 $plugin['settings'] += array(
882 'path' => base_path() . $plugin['path'] . '/' . $plugin['name'],
883 );
884 // Check whether library is present.
885 if (!($plugin['installed'] = file_exists($plugin['js path'] . '/' . $plugin['js file']))) {
886 continue;
887 }
888 }
889 return $plugins;
890 }
891
892 /**
893 * Load include files for wysiwyg implemented by all modules.
894 *
895 * @param $type
896 * The type of includes to search for, can be 'editors'.
897 * @param $hook
898 * The hook name to invoke.
899 * @param $file
900 * An optional include file name without .inc extension to limit the search to.
901 *
902 * @see wysiwyg_get_directories(), _wysiwyg_process_include()
903 */
904 function wysiwyg_load_includes($type = 'editors', $hook = 'editor', $file = NULL) {
905 // Determine implementations.
906 $directories = wysiwyg_get_directories($type);
907 $directories['wysiwyg'] = drupal_get_path('module', 'wysiwyg') . '/' . $type;
908 $file_list = array();
909 foreach ($directories as $module => $path) {
910 $file_list[$module] = drupal_system_listing("/{$file}.inc\$/", $path, 'name', 0);
911 }
912
913 // Load implementations.
914 $info = array();
915 foreach (array_filter($file_list) as $module => $files) {
916 foreach ($files as $file) {
917 include_once './' . $file->uri;
918 $result = _wysiwyg_process_include($module, $module . '_' . $file->name, dirname($file->uri), $hook);
919 if (is_array($result)) {
920 $info = array_merge($info, $result);
921 }
922 }
923 }
924 return $info;
925 }
926
927 /**
928 * Helper function to build paths to libraries.
929 *
930 * @param $library
931 * The external library name to return the path for.
932 * @param $base_path
933 * Whether to prefix the resulting path with base_path().
934 *
935 * @return
936 * The path to the specified library.
937 *
938 * @ingroup libraries
939 */
940 function wysiwyg_get_path($library, $base_path = FALSE) {
941 static $libraries;
942
943 if (!isset($libraries)) {
944 $libraries = wysiwyg_get_libraries();
945 }
946 if (!isset($libraries[$library])) {
947 // Most often, external libraries can be shared across multiple sites.
948 return 'sites/all/libraries/' . $library;
949 }
950
951 $path = ($base_path ? base_path() : '');
952 $path .= $libraries[$library];
953
954 return $path;
955 }
956
957 /**
958 * Return an array of library directories.
959 *
960 * Returns an array of library directories from the all-sites directory
961 * (i.e. sites/all/libraries/), the profiles directory, and site-specific
962 * directory (i.e. sites/somesite/libraries/). The returned array will be keyed
963 * by the library name. Site-specific libraries are prioritized over libraries
964 * in the default directories. That is, if a library with the same name appears
965 * in both the site-wide directory and site-specific directory, only the
966 * site-specific version will be listed.
967 *
968 * @return
969 * A list of library directories.
970 *
971 * @ingroup libraries
972 */
973 function wysiwyg_get_libraries() {
974 global $profile;
975
976 // When this function is called during Drupal's initial installation process,
977 // the name of the profile that is about to be installed is stored in the
978 // global $profile variable. At all other times, the regular system variable
979 // contains the name of the current profile, and we can call variable_get()
980 // to determine the profile.
981 if (!isset($profile)) {
982 $profile = variable_get('install_profile', 'default');
983 }
984
985 $directory = 'libraries';
986 $searchdir = array();
987 $config = conf_path();
988
989 // The 'profiles' directory contains pristine collections of modules and
990 // themes as organized by a distribution. It is pristine in the same way
991 // that /modules is pristine for core; users should avoid changing anything
992 // there in favor of sites/all or sites/<domain> directories.
993 if (file_exists("profiles/$profile/$directory")) {
994 $searchdir[] = "profiles/$profile/$directory";
995 }
996
997 // Always search sites/all/*.
998 $searchdir[] = 'sites/all/' . $directory;
999
1000 // Also search sites/<domain>/*.
1001 if (file_exists("$config/$directory")) {
1002 $searchdir[] = "$config/$directory";
1003 }
1004
1005 // Retrieve list of directories.
1006 // @todo Core: Allow to scan for directories.
1007 $directories = array();
1008 $nomask = array('CVS');
1009 foreach ($searchdir as $dir) {
1010 if (is_dir($dir) && $handle = opendir($dir)) {
1011 while (FALSE !== ($file = readdir($handle))) {
1012 if (!in_array($file, $nomask) && $file[0] != '.') {
1013 if (is_dir("$dir/$file")) {
1014 $directories[$file] = "$dir/$file";
1015 }
1016 }
1017 }
1018 closedir($handle);
1019 }
1020 }
1021
1022 return $directories;
1023 }
1024
1025 /**
1026 * Return a list of directories by modules implementing wysiwyg_include_directory().
1027 *
1028 * @param $plugintype
1029 * The type of a plugin; can be 'editors'.
1030 *
1031 * @return
1032 * An array containing module names suffixed with '_' and their defined
1033 * directory.
1034 *
1035 * @see wysiwyg_load_includes(), _wysiwyg_process_include()
1036 */
1037 function wysiwyg_get_directories($plugintype) {
1038 $directories = array();
1039 foreach (module_implements('wysiwyg_include_directory') as $module) {
1040 $result = module_invoke($module, 'wysiwyg_include_directory', $plugintype);
1041 if (isset($result) && is_string($result)) {
1042 $directories[$module] = drupal_get_path('module', $module) . '/' . $result;
1043 }
1044 }
1045 return $directories;
1046 }
1047
1048 /**
1049 * Process a single hook implementation of a wysiwyg editor.
1050 *
1051 * @param $module
1052 * The module that owns the hook.
1053 * @param $identifier
1054 * Either the module or 'wysiwyg_' . $file->name
1055 * @param $hook
1056 * The name of the hook being invoked.
1057 */
1058 function _wysiwyg_process_include($module, $identifier, $path, $hook) {
1059 $function = $identifier . '_' . $hook;
1060 if (!function_exists($function)) {
1061 return NULL;
1062 }
1063 $result = $function();
1064 if (!isset($result) || !is_array($result)) {
1065 return NULL;
1066 }
1067
1068 // Fill in defaults.
1069 foreach ($result as $editor => $properties) {
1070 $result[$editor]['module'] = $module;
1071 $result[$editor]['name'] = $editor;
1072 $result[$editor]['path'] = $path;
1073 }
1074 return $result;
1075 }
1076
1077 /**
1078 * @} End of "defgroup wysiwyg_api".
1079 */