Advertisement
kt_pixel

WP Plugin Name: Category Icons

Jan 6th, 2014
392
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 61.29 KB | None | 0 0
  1. <?php
  2. /*
  3. Plugin Name: Category Icons
  4. Plugin URI: http://www.category-icons.com/
  5. Description: Easily assign icons to your categories. (Minimum WP version : 2.8)
  6. Version: 2.2.3
  7. Author: Brahim Machkouri
  8. Author URI: http://www.category-icons.com/
  9. Text Domain: category_icons
  10. Domain Path: /languages/
  11. */
  12.  
  13. /*
  14.     This program is free software; you can redistribute it and/or modify
  15.     it under the terms of the GNU General Public License as published by
  16.     the Free Software Foundation; either version 2 of the License, or
  17.     (at your option) any later version.
  18.  
  19.     This program is distributed in the hope that it will be useful,
  20.     but WITHOUT ANY WARRANTY; without even the implied warranty of
  21.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  22.     GNU General Public License for more details.
  23.  
  24.     You should have received a copy of the GNU General Public License
  25.     along with this program; if not, write to the Free Software
  26.     Foundation, Inc., 51 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  27. */
  28.  
  29. // Initialization and Hooks
  30. global $table_prefix,$recent_posts_version;
  31. $wpdb->ig_caticons = $table_prefix.'ig_caticons';
  32. $caticons_datas = array();
  33.  
  34. add_action('init', 'ig_caticons_install');
  35. add_action('admin_menu', 'ig_caticons_adminmenu');
  36. add_action('admin_menu', 'bm_caticons_add_js_libs');
  37. add_filter('pre_kses', 'bm_caticons_plugin_description');
  38. add_action('rss2_head','bm_caticons_rss_flag');
  39. add_action('rdf_header','bm_caticons_rss_flag'); // only for Safari
  40. add_action('atom_ns','bm_caticons_rss_flag');
  41. add_filter('the_excerpt_rss','bm_caticons_rss');
  42. add_filter('the_content','bm_caticons_rss');
  43. add_filter('the_content_rss','bm_caticons_rss');
  44. add_filter('plugin_action_links', 'bm_caticons_plugin_action_links', 10, 2);
  45.  
  46. include_once('category_icons_widget.php');
  47.  
  48. /**
  49.  * Display "Settings" once the plugin is activated
  50.  * @author Brahim Machkouri
  51.  */
  52. function bm_caticons_plugin_action_links($links, $file) {
  53.     if ($file == plugin_basename(dirname(__FILE__).'/category_icons.php')){
  54.         $links[]  = "<a href='edit.php?page=category_icons.php'>" . __('Settings') . "</a>";
  55.       }
  56.     return $links;
  57. }
  58.  
  59. /**
  60.  * WordPress Template Tag to Insert Category Icon
  61.  * @author Brahim Machkouri
  62.  * @param boolean $align align attribute for the image tag
  63.  * @param int $fit_width Maximum width of the image, or desired width if expand is true. Default : -1
  64.  * @param int $fit_height Maximum height (or desired height if $expanded=true) of the image. Default : -1
  65.  * @param boolean $expand Whether the image should be expanded to fit the rectangle specified by fit_xxx. Default : false
  66.  * @param int $cat Category ID. If not specified, the current category is used or the current post's category. Default :
  67.  * @param boolean $small Use the small icon. Default : false
  68.  * @param string $prefix String to echo before the image tag. If no image, no output. Default :
  69.  * @param string $suffix String to echo after the image tag. Ignored if no image found. Default :
  70.  * @param string $class Class attribute for the image tag. Default :
  71.  * @param boolean $link If true, an anchor tag wraps the image (a hyperlink to the category is made). Default : true
  72.  * @param boolean $echo If true the html code will be 'echoed'. If no, it'll be returned. Default : true
  73.  * @param boolean $use_priority If true, only the most prioritized icon will be displayed. Default : false
  74.  * @param int $max_icons Maximum number of icons to display. Default : 3
  75.  * @param boolean $border If true, displays the icon with a border. If false, no border is diplayed. (Don't use this if you want valid Strict XHTML)
  76.  * @param boolean $hierarchical If true, displays the icon in hierarchical order.(horizontally)
  77.  * @return boolean True if image found.
  78.  */
  79. function get_cat_icon($params='') {
  80.     $one_category_only = false;
  81.    
  82.     if (0 < (int) get_option('igcaticons_iconcatpage',0) ) {
  83.         $one_category_only = true;
  84.     }
  85.      
  86.     // Compatibility with qTranslate
  87.     if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) {
  88.         remove_filter('wp_list_categories','qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
  89.         remove_filter('list_cats','qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
  90.     }
  91.    
  92.     // Compatibility with SEO Friendly Images
  93.     if (function_exists('seo_friendly_images') && 1 == get_option('igcaticons_useseo_plugin'))
  94.         add_filter('category_icons', 'seo_friendly_images', 50);
  95.     parse_str($params, $p);
  96.     if (!isset($p['fit_width'])) $p['fit_width'] = (int) get_option('igcaticons_max_width');
  97.     if (!isset($p['fit_height'])) $p['fit_height'] = (int) get_option('igcaticons_max_height');
  98.     if (!isset($p['expand'])) $p['expand'] = false;
  99.     if (!isset($p['small'])) $p['small'] = (int) get_option('igcaticons_use_small');
  100.     if (!isset($p['prefix'])) $p['prefix'] = '';
  101.     if (!isset($p['suffix'])) $p['suffix'] = '';
  102.     if (!isset($p['class'])) $p['class'] = '';
  103.     if (!isset($p['link'])) $p['link'] = true;
  104.     if (!isset($p['echo'])) $p['echo'] = true;
  105.     if (!isset($p['use_priority'])) $p['use_priority'] = false;
  106.     if (!isset($p['max_icons'])) $p['max_icons'] = (int) get_option('igcaticons_max_icons');
  107.    
  108.     if (!isset($p['align'])) $p['align'] = false;
  109.     if (!isset($p['hierarchical'])) $p['hierarchical'] = false;
  110.     if (!$p['hierarchical'] === false) $p['hierarchical'] = bm_caticons_getbool($p['hierarchical']);
  111.    
  112.     if (!isset($p['orderby'])) $p['orderby'] = 'name';
  113.     $p['expand'] = bm_caticons_getbool($p['expand']);
  114.     $p['small'] = bm_caticons_getbool($p['small']);
  115.     $p['echo'] = bm_caticons_getbool($p['echo']);
  116.     if (isset($p['border'])) $p['border'] = bm_caticons_getbool($p['border']);
  117.     $p['use_priority'] = bm_caticons_getbool($p['use_priority']);
  118.     if ($p['max_icons']==1) $p['use_priority'] = true;
  119.     $p['link'] = bm_caticons_getbool($p['link']);
  120.    
  121.     stripslaghes_gpc_arr($p);
  122.     if (is_category() && in_the_loop() && $one_category_only == true ) {
  123.         $cat = (int) get_query_var('cat');
  124.         $category=get_category($cat);
  125.         if (!isset($p['cat']) || !is_array($p['cat'])) {
  126.             $p['cat']=array();
  127.         }
  128.        
  129.         $p['cat'][] = $category->cat_ID;
  130.     }
  131.     else {
  132.         if (!isset($p['cat']) && isset($GLOBALS['post'])) {
  133.             $catlist = get_the_category($GLOBALS['post']->ID);
  134.             if (is_array($catlist)) {
  135.                 $p['cat'] = array();
  136.                 if ($p['orderby']!='name' || $p['hierarchical']==true) {
  137.                     $p['cat'] = bm_caticons_process_categories('orderby='.$p['orderby'].'&hierarchical='.$p['hierarchical']);
  138.                 } else {
  139.                     foreach ($catlist as $categorie) {
  140.                         $p['cat'][] = $categorie->cat_ID; // Adds all the categories in the array
  141.                         $cat[$categorie->cat_ID] = $categorie->name;
  142.                     }
  143.                 }
  144.             }
  145.         }
  146.    
  147.         if (!isset($p['cat'][0])) return;
  148.         if (!is_array($p['cat'])) {
  149.             $categorie= (int) $p['cat'];
  150.             $p['cat'] = array();
  151.             $p['cat'][] = $categorie;
  152.         }
  153.     }
  154.    
  155.     $nb_icons = 0;
  156.     $urlbegin = '';
  157.     $urlend = '';
  158.     $cat_icons = '';
  159.     for ($i=0; $i<count($p['cat']); $i++)   {
  160.         if($p['use_priority']) // if you decide to use the priority feature
  161.             list( $p['cat'][$i] , $priority , $icon , $small_icon ) = ow_caticons_get_priority_icon( $p['cat'] );
  162.         else
  163.             list( $priority , $icon , $small_icon ) = bm_caticons_get_icons( $p['cat'][$i]);
  164.        
  165.         if ($p['small']) {// If we choose to display the small icon
  166.             $file = ig_caticons_path().'/'.$small_icon;
  167.             $url = ig_caticons_url().'/'.$small_icon;
  168.             if (!is_file($file)) {// if the small icon can't be found, the normal one will be loaded
  169.                 $file = ig_caticons_path().'/'.$icon;
  170.                 $url = ig_caticons_url().'/'.$icon;
  171.             }
  172.         }
  173.         else {
  174.             $file = ig_caticons_path().'/'.$icon;
  175.             $url = ig_caticons_url().'/'.$icon;
  176.             if ( !is_file($file) ) {// If the normal icon can't be found, the small one will be loaded
  177.                 $file = ig_caticons_path().'/'.$small_icon;
  178.                 $url = ig_caticons_url().'/'.$small_icon;
  179.             }
  180.         }
  181.         if ( is_file($file) ) {
  182.             if ( $p['link'] ) {
  183.                 $urlbegin = '<a href="'.get_category_link($p['cat'][$i]).'" title="';
  184.                 if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) // Compatibility with qTranslate
  185.                     $urlbegin .= qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage(get_cat_name($p['cat'][$i]));
  186.                 else
  187.                     $urlbegin .= get_cat_name($p['cat'][$i]);
  188.                 $urlbegin .= '">';
  189.                 $urlend = '</a>';
  190.             }
  191.             list( $width , $height , $type , $attr) = getimagesize($file);
  192.             $w = (int) $width;
  193.             $h = (int) $height;
  194.             if (!empty($p['fit_width']) || !empty($p['fit_height']))
  195.                 list($w, $h) = ig_caticons_fit_rect($width, $height, $p['fit_width'], $p['fit_height'], $p['expand']);
  196.             $cat_icons .= $p['prefix'].$urlbegin.'<img ';
  197.             if (!empty($p['class'])) $cat_icons .= 'class="'.$p['class'].'" ';
  198.             if (isset($p['border'])) {
  199.                 if ($p['border'])
  200.                     $cat_icons .= 'border="1" ';
  201.                 else
  202.                     $cat_icons .= 'border="0" ';
  203.             }
  204.             if (!$p['align']===false) $cat_icons .= 'align="'.$p['align'].'" ';
  205.             $fill_with_catname = get_cat_name($p['cat'][$i]);
  206.             $title = 'title="'.$fill_with_catname.'"'; 
  207.             $alt =  'alt="'.$fill_with_catname.'"';;//$title;  
  208.             if (function_exists('seo_friendly_images') && 1 == get_option('igcaticons_useseo_plugin'))  $title = '' ; // Compatibility with qTranslate
  209.             $cat_icons .= 'src="'.$url.'" width="'.$w.'" height="'.$h.'" '.$alt.' '.$title.' />'.$urlend.$p['suffix'];
  210.             $nb_icons++;
  211.         }
  212.         if ( $p['use_priority'] ) break;
  213.         if ( $nb_icons == $p['max_icons']) break;
  214.     }
  215.     if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) {// Add the filter again, as we finished to process the icon(s)
  216.         add_filter('wp_list_categories','qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
  217.         add_filter('list_cats','qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
  218.     }
  219.     $cat_icons = apply_filters('category_icons', $cat_icons);
  220.     if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage') ) // Update the compatibility with qTranslate
  221.         $cat_icons = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($cat_icons);
  222.     if ($p['echo']) {
  223.         if (empty($cat_icons))  
  224.             return false;
  225.         else {
  226.             echo $cat_icons;
  227.             return true; // if echo get_cat_icon() is used, true will be displayed as "1". So the parameter echo=false must be used in this case.
  228.         }
  229.     }
  230.     else
  231.         return $cat_icons;
  232. }
  233.  
  234. /**
  235.  * Order the categories
  236.  * @author Brahim Machkouri
  237.  * @param string $string parameters
  238.  */
  239. function bm_caticons_process_categories($string='') {  
  240.     $caticons_processed = array();
  241.     $catlist = get_the_category($GLOBALS['post']->ID); 
  242.     if (count($catlist)>1) {
  243.         parse_str($string);
  244.         $depth = -1; // Flat
  245.         $r = array('orderby' => 'name', 'order' => 'ASC', 'hierarchical' => false, 'echo' => 0, 'hide_empty' => 0);
  246.         if ($hierarchical==1) {
  247.             $r['hierarchical'] = true;
  248.             $depth = 0 ;
  249.         }
  250.         if (in_array(strtolower($orderby), array('id','slug','count','order','term_order')))
  251.             $r['orderby'] = $orderby;          
  252.         $a = 'array('.bm_caticons_walk_tree(  get_categories( $r ), $depth, $r ).');';
  253.         eval("\$caticons_processed = $a;");
  254.         foreach ($catlist as $object)
  255.             $categories[] = $object->cat_ID;
  256.         $caticons_processed = array_intersect($caticons_processed,$categories);
  257.     } else {
  258.         $caticons_processed = array($catlist[0]->cat_ID);
  259.     }
  260.     return array_values($caticons_processed);
  261. }
  262.  
  263. /**
  264.  * Get the categories ordered the way we want
  265.  * @author Brahim Machkouri
  266.  */
  267. function bm_caticons_walk_tree() { // Greatly inspired from WordPress Source Code
  268.     include_once('category_icons_walker.php');
  269.     $args = func_get_args();
  270.     // the user's options are the third parameter
  271.     if ( empty($args[2]['walker']) || !is_a($args[2]['walker'], 'Walker') )
  272.         $walker = new Walker_Caticons;
  273.     else
  274.         $walker = $args[2]['walker'];
  275.     $string = call_user_func_array(array( &$walker, 'walk' ), $args );
  276.     return substr($string, 0, strlen($string)-1);
  277. }
  278.  
  279. /**
  280.  * WordPress Template Tag to Inject the html image source code of each category contained in the list given as parameter
  281.  * @author Brahim Machkouri
  282.  * @param string $list HTML code of the category list
  283.  * @param string $parameters The parameters of get_cat_icon() function
  284.  */
  285. function put_cat_icons($list,$parameters='',$type='category') {
  286.     global $wpdb,$post;
  287.     $echo_output = true;
  288.     $original_title = $post->post_title;
  289.     $request = "SELECT term_id
  290.                 FROM $wpdb->term_relationships
  291.                 right join $wpdb->term_taxonomy on $wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id
  292.                 left join $wpdb->posts on $wpdb->term_relationships.object_id = $wpdb->posts.ID
  293.                 where post_type = 'page' and $wpdb->term_taxonomy.taxonomy = 'category' and ID=";
  294.     $nb_max_icons_page = (int) get_option('igcaticons_max_icons');
  295.     $cats = array();
  296.     if ($type != 'cat' && $type != 'page') {
  297.         $type = 'cat';
  298.         if (version_compare($GLOBALS['wp_version'], '3.1', '>=') ) {
  299.             $type = 'category_name';
  300.         }
  301.     }
  302.     if (empty($parameters)) // If no parameter is given, the ones from the options will be taken
  303.         $parameters = 'fit_width='.get_option('igcaticons_max_width').'&fit_height='.get_option('igcaticons_max_height').'&small='.(bm_caticons_getbool(get_option('igcaticons_use_small')) ?'true':'false');
  304.     else {
  305.         parse_str($parameters, $p);
  306.         if (isset($p['echo']) && bm_caticons_getbool($p['echo'])===false) {
  307.             $echo_output = false;
  308.         }
  309.         if ( !isset($p['icons_only']) ) {
  310.             $p['icons_only']=0;
  311.         }  
  312.         if ( isset($p['icons_only']) && 'true' == strtolower( $p['icons_only'] ) ) {
  313.             $p['icons_only']=1;
  314.         }
  315.     }
  316.     if (!empty($list)) {
  317.         $myarray = bm_caticons_url_extractor($list);
  318.         foreach ($myarray as $child) {
  319.             $cats = array();
  320.             $pos = strpos($child[0],$type.'=');
  321.             if ($pos>0) {
  322.                 parse_str(substr($child[0],$pos, strlen($child[0])-$pos)); // $cat or $category_name is created from this function
  323.                 if (isset($page) && intval($page) >0) { // get the category from page id
  324.                     $cats = array();
  325.                     $cats = $wpdb->get_results($wpdb->prepare($request.intval($page)),ARRAY_A);
  326.                 }
  327.                 else {
  328.                     if (version_compare($GLOBALS['wp_version'], '3.1', '>=')) {
  329.                         // standard permalinks in wp 3.1+: http://www.sublab.dev/wpdev/?category_name=apple
  330.                         $cats[] = bm_caticons_get_cat_ID_by_slug($category_name);
  331.                     }
  332.                     else { // standard permalinks in wp up to 3.0: http://www.sublab.dev/wpdev/?cat=3
  333.                         $cats[] = (int) $cat;
  334.                     }
  335.                 }
  336.             }
  337.             else {// not standard permalinks
  338.                 $cats = array();
  339.                 $temp = explode('/',($child[0]));
  340.                 $name = '';
  341.                 do
  342.                     $name = array_pop($temp); // get the last non empty/null string from the array
  343.                 while (is_null($name) || empty($name));
  344.                 if ($type == 'cat' OR $type == 'category_name') {
  345.                     $cat  = bm_caticons_get_cat_ID_by_slug(trim($name));
  346.                     $cats[] = $cat;
  347.                 }
  348.                 else {
  349.                     $cats = array();
  350.                     $page  = $wpdb->get_var($wpdb->prepare("SELECT ID FROM `$wpdb->posts` WHERE post_name = '$name'"),0,0);
  351.                     $cats = $wpdb->get_results($wpdb->prepare($request.intval($page)),ARRAY_A);
  352.                 }
  353.             }
  354.             if (is_array($cats[0])) { // Pages Icons
  355.                 $temp = array();
  356.                 for ($i=0; $i<count($cats);$i++) {
  357.                     $temp[$i]= $cats[$i]['term_id'];
  358.                 }
  359.                 $cats = $temp;
  360.                 unset($temp);
  361.             }
  362.             $img = '';
  363.             $i=1;
  364.             if (count($cats)>0) {
  365.                 foreach ($cats as $categ) {
  366.                     if ($categ == 1 && $type == 'page') continue;// Do not display uncategorized icon for a page
  367.                     if ($i > $nb_max_icons_page) break;
  368.                     $post->post_title = get_cat_name($categ);
  369.                     $img .= get_cat_icon($parameters.'&cat='.$categ.'&echo=false&link=false');
  370.                     $i++;
  371.                 }
  372.                 if ( isset($p) && 1 == $p['icons_only'] && !empty($img) ) {
  373.                     $list = str_replace($child[1],'>'.$img.'<', $list);
  374.                 }
  375.                 else {// Inject icon into the list
  376.                     $before_name = bm_caticons_getbool(get_option('igcaticons_before_name'));
  377.                     if ($before_name) { // put the html code of the icons before the category name
  378.                         $cat_name = substr($child[1],1,strlen($child[1]));
  379.                         $list = str_replace('>'.$cat_name, '>'.$img.$cat_name,$list);
  380.                     } else {// else after the category name
  381.                         $new = substr($child[1],0,strlen($child[1])-1);
  382.                         $list = str_replace($child[1], $new.$img.'<', $list);
  383.                     }
  384.                 }
  385.             }
  386.         }
  387.         $list = apply_filters('category_icons_widget', $list);
  388.         if ($echo_output) echo $list;
  389.     }
  390.     else {
  391.         _e("put_cat_icons : your list is empty ! Don't forget to add <strong>echo=0</strong> in the parameters of wp_list_categories().",'category_icons');
  392.     }
  393.     $post->post_title = $original_title;
  394.     if (!$echo_output && !empty($list))  
  395.         return $list;
  396. }
  397.  
  398. /**
  399.  * Get the slug category
  400.  * @author Brahim Machkouri
  401.  * @param string $slug slug from which you want to get the category
  402.  * @return int
  403.  */
  404. function bm_caticons_get_cat_ID_by_slug($slug) {
  405.     $idObj = get_category_by_slug($slug);
  406.    
  407.     $id = false;
  408.     if (is_object($idObj))
  409.      $id = $idObj->term_id;
  410.     else { // if no category id is found, this is ?cat=X given
  411.         list($dummy,$id) = explode('?cat=',$slug);
  412.         $id = (int) $id;
  413.     }
  414.     return $id;
  415. }
  416.  
  417. /**
  418.  * If a RSS feed is created, 'raise the flag'
  419.  * @author Brahim Machkouri
  420.  */
  421. function bm_caticons_rss_flag() {
  422.     global $bm_caticons_rss;
  423.     $bm_caticons_rss = true;
  424. }
  425.  
  426. /**
  427.  * Inject the icons into the feeds
  428.  * Working only with RSS2 and Atom. (And RDF, but only in Safari)
  429.  * @author Brahim Machkouri
  430.  * @param string The content to process
  431.  * @return string The feed content
  432.  */
  433. function bm_caticons_rss($content) {
  434.     global $bm_caticons_rss;
  435.     if ( $bm_caticons_rss && 1 == get_option('igcaticons_rssfeeds')  ) // If the rss flag is raised, inject icons
  436.         $content = get_cat_icon('echo=false&link=false').'<br/>'.$content;
  437.     return $content;
  438. }
  439.  
  440. /**
  441.  * Localization of the plugin description
  442.  * @author Brahim Machkouri
  443.  * @param string The string to process
  444.  * @return string The string to display
  445.  */
  446. function bm_caticons_plugin_description( $string) {
  447.     if (trim($string) == 'Easily assign icons to your categories.') {
  448.         $string = __('Easily assign icons to your categories.','category_icons');
  449.     }
  450.     return $string;
  451. }
  452.  
  453. /**
  454.  * Displays informations in the footer of WordPress
  455.  * @author Brahim Machkouri
  456.  */
  457. function bm_caticons_credits() {
  458.     $translator_name = (__('translator_name','category_icons')) == 'translator_name' ? '' : __('translator_name','category_icons');
  459.     $translator_url  = (__('translator_url','category_icons')) == 'translator_url' ? '' : __('translator_url','category_icons') ;
  460.     $lang = get_locale();
  461.     $plugins = get_plugins();
  462.     $current_version = trim($plugins['category-icons/category_icons.php']['Version']);
  463.     $msg = 'Category Icons '.$current_version.'&nbsp;&nbsp;<img style="border-style:none;vertical-align:middle;padding:0px;padding-bottom:1px;margin:0px;" src="'.trailingslashit(get_option('siteurl')).PLUGINDIR.'/category-icons/images/w3c-xhtml1.0.png" alt="w3c-xhtml" /> | ';
  464.     $msg .= '<a target="_blank" href="http://www.category-icons.com/about/">'.__('About','category_icons').'</a>';
  465.     $msg .= ' | <a target="_blank" href="http://www.category-icons.com/category/howto/">'.__('How To','category_icons').'</a>';
  466.     $msg .= ' | <a target="_blank" href="http://www.category-icons.com/category/documentation/">'.__('Documentation','category_icons').'</a>';
  467.     $msg .= ' | <a target="_blank" href="http://www.category-icons.com/category/faq/">'.__('FAQ','category_icons').'</a>';
  468.     $msg .= ' | <a target="_blank" href="http://www.category-icons.com/translate-the-plugin/">'.__('Translate the plugin','category_icons').'</a>';
  469.     $msg .= ' | <a target="_blank" href="http://www.category-icons.com/troubleshooting/">'.__('Troubleshooting','category_icons').'</a>';
  470.     $msg .= ' | <a target="_blank" href="http://www.category-icons.com/contact/">'.__('Contact the author','category_icons').'</a>' ;
  471.     if (!empty($lang) && !empty($translator_name)) {
  472.         $msg .= (' | ').__('Translated by','category_icons');
  473.         if (!empty($translator_url))
  474.             $msg .= ' <a target="_blank" href="'.$translator_url.'">'.$translator_name.'</a>';
  475.         else
  476.             $msg .= ' '.$translator_name;
  477.     }
  478.     echo $msg.' <br/>';
  479. }
  480.  
  481. /**
  482.  * Loads the scripts needed by the plugin
  483.  * @author Brahim Machkouri
  484.  */
  485. function bm_caticons_add_js_libs() {
  486.     wp_enqueue_script('jquery');
  487.     wp_enqueue_style ( 'caticons-css', WP_PLUGIN_URL.'/category-icons/category_icons.css', array(), '1.0', 'all');
  488.     wp_enqueue_script('admin-forms');//WP 2.5+ only
  489.     wp_enqueue_script('caticons-tablesorter', WP_PLUGIN_URL.'/category-icons/js/jquery.tablesorter.min.js');
  490.     wp_enqueue_script('caticons-metadatas', WP_PLUGIN_URL.'/category-icons/js/jquery.metadata.min.js');
  491.     wp_enqueue_script('caticons-js', WP_PLUGIN_URL.'/category-icons/js/category_icons.js');
  492.     wp_localize_script( 'caticons-js', 'CatIconsSettings',
  493.         array('plugin_url' => get_option('siteurl').WP_PLUGIN_URL.'/category-icons',
  494.               'error' => __('Can\'t contact www.category-icons.com. Retry later, please.','category_icons'))
  495.         );
  496. }
  497.  
  498. /**
  499.  * Return the boolean corresponding to $var
  500.  * @author Brahim Machkouri
  501.  * @param boolean|int|string $var boolean or string or int to eval
  502.  * @return boolean
  503.  */
  504. function bm_caticons_getbool($var) {// i made this function because casting get_option() didn't react as I wanted
  505.     if (is_bool($var)) return $var;
  506.     switch (strtolower($var)) {
  507.         case ('true'):
  508.             return true;
  509.         case ('false'):
  510.         default:
  511.             return false;
  512.     }
  513. }
  514.  
  515. /**
  516.  * Extract the urls & labels
  517.  * @author Brahim Machkouri
  518.  * @param string $string String containing the urls to extract
  519.  * @return array
  520.  */
  521. function bm_caticons_url_extractor($string) {
  522.     $myarray = array();
  523.     if (preg_match_all('/<a\s+.*?href=[\"\']?([^\"\' >]*)[\"\']?[^>]*(>.*?<)\/a>/i', $string, $correspondances, PREG_SET_ORDER))
  524.         foreach ($correspondances as $correspondance)
  525.             array_push($myarray, array($correspondance[1], $correspondance[2]));
  526.     return $myarray;
  527. }
  528.  
  529. /**
  530.  * Find where to place the code (get_cat_icons()) in the template files. This function'll work for numerous templates.
  531.  * For the majority of the templates I've seen, the post title is after an anchor tag or after a h2 tag.
  532.  * So the function search for : <a href...>the_title()</a> and <h2...>the_title()</h2>.
  533.  * @author Brahim Machkouri
  534.  * @param string $filename Name of the template folder
  535.  * @return array
  536.  */
  537. function bm_caticons_template_code($filename='') { //needs to be optimized or rewritten
  538.     $files = array();
  539.     $results = array();
  540.     $position = 0;
  541.     $correspondances = array();
  542.     $filename='';
  543.     $notfound = 0;
  544.     //$path = ABSPATH.WP_CONTENT_DIR.'/themes/'.get_option('template');
  545.     $path = WP_CONTENT_DIR.'/themes/'.get_option('template');
  546.     $getcat_code = "\n<?php if (function_exists('get_cat_icon')) get_cat_icon(); ?>";
  547.    
  548.     if ($handle = opendir($path)) {
  549.         while (false !== ($filename = readdir($handle)))
  550.             if ( '.php' == trim(substr($filename, strrpos($filename, '.'), strlen($filename)-strrpos($filename, '.'))) )
  551.                 $files[] = trim($filename);
  552.         closedir($handle);
  553.     }
  554.  
  555.     foreach ($files as $filename) {// Scan all the php files found for the linked (a href) the_title() function
  556.         $fullfilename = $path.'/'.$filename;
  557.         $string = file_get_contents($fullfilename);
  558.         $found = 0;
  559.        
  560.         if ( (false === strpos(strtolower($string),'put_cat_icons(')) ) {
  561.             if (preg_match_all('/(wp_list_cat?[^\)].*\)[;\s])/i', $string, $correspondances, PREG_SET_ORDER)) {
  562.                 $result = array();
  563.                 foreach ($correspondances as $correspondance) {
  564.                     if ( isset($correspondance[1]) )
  565.                         $result[] = $correspondance[1];
  566.                 }
  567.                
  568.                 $correspondances = array_unique($result);
  569.                 foreach ($correspondances as $correspondance) {
  570.                     if (strpos($correspondance,'(')>0) {// Extract the wp_list_categories() parameters
  571.                         $parameters = '';
  572.                         if (preg_match_all('/[\(](.*[^\)]\))/i', $correspondance, $trouves, PREG_SET_ORDER)) {
  573.                             $parameters = substr($trouves[0][1],0,strlen($trouves[0][0])-2);
  574.                             if ( false === !strpos($parameters,'(') )
  575.                                 $parameters = $trouves[0][1];
  576.                         }
  577.                         // Put the code
  578.                         $putcat_code = "\nif (function_exists('put_cat_icons')) \n\tput_cat_icons( wp_list_categories(".$parameters;
  579.                         if (!empty($parameters))
  580.                             $putcat_code .=".'&";
  581.                         else
  582.                             $putcat_code .= '\'';  
  583.                         $putcat_code .= "echo=0'));\nelse\n\twp_list_categories(".$parameters.')';
  584.                         if (strrpos($correspondance,';')>0)
  585.                             $putcat_code .= ';';
  586.                         if ( 1 == get_option('igcaticons_templatecode_patch') && is_writable($path.'/'.$filename)) {// patch the files
  587.                             $handle = fopen($path.'/'.$filename, "wb");
  588.                             $string = str_replace($correspondance,$putcat_code,$string);
  589.                             if (fwrite($handle, $string)) $results = array($filename,'-','<i>Ok</i>');
  590.                             fclose($handle);
  591.                         }
  592.                         else {// display the informations about the line and column
  593.                             $position = 0;
  594.                             do {
  595.                                 $position = strpos($string,$correspondance,$position); 
  596.                                 if ( !( false === $position )   ) {                
  597.                                     $line_number = substr_count(  substr($string, 0,$position)   ,"\n")+1;                             
  598.                                     $column = $position - strrpos (substr($string, 0,$position),"\n") - 1;
  599.                                     $results[] = array($putcat_code,$filename,$line_number.':'.$column,htmlentities($correspondance));
  600.                                     $position += strlen($correspondance);
  601.                                 }
  602.                             }
  603.                             while ( !( false === $position ));
  604.                         }
  605.                     }
  606.                 }
  607.                
  608.             }
  609.         }
  610.        
  611.         if ( false === strpos(strtolower($string),'get_cat_icon(') ) {
  612.             if (preg_match_all('/(<a\s+.*?href=[\"\']?[^\"\' >]*[\"\']?[^>].*>+[\s\t\r\n]*<\?php +[\/\s\t\r\n$]*?[^>]+[\s\t\r\n]*.*\?>+[\s\t\r\n]*<\/a>)/i', $string, $correspondances, PREG_SET_ORDER)) {
  613.                 $correspondances = array_unique($correspondances);
  614.                 foreach ($correspondances as $correspondance) {
  615.                     if (strpos(strtolower($correspondance[1]),'the_title()')>0) {
  616.                         $found = 1;
  617.                         if (get_option('igcaticons_templatecode_patch')==1 && is_writable($path.'/'.$filename)) {// patch the files
  618.                             $handle = fopen($path.'/'.$filename, "wb");
  619.                             $string = str_replace($correspondance[1],$getcat_code.$correspondance[1],$string);
  620.                             if (fwrite($handle, $string))
  621.                                 $results = array($getcat_code,$filename,'-','<i>Ok</i>');
  622.                             fclose($handle);
  623.                         }
  624.                         else {// display the informations about the line and column
  625.                             do {
  626.                                 $position = strpos($string,$correspondance[1],$position);  
  627.                                 if ( !( false === $position )   ) {                    
  628.                                     $line_number = substr_count(  substr($string, 0,$position)   ,"\n")+1;                             
  629.                                     $column = $position - strrpos (substr($string, 0,$position),"\n") - 1;
  630.                                     $results[] = array($getcat_code,$filename,$line_number.':'.$column,htmlentities($correspondance[1]));
  631.                                     $position += strlen($correspondance[1]);
  632.                                 }
  633.                             }
  634.                             while  (!( false === $position ));
  635.                         }
  636.                     }
  637.                 }
  638.             }
  639.             if ( 0 == $found && preg_match_all('#<h2[^>]*>+[\s\t\r\n]*(<\?php +[\/\s\t\r\n$]*?[^>]+[\s\t\r\n]*.*\?>+[\s\t\r\n]*</h2>)#Ui', $string, $correspondances, PREG_SET_ORDER)) {
  640.                 $correspondances = array_unique($correspondances);
  641.                 foreach ($correspondances as $correspondance) {
  642.                     if (strpos(strtolower($correspondance[1]),'the_title()')>0) {
  643.                         if ( 1 == get_option('igcaticons_templatecode_patch') && is_writable($path.'/'.$filename)) {// patch the files
  644.                             $handle = fopen($path.'/'.$filename, "wb");
  645.                             $string = str_replace($correspondance[1],$getcat_code.$correspondance[1],$string);
  646.                             if (fwrite($handle, $string)) $results = array($getcat_code,$filename,'-','<i>Ok</i>');
  647.                             fclose($handle);
  648.                         }
  649.                         else {// display the informations about the line and column
  650.                             do {
  651.                                 $position = strpos($string,$correspondance[1],$position);  
  652.                                 if ( !( false === $position )   ) {                        
  653.                                     $line_number = substr_count(  substr($string, 0,$position)   ,"\n")+1;                             
  654.                                     $column = $position - strrpos (substr($string, 0,$position),"\n") - 1;
  655.                                     $results[] = array($getcat_code,$filename,$line_number.':'.$column,htmlentities($correspondance[1]));
  656.                                     $position += strlen($correspondance[1]);
  657.                                 }
  658.                             }
  659.                             while (!( false === $position ));
  660.                         }
  661.                     }
  662.                 }
  663.             }  
  664.         }
  665.     }
  666.     return $results;
  667. }
  668.  
  669. /**
  670.  * Display code template table panel.
  671.  * @author Brahim Machkouri
  672.  * @param string $message String to display before the table
  673.  * @param string $code String representing the code to paste
  674.  * @param array $list Every row to display
  675.  * @param string $filter Which type of table to display
  676.  */
  677. function bm_caticons_codetemplate_display($message,$list,$filter) {
  678.     $table = array();
  679.     foreach ($list as $element) {
  680.         if (strpos($element[0],$filter)) $table[] = $element;
  681.     }
  682.     $list = $table;
  683.     if ( 0 < count($list) ) {
  684. ?>
  685.          <?php echo '<p>'.$message.'</p>'; ?>
  686.            <?php if ( 'get_cat_icon' == $filter ) echo '<pre>'.htmlentities($list[0][0]).'</pre>'; ?>
  687.             <table class="widefat">
  688.                 <thead>
  689.                 <tr>
  690.                     <th ><?php _e('Filename','category_icons'); ?></th>
  691.                     <th style="text-align:center"><?php _e('Line Number : Column','category_icons'); ?></th>
  692.                     <th style="text-align:center"><?php _e('Code','category_icons'); ?></th>
  693.                 </tr>
  694.                 </thead>
  695.                 <tbody>
  696.                 <?php
  697.                     $class = '';
  698.                     if ( 0 == count($list) )
  699.                         $list = array(array('-','-','-'));
  700.                     foreach ($list as $element) {  
  701.                         $class = ('alternate' == $class) ? '' : 'alternate';
  702.                         ?>
  703.                     <tr class="<?php echo $class; ?>">
  704.                         <th><?php echo $element[1]; ?></th>
  705.                         <td align="center"><?php echo $element[2]; ?></td>
  706.                         <td align="center"><?php
  707.                             if ( 'get_cat_icon' == $filter )
  708.                                 echo '<img src="'.trailingslashit(get_option('siteurl')).PLUGINDIR.'/category-icons/images/arrowdown.png" alt="arrow" />';
  709.                             echo $element[3];
  710.                             if ( 'put_cat_icon' == $filter )
  711.                                 echo '<br/><b>'.__('by','category_icons').'</b><br/>'.htmlentities($element[0]).'<br/>';
  712.                             ?></td>
  713.                     </tr>
  714.                         <?php
  715.                     }
  716.                 ?></tbody>
  717.          </table>
  718.   <?php
  719.      }
  720. }
  721.  
  722. /**
  723.  * Check if the default upload path is readable.
  724.  * @author Brahim Machkouri
  725.  */
  726. function bm_caticons_check_uploads_path() {
  727.     if (!wp_mkdir_p(ig_caticons_path())) {
  728.    
  729.         $options_file = "options-misc.php";
  730.    
  731.         if (version_compare($GLOBALS['wp_version'], '3.0','>=')) {
  732.             $options_file ="options-media.php";
  733.         }
  734.    
  735.         $message = __('the default upload path is not accessible.','category_icons');
  736.         if (!is_multisite()) {
  737.             $message = "<a href='$options_file'>".$message.'</a>';
  738.         }
  739.         else {
  740.             $message .= ' ( '.ig_caticons_path().' ) <br/>';
  741.         }
  742.    
  743.         if (!is_readable(ig_caticons_path())) {
  744.         ?>
  745.             <div id="message" class="updated fade">
  746.                 <p><strong>
  747.             <?php
  748.                 echo __('Error in Category Icons','category_icons').' : '.$message.__('Please create one or change the permissions on the directory.','category_icons');
  749.             ?>
  750.                 </strong></p>
  751.             </div>
  752.         <?php
  753.         }
  754.     }
  755. }
  756.  
  757. /**
  758.  * Echoes the option tag filled with icons paths
  759.  * @author Brahim Machkouri
  760.  * @param string $selected the icon to select in the dropdown menu
  761.  */
  762. function bm_caticons_get_icons_paths($selected='') {
  763.     $files = array();
  764.     $basepath = ig_caticons_path();
  765.     $files = bm_caticons_recursive_readdir($basepath);
  766.     natcasesort($files);
  767.     foreach ($files as $fullpath => $filename) {
  768.         $sel = ($selected==$fullpath) ? ' selected="selected"' : '';
  769.         echo('<option value="'.htmlspecialchars($fullpath).'"'.$sel.'>'. htmlspecialchars($filename).' ('.str_replace($filename,'',$fullpath).')</option>');
  770.     }
  771. }
  772.  
  773. /**
  774.  * Gets the icons paths
  775.  * @author Brahim Machkouri
  776.  * @param string $folder Name of the folder to browse
  777.  * @param array $files Filenames already found
  778.  * @return array
  779.  */
  780. function bm_caticons_recursive_readdir($folder,$files=array()) {
  781.     $separator = '/';
  782.     $types = explode(' ',get_option('igcaticons_filetypes'));
  783.     if (is_readable($folder) && $handle = opendir($folder)  ) {
  784.         while (false !== ($filename = readdir($handle))) {
  785.             if ($filename !== '.' && $filename !== '..') {
  786.                 $path = $folder.$separator.$filename;
  787.                 if (is_dir ($path))
  788.                     $files = array_unique(array_merge($files, bm_caticons_recursive_readdir($path,$files))); // recursive call
  789.                 else {// files
  790.                     $p = strrpos($filename,'.');
  791.                     if (false===$p || !in_array(strtolower(substr($filename, $p+1)), $types)) continue;
  792.                     else
  793.                         $files[str_replace(ig_caticons_path().$separator,'', trim($path))] = $filename;
  794.                 }
  795.             }
  796.         }
  797.         closedir($handle);
  798.     }
  799.     return $files;
  800. }
  801.  
  802. /**
  803.  * Print category rows for admin panel
  804.  * @author Brahim Machkouri
  805.  * @param int $parent Category ID of the parent
  806.  * @param int $level Level of the category (parent or child)
  807.  * @param array $category Array of categories (Objects)
  808.  * @return false False if no category is found
  809.  */
  810. function bm_caticons_rows( $parent = 0, $level = 0, $categories = 0 ) { // I took the code from template.php of WordPress 2.5 and modified it a little
  811.     if ( !$categories ) {
  812.         $args = array('hide_empty' => 0);
  813.         if ( !empty($_GET['s']) )
  814.             $args['search'] = $_GET['s'];
  815.         $categories = get_categories( $args );
  816.     }
  817.     $children = _get_term_hierarchy('category');
  818.     if ( $categories ) {
  819.         ob_start();
  820.         foreach ( $categories as $category ) {
  821.             if ( $category->parent == $parent) {
  822.                 echo "\t" . _bm_caticons_row( $category, $level );
  823.                 if ( isset($children[$category->term_id]) )
  824.                     bm_caticons_rows( $category->term_id, $level +1, $categories );
  825.             }
  826.         }
  827.         $output = ob_get_contents();
  828.         ob_end_clean();
  829.         $output = apply_filters('bm_caticons_rows', $output);
  830.         echo $output;
  831.     }
  832.     else
  833.         return false;
  834. }
  835.  
  836. /**
  837.  * Display the rows of the icons panel in Icons tab
  838.  * @author Brahim Machkouri
  839.  * @return string
  840.  */
  841. function _bm_caticons_row( $category, $level) { // I took the code from template.php of WordPress 2.5 and modified it a little
  842.     global $class;
  843.     $icons_path = ig_caticons_path();
  844.     $category = get_category( $category );
  845.     $warning_flag = 0;
  846.     $pad = str_repeat( '&#8212; ', $level );
  847.     $name =  $pad . ' ' . $category->name ;
  848.   $warning = "";
  849.     list($priority, $icon, $small_icon) = bm_caticons_get_icons($category->term_id);
  850.     $message_icon = esc_attr(sprintf(__('If you can\'t see the icons, the URL to icons in the Options panel should be set to %s','category_icons'), ig_caticons_url().get_option('igcaticons_path')));
  851.     // Normal icon
  852.     $icon_cell = '';
  853.     if ( !empty($icon) && is_readable( trailingslashit($icons_path).$icon ) ) {
  854.         list($width, $height, $type, $attr) = getimagesize(trailingslashit($icons_path).$icon);
  855.         list($w, $h) = ig_caticons_fit_rect($width, $height, 100, 100);
  856.         $icon_cell = '<img src="'.trailingslashit(ig_caticons_url())."$icon\" width=\"$w\" height=\"$h\" alt=\"icon\" onerror='alert(\"$message_icon\");' /> <br />$icon ($width x $height)";
  857.         $icon_cell = '<a href="'.trailingslashit(ig_caticons_url()).$icon.'">'.$icon_cell.'</a>';
  858.     }
  859.     if ( !empty($icon) && !is_readable( trailingslashit($icons_path).$icon ) ) {
  860.         $icon_cell = '<img src="' . $warning . '">' . trailingslashit($icons_path) . $icon . __(' is not accessible ','category_icons') ;
  861.         $warning_flag = 1;
  862.     }
  863.     // Small icon
  864.     $small_icon_cell = '';
  865.     if ( !empty($small_icon) && is_readable( trailingslashit($icons_path).$small_icon ) ) {
  866.         list($width, $height, $type, $attr) = getimagesize(trailingslashit($icons_path).$small_icon);
  867.         list($w, $h) = ig_caticons_fit_rect($width, $height, 100, 100);
  868.         $small_icon_cell = '<img src="'.trailingslashit(ig_caticons_url())."$small_icon\" width=\"$w\" height=\"$h\" alt=\"small icon\" onerror='alert(\"$message_icon\");'/> <br />$small_icon ($width x $height)";
  869.         $small_icon_cell = '<a href="'.trailingslashit(ig_caticons_url()).$small_icon.'">'.$small_icon_cell.'</a>';
  870.     }
  871.     if ( !empty($small_icon) && !is_readable( trailingslashit($icons_path).$small_icon ) ) {
  872.         $small_icon_cell = '<img src="'.$warning.'">'.trailingslashit($icons_path).$small_icon . __(' is not accessible ', 'category_icons');
  873.         $warning_flag = 1;
  874.     }
  875.     $edit = $name;
  876.     if (is_admin() || current_user_can( 'manage_categories' ))
  877.         $edit = "<a class='row-title' href='".CI_ADMIN_SELF."&amp;ig_module=caticons&amp;ig_tab=icons&amp;action=edit&amp;cat_ID=$category->term_id' title='"
  878.                 . esc_attr(sprintf(__('Edit %s','category_icons'), $category->name)) . "'>" .$name . "</a>";
  879.     $class = " class='alternate'" == $class ? '' : " class='alternate'";
  880.     if ($warning_flag > 0) $class = 'style = "background-color:#FFB06C"';
  881.     $category->count = number_format_i18n( $category->count );
  882.     $posts_count = $category->count;
  883.     // Prepare the output string
  884.     $output = '<tr id="cat-'.$category->term_id.'" '.$class.' >'.
  885.                '<th scope="row" class="check-column" style="text-align:center;vertical-align:middle;padding:7px 0 8px">';
  886.     if (is_admin() || current_user_can( 'manage_categories' ))
  887.         $output .= '<input type="checkbox" name="delete[]" value="'.$category->term_id.'" /></th>';
  888.     else
  889.         $output .= "&nbsp;";
  890.     $output .=  '<td style="vertical-align:middle;">'.$category->term_id.'</td>'.
  891.                 '<td style="vertical-align:middle;">'.$edit.'</td>'.
  892.                 '<td style="vertical-align:middle;">'.$category->description.'</td>'.
  893.                 '<td class="num" style="vertical-align:middle;text-align:center" align="center" >'.$posts_count.'</td>'.
  894.                 '<td class="num" style="vertical-align:middle;text-align:center" align="center">'.$priority.'</td>'.
  895.                 '<td style="vertical-align:middle;text-align:center" align="center">'.$icon_cell.'</td>'.
  896.                 '<td style="vertical-align:middle;text-align:center" align="center">'.$small_icon_cell.'</td>'.
  897.                 "\n\t</tr>\n";
  898.     return apply_filters('bm_caticons_row', $output);
  899. }
  900.  
  901. /**
  902.  * Display the icons panel in Icons tab
  903.  * @author Brahim MACHKOURI
  904.  */
  905. function bm_caticons_adminicons() { // I took some of the code from categories.php of WordPress 2.5 and modified it a little
  906.     global $wpdb;
  907.     $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
  908.     if ( isset($_GET['deleteit']) && isset($_GET['delete']) )
  909.         $action = 'bulk-delete';
  910.     switch($action) {
  911.         case 'update-category-icon':
  912.             $cat_ID = (int) $_GET['cat_ID'];
  913.             $priority = $_REQUEST['ig_priority'];
  914.             $icon = $_REQUEST['ig_icon'];
  915.             $small_icon = $_REQUEST['ig_small_icon'];
  916.             if ( $wpdb->get_var( $wpdb->prepare( "SELECT cat_id FROM $wpdb->ig_caticons WHERE cat_id = '%d' ", $cat_ID ) ) ) {
  917.                 $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->ig_caticons SET priority = '%d', icon = '%s', small_icon='$s' WHERE cat_id = '%d' ", $priority, $icon, $small_icon, $cat_ID ) ) ;
  918.             } else {
  919.                 $wpdb->query($wpdb->prepare("INSERT INTO $wpdb->ig_caticons (cat_id, priority, icon, small_icon) VALUES ('$cat_ID', '$priority', '$icon', '$small_icon')"));
  920.             }
  921.         break;
  922.         case 'delete':
  923.             $cat_ID = (int) $_GET['cat_ID'];
  924.             if (!is_admin() || !current_user_can( 'manage_categories' ))
  925.                 wp_die(__('Are you trying to cheat ?','category_icons'));
  926.             $cat_name = get_catname($cat_ID);
  927.             $request = "DELETE FROM $wpdb->ig_caticons WHERE cat_id='$cat_ID'";
  928.             if (false === $wpdb->query($wpdb->prepare($request) ))
  929.                 wp_die(__('Error in Category Icons','category_icons').' : '.$request);
  930.         break;
  931.         case 'bulk-delete':
  932.             if (!is_admin() || !current_user_can( 'manage_categories' ))
  933.                 wp_die( __('You are not allowed to delete category icons.','category_icons') );
  934.             foreach ( (array) $_GET['delete'] as $cat_ID ) {
  935.                 $cat_name = get_catname($cat_ID);
  936.                 $wpdb->query($wpdb->prepare("DELETE FROM $wpdb->ig_caticons WHERE cat_id='$cat_ID'"));
  937.             }
  938.         break;
  939.     }
  940.     switch ($action) {
  941.     case 'edit':
  942.         $cat_ID = (int) $_GET['cat_ID'];
  943.         $category = get_category_to_edit($cat_ID);
  944.         list($priority, $icon, $small_icon) = bm_caticons_get_icons($cat_ID);
  945.         ?>
  946.         <div class="wrap">
  947.         <h2><?php _e('Select Category Icons','category_icons') ?></h2>
  948.         <form method="post" name="caticons-form1" action="">
  949.           <?php wp_nonce_field('caticons-nonce'); ?>
  950.             <input type="hidden" name="ig_module" value="caticons" />
  951.             <input type="hidden" name="ig_tab" value="icons" />
  952.             <input type="hidden" name="action" value="update-category-icon" />
  953.             <table  border="0" class="form-table">
  954.                 <tr>
  955.                     <th scope="row" style="vertical-align:text-top;"><?php _e('Category ID','category_icons'); ?></th>
  956.                     <td colspan="2" ><?php echo $cat_ID;?></td>
  957.                 </tr>
  958.                 <tr>
  959.                     <th scope="row" style="vertical-align:text-top;"><?php _e('Name','category_icons'); ?></th>
  960.                     <td colspan="2"><?php echo $category->name;?></td>
  961.                 </tr>
  962.                 <tr>
  963.                     <th scope="row" class="num" style="vertical-align:text-top;"><?php _e('Priority','category_icons'); ?></th>
  964.                     <td colspan="2">
  965.                         <input type="text" name="ig_priority" size="5" value="<?php echo $priority; ?>" />
  966.                     </td>
  967.                 </tr>
  968.                 <tr>
  969.                     <th scope="row" style="vertical-align:text-top;"><?php _e('Icon','category_icons'); ?></th>
  970.                     <td valign="top"><label><?php _e('Select a file : ','category_icons');?></label>
  971.                         <select name="ig_icon" onchange="icon_preview.src=('<?php echo ig_caticons_url();?>/'+this.options[this.selectedIndex].value);">
  972.                             <option value="">--- <?php _e('No Icon','category_icons'); ?> ---</option>
  973.                             <?php bm_caticons_get_icons_paths($icon);   ?>
  974.                         </select><br/>
  975.                         <label><?php _e('Or enter an URL : ','category_icons');?><input type="text" name="bm_icon_url"/></label>
  976.                     </td>
  977.                     <td valign="top"><img id="icon_preview" src="<?php echo ig_caticons_url()."/$icon";?>" alt="icon" /></td>
  978.                 </tr>
  979.                 <tr>
  980.                     <th scope="row" style="vertical-align:text-top;"><?php _e('Small Icon','category_icons'); ?></th>
  981.                     <td valign="top"><label><?php _e('Select a file : ','category_icons');?></label>
  982.                         <select name="ig_small_icon" onchange="small_icon_preview.src=('<?php echo ig_caticons_url();?>/'+this.options[this.selectedIndex].value);">
  983.                             <option value="">--- <?php _e('No Icon','category_icons'); ?> ---</option>
  984.                             <?php bm_caticons_get_icons_paths($small_icon); ?>
  985.                         </select><br/>
  986.                         <label><?php _e('Or enter an URL : ','category_icons');?><input type="text" name="bm_smallicon_url"/></label>
  987.                     </td>
  988.                     <td valign="top"><img id="small_icon_preview" src="<?php echo ig_caticons_url()."/$small_icon";?>" alt="small icon" /></td>
  989.                 </tr>
  990.             </table>
  991.             <div class="submit"><input type="submit" name="info_update" value="<?php _e('Select Icons','category_icons');?> &raquo;" /></div>
  992.         </form>
  993.         </div>
  994.         <?php
  995.     break;
  996.     default:
  997.     ?>
  998.     <div class="wrap">
  999.         <form id="posts-filter" action="" method="get" name="caticons-form2">
  1000.         <?php wp_nonce_field('caticons-nonce'); ?>
  1001.             <input type="hidden" name="ig_module" value="caticons" />
  1002.             <input type="hidden" name="page" value="category_icons.php" />
  1003.             <input type="hidden" name="action" value="delete" />
  1004.             <input type="hidden" name="ig_tab" value="icons" />
  1005.        
  1006.         <div class="tablenav">
  1007.             <div class="alignleft">
  1008.                 <input type="submit" value="<?php _e('Delete icons and priority','category_icons'); ?>" name="deleteit" class="button-secondary delete" />
  1009.             </div>
  1010.             <br class="clear" />
  1011.         </div>
  1012.         <br class="clear" />
  1013.         <table class="widefat" id="caticons_table">
  1014.             <thead>
  1015.             <tr>
  1016.                 <th scope="col" id="cb" class="check-column"><input type="checkbox" /></th>
  1017.                 <th scope="col"><?php _e('ID','category_icons') ?></th>
  1018.                 <th scope="col" ><?php _e('Name','category_icons') ?></th>
  1019.                 <th scope="col" style="text-align:center"><?php _e('Description','category_icons') ?></th>
  1020.                 <th scope="col" class="num" style="text-align:center"><?php _e('Posts','category_icons') ?></th>
  1021.                 <th scope="col" style="text-align:center"><?php _e('Priority','category_icons') ?></th>
  1022.                 <th scope="col" style="text-align:center"><?php _e('Icon','category_icons') ?></th>
  1023.                 <th scope="col" style="text-align:center"><?php _e('Small Icon','category_icons') ?></th>
  1024.             </tr>
  1025.             </thead>
  1026.             <tbody id="the-list" class="list:cat">
  1027.         <?php
  1028.         bm_caticons_rows();
  1029.         ?>
  1030.             </tbody>
  1031.         </table>
  1032.         </form>
  1033.         <div class="tablenav">
  1034.         <br class="clear" />
  1035.         </div>
  1036.         <br class="clear" />
  1037.         </div>
  1038.     <?php
  1039.     }// end switch
  1040. }
  1041.  
  1042. /**
  1043.  * Install the plugin
  1044.  * @author Ivan Georgiev
  1045.  */
  1046. function ig_caticons_install() {
  1047.     global $wpdb, $table_prefix;
  1048.   $table = "ig_caticons";
  1049.     $wpdb->query($wpdb->prepare( "CREATE TABLE IF NOT EXISTS `$wpdb->ig_caticons` (`cat_id` INT NOT NULL ,`priority` INT NOT NULL ,`icon` TEXT NOT NULL ,`small_icon` TEXT NOT NULL , PRIMARY KEY ( `cat_id` ))", $table ) ) ;
  1050.     add_option('igcaticons_path', '');
  1051.     add_option('igcaticons_url', '');
  1052.     add_option('igcaticons_filetypes', 'jpg gif jpeg png');
  1053.     add_option('igcaticons_max_icons','3');
  1054.     add_option('igcaticons_before_name','true');
  1055.     add_option('igcaticons_fit_width','-1');
  1056.     add_option('igcaticons_fit_height','-1');
  1057.     add_option('igcaticons_use_small','true');
  1058.     add_option('igcaticons_templatecode_patch','0');
  1059.     add_option('igcaticons_templatecode_sidebar','1');
  1060.     add_option('igcaticons_rssfeeds','1');
  1061.     add_option('igcaticons_useseo_plugin', '0');
  1062.     add_option('igcaticons_max_width','-1');
  1063.     add_option('igcaticons_max_height','-1');
  1064.     add_option('igcaticons_iconcatpage','0');
  1065. }
  1066.  
  1067. /**
  1068.  * Get the upload & siteurl paths
  1069.  * @author Ivan Georgiev
  1070.  * @return array (path, url)
  1071.  */
  1072. function ig_caticons_defupload() {
  1073.     $def_path = str_replace(ABSPATH, '', get_option('upload_path')); // wordpress's option
  1074.     $def_url = trailingslashit(get_option('siteurl')) . $def_path; // idem
  1075.     return array($def_path, $def_url);
  1076. }
  1077.  
  1078. /**
  1079.  * Integrate into the admin menu.
  1080.  * @author Ivan Georgiev, Brahim Machkouri
  1081.  */
  1082. function ig_caticons_adminmenu() {
  1083.     load_plugin_textdomain('category_icons', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
  1084.     $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 'category_icons.php';
  1085.     define('CI_ADMIN_SELF', '?page='.$page);
  1086.     if (function_exists('add_submenu_page'))
  1087.         add_submenu_page('edit.php', __('Category Icons','category_icons') , __('Category Icons','category_icons') , 'manage_categories' , basename(__FILE__) , 'ig_caticons_adminpanel' );
  1088. }
  1089.  
  1090. /**
  1091.  * Handle admin panel
  1092.  * @authors Ivan Georgiev, Brahim Machkouri
  1093.  */
  1094. function ig_caticons_adminpanel() {
  1095.     add_action( 'in_admin_footer', 'bm_caticons_credits' );
  1096.     if (!(file_exists( ABSPATH.'/'.PLUGINDIR.'/category-icons/category_icons.php'))) {
  1097. ?>
  1098.         <div id="message" class="updated fade">
  1099.             <p><strong>
  1100.         <?php
  1101.             echo __('Error in Category Icons','category_icons').' : '.__('you must put the category_icons.php in /wp-content/plugins/category-icons/ directory.<br/> So deactivate the plugin, and move the file into category-icons directory.<br/>Click on Plugins 2 times, to restart the plugin detection.<br/>And then, reactivate it.','category_icons');
  1102.         ?>
  1103.             </strong></p>
  1104.         </div>
  1105. <?php
  1106.     }
  1107.     bm_caticons_check_uploads_path();
  1108.     $tab = isset($_REQUEST['ig_tab']) ? $_REQUEST['ig_tab'] : '';
  1109.     if (isset($_POST['info_update']) && 'options' == $tab && check_admin_referer('caticons-nonce')) {  
  1110.         ?><div class="updated"><p><strong><?php _e('Settings updated.','category_icons');?></strong></p></div><?php
  1111.         update_option('igcaticons_path', $_POST['igcaticons_path']);
  1112.         update_option('igcaticons_url', $_POST['igcaticons_url']);
  1113.         update_option('igcaticons_filetypes', $_POST['igcaticons_filetypes']);
  1114.         update_option('igcaticons_max_icons', $_POST['igcaticons_max_icons']);
  1115.         update_option('igcaticons_before_name', $_POST['igcaticons_before_name']);
  1116.         update_option('igcaticons_max_width', $_POST['igcaticons_max_width']);
  1117.         update_option('igcaticons_max_height', $_POST['igcaticons_max_height']);
  1118.        
  1119.         bm_caticons_updatemyoption('igcaticons_templatecode_patch');
  1120.         bm_caticons_updatemyoption('igcaticons_templatecode_sidebar');
  1121.         bm_caticons_updatemyoption('igcaticons_rssfeeds');  
  1122.         bm_caticons_updatemyoption('igcaticons_useseo_plugin');
  1123.         bm_caticons_updatemyoption('igcaticons_iconcatpage');      
  1124.     }
  1125.    
  1126.     bm_caticons_menu($tab);
  1127.     switch ($tab) {
  1128.         case ('icons'):
  1129.             bm_caticons_adminicons();
  1130.         break;
  1131.         case ('template'):
  1132.             bm_caticons_admintemplate();
  1133.         break;
  1134.         case ('options'):
  1135.         default:
  1136.             bm_caticons_adminoptions();
  1137.     }
  1138. }
  1139.  
  1140. // for the checkboxes options
  1141. function bm_caticons_updatemyoption($option) {
  1142.     if (isset($_POST[$option])) {
  1143.         update_option($option, $_POST[$option]);
  1144.     }
  1145.     else {
  1146.         update_option($option, 0);
  1147.     }  
  1148. }
  1149. /**
  1150.  * Display the menu (Icons, Options, Template Tags)
  1151.  * @author Brahim Machkouri
  1152.  * @param string $tab The tab that was seleted
  1153.  */
  1154. function bm_caticons_menu($tab) {
  1155. ?> <div class="wrap"><?php screen_icon(); ?>
  1156.     <h2><a target="_blank" href="http://www.category-icons.com/"><?php _e('Category Icons','category_icons'); ?></a></h2>
  1157.     <ul style="display:inline" id="submenu" class="subsubsub">
  1158.       <li id="caticons_icons" style="font-size:12px"> <a style="display:inline" href="<?php echo CI_ADMIN_SELF;?>&amp;ig_module=caticons&amp;ig_tab=icons" <?php if ('icons' == $tab ) echo 'class="current"'; ?>><?php _e('Icons','category_icons'); ?></a>&nbsp;</li>
  1159.       <li id="caticons_options" style="font-size:12px"> <a style="display:inline" href="<?php echo CI_ADMIN_SELF;?>&amp;ig_module=caticons&amp;ig_tab=options" <?php if ('options' == $tab || empty($tab)) echo 'class="current"'; ?>><?php _e('Options','category_icons'); ?></a>&nbsp;</li>
  1160.       <li id="caticons_templatecode" style="font-size:12px"> <a style="display:inline" href="<?php echo CI_ADMIN_SELF;?>&amp;ig_module=caticons&amp;ig_tab=template" <?php if ('template' == $tab ) echo 'class="current"'; ?>><?php _e('Template Tags','category_icons'); ?></a>&nbsp;</li>
  1161.      </ul>
  1162.      </div><div class="clear"></div>
  1163. <?php    
  1164. }
  1165.  
  1166. /**
  1167.  * Display the Options tab
  1168.  * @author Brahim Machkouri
  1169.  */
  1170. function bm_caticons_adminoptions() {  
  1171.     list($def_path, $def_url) = ig_caticons_defupload();
  1172. ?><div class="form-wrap">
  1173.     <form method="post" action="" name="caticons-form3">
  1174.     <?php wp_nonce_field('caticons-nonce'); ?>
  1175.     <input type="hidden" name="ig_module" value="caticons"/>
  1176.     <input type="hidden" name="ig_tab" value="options"/>
  1177.     <div class="col-container">
  1178.         <div id="col-right">
  1179.             <div class="metabox-holder">   
  1180.                 <div class="postbox">
  1181.                     <h3 class="hndle"><span><?php _e('Template Tags','category_icons'); ?></span></h3>
  1182.                     <div class="inside">
  1183.                         <label class="selectit"><input type="checkbox" name="igcaticons_templatecode_patch" id="templatecode_patch" value="1" <?php checked('1', get_option('igcaticons_templatecode_patch')); ?> />
  1184.                         <?php _e('Patch the files if possible (check for true)','category_icons');  ?></label>
  1185.                         <label class="selectit"><input type="checkbox" name="igcaticons_templatecode_sidebar" id="templatecode_sidebar" value="1" <?php checked('1', get_option('igcaticons_templatecode_sidebar')); ?> />
  1186.                         <?php _e('Process the list of categories (usually used in sidebar) ?','category_icons');?></label>
  1187.                     </div>
  1188.                 </div>
  1189.             </div>
  1190.             <div class="metabox-holder">   
  1191.                 <div class="postbox">
  1192.                 <h3 class="hndle"><span><?php _e('Position of the category icon in the sidebar','category_icons'); ?></span></h3>
  1193.             <div class="inside">
  1194.                 <label><input type="radio" name="igcaticons_before_name" id="before_name_left" value="true" <?php  checked('true',get_option('igcaticons_before_name')); ?>/>&nbsp;<?php _e('Left','category_icons');?></label>
  1195.                 <label><input type="radio" name="igcaticons_before_name" id="before_name_right" value="false" <?php checked('false',get_option('igcaticons_before_name')); ?>/>&nbsp;<?php _e('Right','category_icons');?></label>
  1196.                 <p><?php _e("Select 'Left' if you want to put the category icon in front of the category name in the sidebar, or 'Right' if you want to put it after. <b>Remember that you must use the put_cat_icons() function to display icons in the sidebar, unless you use the <a href='widgets.php'>widget</a></b>.",'category_icons');?></p>
  1197.             </div>
  1198.             </div>
  1199.             </div>
  1200.                 <label><input type="checkbox" name="igcaticons_rssfeeds" id="rssfeeds" value="1" <?php checked('1', get_option('igcaticons_rssfeeds')); ?> />&nbsp;<?php _e('Display category icons in RSS feeds','category_icons'); ?></label>
  1201.                 <label><input type="checkbox" name="igcaticons_iconcatpage" id="iconcatpage" value="1" <?php checked('1', get_option('igcaticons_iconcatpage')); ?> />&nbsp;<?php _e('Display only the icon of the selected category in the category page','category_icons'); ?></label>
  1202.                
  1203.             <?php if (function_exists('seo_friendly_images')) : ?>
  1204.                 <label><input type="checkbox" name="igcaticons_useseo_plugin" id="useseofriendlyimages" value="1" <?php checked('1', get_option('igcaticons_useseo_plugin')); ?> />
  1205.             <?php _e('Use SEO Friendly Images plugin','category_icons'); ?></label>
  1206.             <?php  endif; ?>
  1207.          
  1208.         </div>
  1209.         <div id="col-left">
  1210.             <div class="form-field">
  1211.                 <label><?php _e('Local Path to Icons','category_icons');?></label>
  1212.                 <input type="text" name="igcaticons_path" size="50" value="<?php echo htmlspecialchars(get_option('igcaticons_path')); ?>" />
  1213.                 <p><?php _e('Leave blank to use default upload path','category_icons');?>.</p>
  1214.                  <p><?php echo __('Your local path to icons is set to ','category_icons').trailingslashit(ig_caticons_path()); ?></p>
  1215.             </div>
  1216.             <div class="form-field">
  1217.                 <label><?php _e('URL to Icons','category_icons');?></label>
  1218.                 <input type="text" name="igcaticons_url" size="50" value="<?php echo htmlspecialchars(get_option('igcaticons_url')); ?>" />
  1219.                 <p><?php _e('Leave blank to use default upload url','category_icons');?>.</p>
  1220.                 <p><?php echo __('Your URL to icons is set to ','category_icons').trailingslashit(ig_caticons_url()); ?></p>
  1221.             </div>
  1222.             <div class="form-field">
  1223.                 <label><?php _e('Image File Types','category_icons');?></label>
  1224.                 <input type="text" name="igcaticons_filetypes" size="50" value="<?php echo htmlspecialchars(get_option('igcaticons_filetypes')); ?>" />
  1225.                 <p><?php _e("Separate by space or comma. E.g. 'jpg gif jpeg png'",'category_icons');?></p>
  1226.             </div>
  1227.             <div class="form-field">
  1228.                 <label><?php _e('Maximum icon width','category_icons');?></label>
  1229.                 <input type="text" name="igcaticons_max_width" size="3" value="<?php echo htmlspecialchars(get_option('igcaticons_max_width')); ?>" />
  1230.                 <p><?php _e('Enter the maximum width of an icon.','category_icons');?></p>
  1231.             </div> 
  1232.             <div class="form-field">
  1233.                 <label><?php _e('Maximum icon height','category_icons');?></label>
  1234.                 <input type="text" name="igcaticons_max_height" size="3" value="<?php echo htmlspecialchars(get_option('igcaticons_max_height')); ?>" />
  1235.                 <p><?php _e('Enter the maximum height of an icon.','category_icons');?></p>
  1236.             </div>
  1237.             <div class="form-field">
  1238.                 <label><?php _e('Maximum number of icons','category_icons');?></label>
  1239.                 <input type="text" name="igcaticons_max_icons" size="3" value="<?php echo htmlspecialchars(get_option('igcaticons_max_icons')); ?>" />
  1240.                 <p><?php _e('Enter the maximum number of icons to display in front of the posts titles.','category_icons');?></p>
  1241.             </div>
  1242.             <div class="submit">
  1243.                 <input type="submit" name="info_update" value="<?php _e('Update Options','category_icons');?> &raquo;" />
  1244.             </div> 
  1245.         </div>
  1246.     </div>
  1247.     </form>
  1248. </div>
  1249. <?php
  1250. }
  1251.  
  1252. /**
  1253.  * Display the 'Template Tags' tab
  1254.  * @author Brahim Machkouri
  1255.  */
  1256. function bm_caticons_admintemplate() {
  1257.     $list = bm_caticons_template_code();
  1258.    
  1259.     $message = __('Remember that these locations are just where you COULD paste the tag, not where you MUST paste it. It\'s up to you to find the appropriate location within your template files. The tag is usually within the Loop.','category_icons');
  1260.     $message .=' '.__('Paste the following code in the listed files, at the line and column numbers displayed below.','category_icons');
  1261.     if ( 0 == count($list) )
  1262.         $message = __('There\'s nothing to do.','category_icons');
  1263. ?>
  1264. <div class="wrap"><h2><?php
  1265.             $ct = wp_get_theme();//current_theme_info();
  1266.             _e('Template Tags for','category_icons');
  1267.             echo ' '.$ct->name;
  1268.         ?></h2>
  1269.     <h3><a target="_blank" href="http://www.category-icons.com/2008/03/12/function-get_cat_icon/">get_cat_icon()</a></h3>
  1270. <?php
  1271.     if ( 0 < count($list) ) {  
  1272.         bm_caticons_codetemplate_display($message,$list,'get_cat_icon');
  1273.         if (get_option('igcaticons_templatecode_sidebar')==1) {
  1274.             echo '<h3><a target="_blank" href="http://www.category-icons.com/2008/03/12/function-put_cat_icon/">put_cat_icons()</a></h3>';
  1275.             $message = __('Replace the code','category_icons');
  1276.             bm_caticons_codetemplate_display($message,$list,'put_cat_icon');
  1277.         }
  1278.     }
  1279. ?>
  1280.    
  1281. </div>
  1282. <?php
  1283. }
  1284.  
  1285. /**
  1286.  * Get the icons base path.
  1287.  * @author Ivan Georgiev
  1288.  * @return array
  1289.  */
  1290. function ig_caticons_path() {
  1291.     $path = get_option('igcaticons_path');
  1292.     $def = ig_caticons_defupload();
  1293.    
  1294.     if (empty($path))
  1295.         return ABSPATH.$def[0];
  1296.     else
  1297.         return ABSPATH.$path;
  1298. }
  1299.  
  1300. /**
  1301.  * Get the icons base url.
  1302.  * @author Ivan Georgiev
  1303.  * @return array
  1304.  */
  1305. function ig_caticons_url() {
  1306.     $url = get_option('igcaticons_url');
  1307.     $def = ig_caticons_defupload();
  1308.     if (empty($url))
  1309.         return $def[1];
  1310.     else
  1311.         return $url;
  1312. }
  1313.  
  1314. /**
  1315.  * Get file types to show when selecting icons.
  1316.  * @author Ivan Georgiev
  1317.  * @return array
  1318.  */
  1319. function ig_caticons_filetypes() {
  1320.     $types = get_option('igcaticons_filetypes');
  1321.     if (empty($types))
  1322.         return get_option('fileupload_allowedtypes');
  1323.     else
  1324.         return $types;
  1325. }
  1326.  
  1327. /**
  1328.  * Get category icons
  1329.  * @author Ivan Georgiev
  1330.  * @param int $cat Category ID
  1331.  * @return array (priority, icon, small_icon)
  1332.  */
  1333. function bm_caticons_get_icons($cat=0) {
  1334.     global $wpdb, $caticons_datas; 
  1335.    
  1336.     $cat = (int) $cat;//$wpdb->escape($cat);
  1337.     $result = false;
  1338.     $table = "ig_caticons";
  1339.     if (empty($caticons_datas)) {
  1340.         $datas = $wpdb->get_results( $wpdb->prepare( " SELECT cat_id, priority, icon, small_icon FROM $wpdb->ig_caticons", $table ) ) ;
  1341.         foreach ($datas as $row) {
  1342.             $caticons_datas[$row->cat_id] = array ($row->priority, $row->icon, $row->small_icon);
  1343.         }
  1344.     }
  1345.     if (isset($caticons_datas[$cat])) $result = $caticons_datas[$cat];
  1346.    
  1347.     return $result;
  1348. }
  1349.  
  1350. /**
  1351.  * Get category icon with the hightest priority.
  1352.  * @param array $cats Array of Category IDs
  1353.  * @return array (cat_id, priority, icon, small_icon)
  1354.  * @author Oliver Weichhold
  1355.  */
  1356. function ow_caticons_get_priority_icon($cats) {
  1357.     global $wpdb;
  1358.     $instr = '';
  1359.     foreach($cats as $cat)
  1360.         $instr .= $wpdb->escape($cat).',';
  1361.     $instr = preg_replace('/,$/','', $instr); // Remove trailing comma
  1362.     if ($row = $wpdb->get_row( $wpdb->prepare( "SELECT cat_id, priority, icon, small_icon FROM $wpdb->ig_caticons WHERE cat_id IN(%s) ORDER BY priority DESC LIMIT 1", $instr ) ) ) {
  1363.         $result = array( $row->cat_id, $row->priority, $row->icon, $row->small_icon ) ;
  1364.         //print_r($instr);
  1365.         return $result ;
  1366.     }
  1367.     else    {
  1368.         return false;
  1369.     }
  1370. }
  1371.  
  1372. /**
  1373.  * Utility function to compute a rectangle to fit a given rectangle by maintaining the aspect ratio.
  1374.  * @author Ivan Georgiev
  1375.  * @param int $width Width of the rectangle
  1376.  * @param int $height Height of the rectangle
  1377.  * @param int $max_width Maximum Width of the new rectangle
  1378.  * @param int $max_height Maximum Height of the new rectangle
  1379.  * @param boolean $expand Expand the rectangle ? Default : false
  1380.  * @return array (width, height)
  1381.  */
  1382. function ig_caticons_fit_rect($width, $height, $max_width=-1, $max_height=-1, $expand=false) {
  1383.     $h = (int) $height;
  1384.     $w = (int) $width;
  1385.     if ($max_width>0 && ($w > $max_width || $expand)) {
  1386.         $w = $max_width;
  1387.         $h = floor(($w*$height)/$width);
  1388.     }
  1389.     if ($max_height>0 && $h >$max_height) {
  1390.         $h = $max_height;
  1391.         $w = floor(($h*$width)/$height);
  1392.     }
  1393.     return array($w,$h);
  1394. }
  1395.  
  1396. if (!function_exists('stripslaghes_gpc_arr')) {
  1397.     function stripslaghes_gpc_arr(&$arr) {
  1398.         if (get_magic_quotes_gpc()) {
  1399.             foreach(array_keys($arr) as $k) $arr[$k] = stripslashes($arr[$k]);
  1400.         }
  1401.     }
  1402. }
  1403.  
  1404. /**
  1405.  * Adds compatibility with Recent posts and recent comments, similar posts from Rob Marsh (http://rmarsh.com/)
  1406.  * Just use the tag {caticons} to display the category icon
  1407.  * @author Brahim Machkouri
  1408.  */
  1409.     function otf_caticons($option_key, $result, $ext) {
  1410.         $categories = get_the_category($result->ID);
  1411.         return get_cat_icon('cat='.$categories[0]->term_id.'&echo=0');
  1412.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement