]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/includes/plugin.php
4f469c9611806ea720da43e73c0f334a68267d20
[autoinstalls/wordpress.git] / wp-admin / includes / plugin.php
1 <?php
2 /**
3  * WordPress Plugin Administration API
4  *
5  * @package WordPress
6  * @subpackage Administration
7  */
8
9 /**
10  * Parse the plugin contents to retrieve plugin's metadata.
11  *
12  * The metadata of the plugin's data searches for the following in the plugin's
13  * header. All plugin data must be on its own line. For plugin description, it
14  * must not have any newlines or only parts of the description will be displayed
15  * and the same goes for the plugin data. The below is formatted for printing.
16  *
17  * <code>
18  * /*
19  * Plugin Name: Name of Plugin
20  * Plugin URI: Link to plugin information
21  * Description: Plugin Description
22  * Author: Plugin author's name
23  * Author URI: Link to the author's web site
24  * Version: Must be set in the plugin for WordPress 2.3+
25  * Text Domain: Optional. Unique identifier, should be same as the one used in
26  *              plugin_text_domain()
27  * Domain Path: Optional. Only useful if the translations are located in a
28  *              folder above the plugin's base path. For example, if .mo files are
29  *              located in the locale folder then Domain Path will be "/locale/" and
30  *              must have the first slash. Defaults to the base folder the plugin is
31  *              located in.
32  *  * / # Remove the space to close comment
33  * </code>
34  *
35  * Plugin data returned array contains the following:
36  *              'Name' - Name of the plugin, must be unique.
37  *              'Title' - Title of the plugin and the link to the plugin's web site.
38  *              'Description' - Description of what the plugin does and/or notes
39  *              from the author.
40  *              'Author' - The author's name
41  *              'AuthorURI' - The authors web site address.
42  *              'Version' - The plugin version number.
43  *              'PluginURI' - Plugin web site address.
44  *              'TextDomain' - Plugin's text domain for localization.
45  *              'DomainPath' - Plugin's relative directory path to .mo files.
46  *
47  * Some users have issues with opening large files and manipulating the contents
48  * for want is usually the first 1kiB or 2kiB. This function stops pulling in
49  * the plugin contents when it has all of the required plugin data.
50  *
51  * The first 8kiB of the file will be pulled in and if the plugin data is not
52  * within that first 8kiB, then the plugin author should correct their plugin
53  * and move the plugin data headers to the top.
54  *
55  * The plugin file is assumed to have permissions to allow for scripts to read
56  * the file. This is not checked however and the file is only opened for
57  * reading.
58  *
59  * @link http://trac.wordpress.org/ticket/5651 Previous Optimizations.
60  * @link http://trac.wordpress.org/ticket/7372 Further and better Optimizations.
61  * @since 1.5.0
62  *
63  * @param string $plugin_file Path to the plugin file
64  * @param bool $markup If the returned data should have HTML markup applied
65  * @param bool $translate If the returned data should be translated
66  * @return array See above for description.
67  */
68 function get_plugin_data( $plugin_file, $markup = true, $translate = true ) {
69         // We don't need to write to the file, so just open for reading.
70         $fp = fopen($plugin_file, 'r');
71
72         // Pull only the first 8kiB of the file in.
73         $plugin_data = fread( $fp, 8192 );
74
75         // PHP will close file handle, but we are good citizens.
76         fclose($fp);
77
78         preg_match( '|Plugin Name:(.*)$|mi', $plugin_data, $name );
79         preg_match( '|Plugin URI:(.*)$|mi', $plugin_data, $uri );
80         preg_match( '|Version:(.*)|i', $plugin_data, $version );
81         preg_match( '|Description:(.*)$|mi', $plugin_data, $description );
82         preg_match( '|Author:(.*)$|mi', $plugin_data, $author_name );
83         preg_match( '|Author URI:(.*)$|mi', $plugin_data, $author_uri );
84         preg_match( '|Text Domain:(.*)$|mi', $plugin_data, $text_domain );
85         preg_match( '|Domain Path:(.*)$|mi', $plugin_data, $domain_path );
86
87         foreach ( array( 'name', 'uri', 'version', 'description', 'author_name', 'author_uri', 'text_domain', 'domain_path' ) as $field ) {
88                 if ( !empty( ${$field} ) )
89                         ${$field} = _cleanup_header_comment(${$field}[1]);
90                 else
91                         ${$field} = '';
92         }
93
94         $plugin_data = array(
95                                 'Name' => $name, 'Title' => $name, 'PluginURI' => $uri, 'Description' => $description,
96                                 'Author' => $author_name, 'AuthorURI' => $author_uri, 'Version' => $version,
97                                 'TextDomain' => $text_domain, 'DomainPath' => $domain_path
98                                 );
99         if ( $markup || $translate )
100                 $plugin_data = _get_plugin_data_markup_translate($plugin_file, $plugin_data, $markup, $translate);
101
102         return $plugin_data;
103 }
104
105 function _get_plugin_data_markup_translate($plugin_file, $plugin_data, $markup = true, $translate = true) {
106
107         //Translate fields
108         if( $translate && ! empty($plugin_data['TextDomain']) ) {
109                 if( ! empty( $plugin_data['DomainPath'] ) )
110                         load_plugin_textdomain($plugin_data['TextDomain'], dirname($plugin_file). $plugin_data['DomainPath']);
111                 else
112                         load_plugin_textdomain($plugin_data['TextDomain'], dirname($plugin_file));
113
114                 foreach ( array('Name', 'PluginURI', 'Description', 'Author', 'AuthorURI', 'Version') as $field )
115                         $plugin_data[ $field ] = translate($plugin_data[ $field ], $plugin_data['TextDomain']);
116         }
117
118         //Apply Markup
119         if ( $markup ) {
120                 if ( ! empty($plugin_data['PluginURI']) && ! empty($plugin_data['Name']) )
121                         $plugin_data['Title'] = '<a href="' . $plugin_data['PluginURI'] . '" title="' . __( 'Visit plugin homepage' ) . '">' . $plugin_data['Name'] . '</a>';
122                 else
123                         $plugin_data['Title'] = $plugin_data['Name'];
124
125                 if ( ! empty($plugin_data['AuthorURI']) && ! empty($plugin_data['Author']) )
126                         $plugin_data['Author'] = '<a href="' . $plugin_data['AuthorURI'] . '" title="' . __( 'Visit author homepage' ) . '">' . $plugin_data['Author'] . '</a>';
127
128                 $plugin_data['Description'] = wptexturize( $plugin_data['Description'] );
129                 if( ! empty($plugin_data['Author']) )
130                         $plugin_data['Description'] .= ' <cite>' . sprintf( __('By %s'), $plugin_data['Author'] ) . '.</cite>';
131         }
132
133         $plugins_allowedtags = array('a' => array('href' => array(),'title' => array()),'abbr' => array('title' => array()),'acronym' => array('title' => array()),'code' => array(),'em' => array(),'strong' => array());
134
135         // Sanitize all displayed data
136         $plugin_data['Title']       = wp_kses($plugin_data['Title'], $plugins_allowedtags);
137         $plugin_data['Version']     = wp_kses($plugin_data['Version'], $plugins_allowedtags);
138         $plugin_data['Description'] = wp_kses($plugin_data['Description'], $plugins_allowedtags);
139         $plugin_data['Author']      = wp_kses($plugin_data['Author'], $plugins_allowedtags);
140
141         return $plugin_data;
142 }
143
144 /**
145  * Get a list of a plugin's files.
146  *
147  * @since 2.8.0
148  *
149  * @param string $plugin Plugin ID
150  * @return array List of files relative to the plugin root.
151  */
152 function get_plugin_files($plugin) {
153         $plugin_file = WP_PLUGIN_DIR . '/' . $plugin;
154         $dir = dirname($plugin_file);
155         $plugin_files = array($plugin);
156         if ( is_dir($dir) && $dir != WP_PLUGIN_DIR ) {
157                 $plugins_dir = @ opendir( $dir );
158                 if ( $plugins_dir ) {
159                         while (($file = readdir( $plugins_dir ) ) !== false ) {
160                                 if ( substr($file, 0, 1) == '.' )
161                                         continue;
162                                 if ( is_dir( $dir . '/' . $file ) ) {
163                                         $plugins_subdir = @ opendir( $dir . '/' . $file );
164                                         if ( $plugins_subdir ) {
165                                                 while (($subfile = readdir( $plugins_subdir ) ) !== false ) {
166                                                         if ( substr($subfile, 0, 1) == '.' )
167                                                                 continue;
168                                                         $plugin_files[] = plugin_basename("$dir/$file/$subfile");
169                                                 }
170                                                 @closedir( $plugins_subdir );
171                                         }
172                                 } else {
173                                         if ( plugin_basename("$dir/$file") != $plugin )
174                                                 $plugin_files[] = plugin_basename("$dir/$file");
175                                 }
176                         }
177                         @closedir( $plugins_dir );
178                 }
179         }
180
181         return $plugin_files;
182 }
183
184 /**
185  * Check the plugins directory and retrieve all plugin files with plugin data.
186  *
187  * WordPress only supports plugin files in the base plugins directory
188  * (wp-content/plugins) and in one directory above the plugins directory
189  * (wp-content/plugins/my-plugin). The file it looks for has the plugin data and
190  * must be found in those two locations. It is recommended that do keep your
191  * plugin files in directories.
192  *
193  * The file with the plugin data is the file that will be included and therefore
194  * needs to have the main execution for the plugin. This does not mean
195  * everything must be contained in the file and it is recommended that the file
196  * be split for maintainability. Keep everything in one file for extreme
197  * optimization purposes.
198  *
199  * @since unknown
200  *
201  * @param string $plugin_folder Optional. Relative path to single plugin folder.
202  * @return array Key is the plugin file path and the value is an array of the plugin data.
203  */
204 function get_plugins($plugin_folder = '') {
205
206         if ( ! $cache_plugins = wp_cache_get('plugins', 'plugins') )
207                 $cache_plugins = array();
208
209         if ( isset($cache_plugins[ $plugin_folder ]) )
210                 return $cache_plugins[ $plugin_folder ];
211
212         $wp_plugins = array ();
213         $plugin_root = WP_PLUGIN_DIR;
214         if( !empty($plugin_folder) )
215                 $plugin_root .= $plugin_folder;
216
217         // Files in wp-content/plugins directory
218         $plugins_dir = @ opendir( $plugin_root);
219         $plugin_files = array();
220         if ( $plugins_dir ) {
221                 while (($file = readdir( $plugins_dir ) ) !== false ) {
222                         if ( substr($file, 0, 1) == '.' )
223                                 continue;
224                         if ( is_dir( $plugin_root.'/'.$file ) ) {
225                                 $plugins_subdir = @ opendir( $plugin_root.'/'.$file );
226                                 if ( $plugins_subdir ) {
227                                         while (($subfile = readdir( $plugins_subdir ) ) !== false ) {
228                                                 if ( substr($subfile, 0, 1) == '.' )
229                                                         continue;
230                                                 if ( substr($subfile, -4) == '.php' )
231                                                         $plugin_files[] = "$file/$subfile";
232                                         }
233                                 }
234                         } else {
235                                 if ( substr($file, -4) == '.php' )
236                                         $plugin_files[] = $file;
237                         }
238                 }
239         }
240         @closedir( $plugins_dir );
241         @closedir( $plugins_subdir );
242
243         if ( !$plugins_dir || empty($plugin_files) )
244                 return $wp_plugins;
245
246         foreach ( $plugin_files as $plugin_file ) {
247                 if ( !is_readable( "$plugin_root/$plugin_file" ) )
248                         continue;
249
250                 $plugin_data = get_plugin_data( "$plugin_root/$plugin_file", false, false ); //Do not apply markup/translate as it'll be cached.
251
252                 if ( empty ( $plugin_data['Name'] ) )
253                         continue;
254
255                 $wp_plugins[plugin_basename( $plugin_file )] = $plugin_data;
256         }
257
258         uasort( $wp_plugins, create_function( '$a, $b', 'return strnatcasecmp( $a["Name"], $b["Name"] );' ));
259
260         $cache_plugins[ $plugin_folder ] = $wp_plugins;
261         wp_cache_set('plugins', $cache_plugins, 'plugins');
262
263         return $wp_plugins;
264 }
265
266 /**
267  * Check whether the plugin is active by checking the active_plugins list.
268  *
269  * @since 2.5.0
270  *
271  * @param string $plugin Base plugin path from plugins directory.
272  * @return bool True, if in the active plugins list. False, not in the list.
273  */
274 function is_plugin_active($plugin) {
275         return in_array($plugin, get_option('active_plugins'));
276 }
277
278 /**
279  * Attempts activation of plugin in a "sandbox" and redirects on success.
280  *
281  * A plugin that is already activated will not attempt to be activated again.
282  *
283  * The way it works is by setting the redirection to the error before trying to
284  * include the plugin file. If the plugin fails, then the redirection will not
285  * be overwritten with the success message. Also, the options will not be
286  * updated and the activation hook will not be called on plugin error.
287  *
288  * It should be noted that in no way the below code will actually prevent errors
289  * within the file. The code should not be used elsewhere to replicate the
290  * "sandbox", which uses redirection to work.
291  * {@source 13 1}
292  *
293  * If any errors are found or text is outputted, then it will be captured to
294  * ensure that the success redirection will update the error redirection.
295  *
296  * @since unknown
297  *
298  * @param string $plugin Plugin path to main plugin file with plugin data.
299  * @param string $redirect Optional. URL to redirect to.
300  * @return WP_Error|null WP_Error on invalid file or null on success.
301  */
302 function activate_plugin($plugin, $redirect = '') {
303         $current = get_option('active_plugins');
304         $plugin = plugin_basename(trim($plugin));
305
306         $valid = validate_plugin($plugin);
307         if ( is_wp_error($valid) )
308                 return $valid;
309
310         if ( !in_array($plugin, $current) ) {
311                 if ( !empty($redirect) )
312                         wp_redirect(add_query_arg('_error_nonce', wp_create_nonce('plugin-activation-error_' . $plugin), $redirect)); // we'll override this later if the plugin can be included without fatal error
313                 ob_start();
314                 @include(WP_PLUGIN_DIR . '/' . $plugin);
315                 $current[] = $plugin;
316                 sort($current);
317                 update_option('active_plugins', $current);
318                 do_action('activate_' . $plugin);
319                 ob_end_clean();
320         }
321
322         return null;
323 }
324
325 /**
326  * Deactivate a single plugin or multiple plugins.
327  *
328  * The deactivation hook is disabled by the plugin upgrader by using the $silent
329  * parameter.
330  *
331  * @since unknown
332  *
333  * @param string|array $plugins Single plugin or list of plugins to deactivate.
334  * @param bool $silent Optional, default is false. Prevent calling deactivate hook.
335  */
336 function deactivate_plugins($plugins, $silent= false) {
337         $current = get_option('active_plugins');
338
339         if ( !is_array($plugins) )
340                 $plugins = array($plugins);
341
342         foreach ( $plugins as $plugin ) {
343                 $plugin = plugin_basename($plugin);
344                 if( ! is_plugin_active($plugin) )
345                         continue;
346                 array_splice($current, array_search( $plugin, $current), 1 ); // Fixed Array-fu!
347                 if ( ! $silent ) //Used by Plugin updater to internally deactivate plugin, however, not to notify plugins of the fact to prevent plugin output.
348                         do_action('deactivate_' . trim( $plugin ));
349         }
350
351         update_option('active_plugins', $current);
352 }
353
354 /**
355  * Activate multiple plugins.
356  *
357  * When WP_Error is returned, it does not mean that one of the plugins had
358  * errors. It means that one or more of the plugins file path was invalid.
359  *
360  * The execution will be halted as soon as one of the plugins has an error.
361  *
362  * @since unknown
363  *
364  * @param string|array $plugins
365  * @param string $redirect Redirect to page after successful activation.
366  * @return bool|WP_Error True when finished or WP_Error if there were errors during a plugin activation.
367  */
368 function activate_plugins($plugins, $redirect = '') {
369         if ( !is_array($plugins) )
370                 $plugins = array($plugins);
371
372         $errors = array();
373         foreach ( (array) $plugins as $plugin ) {
374                 if ( !empty($redirect) )
375                         $redirect = add_query_arg('plugin', $plugin, $redirect);
376                 $result = activate_plugin($plugin, $redirect);
377                 if ( is_wp_error($result) )
378                         $errors[$plugin] = $result;
379         }
380
381         if ( !empty($errors) )
382                 return new WP_Error('plugins_invalid', __('One of the plugins is invalid.'), $errors);
383
384         return true;
385 }
386
387 /**
388  * Remove directory and files of a plugin for a single or list of plugin(s).
389  *
390  * If the plugins parameter list is empty, false will be returned. True when
391  * completed.
392  *
393  * @since unknown
394  *
395  * @param array $plugins List of plugin
396  * @param string $redirect Redirect to page when complete.
397  * @return mixed
398  */
399 function delete_plugins($plugins, $redirect = '' ) {
400         global $wp_filesystem;
401
402         if( empty($plugins) )
403                 return false;
404
405         $checked = array();
406         foreach( $plugins as $plugin )
407                 $checked[] = 'checked[]=' . $plugin;
408
409         ob_start();
410         $url = wp_nonce_url('plugins.php?action=delete-selected&verify-delete=1&' . implode('&', $checked), 'bulk-manage-plugins');
411         if ( false === ($credentials = request_filesystem_credentials($url)) ) {
412                 $data = ob_get_contents();
413                 ob_end_clean();
414                 if( ! empty($data) ){
415                         include_once( ABSPATH . 'wp-admin/admin-header.php');
416                         echo $data;
417                         include( ABSPATH . 'wp-admin/admin-footer.php');
418                         exit;
419                 }
420                 return;
421         }
422
423         if ( ! WP_Filesystem($credentials) ) {
424                 request_filesystem_credentials($url, '', true); //Failed to connect, Error and request again
425                 $data = ob_get_contents();
426                 ob_end_clean();
427                 if( ! empty($data) ){
428                         include_once( ABSPATH . 'wp-admin/admin-header.php');
429                         echo $data;
430                         include( ABSPATH . 'wp-admin/admin-footer.php');
431                         exit;
432                 }
433                 return;
434         }
435
436         if ( ! is_object($wp_filesystem) )
437                 return new WP_Error('fs_unavailable', __('Could not access filesystem.'));
438
439         if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() )
440                 return new WP_Error('fs_error', __('Filesystem error'), $wp_filesystem->errors);
441
442         //Get the base plugin folder
443         $plugins_dir = $wp_filesystem->wp_plugins_dir();
444         if ( empty($plugins_dir) )
445                 return new WP_Error('fs_no_plugins_dir', __('Unable to locate WordPress Plugin directory.'));
446
447         $plugins_dir = trailingslashit( $plugins_dir );
448
449         $errors = array();
450
451         foreach( $plugins as $plugin_file ) {
452                 // Run Uninstall hook
453                 if ( is_uninstallable_plugin( $plugin_file ) )
454                         uninstall_plugin($plugin_file);
455
456                 $this_plugin_dir = trailingslashit( dirname($plugins_dir . $plugin_file) );
457                 // If plugin is in its own directory, recursively delete the directory.
458                 if ( strpos($plugin_file, '/') && $this_plugin_dir != $plugins_dir ) //base check on if plugin includes directory seperator AND that its not the root plugin folder
459                         $deleted = $wp_filesystem->delete($this_plugin_dir, true);
460                 else
461                         $deleted = $wp_filesystem->delete($plugins_dir . $plugin_file);
462
463                 if ( ! $deleted )
464                         $errors[] = $plugin_file;
465         }
466
467         if ( ! empty($errors) )
468                 return new WP_Error('could_not_remove_plugin', sprintf(__('Could not fully remove the plugin(s) %s'), implode(', ', $errors)) );
469
470         // Force refresh of plugin update information
471         if ( $current = get_transient('update_plugins') ) {
472                 unset( $current->response[ $plugin_file ] );
473                 set_transient('update_plugins', $current);
474         }
475
476         return true;
477 }
478
479 function validate_active_plugins() {
480         $check_plugins = get_option('active_plugins');
481
482         // Sanity check.  If the active plugin list is not an array, make it an
483         // empty array.
484         if ( !is_array($check_plugins) ) {
485                 update_option('active_plugins', array());
486                 return;
487         }
488
489         //Invalid is any plugin that is deactivated due to error.
490         $invalid = array();
491
492         // If a plugin file does not exist, remove it from the list of active
493         // plugins.
494         foreach ( $check_plugins as $check_plugin ) {
495                 $result = validate_plugin($check_plugin);
496                 if ( is_wp_error( $result ) ) {
497                         $invalid[$check_plugin] = $result;
498                         deactivate_plugins( $check_plugin, true);
499                 }
500         }
501         return $invalid;
502 }
503
504 /**
505  * Validate the plugin path.
506  *
507  * Checks that the file exists and {@link validate_file() is valid file}.
508  *
509  * @since unknown
510  *
511  * @param string $plugin Plugin Path
512  * @return WP_Error|int 0 on success, WP_Error on failure.
513  */
514 function validate_plugin($plugin) {
515         if ( validate_file($plugin) )
516                 return new WP_Error('plugin_invalid', __('Invalid plugin path.'));
517         if ( ! file_exists(WP_PLUGIN_DIR . '/' . $plugin) )
518                 return new WP_Error('plugin_not_found', __('Plugin file does not exist.'));
519
520         $installed_plugins = get_plugins();
521         if ( ! isset($installed_plugins[$plugin]) )
522                 return new WP_Error('no_plugin_header', __('The plugin does not have a valid header.'));
523         return 0;
524 }
525
526 /**
527  * Whether the plugin can be uninstalled.
528  *
529  * @since 2.7.0
530  *
531  * @param string $plugin Plugin path to check.
532  * @return bool Whether plugin can be uninstalled.
533  */
534 function is_uninstallable_plugin($plugin) {
535         $file = plugin_basename($plugin);
536
537         $uninstallable_plugins = (array) get_option('uninstall_plugins');
538         if ( isset( $uninstallable_plugins[$file] ) || file_exists( WP_PLUGIN_DIR . '/' . dirname($file) . '/uninstall.php' ) )
539                 return true;
540
541         return false;
542 }
543
544 /**
545  * Uninstall a single plugin.
546  *
547  * Calls the uninstall hook, if it is available.
548  *
549  * @since 2.7.0
550  *
551  * @param string $plugin Relative plugin path from Plugin Directory.
552  */
553 function uninstall_plugin($plugin) {
554         $file = plugin_basename($plugin);
555
556         $uninstallable_plugins = (array) get_option('uninstall_plugins');
557         if ( file_exists( WP_PLUGIN_DIR . '/' . dirname($file) . '/uninstall.php' ) ) {
558                 if ( isset( $uninstallable_plugins[$file] ) ) {
559                         unset($uninstallable_plugins[$file]);
560                         update_option('uninstall_plugins', $uninstallable_plugins);
561                 }
562                 unset($uninstallable_plugins);
563
564                 define('WP_UNINSTALL_PLUGIN', $file);
565                 include WP_PLUGIN_DIR . '/' . dirname($file) . '/uninstall.php';
566
567                 return true;
568         }
569
570         if ( isset( $uninstallable_plugins[$file] ) ) {
571                 $callable = $uninstallable_plugins[$file];
572                 unset($uninstallable_plugins[$file]);
573                 update_option('uninstall_plugins', $uninstallable_plugins);
574                 unset($uninstallable_plugins);
575
576                 include WP_PLUGIN_DIR . '/' . $file;
577
578                 add_action( 'uninstall_' . $file, $callable );
579                 do_action( 'uninstall_' . $file );
580         }
581 }
582
583 //
584 // Menu
585 //
586
587 function add_menu_page( $page_title, $menu_title, $access_level, $file, $function = '', $icon_url = '' ) {
588         global $menu, $admin_page_hooks;
589
590         $file = plugin_basename( $file );
591
592         $admin_page_hooks[$file] = sanitize_title( $menu_title );
593
594         $hookname = get_plugin_page_hookname( $file, '' );
595         if (!empty ( $function ) && !empty ( $hookname ))
596                 add_action( $hookname, $function );
597
598         if ( empty($icon_url) )
599                 $icon_url = 'images/generic.png';
600         elseif ( is_ssl() && 0 === strpos($icon_url, 'http://') )
601                 $icon_url = 'https://' . substr($icon_url, 7);
602
603         $menu[] = array ( $menu_title, $access_level, $file, $page_title, 'menu-top ' . $hookname, $hookname, $icon_url );
604
605         return $hookname;
606 }
607
608 function add_object_page( $page_title, $menu_title, $access_level, $file, $function = '', $icon_url = '') {
609         global $menu, $admin_page_hooks, $_wp_last_object_menu;
610
611         $file = plugin_basename( $file );
612
613         $admin_page_hooks[$file] = sanitize_title( $menu_title );
614
615         $hookname = get_plugin_page_hookname( $file, '' );
616         if (!empty ( $function ) && !empty ( $hookname ))
617                 add_action( $hookname, $function );
618
619         if ( empty($icon_url) )
620                 $icon_url = 'images/generic.png';
621
622         $_wp_last_object_menu++;
623
624         $menu[$_wp_last_object_menu] = array ( $menu_title, $access_level, $file, $page_title, 'menu-top ' . $hookname, $hookname, $icon_url );
625
626         return $hookname;
627 }
628
629 function add_utility_page( $page_title, $menu_title, $access_level, $file, $function = '', $icon_url = '') {
630         global $menu, $admin_page_hooks, $_wp_last_utility_menu;
631
632         $file = plugin_basename( $file );
633
634         $admin_page_hooks[$file] = sanitize_title( $menu_title );
635
636         $hookname = get_plugin_page_hookname( $file, '' );
637         if (!empty ( $function ) && !empty ( $hookname ))
638                 add_action( $hookname, $function );
639
640         if ( empty($icon_url) )
641                 $icon_url = 'images/generic.png';
642         elseif ( is_ssl() && 0 === strpos($icon_url, 'http://') )
643                 $icon_url = 'https://' . substr($icon_url, 7);
644
645         $_wp_last_utility_menu++;
646
647         $menu[$_wp_last_utility_menu] = array ( $menu_title, $access_level, $file, $page_title, 'menu-top ' . $hookname, $hookname, $icon_url );
648
649         return $hookname;
650 }
651
652 function add_submenu_page( $parent, $page_title, $menu_title, $access_level, $file, $function = '' ) {
653         global $submenu;
654         global $menu;
655         global $_wp_real_parent_file;
656         global $_wp_submenu_nopriv;
657
658         $file = plugin_basename( $file );
659
660         $parent = plugin_basename( $parent);
661         if ( isset( $_wp_real_parent_file[$parent] ) )
662                 $parent = $_wp_real_parent_file[$parent];
663
664         if ( !current_user_can( $access_level ) ) {
665                 $_wp_submenu_nopriv[$parent][$file] = true;
666                 return false;
667         }
668
669         // If the parent doesn't already have a submenu, add a link to the parent
670         // as the first item in the submenu.  If the submenu file is the same as the
671         // parent file someone is trying to link back to the parent manually.  In
672         // this case, don't automatically add a link back to avoid duplication.
673         if (!isset( $submenu[$parent] ) && $file != $parent  ) {
674                 foreach ( (array)$menu as $parent_menu ) {
675                         if ( $parent_menu[2] == $parent && current_user_can( $parent_menu[1] ) )
676                                 $submenu[$parent][] = $parent_menu;
677                 }
678         }
679
680         $submenu[$parent][] = array ( $menu_title, $access_level, $file, $page_title );
681
682         $hookname = get_plugin_page_hookname( $file, $parent);
683         if (!empty ( $function ) && !empty ( $hookname ))
684                 add_action( $hookname, $function );
685
686         return $hookname;
687 }
688
689 /**
690  * Add sub menu page to the tools main menu.
691  *
692  * @param string $page_title
693  * @param unknown_type $menu_title
694  * @param unknown_type $access_level
695  * @param unknown_type $file
696  * @param unknown_type $function
697  * @return unknown
698  */
699 function add_management_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
700         return add_submenu_page( 'tools.php', $page_title, $menu_title, $access_level, $file, $function );
701 }
702
703 function add_options_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
704         return add_submenu_page( 'options-general.php', $page_title, $menu_title, $access_level, $file, $function );
705 }
706
707 function add_theme_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
708         return add_submenu_page( 'themes.php', $page_title, $menu_title, $access_level, $file, $function );
709 }
710
711 function add_users_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
712         if ( current_user_can('edit_users') )
713                 $parent = 'users.php';
714         else
715                 $parent = 'profile.php';
716         return add_submenu_page( $parent, $page_title, $menu_title, $access_level, $file, $function );
717 }
718
719 function add_dashboard_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
720         return add_submenu_page( 'index.php', $page_title, $menu_title, $access_level, $file, $function );
721 }
722
723 function add_posts_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
724         return add_submenu_page( 'edit.php', $page_title, $menu_title, $access_level, $file, $function );
725 }
726
727 function add_media_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
728         return add_submenu_page( 'upload.php', $page_title, $menu_title, $access_level, $file, $function );
729 }
730
731 function add_links_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
732         return add_submenu_page( 'link-manager.php', $page_title, $menu_title, $access_level, $file, $function );
733 }
734
735 function add_pages_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
736         return add_submenu_page( 'edit-pages.php', $page_title, $menu_title, $access_level, $file, $function );
737 }
738
739 function add_comments_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
740         return add_submenu_page( 'edit-comments.php', $page_title, $menu_title, $access_level, $file, $function );
741 }
742
743 //
744 // Pluggable Menu Support -- Private
745 //
746
747 function get_admin_page_parent( $parent = '' ) {
748         global $parent_file;
749         global $menu;
750         global $submenu;
751         global $pagenow;
752         global $plugin_page;
753         global $_wp_real_parent_file;
754         global $_wp_menu_nopriv;
755         global $_wp_submenu_nopriv;
756
757         if ( !empty ( $parent ) && 'admin.php' != $parent ) {
758                 if ( isset( $_wp_real_parent_file[$parent] ) )
759                         $parent = $_wp_real_parent_file[$parent];
760                 return $parent;
761         }
762 /*
763         if ( !empty ( $parent_file ) ) {
764                 if ( isset( $_wp_real_parent_file[$parent_file] ) )
765                         $parent_file = $_wp_real_parent_file[$parent_file];
766
767                 return $parent_file;
768         }
769 */
770
771         if ( $pagenow == 'admin.php' && isset( $plugin_page ) ) {
772                 foreach ( (array)$menu as $parent_menu ) {
773                         if ( $parent_menu[2] == $plugin_page ) {
774                                 $parent_file = $plugin_page;
775                                 if ( isset( $_wp_real_parent_file[$parent_file] ) )
776                                         $parent_file = $_wp_real_parent_file[$parent_file];
777                                 return $parent_file;
778                         }
779                 }
780                 if ( isset( $_wp_menu_nopriv[$plugin_page] ) ) {
781                         $parent_file = $plugin_page;
782                         if ( isset( $_wp_real_parent_file[$parent_file] ) )
783                                         $parent_file = $_wp_real_parent_file[$parent_file];
784                         return $parent_file;
785                 }
786         }
787
788         if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$pagenow][$plugin_page] ) ) {
789                 $parent_file = $pagenow;
790                 if ( isset( $_wp_real_parent_file[$parent_file] ) )
791                         $parent_file = $_wp_real_parent_file[$parent_file];
792                 return $parent_file;
793         }
794
795         foreach (array_keys( (array)$submenu ) as $parent) {
796                 foreach ( $submenu[$parent] as $submenu_array ) {
797                         if ( isset( $_wp_real_parent_file[$parent] ) )
798                                 $parent = $_wp_real_parent_file[$parent];
799                         if ( $submenu_array[2] == $pagenow ) {
800                                 $parent_file = $parent;
801                                 return $parent;
802                         } else
803                                 if ( isset( $plugin_page ) && ($plugin_page == $submenu_array[2] ) ) {
804                                         $parent_file = $parent;
805                                         return $parent;
806                                 }
807                 }
808         }
809
810         if ( empty($parent_file) )
811                 $parent_file = '';
812         return '';
813 }
814
815 function get_admin_page_title() {
816         global $title;
817         global $menu;
818         global $submenu;
819         global $pagenow;
820         global $plugin_page;
821
822         if ( isset( $title ) && !empty ( $title ) ) {
823                 return $title;
824         }
825
826         $hook = get_plugin_page_hook( $plugin_page, $pagenow );
827
828         $parent = $parent1 = get_admin_page_parent();
829
830         if ( empty ( $parent) ) {
831                 foreach ( (array)$menu as $menu_array ) {
832                         if ( isset( $menu_array[3] ) ) {
833                                 if ( $menu_array[2] == $pagenow ) {
834                                         $title = $menu_array[3];
835                                         return $menu_array[3];
836                                 } else
837                                         if ( isset( $plugin_page ) && ($plugin_page == $menu_array[2] ) && ($hook == $menu_array[3] ) ) {
838                                                 $title = $menu_array[3];
839                                                 return $menu_array[3];
840                                         }
841                         } else {
842                                 $title = $menu_array[0];
843                                 return $title;
844                         }
845                 }
846         } else {
847                 foreach (array_keys( $submenu ) as $parent) {
848                         foreach ( $submenu[$parent] as $submenu_array ) {
849                                 if ( isset( $plugin_page ) &&
850                                         ($plugin_page == $submenu_array[2] ) &&
851                                         (($parent == $pagenow ) || ($parent == $plugin_page ) || ($plugin_page == $hook ) || (($pagenow == 'admin.php' ) && ($parent1 != $submenu_array[2] ) ) )
852                                         ) {
853                                                 $title = $submenu_array[3];
854                                                 return $submenu_array[3];
855                                         }
856
857                                 if ( $submenu_array[2] != $pagenow || isset( $_GET['page'] ) ) // not the current page
858                                         continue;
859
860                                 if ( isset( $submenu_array[3] ) ) {
861                                         $title = $submenu_array[3];
862                                         return $submenu_array[3];
863                                 } else {
864                                         $title = $submenu_array[0];
865                                         return $title;
866                                 }
867                         }
868                 }
869                 if ( !isset($title) || empty ( $title ) ) {
870                         foreach ( $menu as $menu_array ) {
871                                 if ( isset( $plugin_page ) &&
872                                         ($plugin_page == $menu_array[2] ) &&
873                                         ($pagenow == 'admin.php' ) &&
874                                         ($parent1 == $menu_array[2] ) )
875                                         {
876                                                 $title = $menu_array[3];
877                                                 return $menu_array[3];
878                                         }
879                         }
880                 }
881         }
882
883         return $title;
884 }
885
886 function get_plugin_page_hook( $plugin_page, $parent_page ) {
887         $hook = get_plugin_page_hookname( $plugin_page, $parent_page );
888         if ( has_action($hook) )
889                 return $hook;
890         else
891                 return null;
892 }
893
894 function get_plugin_page_hookname( $plugin_page, $parent_page ) {
895         global $admin_page_hooks;
896
897         $parent = get_admin_page_parent( $parent_page );
898
899         $page_type = 'admin';
900         if ( empty ( $parent_page ) || 'admin.php' == $parent_page || isset( $admin_page_hooks[$plugin_page] ) ) {
901                 if ( isset( $admin_page_hooks[$plugin_page] ) )
902                         $page_type = 'toplevel';
903                 else
904                         if ( isset( $admin_page_hooks[$parent] ))
905                                 $page_type = $admin_page_hooks[$parent];
906         } else if ( isset( $admin_page_hooks[$parent] ) ) {
907                 $page_type = $admin_page_hooks[$parent];
908         }
909
910         $plugin_name = preg_replace( '!\.php!', '', $plugin_page );
911
912         return $page_type.'_page_'.$plugin_name;
913 }
914
915 function user_can_access_admin_page() {
916         global $pagenow;
917         global $menu;
918         global $submenu;
919         global $_wp_menu_nopriv;
920         global $_wp_submenu_nopriv;
921         global $plugin_page;
922
923         $parent = get_admin_page_parent();
924
925         if ( !isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$parent][$pagenow] ) )
926                 return false;
927
928         if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$parent][$plugin_page] ) )
929                 return false;
930
931         if ( empty( $parent) ) {
932                 if ( isset( $_wp_menu_nopriv[$pagenow] ) )
933                         return false;
934                 if ( isset( $_wp_submenu_nopriv[$pagenow][$pagenow] ) )
935                         return false;
936                 if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$pagenow][$plugin_page] ) )
937                         return false;
938                 foreach (array_keys( $_wp_submenu_nopriv ) as $key ) {
939                         if ( isset( $_wp_submenu_nopriv[$key][$pagenow] ) )
940                                 return false;
941                         if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$key][$plugin_page] ) )
942                         return false;
943                 }
944                 return true;
945         }
946
947         if ( isset( $submenu[$parent] ) ) {
948                 foreach ( $submenu[$parent] as $submenu_array ) {
949                         if ( isset( $plugin_page ) && ( $submenu_array[2] == $plugin_page ) ) {
950                                 if ( current_user_can( $submenu_array[1] ))
951                                         return true;
952                                 else
953                                         return false;
954                         } else if ( $submenu_array[2] == $pagenow ) {
955                                 if ( current_user_can( $submenu_array[1] ))
956                                         return true;
957                                 else
958                                         return false;
959                         }
960                 }
961         }
962
963         foreach ( $menu as $menu_array ) {
964                 if ( $menu_array[2] == $parent) {
965                         if ( current_user_can( $menu_array[1] ))
966                                 return true;
967                         else
968                                 return false;
969                 }
970         }
971
972         return true;
973 }
974
975 /* Whitelist functions */
976
977 /**
978  * Register a setting and its sanitization callback
979  *
980  * @since 2.7.0
981  *
982  * @param string $option_group A settings group name.  Can be anything.
983  * @param string $option_name The name of an option to sanitize and save.
984  * @param unknown_type $sanitize_callback A callback function that sanitizes the option's value.
985  * @return unknown
986  */
987 function register_setting($option_group, $option_name, $sanitize_callback = '') {
988         return add_option_update_handler($option_group, $option_name, $sanitize_callback);
989 }
990
991 /**
992  * Unregister a setting
993  *
994  * @since 2.7.0
995  *
996  * @param unknown_type $option_group
997  * @param unknown_type $option_name
998  * @param unknown_type $sanitize_callback
999  * @return unknown
1000  */
1001 function unregister_setting($option_group, $option_name, $sanitize_callback = '') {
1002         return remove_option_update_handler($option_group, $option_name, $sanitize_callback);
1003 }
1004
1005 /**
1006  * {@internal Missing Short Description}}
1007  *
1008  * @since unknown
1009  *
1010  * @param unknown_type $option_group
1011  * @param unknown_type $option_name
1012  * @param unknown_type $sanitize_callback
1013  */
1014 function add_option_update_handler($option_group, $option_name, $sanitize_callback = '') {
1015         global $new_whitelist_options;
1016         $new_whitelist_options[ $option_group ][] = $option_name;
1017         if ( $sanitize_callback != '' )
1018                 add_filter( "sanitize_option_{$option_name}", $sanitize_callback );
1019 }
1020
1021 /**
1022  * {@internal Missing Short Description}}
1023  *
1024  * @since unknown
1025  *
1026  * @param unknown_type $option_group
1027  * @param unknown_type $option_name
1028  * @param unknown_type $sanitize_callback
1029  */
1030 function remove_option_update_handler($option_group, $option_name, $sanitize_callback = '') {
1031         global $new_whitelist_options;
1032         $pos = array_search( $option_name, (array) $new_whitelist_options );
1033         if ( $pos !== false )
1034                 unset( $new_whitelist_options[ $option_group ][ $pos ] );
1035         if ( $sanitize_callback != '' )
1036                 remove_filter( "sanitize_option_{$option_name}", $sanitize_callback );
1037 }
1038
1039 /**
1040  * {@internal Missing Short Description}}
1041  *
1042  * @since unknown
1043  *
1044  * @param unknown_type $options
1045  * @return unknown
1046  */
1047 function option_update_filter( $options ) {
1048         global $new_whitelist_options;
1049
1050         if ( is_array( $new_whitelist_options ) )
1051                 $options = add_option_whitelist( $new_whitelist_options, $options );
1052
1053         return $options;
1054 }
1055 add_filter( 'whitelist_options', 'option_update_filter' );
1056
1057 /**
1058  * {@internal Missing Short Description}}
1059  *
1060  * @since unknown
1061  *
1062  * @param unknown_type $new_options
1063  * @param unknown_type $options
1064  * @return unknown
1065  */
1066 function add_option_whitelist( $new_options, $options = '' ) {
1067         if( $options == '' ) {
1068                 global $whitelist_options;
1069         } else {
1070                 $whitelist_options = $options;
1071         }
1072         foreach( $new_options as $page => $keys ) {
1073                 foreach( $keys as $key ) {
1074                         if ( !isset($whitelist_options[ $page ]) || !is_array($whitelist_options[ $page ]) ) {
1075                                 $whitelist_options[ $page ] = array();
1076                                 $whitelist_options[ $page ][] = $key;
1077                         } else {
1078                                 $pos = array_search( $key, $whitelist_options[ $page ] );
1079                                 if ( $pos === false )
1080                                         $whitelist_options[ $page ][] = $key;
1081                         }
1082                 }
1083         }
1084         return $whitelist_options;
1085 }
1086
1087 /**
1088  * {@internal Missing Short Description}}
1089  *
1090  * @since unknown
1091  *
1092  * @param unknown_type $del_options
1093  * @param unknown_type $options
1094  * @return unknown
1095  */
1096 function remove_option_whitelist( $del_options, $options = '' ) {
1097         if( $options == '' ) {
1098                 global $whitelist_options;
1099         } else {
1100                 $whitelist_options = $options;
1101         }
1102         foreach( $del_options as $page => $keys ) {
1103                 foreach( $keys as $key ) {
1104                         if ( isset($whitelist_options[ $page ]) && is_array($whitelist_options[ $page ]) ) {
1105                                 $pos = array_search( $key, $whitelist_options[ $page ] );
1106                                 if( $pos !== false )
1107                                         unset( $whitelist_options[ $page ][ $pos ] );
1108                         }
1109                 }
1110         }
1111         return $whitelist_options;
1112 }
1113
1114 /**
1115  * Output nonce, action, and option_page fields for a settings page.
1116  *
1117  * @since 2.7.0
1118  *
1119  * @param string $option_group A settings group name.  This should match the group name used in register_setting().
1120  */
1121 function settings_fields($option_group) {
1122         echo "<input type='hidden' name='option_page' value='" . esc_attr($option_group) . "' />";
1123         echo '<input type="hidden" name="action" value="update" />';
1124         wp_nonce_field("$option_group-options");
1125 }
1126
1127 ?>