All pastes #443387 Raw Edit

Anonymous

public php v1 · immutable
·published 2007-04-16 19:46 UTC
rendered paste body
<?php/*Plugin Name: Category IconsPlugin URI: http://devcorner.georgievi.net/wp-plugins/wp-category-icons/Description: Makes it possible to assign icons to categories.Version: 1.5Author: Ivan GeorgievAuthor URI: http://devcorner.georgievi.net/*//*  Copyright 2005  Ivan Georgiev  (email : ivan@georgievi.net)    This program is free software; you can redistribute it and/or modify    it under the terms of the GNU General Public License as published by    the Free Software Foundation; either version 2 of the License, or    (at your option) any later version.    This program is distributed in the hope that it will be useful,    but WITHOUT ANY WARRANTY; without even the implied warranty of    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    GNU General Public License for more details.    You should have received a copy of the GNU General Public License    along with this program; if not, write to the Free Software    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA*/?><?php/** * @todo While I was packaging for deployment I came upon the CategoryIcon plugin [http://wiki.wordpress.org/CategoryIcon%20Plugin] - it is a good idea to make it possible to show icons to posts. This could have an option into the admin panel or can be defined on per category basis? *//******************* Initialization and Hooks *****************************/$wpdb->ig_caticons = $table_prefix.'ig_caticons';if (basename($_SERVER['SCRIPT_NAME']) == 'plugins.php' && isset($_GET['activate'])  && $_GET['activate'] == 'true')   add_action('init', 'ig_caticons_install');add_action('admin_menu', 'ig_caticons_adminmenu');/*------------------ Initialization and Hooks END ----------------------------*//** * WordPress Template Tag to Insert Category Icon * @param $fit_width int [-1] Maximum width (or desired width if $expanded=true) of the image. * @param $fit_height int[-1] Macimum height (or desired height if $expanded=true) of the image. * @param $expand boolean [false] Whether the image should be expanded to fit the rectangle specified by fit_xxx. * @param $cat int Category ID. If not specified, the current category is used or the current post's category. * @param $small boolean [false] Use the small icon. * @param $prefix string String to echo before the image tag. If no image, no otuput. * @param $suffix string String to echo after the image tag. Ignored if no image found. * @param $class string [] Class attribute for the image tag. * @param $link boolean [1] If true the image is made a hyperlink (wrapped by anchor tag). * * @return boolean True if image found. */function get_cat_icon($params="") {	parse_str($params, $p);	if (!isset($p['fit_width'])) $p['fit_width']=-1;	if (!isset($p['fit_height'])) $p['fit_height']=-1;	if (!isset($p['expand'])) $p['expand']=false;	if (!isset($p['cat'])) $p['cat']=$GLOBALS['cat'];	if (!isset($p['small'])) $p['small']=false;	if (!isset($p['prefix'])) $p['prefix'] = '';	if (!isset($p['suffix'])) $p['suffix'] = '';	if (!isset($p['class'])) $p['class'] = '';	if (!isset($p['link'])) $p['link'] = 1;	stripslaghes_gpc_arr($p);	if (empty($p['cat']) && isset($GLOBALS['post'])) {		$catlist = get_the_category($GLOBALS['post']->ID);		if (is_array($catlist)) {			$p['cat'] = $catlist[0]->cat_ID;		}	}	if (!isset($p['cat'])) return;	list($icon, $small_icon) = ig_caticons_get_icons($p['cat']);	if ($p['small']) {		$file = ig_caticons_path()."/$small_icon";		$url = ig_caticons_url()."/$small_icon";		if (!is_file($file)) {			$file = ig_caticons_path()."/$icon";			$url = ig_caticons_url()."/$icon";		}	} else {		$file = ig_caticons_path()."/$icon";		$url = ig_caticons_url()."/$icon";		if (!is_file($file)) {			$file = ig_caticons_path()."/$small_icon";			$url = ig_caticons_url()."/$small_icon";		}	}	if ($p['link']) {		$p['prefix'] .= '<a href="'.get_category_link($p['cat']).'">';		$p['suffix'] = '</a>'.$p['suffix'];	}	if (is_file($file)) {		list($width, $height, $type, $attr) = getimagesize($file);		list($w, $h) = ig_fit_rect($width, $height, $p['fit_width'], $p['fit_height'], $p['expand']);		echo("$p[prefix]<img class=\"$p[class]\" src=\"$url\" width=\"$w\" height=\"$h\"/>$p[suffix]");		return true;	}	return false;}/** * Install the plugin * @access private */function ig_caticons_install() {	global $wpdb, $table_prefix;	$wpdb->query("CREATE TABLE IF NOT EXISTS `$wpdb->ig_caticons` (`cat_id` INT NOT NULL ,`icon` TEXT NOT NULL ,`small_icon` TEXT NOT NULL ,PRIMARY KEY ( `cat_id` ))");	add_option('igcaticons_path', '');	add_option('igcaticons_url', '');	add_option('igcaticons_filetypes', 'jpg gif jpeg png');}function ig_caticons_defupload() {	$def_path = str_replace(ABSPATH, '', get_settings('upload_path'));	$def_url = trailingslashit(get_settings('siteurl')) . $def_path;	return array($def_path, $def_url);}/** * Integrate into the admin menu. * @access private */function ig_caticons_adminmenu() {	define('IG_ADMIN_SELF', $_SERVER['PHP_SELF'].'?page='.$_REQUEST['page']);	if (function_exists('add_options_page'))		add_options_page(			'Cat Icons',			'Category Icons',			5,			basename(__FILE__),			'ig_caticons_adminpanel');}/** * Handle admin panel * @access private */function ig_caticons_adminpanel() {?>	<div class="wrap">		<strong>Select:</strong> <a href="<?php echo IG_ADMIN_SELF;?>&ig_module=caticons&ig_tab=manage">Manage</a> | <a href="<?php echo IG_ADMIN_SELF;?>&ig_module=caticons&ig_tab=options">Options</a>	</div><?php	$tab = isset($_REQUEST['ig_tab']) ? $_REQUEST['ig_tab'] : '';	switch ($tab) {		case ('manage'):			ig_caticons_adminmanage();		break;		default:			ig_caticons_adminoptions();		break;	}}/** * Handle manage tab (plugin section) from the admin panel. * @access private */function ig_caticons_adminmanage() {	global $wpdb;	$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';	switch ($action) {		case 'delete':			$cat = $wpdb->escape($_REQUEST['cat_ID']);			$wpdb->query("DELETE FROM $wpdb->ig_caticons WHERE cat_id='$cat'");		break;		case 'do_select':			$cat = $wpdb->escape($_REQUEST['cat_ID']);			$icon = $wpdb->escape($_REQUEST['ig_icon']);			$small_icon = $wpdb->escape($_REQUEST['ig_small_icon']);			if ($wpdb->get_var("SELECT cat_id FROM $wpdb->ig_caticons WHERE cat_id='$cat'")) {				$wpdb->query("UPDATE $wpdb->ig_caticons SET icon='$icon', small_icon='$small_icon' WHERE cat_id='$cat'");			} else {				$wpdb->query("INSERT INTO $wpdb->ig_caticons (cat_id, icon, small_icon) VALUES ('$cat', '$icon', '$small_icon')");			}		break;	}	switch ($action) :		// List categories	case 'select':		$cat = $wpdb->escape($_REQUEST['cat_ID']);		$c = $wpdb->get_row("SELECT * FROM $wpdb->categories WHERE cat_ID=$cat");		list($icon, $small_icon) = ig_caticons_get_icons($c->cat_ID);?><div class="wrap"><h2><?php _e('Select Category Icons') ?> </h2><form method="post" action="">	<input type="hidden" name="ig_module" value="caticons" />	<input type="hidden" name="ig_tab" value="manage" />	<input type="hidden" name="action" value="do_select" /><table cellspacing="1" cellpadding="2" border="0">	<tr>		<th scope="row" align="right" valign="top">Category ID:</th>		<td><?php echo $c->cat_ID;?></td>	</tr>	<tr>		<th scope="row" align="right" valign="top">Name:</th>		<td><?php echo $c->cat_name;?></td>	</tr>	<tr>		<th scope="row" align="right" valign="top">Icon:</th>		<td valign="top">			<select name="ig_icon" rows="10" onChange="icon_preview.src=('<?php echo ig_caticons_url();?>/'+this.options[this.selectedIndex].value);">				<option value="">--- No Icon ---</option>				<?php ig_caticons_iconoptions($icon); ?>			</select>		</td>		<td valign="top"><img id="icon_preview" src="<?php echo ig_caticons_url()."/$icon";?>" /></td>	</tr>	<tr>		<th scope="row" align="right" valign="top">Small Icon:</th>		<td valign="top">			<select name="ig_small_icon" rows="10" onChange="small_icon_preview.src=('<?php echo ig_caticons_url();?>/'+this.options[this.selectedIndex].value);">				<option value="">--- No Icon ---</option>				<?php ig_caticons_iconoptions($small_icon); ?>			</select>		</td>		<td valign="top"><img id="small_icon_preview" src="<?php echo ig_caticons_url()."/$small_icon";?>" /></td>	</tr></table>	<div class="submit"><input type="submit" name="info_update" value="Select Icons &raquo;" /></div></div><?php	break;	default:?><div class="wrap"><h2><?php _e('Manage Categories') ?> </h2><table width="100%" cellpadding="3" cellspacing="3">	<tr>		<th scope="col"><?php _e('ID') ?></th>        <th scope="col"><?php _e('Name') ?></th>        <th scope="col"><?php _e('Icon') ?></th>        <th scope="col"><?php _e('Small Icon') ?></th>        <th colspan="2"><?php _e('Action') ?></th>	</tr><?phpig_caticons_rows();?></table></div><?php	endswitch;}/** * Handle options tab (plugin section) from the admin panel. * @access private */function ig_caticons_adminoptions() {	if (isset($_POST['info_update'])) {		?><div class="updated"><p><strong>Settings updated.</strong></p></div><?php		update_option('igcaticons_path', $_POST['igcaticons_path']);		update_option('igcaticons_url', $_POST['igcaticons_url']);		update_option('igcaticons_filetypes', $_POST['igcaticons_filetypes']);	}	list($def_path, $def_url) = ig_caticons_defupload();?><div class=wrap>  <form method="post" action="">	<input type="hidden" name="ig_module" value="caticons">	<input type="hidden" name="ig_tab" value="options">    <h2>Category Icons Settings</h2>     <fieldset name="set1">		<legend>General Settings</legend>		<table cellspacing="0" cellpadding="2" border="0">			<tr>				<th align="right" valign="top">Local Path to Icons:</th>				<td><input type="text" name="igcaticons_path" size="50" value="<?php echo htmlspecialchars(get_option('igcaticons_path')); ?>" /><br />Leave blank to use default upload path (<?php echo htmlspecialchars($def_path); ?>).</td>			</tr>			<tr>				<th align="right" valign="top">URL to Icons:</th>				<td><input type="text" name="igcaticons_url" size="50" value="<?php echo htmlspecialchars(get_option('igcaticons_url')); ?>" /><br />Leave blank to use default upload url (<?php echo htmlspecialchars($def_url); ?>).</td>			</tr>			<tr>				<th align="right" valign="top">Image File Types:</th>				<td><input type="text" name="igcaticons_filetypes" size="50" value="<?php echo htmlspecialchars(get_option('igcaticons_filetypes')); ?>" /><br />Separate by space or comma. E.g. "jpg gif jpeg png"</td>			</tr>		</table>     </fieldset>	<div class="submit"><input type="submit" name="info_update" value="Update Options &raquo;" /></div>  </form></div><?}/** * Get the icons base path. */function ig_caticons_path() {	$path = get_option('igcaticons_path');	$def = ig_caticons_defupload();	if (''==$path)		return ABSPATH.$def[0];	else		return ABSPATH.$path;}/** * Get the icons base url. */function ig_caticons_url() {	$url = get_option('igcaticons_url');	$def = ig_caticons_defupload();	if (''==$url)		return $def[1];	else		return $url;}/** * Get file types to show when selecting icons. */function ig_caticons_filetypes() {	$types = get_option('igcaticons_filetypes');	if (''==$types)		return get_option('fileupload_allowedtypes');	else		return $types;}/** * Print list of options for selecting icon. * @access private */function ig_caticons_iconoptions($selected='') {	$path = ig_caticons_path();	$d = dir($path);	$ext = explode(' ', strtolower(ig_caticons_filetypes()));	echo("Browse for ... $path");	while (false !== ($entry = $d->read())) {		if (is_dir($path.DIRECTORY_SEPARATOR.$entry)) continue;		$p = strrpos($entry,'.');		if (false===$p || !in_array(strtolower(substr($entry, $p+1)), $ext)) continue;		$sel = ($selected==$entry) ? ' selected="selected"' : '';		$entry_escaped = htmlspecialchars($entry);		echo("<option value=\"$entry_escaped\"$sel>$entry_escaped</option>");	}	$d->close();}/** * Get category icons. * @param int $cat Category ID * @return array (icon, small_icon) */function ig_caticons_get_icons($cat) {	global $wpdb;	$cat = $wpdb->escape($cat);	if ($row = $wpdb->get_row("SELECT icon, small_icon FROM $wpdb->ig_caticons WHERE cat_id='$cat'")) {		return array($row->icon, $row->small_icon);	} else return false;}/** * Utility function to compute a rectangle to fit a given rectangle by maintaining the aspect ratio. */function ig_fit_rect($width, $height, $max_width=-1, $max_height=-1, $expand=false) {	$h = $height;	$w = $width;	if ($max_width>0 && ($w > $max_width || $expand)) {		$w = $max_width;		$h = floor(($w*$height)/$width);	}	if ($max_height>0 && $h >$max_height) {		$h = $max_height;		$w = floor(($h*$width)/$height);	}	return array($w,$h);}/** * Print category rows for admin panel */function ig_caticons_rows($parent = 0, $level = 0, $categories = 0) {	global $wpdb, $class, $user_level;	if (!$categories)		$categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_name");	if ($categories) {		foreach ($categories as $category) {			if ($category->category_parent == $parent) {				list($icon, $small_icon) = ig_caticons_get_icons($category->cat_ID);				$icon_cell = '';				if (''!=$icon) {					list($width, $height, $type, $attr) = getimagesize(ig_caticons_path()."/$icon");					list($w, $h) = ig_fit_rect($width, $height, 100, 100);					$icon_cell = '<img src="'.ig_caticons_url()."/$icon\" alt=\"$small_icon\" width=\"$w\" height=\"$h\"/> <br />$icon ($width x $height)";				}				$small_icon_cell = '';				if (''!=$small_icon) {					list($width, $height, $type, $attr) = getimagesize(ig_caticons_path()."/$small_icon");					list($w, $h) = ig_fit_rect($width, $height, 100, 100);$small_icon_cell = '<img src="'.ig_caticons_url()."/$small_icon\" alt=\"$small_icon\" width=\"$w\" height=\"$h\" /> <br />$small_icon ($width x $height)";				}				$category->cat_name = wp_specialchars($category->cat_name);				$count = $wpdb->get_var("SELECT COUNT(post_id) FROM $wpdb->post2cat WHERE category_id = $category->cat_ID");				$pad = str_repeat('&#8212; ', $level);				if ( $user_level > 3 )					$edit = "<a href='".IG_ADMIN_SELF."&ig_module=caticons&ig_tab=manage&action=select&cat_ID=$category->cat_ID' class='edit'>" . __('Select') . "</a></td><td><a href='".IG_ADMIN_SELF."&ig_module=caticons&ig_tab=manage&action=change&cat_ID=$category->cat_ID' onclick=\"return confirm('".  sprintf(__("You are about to remove the category \'%s\' icons.\\n  \'OK\' to remove, \'Cancel\' to stop."), addslashes($category->cat_name)) . "')\" class='delete'>" .  __('Remove') . "</a>";				else					$edit = '';				$class = ('alternate' == $class) ? '' : 'alternate';				echo "<tr class='$class'><th scope='row'>$category->cat_ID</th><td>$pad $category->cat_name</td>				<td align=\"center\">$icon_cell</td>				<td align=\"center\">$small_icon_cell</td>				<td>$edit</td>				</tr>";				ig_caticons_rows($category->cat_ID, $level + 1, $categories);			}		}	} else {		return false;	}}if (!function_exists('stripslaghes_gpc_arr')) {function stripslaghes_gpc_arr(&$arr) {	if (get_magic_quotes_gpc()) {		foreach(array_keys($arr) as $k) $arr[$k] = stripslashes($arr[$k]);	}}}?>