<?php

////////////////////////////////////////////////////////////////////////////////
// Recent Comments
////////////////////////////////////////////////////////////////////////////////
function mw_recent_comments(
	$no_comments = 10,
	$show_pass_post = false,
	$title_length = 100, 	// shortens the title if it is longer than this number of chars
	$author_length = 30,	// shortens the author if it is longer than this number of chars
	$wordwrap_length = 50, // adds a blank if word is longer than this number of chars
	$type = 'all', 	// Comments, trackbacks, or both?
	$format = '<li>%date%: <a href="%permalink%" title="%title%">%title%</a> (von %author_full%)</li>',
	$date_format = 'd.m',
	$none_found = '<li>No Comments.</li>',	// None found
	$type_text_pingback = 'Pingback of',
	$type_text_trackback = 'Trackback of',
	$type_text_comment = 'of'

	) {

	//Language...
	$mwlang_anonymous = 'Anonym'; // Anonymous
	$mwlang_authorurl_title_before = 'Website of &lsaquo;';
	$mwlang_authorurl_title_after = '&rsaquo; visit';


    global $wpdb;

    $request = "SELECT ID, comment_ID, comment_content, comment_author, comment_author_url, comment_date, post_title, comment_type
				FROM $wpdb->comments LEFT JOIN $wpdb->posts ON $wpdb->posts.ID=$wpdb->comments.comment_post_ID
				WHERE post_status IN ('publish','static')";

	switch($type) {
		case 'all':
			// add nothing
			break;
		case 'comment_only':
			//
			$request .= "AND $wpdb->comments.comment_type='' ";
			break;
		case 'trackback_only':
			$request .= "AND ( $wpdb->comments.comment_type='trackback' OR $wpdb->comments.comment_type='pingback' ) ";
			break;
	 default:
 		//
			break;

	}

	if (!$show_pass_post) $request .= "AND post_password ='' ";

	$request .= "AND comment_approved = '1' ORDER BY comment_ID DESC LIMIT $no_comments";

	$comments = $wpdb->get_results($request);
    $output = '';
	if ($comments) {
    	foreach ($comments as $comment) {

			// Permalink to post/comment
			$loop_res['permalink'] = get_permalink($comment->ID). '#comment-' . $comment->comment_ID;

			// Title of the post
			$loop_res['post_title'] = stripslashes($comment->post_title);
			$loop_res['post_title'] = wordwrap($loop_res['post_title'], $wordwrap_length, ' ' , 1);

			if (strlen($loop_res['post_title']) >= $title_length) {
				$loop_res['post_title'] = substr($loop_res['post_title'], 0, $title_length) . '&#8230;';
			}

			// Author's name only
        	$loop_res['author_name'] = stripslashes($comment->comment_author);
			$loop_res['author_name'] = wordwrap($loop_res['author_name'], $wordwrap_length, ' ' , 1);

			if ($loop_res['author_name'] == '') $loop_res['author_name'] = $mwlang_anonymous;
			if (strlen($loop_res['author_name']) >= $author_length) {
				$loop_res['author_name'] = substr($loop_res['author_name'], 0, $author_length) . '&#8230;';
			}

			// Full author (link, name)
			$author_url = $comment->comment_author_url;
			if (empty($author_url)) {
				$loop_res['author_full'] = $loop_res['author_name'];
			} else {
				$loop_res['author_full'] = '<a href="' . $author_url . '" title="' . $mwlang_authorurl_title_before . $loop_res['author_name'] . $mwlang_authorurl_title_after . '">' . $loop_res['author_name'] . '</a>';
			}

/*
			// Comment excerpt
			$comment_excerpt = strip_tags($comment->comment_content);
			$comment_excerpt = stripslashes($comment_excerpt);
			if (strlen($comment_excerpt) >= $comment_length) {
				$comment_excerpt = substr($comment_excerpt, 0, $comment_length) . '...';
			}

*/

			// Comment type
			if ( $comment->comment_type == 'pingback' ) {
				$loop_res['comment_type'] = $type_text_pingback;
			} elseif ( $comment->comment_type == 'trackback' ) {
				$loop_res['comment_type'] = $type_text_trackback;
			} else {
				$loop_res['comment_type'] = $type_text_comment;
			}

			// Date of comment
			$loop_res['comment_date'] = mysql2date($date_format, $comment->comment_date);

			// Output element
			$element_loop = str_replace('%permalink%', $loop_res['permalink'], $format);
			$element_loop = str_replace('%title%', $loop_res['post_title'], $element_loop);
			$element_loop = str_replace('%author_name%', $loop_res['author_name'], $element_loop);
			$element_loop = str_replace('%author_full%', $loop_res['author_full'], $element_loop);
			$element_loop = str_replace('%date%', $loop_res['comment_date'], $element_loop);
			$element_loop = str_replace('%type%', $loop_res['comment_type'], $element_loop);


			$output .= $element_loop . "\n";


		} //foreach

		$output = convert_smilies($output);

	} else {
		$output .= $none_found;
    }

    echo $output;
}

