]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions-plugins.php
Remove unnecessary function_exists()
[Github/YOURLS.git] / includes / functions-plugins.php
1 <?php
2
3 /**
4  * The filter/plugin API is located in this file, which allows for creating filters
5  * and hooking functions, and methods. The functions or methods will be run when
6  * the filter is called.
7  *
8  * Any of the syntaxes explained in the PHP documentation for the
9  * {@link http://us2.php.net/manual/en/language.pseudo-types.php#language.types.callback 'callback'}
10  * type are valid.
11  *
12  * This API is heavily inspired by the one I implemented in Zenphoto 1.3, which was heavily inspired by the one used in WordPress.
13  *
14  * @author Ozh
15  * @since 1.5
16  */
17
18 $yourls_filters = array();
19 /* This global var will collect filters with the following structure:
20  * $yourls_filters['hook']['array of priorities']['serialized function names']['array of ['array (functions, accepted_args)]']
21  */
22
23 /**
24  * Registers a filtering function
25  * 
26  * Typical use:
27  *              yourls_add_filter('some_hook', 'function_handler_for_hook');
28  *
29  * @global array $yourls_filters Storage for all of the filters
30  * @param string $hook the name of the YOURLS element to be filtered or YOURLS action to be triggered
31  * @param callback $function_name the name of the function that is to be called.
32  * @param integer $priority optional. Used to specify the order in which the functions associated with a particular action are executed (default=10, lower=earlier execution, and functions with the same priority are executed in the order in which they were added to the filter)
33  * @param int $accepted_args optional. The number of arguments the function accept (default is the number provided).
34  * @param string $type
35  */
36 function yourls_add_filter( $hook, $function_name, $priority = 10, $accepted_args = NULL, $type = 'filter' ) {
37         global $yourls_filters;
38         // At this point, we cannot check if the function exists, as it may well be defined later (which is OK)
39         $id = yourls_filter_unique_id( $hook, $function_name, $priority );
40         
41         $yourls_filters[ $hook ][ $priority ][ $id ] = array(
42                 'function'      => $function_name,
43                 'accepted_args' => $accepted_args,
44                 'type'          => $type,
45         );
46 }
47
48 /**
49  * Hooks a function on to a specific action.
50  *
51  * Actions are the hooks that YOURLS launches at specific points
52  * during execution, or when specific events occur. Plugins can specify that
53  * one or more of its PHP functions are executed at these points, using the
54  * Action API.
55  *
56  * @param string $hook The name of the action to which the $function_to_add is hooked.
57  * @param callback $function_name The name of the function you wish to be called.
58  * @param int $priority optional. Used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
59  * @param int $accepted_args optional. The number of arguments the function accept (default 1).
60  */
61 function yourls_add_action( $hook, $function_name, $priority = 10, $accepted_args = 1 ) {
62         return yourls_add_filter( $hook, $function_name, $priority, $accepted_args, 'action' );
63 }
64
65
66
67 /**
68  * Build Unique ID for storage and retrieval.
69  *
70  * Simply using a function name is not enough, as several functions can have the same name when they are enclosed in classes.
71  *
72  * @global array $yourls_filters storage for all of the filters
73  * @param string $hook hook to which the function is attached
74  * @param string|array $function used for creating unique id
75  * @param int|bool $priority used in counting how many hooks were applied.  If === false and $function is an object reference, we return the unique id only if it already has one, false otherwise.
76  * @return string unique ID for usage as array key
77  */
78 function yourls_filter_unique_id( $hook, $function, $priority ) {
79         global $yourls_filters;
80
81         // If function then just skip all of the tests and not overwrite the following.
82         if ( is_string( $function ) ) {
83                 return $function;
84     }
85     
86         if( is_object($function) ) {
87                 // Closures are currently implemented as objects
88                 $function = array( $function, '' );
89         } else {
90                 $function = (array) $function;
91         }
92
93         // Object Class Calling
94         if ( is_object( $function[0] ) ) {
95         return spl_object_hash( $function[0] ) . $function[1];
96         }
97     // Static Calling
98         else if ( is_string( $function[0] ) ) {
99                 return $function[0]. '::' .$function[1];
100     }
101 }
102
103 /**
104  * Performs a filtering operation on a YOURLS element or event.
105  *
106  * Typical use:
107  *
108  *              1) Modify a variable if a function is attached to hook 'yourls_hook'
109  *              $yourls_var = "default value";
110  *              $yourls_var = yourls_apply_filter( 'yourls_hook', $yourls_var );
111  *
112  *              2) Trigger functions is attached to event 'yourls_event'
113  *              yourls_apply_filter( 'yourls_event' );
114  *      (see yourls_do_action() )
115  * 
116  * Returns an element which may have been filtered by a filter.
117  *
118  * @global array $yourls_filters storage for all of the filters
119  * @param string $hook the name of the YOURLS element or action
120  * @param mixed $value the value of the element before filtering
121  * @return mixed
122  */
123 function yourls_apply_filter( $hook, $value = '' ) {
124         global $yourls_filters;
125         if ( !isset( $yourls_filters[ $hook ] ) )
126                 return $value;
127         
128         $args = func_get_args();
129         
130         // Sort filters by priority
131         ksort( $yourls_filters[ $hook ] );
132         
133         // Loops through each filter
134         reset( $yourls_filters[ $hook ] );
135         do {
136                 foreach( (array) current( $yourls_filters[ $hook ] ) as $the_ ) {
137                         if ( !is_null( $the_['function'] ) ){
138                                 $args[1] = $value;
139                                 $count = $the_['accepted_args'];
140                                 if ( is_null( $count ) ) {
141                                         $_value = call_user_func_array( $the_['function'], array_slice( $args, 1 ) );
142                                 } else {
143                                         $_value = call_user_func_array( $the_['function'], array_slice( $args, 1, (int) $count ) );
144                                 }
145                         }
146                         if( $the_['type'] == 'filter' )
147                                 $value = $_value;
148                 }
149
150         } while ( next( $yourls_filters[ $hook ] ) !== false );
151         
152         if( $the_['type'] == 'filter' )
153                 return $value;
154 }
155
156 /**
157  * Performs an action triggered by a YOURLS event.
158
159  * @param string $hook the name of the YOURLS action
160  * @param mixed $arg action arguments
161  */
162 function yourls_do_action( $hook, $arg = '' ) {
163         global $yourls_actions;
164         
165         // Keep track of actions that are "done"
166         if ( !isset( $yourls_actions ) )
167                 $yourls_actions = array();
168         if ( !isset( $yourls_actions[ $hook ] ) )
169                 $yourls_actions[ $hook ] = 1;
170         else
171                 ++$yourls_actions[ $hook ];
172
173         $args = array();
174         if ( is_array( $arg ) && 1 == count( $arg ) && isset( $arg[0] ) && is_object( $arg[0] ) ) // array(&$this)
175                 $args[] =& $arg[0];
176         else
177                 $args[] = $arg;
178         for ( $a = 2; $a < func_num_args(); $a++ )
179                 $args[] = func_get_arg( $a );
180         
181         yourls_apply_filter( $hook, $args );
182 }
183
184 /**
185 * Retrieve the number times an action is fired.
186 *
187 * @param string $hook Name of the action hook.
188 * @return int The number of times action hook <tt>$hook</tt> is fired
189 */
190 function yourls_did_action( $hook ) {
191         global $yourls_actions;
192         if ( !isset( $yourls_actions ) || !isset( $yourls_actions[ $hook ] ) )
193                 return 0;
194         return $yourls_actions[ $hook ];
195 }
196
197 /**
198  * Removes a function from a specified filter hook.
199  *
200  * This function removes a function attached to a specified filter hook. This
201  * method can be used to remove default functions attached to a specific filter
202  * hook and possibly replace them with a substitute.
203  *
204  * To remove a hook, the $function_to_remove and $priority arguments must match
205  * when the hook was added.
206  *
207  * @global array $yourls_filters storage for all of the filters
208  * @param string $hook The filter hook to which the function to be removed is hooked.
209  * @param callback $function_to_remove The name of the function which should be removed.
210  * @param int $priority optional. The priority of the function (default: 10).
211  * @return boolean Whether the function was registered as a filter before it was removed.
212  */
213 function yourls_remove_filter( $hook, $function_to_remove, $priority = 10 ) {
214         global $yourls_filters;
215         
216         $function_to_remove = yourls_filter_unique_id( $hook, $function_to_remove, $priority );
217
218         $remove = isset( $yourls_filters[ $hook ][ $priority ][ $function_to_remove ] );
219
220         if ( $remove === true ) {
221                 unset ( $yourls_filters[$hook][$priority][$function_to_remove] );
222                 if ( empty( $yourls_filters[$hook][$priority] ) )
223                         unset( $yourls_filters[$hook] );
224         }
225         return $remove;
226 }
227
228 /**
229  * Removes a function from a specified action hook.
230  *
231  * @see yourls_remove_filter()
232  *
233  * @param string $hook The action hook to which the function to be removed is hooked.
234  * @param callback $function_to_remove The name of the function which should be removed.
235  * @param int $priority optional. The priority of the function (default: 10).
236  * @return boolean Whether the function was registered as an action before it was removed.
237  */
238
239 function yourls_remove_action( $hook, $function_to_remove, $priority = 10 ) {
240     return yourls_remove_filter( $hook, $function_to_remove, $priority );
241 }
242
243 /**
244  * Check if any filter has been registered for a hook.
245  *
246  * @global array $yourls_filters storage for all of the filters
247  * @param string $hook The name of the filter hook.
248  * @param callback $function_to_check optional.  If specified, return the priority of that function on this hook or false if not attached.
249  * @return int|boolean Optionally returns the priority on that hook for the specified function.
250  */
251 function yourls_has_filter( $hook, $function_to_check = false ) {
252         global $yourls_filters;
253
254         $has = !empty( $yourls_filters[ $hook ] );
255         if ( false === $function_to_check || false == $has ) {
256                 return $has;
257         }
258         if ( !$idx = yourls_filter_unique_id( $hook, $function_to_check, false ) ) {
259                 return false;
260         }
261
262         foreach ( (array) array_keys( $yourls_filters[ $hook ] ) as $priority ) {
263                 if ( isset( $yourls_filters[ $hook ][ $priority ][ $idx ] ) )
264                         return $priority;
265         }
266         return false;
267 }
268
269 function yourls_has_action( $hook, $function_to_check = false ) {
270         return yourls_has_filter( $hook, $function_to_check );
271 }
272
273 /**
274  * Return number of active plugins
275  *
276  * @return integer Number of activated plugins
277  */
278 function yourls_has_active_plugins( ) {
279         global $ydb;
280         
281         if( !property_exists( $ydb, 'plugins' ) || !$ydb->plugins )
282                 $ydb->plugins = array();
283                 
284         return count( $ydb->plugins );
285 }
286
287
288 /**
289  * List plugins in /user/plugins
290  *
291  * @global object $ydb Storage of mostly everything YOURLS needs to know
292  * @return array Array of [/plugindir/plugin.php]=>array('Name'=>'Ozh', 'Title'=>'Hello', )
293  */
294 function yourls_get_plugins( ) {
295         $plugins = (array) glob( YOURLS_PLUGINDIR .'/*/plugin.php');
296         
297         if( !$plugins )
298                 return array();
299         
300         foreach( $plugins as $key => $plugin ) {
301                 $_plugin = yourls_plugin_basename( $plugin );
302                 $plugins[ $_plugin ] = yourls_get_plugin_data( $plugin );
303                 unset( $plugins[ $key ] );
304         }
305         
306         return $plugins;
307 }
308
309 /**
310  * Check if a plugin is active
311  *
312  * @param string $plugin Physical path to plugin file
313  * @return bool
314  */
315 function yourls_is_active_plugin( $plugin ) {
316         if( !yourls_has_active_plugins( ) )
317                 return false;
318         
319         global $ydb;
320         $plugin = yourls_plugin_basename( $plugin );
321         
322         return in_array( $plugin, $ydb->plugins );
323
324 }
325
326 /**
327  * Parse a plugin header
328  *
329  * @param string $file Physical path to plugin file
330  * @return array Array of 'Field'=>'Value' from plugin comment header lines of the form "Field: Value"
331  */
332 function yourls_get_plugin_data( $file ) {
333         $fp = fopen( $file, 'r' ); // assuming $file is readable, since yourls_load_plugins() filters this
334         $data = fread( $fp, 8192 ); // get first 8kb
335         fclose( $fp );
336         
337         // Capture all the header within first comment block
338         if( !preg_match( '!.*?/\*(.*?)\*/!ms', $data, $matches ) )
339                 return array();
340         
341         // Capture each line with "Something: some text"
342         unset( $data );
343         $lines = preg_split( "[\n|\r]", $matches[1] );
344         unset( $matches );
345
346         $plugin_data = array();
347         foreach( $lines as $line ) {
348                 if( !preg_match( '!(.*?):\s+(.*)!', $line, $matches ) )
349                         continue;
350                 
351                 list( $null, $field, $value ) = array_map( 'trim', $matches);
352                 $plugin_data[ $field ] = $value;
353         }
354         
355         return $plugin_data;
356 }
357
358 // Include active plugins
359 function yourls_load_plugins() {
360         // Don't load plugins when installing or updating
361         if( yourls_is_installing() OR yourls_is_upgrading() )
362                 return;
363         
364         $active_plugins = yourls_get_option( 'active_plugins' );
365         if( false === $active_plugins )
366                 return;
367         
368         global $ydb;
369         $ydb->plugins = array();
370         
371         foreach( (array)$active_plugins as $key=>$plugin ) {
372                 if( yourls_validate_plugin_file( YOURLS_PLUGINDIR.'/'.$plugin ) ) {
373                         include_once( YOURLS_PLUGINDIR.'/'.$plugin );
374                         $ydb->plugins[] = $plugin;
375                         unset( $active_plugins[$key] );
376                 }
377         }
378         
379         // $active_plugins should be empty now, if not, a plugin could not be find: remove it
380         if( count( $active_plugins ) ) {
381                 yourls_update_option( 'active_plugins', $ydb->plugins );
382                 $message = yourls_n( 'Could not find and deactivated plugin :', 'Could not find and deactivated plugins :', count( $active_plugins ) );
383                 $missing = '<strong>'.join( '</strong>, <strong>', $active_plugins ).'</strong>';
384                 yourls_add_notice( $message .' '. $missing );
385         }
386 }
387
388 /**
389  * Check if a file is safe for inclusion (well, "safe", no guarantee)
390  *
391  * @param string $file Full pathname to a file
392  * @return bool
393  */
394 function yourls_validate_plugin_file( $file ) {
395         if (
396                 false !== strpos( $file, '..' )
397                 OR
398                 false !== strpos( $file, './' )
399                 OR
400                 'plugin.php' !== substr( $file, -10 )   // a plugin must be named 'plugin.php'
401                 OR
402                 !is_readable( $file )
403         )
404                 return false;
405                 
406         return true;
407 }
408
409 /**
410  * Activate a plugin
411  *
412  * @param string $plugin Plugin filename (full or relative to plugins directory)
413  * @return mixed string if error or true if success
414  */
415 function yourls_activate_plugin( $plugin ) {
416         // validate file
417         $plugin = yourls_plugin_basename( $plugin );
418         $plugindir = yourls_sanitize_filename( YOURLS_PLUGINDIR );
419         if( !yourls_validate_plugin_file( $plugindir.'/'.$plugin ) )
420                 return yourls__( 'Not a valid plugin file' );
421                 
422         // check not activated already
423         global $ydb;
424         if( yourls_has_active_plugins() && in_array( $plugin, $ydb->plugins ) )
425                 return yourls__( 'Plugin already activated' );
426         
427         // attempt activation. TODO: uber cool fail proof sandbox like in WP.
428         ob_start();
429         include_once( YOURLS_PLUGINDIR.'/'.$plugin );
430         if ( ob_get_length() > 0 ) {
431                 // there was some output: error
432                 $output = ob_get_clean();
433                 return yourls_s( 'Plugin generated unexpected output. Error was: <br/><pre>%s</pre>', $output );
434         }
435     ob_end_clean();
436
437         // so far, so good: update active plugin list
438         $ydb->plugins[] = $plugin;
439         yourls_update_option( 'active_plugins', $ydb->plugins );
440         yourls_do_action( 'activated_plugin', $plugin );
441         yourls_do_action( 'activated_' . $plugin );
442         
443         return true;
444 }
445
446 /**
447  * Deactivate a plugin
448  *
449  * @param string $plugin Plugin filename (full relative to plugins directory)
450  * @return mixed string if error or true if success
451  */
452 function yourls_deactivate_plugin( $plugin ) {
453         $plugin = yourls_plugin_basename( $plugin );
454
455         // Check plugin is active
456         if( !yourls_is_active_plugin( $plugin ) )
457                 return yourls__( 'Plugin not active' );
458         
459         // Deactivate the plugin
460         global $ydb;
461         $key = array_search( $plugin, $ydb->plugins );
462         if( $key !== false ) {
463                 array_splice( $ydb->plugins, $key, 1 );
464         }
465         
466         yourls_update_option( 'active_plugins', $ydb->plugins );
467         yourls_do_action( 'deactivated_plugin', $plugin );
468         yourls_do_action( 'deactivated_' . $plugin );
469         
470         return true;
471 }
472
473 /**
474  * Return the path of a plugin file, relative to the plugins directory
475  */
476 function yourls_plugin_basename( $file ) {
477         $file = yourls_sanitize_filename( $file );
478         $plugindir = yourls_sanitize_filename( YOURLS_PLUGINDIR );
479         $file = str_replace( $plugindir, '', $file );
480         return trim( $file, '/' );
481 }
482
483 /**
484  * Return the URL of the directory a plugin
485  */
486 function yourls_plugin_url( $file ) {
487         $url = YOURLS_PLUGINURL . '/' . yourls_plugin_basename( $file );
488         if( yourls_is_ssl() or yourls_needs_ssl() )
489                 $url = str_replace( 'http://', 'https://', $url );
490         return yourls_apply_filter( 'plugin_url', $url, $file );
491 }
492
493 /**
494  * Display list of links to plugin admin pages, if any
495  */
496 function yourls_list_plugin_admin_pages() {
497         global $ydb;
498         
499         if( !property_exists( $ydb, 'plugin_pages' ) || !$ydb->plugin_pages )
500                 return;
501         
502         $plugin_links = array();
503         foreach( (array)$ydb->plugin_pages as $plugin => $page ) {
504                 $plugin_links[ $plugin ] = array(
505                         'url'    => yourls_admin_url( 'plugins.php?page='.$page['slug'] ),
506                         'anchor' => $page['title'],
507                 );
508         }
509         return $plugin_links;
510 }
511
512 /**
513  * Register a plugin administration page
514  */
515 function yourls_register_plugin_page( $slug, $title, $function ) {
516         global $ydb;
517         
518         if( !property_exists( $ydb, 'plugin_pages' ) || !$ydb->plugin_pages )
519                 $ydb->plugin_pages = array();
520
521         $ydb->plugin_pages[ $slug ] = array(
522                 'slug'     => $slug,
523                 'title'    => $title,
524                 'function' => $function,
525         );
526 }
527
528 /**
529  * Handle plugin administration page
530  *
531  */
532 function yourls_plugin_admin_page( $plugin_page ) {
533         global $ydb;
534
535         // Check the plugin page is actually registered
536         if( !isset( $ydb->plugin_pages[$plugin_page] ) ) {
537                 yourls_die( yourls__( 'This page does not exist. Maybe a plugin you thought was activated is inactive?' ), yourls__( 'Invalid link' ) );
538         }
539         
540         // Draw the page itself
541         yourls_do_action( 'load-' . $plugin_page);
542         yourls_html_head( 'plugin_page_' . $plugin_page, $ydb->plugin_pages[$plugin_page]['title'] );
543         yourls_html_logo();
544         yourls_html_menu();
545         
546         call_user_func( $ydb->plugin_pages[$plugin_page]['function'] );
547         
548         yourls_html_footer();
549         
550         die();
551 }
552
553
554 /**
555  * Callback function: Sort plugins 
556  *
557  * @link http://php.net/uasort
558  *
559  * @param array $plugin_a
560  * @param array $plugin_b
561  * @return int 0, 1 or -1, see uasort()
562  */
563 function yourls_plugins_sort_callback( $plugin_a, $plugin_b ) {
564         $orderby = yourls_apply_filter( 'plugins_sort_callback', 'Plugin Name' );
565         $order   = yourls_apply_filter( 'plugins_sort_callback', 'ASC' );
566
567         $a = isset( $plugin_a[ $orderby ] ) ? $plugin_a[ $orderby ] : '';
568         $b = isset( $plugin_b[ $orderby ] ) ? $plugin_b[ $orderby ] : '';
569
570         if ( $a == $b )
571                 return 0;
572
573         if ( 'DESC' == $order )
574                 return ( $a < $b ) ? 1 : -1;
575         else
576                 return ( $a < $b ) ? -1 : 1;            
577 }