Location: PHPKode > projects > ProjectPress > projectpress/pm-includes/functions-plugins.php
<?php
if(!defined('access')) die ('You are not allowed to execute this file directly.');

/**
 * @package AdvPlugin - Advanced Plugin System
 * @author Sourcegeek
 *
 *
*/

	/**
	 *@var int
	 *
	*/
	$version = 1.1;
	
	/**
	 *@var array
	 *
	*/
	//$hooks = array();
	
	/**
	 *@var array
	 *
	*/
	$filters = array();
	
	/**
	 *@var string
	 *
	*/
	$plugins_dir = '';
	
	
	/**
	 * private handle
	 * Error handler
	 *
	*/
	function handle($function, $err) {
		if ( pmdb::connect()->is_error() ) {
			pmdb::connect()->last_error = "$function - $err. Function not connected to MySQL";
			return false;
		}
		return true;
	}
	
	
	/**
	 * public check_plugin
	 * Checks if the specified plugin exists
	 *
	 *@param string plugin
	 *
	*/
	function check_plugin($plugin) {
		global $plugins_dir;

		if(substr($plugin, 0, strlen($plugins_dir)) == $plugins_dir) {
			$plugin = substr($plugin, strlen($plugins_dir), strlen($plugin));
		}
	
		if(substr($plugin, -4) != '.php')
			$plugin .= '.php';
			
		if(file_exists($plugins_dir.$plugin))
			return true;
		return false;
	}
	
	
	/**
	 * public set_plugins_dir
	 * Sets new plugins dir
	 *
	 *@param string dir
	 *
	*/
	function set_plugins_dir($dir) {
		global $plugins_dir;
		if(substr($dir, -1) != '/')
			$plugins_dir = $dir.'/';
		else
			$plugins_dir = $dir;
		return true;
	}
	
	
	/**
	 * public get_plugin_info
	 * Returns the plugin info
	 *
	 *@param string plugin
	 *
	*/
	function get_plugin_info($plugin) {
		global $plugins_dir;
		if(substr($plugin, 0, strlen($plugins_dir)) == $plugins_dir) {
			$plugin = substr($plugin, strlen($plugins_dir), strlen($plugin));
		}
		
		if(substr($plugin, -4) != '.php')
			$plugin .= '.php';
			
		$plugin_name = $plugin;
		
		if(check_plugin($plugin) == false) {
			pmdb::connect()->last_error = "get_plugin_info - '$plugin' plugin doesn't exists";
			return false;
		}
		
		// Load it
		$plugin = file_get_contents($plugins_dir.$plugin);
		if(!$plugin) {
			pmdb::connect()->last_error = "get_plugin_info - Cannot load plugin info";
			return false;
		}
		
		// Get plugin info with regexp
		preg_match('/\/\*+(.*)\*\//ims', $plugin, $res);
		$plugin_header = $res[1];
		
		$info_types = array(
			'Name: ' => 'name',
			'Plugin URI: ' => 'url',
			'Version: ' => 'version',
			'Description: ' => 'description',
			'Author: ' => 'author',
			'Author URI: ' => 'author_url'
		);
		
		foreach($info_types as $regex => $var) {
			preg_match("/$regex(.*)/", $plugin_header, $$var);
		}

		foreach($info_types as $regex => $var) {
			if(!empty($$var))
				$$var = trim(${$var}[1]);
			else
				$$var = '';
		}
		
		$plugin_info = array(
			'Name' => $name,
			'Plugin URI' => $url,
			'Version' => $version,
			'Description' => $description,
			'Author' => $author,
			'Author URI' => $author_url,
			'Activated' => is_activated($plugin_name)
		);
		return $plugin_info;
	}
	
	
	/**
	 * public get_plugins_info
	 * Returns the plugins info of all the plugins in
	 * the plugins dir
	 *
	*/
	function get_plugins_info() {
		global $plugins_dir;
		$res = array();
		foreach(glob($plugins_dir.'*.php') as $file)
			$res[$file] = get_plugin_info(str_replace($plugins_dir, '', $file));
		if(count($res) == 0)
			return false;
		return $res;
	}
	
	
	/**
	 * public get_activated_plugins_info
	 * Returns the plugin info of all the activated plugins
	 * in MySQL
	 *
	*/
	function get_activated_plugins_info() {
		global $plugins_dir;
		if(handle('get_activated_plugins_info', 'Cannot get plugins info') === false)
			return false;
		
		$res = array();
		$qry = pmdb::connect()->query("SELECT * FROM " . DB . "plugins") or die ('AdvPlugin - get_activated_plugins_info
		- Cannot get info from MySQL');
		while($res = $qry->fetch_assoc()) {
			$plugin = $res['plugin_loc'];
			
			if(!file_exists($plugin)) {
				pmdb::connect()->last_error = "get_activated_plugins_info - '$plugin' plugin doesn't exists";
				return false;
			}
			
			$res[$file] = get_plugin_info(str_replace($plugins_dir, '', $plugin));
		}
		
		return $res;
	}
	
	
	/**
	 * public activate_plugin
	 * Activates the specified plugin
	 *
	 *@param string plugin
	 *
	*/
	function activate_plugin($plugin) {
		global $plugins_dir;
		if(handle('activate_plugin', 'Cannot activate plugin') === false)
			return false;
			
		if(substr($plugin, 0, strlen($plugins_dir)) == $plugins_dir) {
			$plugin = substr($plugin, strlen($plugins_dir), strlen($plugin));
		}
		
		if(substr($plugin, -4) != '.php')
			$plugin .= '.php';
		
		$plugindir = $plugins_dir.$plugin;
			
		if(check_plugin($plugin) == false) {
			pmdb::connect()->last_error = "activate_plugin - '$plugin' plugin doesn't exists";
			return false;
		}
		
		// All were ok, let's activate
		// Check if already exist
		$qry = pmdb::connect()->query("SELECT * FROM " . DB . "plugins WHERE plugin_loc = '$plugindir'") or die ('AdvPlugin - activate_plugin
		- Cannot activate plugin in MySQL');
		if($qry->num_rows > 0)
			return true;
			
		$qry = pmdb::connect()->query("INSERT INTO " . DB . "plugins(plugin_loc) VALUES ('$plugindir')") or die ('AdvPlugin - activate_plugin
		- Cannot activate plugin in MySQL');
		return true;
	}
	
	
	/**
	 * public deactivate_plugin
	 * Deactivates the specified plugin
	 *
	 *@param string plugin
	 *
	*/
	function deactivate_plugin($plugin) {
		global $plugins_dir;
		if(handle('deactivate_plugin', 'Cannot deactivate plugin') == false)
			return false;
			
		if(substr($plugin, 0, strlen($plugins_dir)) == $plugins_dir) {
			$plugin = substr($plugin, strlen($plugins_dir), strlen($plugin));
		}
			
		if(substr($plugin, -4) != '.php')
			$plugin .= '.php';
		
		$plugindir = $plugins_dir.$plugin;
		
		if(check_plugin($plugin) == false) {
			pmdb::connect()->last_error = "deactivate_plugin - '$plugin' plugin doesn't exists";
			return false;
		}
		
		// Is not activated, so, true...
		$qry = pmdb::connect()->query("SELECT * FROM " . DB . "plugins WHERE plugin_loc = '$plugindir'") or die ('AdvPlugin - activate_plugin
		- Cannot deactivate plugin in MySQL');
		if($qry->num_rows == 0)
			return true;
			
		// Activate, delete!
		$qry = pmdb::connect()->query("DELETE FROM " . DB . "plugins WHERE plugin_loc = '$plugindir'") or die ('AdvPlugin - activate_plugin
		- Cannot deactivate plugin in MySQL');
		return true;
	}
	
	
	/**
	 * public load_plugin
	 * Loads (includes) the specified plugin (activaded or deactivated)
	 *
	 *@param string plugin
	 *
	*/
	function load_plugin($plugin) {
		global $plugins_dir;
		if(handle('load_plugin', 'Cannot load plugin') == false)
			return false;
			
		if(substr($plugin, 0, strlen($plugins_dir)) == $plugins_dir) {
			$plugin = substr($plugin, strlen($plugins_dir), strlen($plugin));
		}
		
		if(substr($plugin, -4) != '.php')
			$plugin .= '.php';
		
		$plugindir = $plugins_dir.$plugin;
		
		if(check_plugin($plugin) == false) {
			pmdb::connect()->last_error = "load_plugin - '$plugin' plugin doesn't exists";
			return false;
		}
		
		if(check_plugin($plugin) == false) {
			pmdb::connect()->last_error = "load_plugin - '$plugindir' plugin doesn't exists";
			return false;
		}
		
		require_once $plugindir;
		return true;
	}
	
	
	/**
	 * public load_activated_plugin
	 * Loads (includes) the specified plugin ONLY if it is
	 * activated
	 *
	 *@param string plugin
	 *
	*/
	function load_activated_plugin($plugin) {
		global $plugins_dir;
		if(handle('load_activated_plugin', 'Cannot load plugin') == false)
			return false;
			
		if(substr($plugin, 0, strlen($plugins_dir)) == $plugins_dir) {
			$plugin = substr($plugin, strlen($plugins_dir), strlen($plugin));
		}
		
		if(substr($plugin, -4) != '.php')
			$plugin .= '.php';
		
		$plugindir = $plugins_dir.$plugin;
		
		if(check_plugin($plugin) == false) {
			pmdb::connect()->last_error = "load_plugin - '$plugindir' plugin doesn't exists";
			return false;
		}
		
		$qry = pmdb::connect()->query("SELECT * FROM " . DB . "plugins WHERE plugin_loc = '$plugindir'") or die ('AdvPlugin - 
		load_activated_plugin - Cannot check active plugin in MySQL');
		if($qry->num_rows > 0) {
			if(check_plugin($plugin) == false) {
				pmdb::connect()->last_error = "load_activated_plugin - '$plugin' plugin doesn't exists";
				return false;
			}
			require_once $plugindir;
		}
		
		return true;
	}
	
	
	/**
	 * public load_activated_plugins
	 * Loads (includes) all the activated plugins
	 *
	*/
	function load_activated_plugins() {
		if(handle('load_activated_plugins', 'Cannot load plugins') == false)
			return false;
		
		$qry = pmdb::connect()->query("SELECT * FROM " . DB . "plugins") or die ('AdvPlugin - load_activated_plugins - Cannot get
		loaded plugins');
		
		while($res = $qry->fetch_assoc()) {
			$tmpPlugin = $res['plugin_loc'];
			
			if(!file_exists($tmpPlugin)) {
				pmdb::connect()->last_error = "load_activated_plugins - '$tmpPlugin' plugin doesn't exists";
				return false;
			}
			
			require_once $tmpPlugin;
		}
	}
	
	
	/**
	 * public load_plugins
	 * Loads all the plugins in the plugins dir
	 *
	*/
	function load_plugins() {
		global $plugins_dir;
		foreach(glob($plugins_dir.'*.php') as $file)
			require_once $file;
		return true;
	}
	
	
	/**
	 * public get_activated_plugins
	 * Returns all the activated plugins in MySQL
	 *
	*/
	function get_activated_plugins() {
		global $plugins_dir;
		if(handle('get_activated_plugins', 'Cannot get activated plugins') == false)
			return false;
	
		$qry = pmdb::connect()->query("SELECT * FROM " . DB . "plugins") or die ('AdvPlugin - get_activated_plugins - Cannot get
		activated plugins');
		
		$result = array();
		while($res = $qry->fetch_assoc()) {
			if(file_exists($res['plugin_loc'])) {
				if(substr($res['plugin_loc'], 0, strlen($plugins_dir)) == $plugins_dir)
					$result[] = substr($res['plugin_loc'], strlen($plugins_dir), strlen($res['plugin_loc']));
			}
		}
		if(count($result) == 0)
			return false;
		return $result;
	}
	
	
	/**
	 * public get_plugins
	 * Returns all the plugins in the plugins dir
	 *
	*/
	function get_plugins() {
		global $plugins_dir;
		$res = array();
		foreach(glob($plugins_dir.'*.php') as $file)
			$res[] = $file;
		
		if(count($res) == 0)
			return false;
		return $res;
	}
	
	
	/**
	 * public get_plugins_specific
	 * Returns all the plugins in the plugins dir
	 * and specifies if are activated
	 *
	*/
	function get_plugins_specific() {
		global $plugins_dir;
		$res = array();
		$counter = 0;
		foreach(glob($plugins_dir.'*.php') as $file) {
			$qry = pmdb::connect()->query("SELECT * FROM " . DB . "plugins WHERE plugin_loc='$file'") or die ('AdvPlugin - get_
			plugins_specific - Cannot get plugins from MySQL');
			$res[$counter]['file'] = $file;
			$res[$counter]['file_nodir'] = str_replace($plugins_dir, '', $file);
			if($qry->num_rows > 0)
				$res[$counter]['activated'] = true;
			else
				$res[$counter]['activated'] = false;
				
			$counter++;
		}
		
		if(count($res) == 0)
			return false;
		return $res;
	}
	
	
	/**
	 * public is_activated
	 * Checks if the plugin is activated
	 *
	 *@param string plugin
	 *
	*/
	function is_activated($plugin) {
		global $plugins_dir;
		if(substr($plugin, 0, strlen($plugins_dir)) == $plugins_dir) {
			$plugin = substr($plugin, strlen($plugins_dir), strlen($plugin));
		}
		
		$plugin = $plugins_dir.$plugin;
		
		$qry = pmdb::connect()->query("SELECT * FROM " . DB . "plugins WHERE plugin_loc='$plugin'") or die ('AdvPlugin - 
		is_activated - Cannot check activated in MySQL');
		if($qry->num_rows > 0)
			return true;
		return false;
	}

	/**
	 * public add_func
	 * Allows to call a function with another
	 * name
	 *
	 * @param string new_name
	 * @param string old_name
	 * @param int params
	 *
	*/
	function add_func($new_name, $old_name, $params = 0) {
		$var_names = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 'r', 't', 'u', 'v', 'w', 'x', 'y', 'z');
		
		if(!is_callable($old_name)) {
			pmdb::connect()->last_error[] = "add_func - '$old_name' function is not callable";
			return false;
		}
		
		$str = "function $new_name(";
		$params_ = null;
		for($i = 0; $i < $params; $i++)
			$params_ .= '$'.$var_names[$i].',';
		$params_ = substr($params_, 0, strlen($params_) - 1);
		$str .= $params_.") { return $old_name($params_); }";
		eval($str);
		
		return true;
	}
	
	/**
 	* Registers a filtering function
 	* 
 	* Typical use: add_filter('some_hook', 'function_handler_for_hook');
 	*
 	* @global array $filters Storage for all of the filters
 	* @param string $hook the name of the PM element to be filtered or PM action to be triggered
 	* @param callback $function the name of the function that is to be called.
 	* @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)
 	* @param int $accepted_args optional. The number of arguments the function accept (default is the number provided).
 	*/
	function add_filter( $hook, $function, $priority = 10, $accepted_args = NULL ) {
		global $filters;
		
		// At this point, we cannot check if the function exists, as it may well be defined later (which is OK)
		$id = filter_unique_id( $hook, $function, $priority );
	
		$filters[$hook][$priority][$id] = array(
			'function' => $function,
			'accepted_args' => $accepted_args,
		);
	}
	
	
	/**
	 * add_action
	 * Adds a hook
	 *
	 *@param string hook
	 *@param string function
	 *
	*/
	function add_action($hook, $function, $priority = 10, $accepted_args = 1) {
		return add_filter( $hook, $function, $priority, $accepted_args );
	}
	
	/**
 	* Build Unique ID for storage and retrieval.
 	*
 	* Simply using a function name is not enough, as several functions can have the same name when they are enclosed in classes.
 	*
 	* @global array $filters storage for all of the filters
 	* @param string $hook hook to which the function is attached
 	* @param string|array $function used for creating unique id
 	* @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.
 	* @param string $type filter or action
 	* @return string unique ID for usage as array key
 	*/
	function filter_unique_id( $hook, $function, $priority ) {
		global $filters;

		// If function then just skip all of the tests and not overwrite the following.
		if ( is_string($function) )
			return $function;
		// Object Class Calling
		else if (is_object($function[0]) ) {
			$obj_idx = get_class($function[0]).$function[1];
			if ( !isset($function[0]->_filters_id) ) {
				if ( false === $priority )
					return false;
				$count = isset($filters[$hook][$priority]) ? count((array)$filters[$hook][$priority]) : 0;
				$function[0]->_filters_id = $count;
				$obj_idx .= $count;
				unset($count);
			} else
				$obj_idx .= $function[0]->_filters_id;
			return $obj_idx;
		}
		// Static Calling
		else if ( is_string($function[0]) )
			return $function[0].$function[1];
	}
	
	/**
 	* Performs a filtering operation on a PM element or event.
 	*
 	* Typical use:
 	*
 	* 		1) Modify a variable if a function is attached to hook 'hook'
 	*		$var = "default value";
 	*		$var = apply_filter( 'hook', $var );
 	*
 	*		2) Trigger functions is attached to event 'pm_event'
 	*		apply_filter( 'event' );
 	*       (see do_action() )
 	* 
 	* Returns an element which may have been filtered by a filter.
 	*
 	* @global array $filters storage for all of the filters
 	* @param string $hook the name of the PM element or action
 	* @param mixed $value the value of the element before filtering
 	* @return mixed
 	*/
	function apply_filter( $hook, $value = '' ) {
		global $filters;
		if ( !isset( $filters[$hook] ) )
			return $value;
	
		$args = func_get_args();
	
		// Sort filters by priority
		ksort( $filters[$hook] );
	
		// Loops through each filter
		reset( $filters[$hook] );
		do {
			foreach( (array) current($filters[$hook]) as $the_ )
				if ( !is_null($the_['function']) ){
					$args[1] = $value;
					$count = $the_['accepted_args'];
					if (is_null($count)) {
						$value = call_user_func_array($the_['function'], array_slice($args, 1));
					} else {
						$value = call_user_func_array($the_['function'], array_slice($args, 1, (int) $count));
					}
				}

		} while ( next($filters[$hook]) !== false );
	
		return $value;
	}
	
	function do_action( $hook, $arg = '' ) {
		$args = array();
		if ( is_array($arg) && 1 == count($arg) && isset($arg[0]) && is_object($arg[0]) ) // array(&$this)
			$args[] =& $arg[0];
		else
			$args[] = $arg;
		for ( $a = 2; $a < func_num_args(); $a++ )
			$args[] = func_get_arg($a);
	
		apply_filter( $hook, $args );
	}
	
	/**
 	* Removes a function from a specified filter hook.
 	*
 	* This function removes a function attached to a specified filter hook. This
 	* method can be used to remove default functions attached to a specific filter
 	* hook and possibly replace them with a substitute.
 	*
 	* To remove a hook, the $function_to_remove and $priority arguments must match
 	* when the hook was added.
 	*
 	* @global array $filters storage for all of the filters
 	* @param string $hook The filter hook to which the function to be removed is hooked.
 	* @param callback $function_to_remove The name of the function which should be removed.
 	* @param int $priority optional. The priority of the function (default: 10).
 	* @param int $accepted_args optional. The number of arguments the function accepts (default: 1).
 	* @return boolean Whether the function was registered as a filter before it was removed.
 	*/
	function remove_filter( $hook, $function_to_remove, $priority = 10, $accepted_args = 1 ) {
		global $filters;

		$function_to_remove = filter_unique_id($hook, $function_to_remove, $priority);
		
		$remove = isset ($filters[$hook][$priority][$function_to_remove]);

		if ( $remove === true ) {
			unset ($filters[$hook][$priority][$function_to_remove]);
			if ( empty($filters[$hook][$priority]) )
				unset ($filters[$hook]);
		}
		return $remove;
	}
	
	/**
 	* Check if any filter has been registered for a hook.
 	*
 	* @global array $filters storage for all of the filters
 	* @param string $hook The name of the filter hook.
 	* @param callback $function_to_check optional.  If specified, return the priority of that function on this hook or false if not attached.
 	* @return int|boolean Optionally returns the priority on that hook for the specified function.
 	*/
	function has_filter( $hook, $function_to_check = false ) {
		global $filters;

		$has = !empty($filters[$hook]);
		if ( false === $function_to_check || false == $has ) {
			return $has;
		}
		if ( !$idx = filter_unique_id($hook, $function_to_check, false) ) {
		return false;
		}

		foreach ( (array) array_keys($filters[$hook]) as $priority ) {
			if ( isset($filters[$hook][$priority][$idx]) )
				return $priority;
		}
		return false;
	}
	
	function has_action( $hook, $function_to_check = false ) {
		return has_filter( $hook, $function_to_check );
	}
	
	/**
 	* Return number of active plugins
 	*
 	* @return integer Number of activated plugins
 	*/
	function has_active_plugins( ) {
	
		if( !property_exists( pmdb::connect(), 'plugins' ) || !pmdb::connect()->plugins )
			pmdb::connect()->plugins = array();
		
		return count( pmdb::connect()->plugins );
	}

	/**
 	* Display list of links to plugin admin pages, if any
 	*/
	function list_plugin_admin_pages() {
	
		if( !property_exists( pmdb::connect(), 'plugin_pages' ) || !pmdb::connect()->plugin_pages )
			return;
		
		foreach( (array)pmdb::connect()->plugin_pages as $page ) {
			echo '<a href="plugins.php?page='.$page['slug'].'">'.$page['title']."</a>";
		}
	}

	/**
 	* Register a plugin administration page
 	*/
	function register_plugin_page( $slug, $title, $function ) {
	
		if( !property_exists( pmdb::connect(), 'plugin_pages' ) || !pmdb::connect()->plugin_pages )
			pmdb::connect()->plugin_pages = array();

		pmdb::connect()->plugin_pages[ $slug ] = array(
			'slug'  => $slug,
			'title' => $title,
			'function' => $function,
		);
	}

	/**
 	* Handle plugin administration page
 	*/
	function plugin_admin_page( $plugin_page ) {

		// Check the plugin page is actually registered
		if( !isset( pmdb::connect()->plugin_pages[$plugin_page] ) ) {
			pm_die( 'This page does not exist. Maybe a plugin you thought was activated is inactive?', 'Inactive Plugin' );
		}
	
		// Draw the page itself
		do_action( 'load-' . $plugin_page);
	
		call_user_func( pmdb::connect()->plugin_pages[$plugin_page]['function'] );
	
		include(PM_DIR . 'pm-includes/footer.php');
	
		die();
	}
Return current item: ProjectPress