if ( function_exists('register_sidebars') )
    register_sidebars(3, array(
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget' => '</ul></div>',
        'before_title' => '<h2>',
        'after_title' => '</h2><ul>',
    ));

function ac_delicious_script() {
    echo '<script type="text/javascript" src="http://del.icio.us/js/playtagger"></script>';
}
add_action('wp_head', 'ac_delicious_script');

/*     Variables     */
@define('CATEGORYTAGGING_VERSION', '2.4'); // Version
@define('CATEGORYTAGGING_BUILD', 1); // Build version

@define('CATEGORYTAGGING_ROOT', get_bloginfo('url') . '/' . PLUGINDIR . '/category-tagging/'); // Category Tagging directory


/*     Category Cloud Function <cattag_tagcloud>     */
function cattag_tagcloud(
	$min_scale = 10,
	$max_scale = 30,
	$min_include = 0,		// The minimum count to include a tag in the cloud. The default is 0 (include all tags).
	$sort_by = 'NAME_ASC',	// NAME_ASC | NAME_DESC | WEIGHT_ASC | WEIGHT_DESC
	$exclude = '',			// Tags to be excluded
	$include = '',			// Only these tags will be considered if you enter one ore more IDs
	$format = '<li><a rel="tag" href="%link%" title="%description% (%count%)" style="font-size:%size%pt">%title%<sub style="font-size:60%; color:#ccc;">%count%</sub></a></li>',
	$notfound = 'No tags found.'
	) {
	
	##############################################
	# Globals, variables, etc.
	##############################################
	$opt = array();

	$min_scale = (int) $min_scale;
	$max_scale = (int) $max_scale;
	$min_include = (int) $min_include;
	$exclude = preg_replace('/[^0-9,]/', '', $exclude);	// remove everything except 0-9 and comma
	$include = preg_replace('/[^0-9,]/', '', $include);	// remove everything except 0-9 and comma


	##############################################
	# Prepare order
	##############################################
	switch (strtoupper($sort_by)) {
		case 'NAME_DESC':
			$opt['$orderby'] = 'name';
			$opt['$ordertype'] = 'DESC';
	   		break;
		case 'WEIGHT_ASC':
			$opt['$orderby'] = 'count';
			$opt['$ordertype'] = 'ASC';
	   		break;
		case 'WEIGHT_DESC':
			$opt['$orderby'] = 'count';
			$opt['$ordertype'] = 'DESC';
	   		break;
		case 'RANDOM':	// Will be shuffled later 
			$opt['$orderby'] = 'name';
			$opt['$ordertype'] = 'ASC';
	   		break;
		default:	// 'NAME_ASC'
			$opt['$orderby'] = 'name';
			$opt['$ordertype'] = 'ASC';
	}

	##############################################
	# Retrieve categories
	##############################################	
	$catObjectOpt = array('type' => 'post', 'child_of' => 0, 'orderby' => $opt['$orderby'], 'order' => $opt['$ordertype'],
			'hide_empty' => true, 'include_last_update_time' => false, 'hierarchical' => 0, 'exclude' => $exclude, 'include' => $include,
			'number' => '', 'pad_counts' => false);
	$catObject = get_categories($catObjectOpt); // Returns an object of the categories
		
	##############################################
	# Prepare array
	##############################################
	// Convert object into array
	$catArray = cattag_aux_object_to_array($catObject); 

	// Remove tags
	$helper  = array_keys($catArray);	// for being able to unset 
	foreach( $helper as $cat ) { 
		if ( $catArray[$cat]['category_count'] < $min_include ) {
			unset($catArray[$cat]);
		}
	}

	// Exit if no tag found
	if (count($catArray) == 0) {
		return $notfound;
	}

	##############################################
	# Prepare font scaling
	##############################################
	// Get counts for calculating min and max values
	$countsArr = array();
	foreach( $catArray as $cat ) { $countsArr[] = $cat['category_count']; }
	$count_min = min($countsArr);
	$count_max = max($countsArr);
	
	// Calculate
	$spread_current = $count_max - $count_min; 
	$spread_default = $max_scale - $min_scale;
	if ($spread_current <= 0) { $spread_current = 1; };
	if ($spread_default <= 0) { $spread_default = 1; }
	$scale_factor = $spread_default / $spread_current;


	##############################################
	# Loop thru the values and create the result
	##############################################

	// Shuffle... -- thanks to Alex <http://www.artsy.ca/archives/159>
	if ( strtoupper($sort_by) == 'RANDOM') {
		$catArray = cattag_aux_shuffle_assoc($catArray);
	}

	$result = '';
	foreach( $catArray as $cat ) {

		// format
		$element_loop = $format;
		// font scaling		
		$final_font = (int) (($cat['category_count'] - $count_min) * $scale_factor + $min_scale);

		// replace identifiers
		$element_loop = str_replace('%link%', get_category_link($cat['cat_ID']), $element_loop);
		$element_loop = str_replace('%title%', $cat['cat_name'], $element_loop);
		$element_loop = str_replace('%description%', $cat['category_description'], $element_loop);
		$element_loop = str_replace('%count%', $cat['category_count'], $element_loop);
		$element_loop = str_replace('%size%', $final_font, $element_loop);

		// result
		$result .= $element_loop . "\n";	
	}

	$result = "\n" . '<!-- Tag Cloud, generated by \'Category Tagging\' plugin - http://blog.bull3t.me.uk/ -->' . "\n" . $result; // Please do not remove this line.
	return $result;

}


/*     Related Posts Function <cattag_related_posts>     */
function cattag_related_posts(
	$order = 'RANDOM',
	$limit = 5,
	$exclude = '',
	$display_posts = true,
	$display_pages = false,	
	$format = '<li>%date%: <a href="%permalink%" title="%title%">%title%</a> (%commentcount%)</li>',
	$dateformat = 'd.m.y',
	$notfound = '<li>No related posts found.</li>',
	$limit_days = 365
	) {

	##############################################
	# Globals, variables, etc.
	##############################################
	global $wpdb, $post, $wp_version;
	
	$limit = (int) $limit;
	$exclude = preg_replace('/[^0-9,]/','',$exclude);	// remove everything except 0-9 and comma


	##############################################
	# Prepare selection of posts and pages
	##############################################
	if ( ($display_posts === true) AND ($display_pages === true) ) {
		// Display both posts and pages
		$poststatus = "IN('publish', 'static')";
	} elseif ( ($display_posts === true) AND ($display_pages === false) ) {
		// Display posts only
		$poststatus = "= 'publish'";
	} elseif ( ($display_posts === false) AND ($display_pages === true) ) {
		// Display pages only
		$poststatus = "= 'static'";
	} else {
		// Nothing can be displayed
		return $notfound;
	}

	##############################################
	# Prepare exlusion of categories
	##############################################	
	$exclude_ids_sql = ($exclude == '') ? '' : 'AND post2cat.category_id NOT IN(' . $exclude . ')';


	##############################################
	# Put the category IDs into a comma-separated string
	##############################################
	$catsList = '';
	$count = 0;
	foreach((get_the_category()) as $loop_cat) { 
		// Add category id to list
		$catsList .= ( $catsList == '' ) ? $loop_cat->cat_ID : ',' . $loop_cat->cat_ID;
	}

	##############################################
	# Prepare order
	##############################################
	switch (strtoupper($order)) {
		case 'RANDOM':
			$order_by = 'RAND()';
			break;
		default:	// 'DATE_DESC'
			$order_by = 'posts.post_date DESC';
	}


	##############################################
	# Set limit of posting date. 86400 seconds = 1 day
	##############################################
	$timelimit = '';
	if ($limit_days != 0) $timelimit = 'AND posts.post_date > ' . date('YmdHis', time() - $limit_days*86400);


	##############################################
 	# SQL query. DISTINCT is here for getting a unique result without duplicates
	##############################################
	// since we support >= WP 2.1 only, stuff like AND posts.post_date < '" . current_time('mysql') . "'
	// is not necessary as future posts now gain the post_status of 'future' 
	
	if ($wp_version < "2.3") {
		// check wp version - if lower than 2.3 use old database format of 'categories' and 'post2cat'
		$queryresult = $wpdb->get_results("SELECT DISTINCT posts.ID, posts.post_title, posts.post_date, posts.comment_count
								FROM $wpdb->posts posts, $wpdb->post2cat post2cat
								WHERE posts.ID <> $post->ID
								AND posts.post_status $poststatus
								AND posts.ID = post2cat.post_id
								AND post2cat.category_id IN($catsList)
								$timelimit
								$exclude_ids_sql
								ORDER BY $order_by 
								LIMIT $limit
								");
	} else {
		// check wp version - if higher than 2.3 change to new database format of 'terms'
		$queryresult = $wpdb->get_results("SELECT DISTINCT posts.ID, posts.post_title, posts.post_date, posts.comment_count
								FROM $wpdb->posts posts, $wpdb->term_relationships term_relationships, $wpdb->term_taxonomy term_taxonomy
								WHERE posts.ID <> $post->ID
								AND posts.post_status $poststatus
								AND posts.ID = term_relationships.object_id
								AND term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
								AND term_taxonomy.term_id IN($catsList)
								$timelimit
								$exclude_ids_sql
								ORDER BY $order_by 
								LIMIT $limit
								");
	}

	##############################################
	// Return the related posts
	##############################################
	$result = '';
	if (count($queryresult) > 0) {
		foreach($queryresult as $tag_loop) {
			// Date of post
			$loop_postdate = mysql2date($dateformat, $tag_loop->post_date);
			// Get format
			$element_loop = $format;
			// Replace identifiers
			$element_loop = str_replace('%date%', $loop_postdate, $element_loop);
			$element_loop = str_replace('%permalink%', get_permalink($tag_loop->ID), $element_loop);
			$element_loop = str_replace('%title%', $tag_loop->post_title, $element_loop);
			$element_loop = str_replace('%commentcount%', $tag_loop->comment_count, $element_loop);
			// Add to list
			$result .= $element_loop . "\n";
		}
		$result = "\n" . '<!-- Related Posts, generated by \'Category Tagging\' plugin - http://blog.bull3t.me.uk/ -->' . "\n" . $result; // Please do not remove this line.
		return $result;
	} else {
		return $notfound;
	}

}


################################################################################
# Additional functions
################################################################################
function cattag_aux_object_to_array($obj) {
	// dumps all the object properties and its associations recursively into an array
	// Source: http://de3.php.net/manual/de/function.get-object-vars.php#62470
       $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
       foreach ($_arr as $key => $val) {
               $val = (is_array($val) || is_object($val)) ? cattag_aux_object_to_array($val) : $val;
               $arr[$key] = $val;
       }
       return $arr;
}

function cattag_aux_shuffle_assoc($input_array) {
	   if(!is_array($input_array) or !count($input_array))
	       return null;
	   $randomized_keys = array_rand($input_array, count($input_array));
	   $output_array = array();
	   foreach($randomized_keys as $current_key) {
	       $output_array[$current_key] = $input_array[$current_key];
	       unset($input_array[$current_key]);
	   }
	   return $output_array;
}