<?php
// ===== Localization =================================================
load_theme_textdomain('r755', get_template_directory() . '/lang');


// ===== Local Dates ==================================================
function local_date_replace($text) {
	$days_english = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday',
	'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 
	'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 
	'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 
	'1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '0th');
	
	$days_local = array(__('Monday', 'r755'), __('Tuesday', 'r755'), __('Wednesday', 'r755'), __('Thursday', 'r755'), __('Friday', 'r755'), __('Saturday', 'r755'), __('Sunday', 'r755'), 
	__('Mon', 'r755'), __('Tue', 'r755'), __('Wed', 'r755'), __('Thu', 'r755'), __('Fri', 'r755'), __('Sat', 'r755'), __('Sun', 'r755'), 
	__('January', 'r755'), __('February', 'r755'), __('March', 'r755'), __('April', 'r755'), __('May', 'r755'), __('June', 'r755'), __('July', 'r755'), __('August', 'r755'), __('September', 'r755'), __('October', 'r755'), __('November', 'r755'), __('December', 'r755'), 
	__('Jan', 'r755'), __('Feb', 'r755'), __('Mar', 'r755'), __('Apr', 'r755'), __('May', 'r755'), __('Jun', 'r755'), __('Jul', 'r755'), __('Aug', 'r755'), __('Sep', 'r755'), __('Oct', 'r755'), __('Nov', 'r755'), __('Dec', 'r755'),
	__('1st', 'r755'), __('2nd', 'r755'), __('3rd', 'r755'), __('4th', 'r755'), __('5th', 'r755'), __('6th', 'r755'), __('7th', 'r755'), __('8th', 'r755'), __('9th', 'r755'), __('0th', 'r755'));
	$text = str_replace($days_english, $days_local, $text);
	return $text;
}

add_filter('the_time', 'local_date_replace');
add_filter('get_the_time', 'local_date_replace');
add_filter('the_modified_time', 'local_date_replace');
add_filter('the_date', 'local_date_replace');
add_filter('the_modified_date', 'local_date_replace');
add_filter('get_comment_date','local_date_replace');
add_filter('wp_title','local_date_replace');


// ===== Theme Options ================================================
$themename = "R755";
$shortname = "r755";
$options = array (
			array(	"name" => "About",
				"type" => "subhead"),
			array(	"name" => "About sidebar text state",
            	"desc" => "Enable or disable the about text in the sidebar.",
				"id" => $shortname."_about_state",
				"std" => "Enabled",
				"type" => "select",
				"options" => array("Enabled","Disabled")),
			array(  "name" => "About",
        		"type" => "title"),
			array(	"type" => "open"),
			array(	"name" => "Title",
        		"desc" => "Enter a title to be displayed in your sidebar about text.  Default currently set to 'About'",
        		"id" => $shortname."_about_title",
        		"std" => "",
        		"type" => "text"),
			array(	"name" => "Image URL",
        		"desc" => "Provide the full path to a 80x80 image of yourself.  Leave blank if you don't have one.",
        		"id" => $shortname."_image_url",
        		"std" => "",
        		"type" => "text"),
			array(	"name" => "Message",
        		"desc" => "Input the content of about text.  Tell us about yourself and your blog.",
        		"id" => $shortname."_about_message",
        		"type" => "textarea",
				"options" => array("rows" => "5",
									"cols" => "30")),					
			array(	"name" => "About URL",
        		"desc" => "Provide the full path to a more detailed about page.  Leave blank if you don't have one.",
        		"id" => $shortname."_about_url",
        		"std" => "",
        		"type" => "text"),
			array(	"name" => "Navigation",
				"type" => "subhead"),
			array(  "name" => "Exclude pages from sidebar navigation",
				"id" => $shortname."_pages_to_exclude",
              	"desc" => "Page ID's you don't want displayed in your navigation. Use a comma-delimited list, eg. 1,2,3",
              	"std" => "",
              	"type" => "text"),
        	array(	"name" => "Sidebar Feed Box",
              	"type" => "subhead"),
        	array(	"name" => "Feed box state",
            	"desc" => "Enable or disable the feed box in the sidebar.",
				"id" => $shortname."_feed_state",
				"std" => "Enabled",
				"type" => "select",
				"options" => array("Enabled","Disabled")),
        	array(	"name" => "Feed box title text",
				"id" => $shortname."_feed_title",
              	"desc" => "Title of your feed box.",
				"std" => "Feeds",
				"type" => "text"),
        	array(	"name" => "Feed box intro text",
				"id" => $shortname."_feed_intro",
				"desc" => "Enter your feed intro text here.",
				"std" => "Get updates delivered to your reader or your inbox:",
				"type" => "textarea",
				"options" => array("rows" => "5",
									"cols" => "30") ),
        	array(	"name" => "<a href=\"http://www.feedburner.com\">Feedburner</a> email updates link",
				"id" => $shortname."_feed_email",
				"desc" => "Enter your feed email link here. <strong>Do not paste the entire link code, just the URL.</strong><br /><del>&#60;a href=&#34;</del> <code>http://www.feedburner.com/fb/a/emailverifySubmit?feedId=000000&amp;loc=en_US</code> <del>&#34;&#62;Subscribe to Your Feed by Email&#60;/a&#62;</del>",
				"std" => "http://www.feedburner.com/fb/a/emailverifySubmit?feedId=YOURFEEDID&loc=en_US",
				"type" => "textarea",
				"options" => array("rows" => "2",
									"cols" => "30") ),
			array(	"name" => "Header",
				"type" => "subhead"),
			array(	"name" => "Header code",
				"id" => $shortname."_header_code",
				"desc" => "If you use Javascript or need any other code in your header just copy and paste it here.<br /> It will be inserted before the closing <code>&#60;/header&#62;</code> tag.",
				"std" => "",
				"type" => "textarea",
				"options" => array("rows" => "5",
									"cols" => "30") ),	
			array(	"name" => "Social Bookmarks",
				"type" => "subhead"),
			array(	"name" => "Social bookmarks code",
				"id" => $shortname."_social_code",
				"desc" => "If you want to add any social bookmarking code right after your posts just copy and paste it here.",
				"std" => "",
				"type" => "textarea",
				"options" => array("rows" => "5",
									"cols" => "30") ),	
			array(	"name" => "Footer",
				"type" => "subhead"),
			array(	"name" => "Copyright notice",
				"id" => $shortname."_copyright_name",
              	"desc" => "Enter your copyright info above.",
				"std" => "Your Name Here",
				"type" => "text"),			
			array(	"name" => "Stats code",
				"id" => $shortname."_stats_code",
				"desc" => "If you use Google Analytics or any other tracking script in your footer just copy and paste it here.<br /> The script will be inserted before the closing <code>&#60;/body&#62;</code> tag.",
				"std" => "",
				"type" => "textarea",
				"options" => array("rows" => "5",
									"cols" => "30") ),
		  );
function mytheme_add_admin() {
    global $themename, $shortname, $options;
    if ( $_GET['page'] == basename(__FILE__) ) {
        if ( 'save' == $_REQUEST['action'] ) {
                foreach ($options as $value) {
                    update_option( $value['id'], $_REQUEST[ $value['id'] ] ); }
                foreach ($options as $value) {
                    if( isset( $_REQUEST[ $value['id'] ] ) ) { update_option( $value['id'], $_REQUEST[ $value['id'] ]  ); } else { delete_option( $value['id'] ); } }
                header("Location: themes.php?page=functions.php&saved=true");
                die;
        } else if( 'reset' == $_REQUEST['action'] ) {
            foreach ($options as $value) {
                delete_option( $value['id'] ); }
            header("Location: themes.php?page=functions.php&saved=true");
            die;
        }
    }
    add_theme_page($themename." Options", "$themename Options", 'edit_themes', basename(__FILE__), 'mytheme_admin');
}
//add_theme_page($themename . 'Header Options', 'Header Options', 'edit_themes', basename(__FILE__), 'headimage_admin');
function headimage_admin(){
}
function mytheme_admin() {
    global $themename, $shortname, $options;
    if ( $_REQUEST['saved'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings saved.</strong></p></div>';
    if ( $_REQUEST['reset'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings reset.</strong></p></div>'; 
?>
<div class="wrap">
<h2 class="updatehook" style=" padding-top: 20px; font-size: 2.8em;"><?php echo $themename; ?> Options</h2>
<p style="line-height: 1.6em; font-size: 1.2em; width: 75%;">Welcome to the R755 Options menu. If you have any questions add a comment to the <a href="http://www.varometro.net/blog/r755_theme/">R755 theme page</a>.</p>
<form method="post">
  <table class="form-table">
    <?php foreach ($options as $value) {
	switch ( $value['type'] ) {
		case 'subhead':
		?>
  </table>
  <h3><?php echo $value['name']; ?></h3>
  <table class="form-table">
    <?php
		break;
		case 'text':
		option_wrapper_header($value);
		?>
    <input name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" value="<?php if ( get_settings( $value['id'] ) != "") { echo get_settings( $value['id'] ); } else { echo $value['std']; } ?>" />
    <?php
		option_wrapper_footer($value);
		break;
		
		case 'select':
		option_wrapper_header($value);
		?>
    <select name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>">
      <?php foreach ($value['options'] as $option) { ?>
      <option <?php if ( get_settings( $value['id'] ) == $option) { echo ' selected="selected"'; } elseif ($option == $value['std']) { echo ' selected="selected"'; } ?>><?php echo $option; ?></option>
      <?php } ?>
    </select>
    <?php
		option_wrapper_footer($value);
		break;
		case 'textarea':
		$ta_options = $value['options'];
		option_wrapper_header($value);
		?>
    <textarea name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" cols="<?php echo $ta_options['cols']; ?>" rows="<?php echo $ta_options['rows']; ?>"><?php 
				if( get_settings($value['id']) != "") {
						echo stripslashes(get_settings($value['id']));
					}else{
						echo stripslashes($value['std']);
				}?>
</textarea>
    <?php
		option_wrapper_footer($value);
		break;
		case "radio":
		option_wrapper_header($value);
 		foreach ($value['options'] as $key=>$option) { 
				$radio_setting = get_settings($value['id']);
				if($radio_setting != ''){
		    		if ($key == get_settings($value['id']) ) {
						$checked = "checked=\"checked\"";
						} else {
							$checked = "";
						}
				}else{
					if($key == $value['std']){
						$checked = "checked=\"checked\"";
					}else{
						$checked = "";
					}
				}?>
    <input type="radio" name="<?php echo $value['id']; ?>" value="<?php echo $key; ?>" <?php echo $checked; ?> />
    <?php echo $option; ?><br />
    <?php 
		}
		option_wrapper_footer($value);
		break;
		case "checkbox":
		option_wrapper_header($value);
						if(get_settings($value['id'])){
							$checked = "checked=\"checked\"";
						}else{
							$checked = "";
						}
					?>
    <input type="checkbox" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" value="true" <?php echo $checked; ?> />
    <?php
		option_wrapper_footer($value);
		break;
		default:
		break;
	}
}
?>
  </table>
  <p class="submit">
    <input name="save" type="submit" value="Save changes" />
    <input type="hidden" name="action" value="save" />
  </p>
</form>
<form method="post">
  <p class="submit">
    <input name="reset" type="submit" value="Reset" />
    <input type="hidden" name="action" value="reset" />
  </p>
</form>
<?php
}
function option_wrapper_header($values){
	?>
<tr valign="top">
  <th scope="row"><?php echo $values['name']; ?>:</th>
  <td><?php
}
function option_wrapper_footer($values){
	?>
    <br />
    <br />
    <?php echo $values['desc']; ?> </td>
</tr>
<?php 
}
add_action('admin_menu', 'mytheme_add_admin');


// ===== Ping/Track/Comment Count =====================================
function get_comment_type_count($type='all', $post_id = 0) {
    global $cjd_comment_count_cache, $id, $post;
    if ( !$post_id )
        $post_id = $post->ID;
    if ( !$post_id )
        return;

    if ( !isset($cjd_comment_count_cache[$post_id]) ) {
        $p = get_post($post_id);
        $p = array($p);
        update_comment_type_cache($p);
    }

    if ( $type == 'pingback' || $type == 'trackback' || $type == 'comment' )
        return $cjd_comment_count_cache[$post_id][$type];
    elseif ( $type == 'ping' )
        return $cjd_comment_count_cache[$post_id]['pingback'] + $cjd_comment_count_cache[$post_id]['trackback'];
    else
        return array_sum((array) $cjd_comment_count_cache[$post_id]);

}

function comment_type_count($type = 'all', $post_id = 0) {
        echo get_comment_type_count($type, $post_id);
}


function update_comment_type_cache(&$queried_posts) {
    global $cjd_comment_count_cache, $wpdb;

    if ( !$queried_posts )
        return $queried_posts;


    foreach ( (array) $queried_posts as $post )
        if ( !isset($cjd_comment_count_cache[$post->ID]) )
            $post_id_list[] = $post->ID;

    if ( $post_id_list ) {
        $post_id_list = implode(',', $post_id_list);

        foreach ( array('', 'pingback', 'trackback') as $type ) {
            $counts = $wpdb->get_results("SELECT ID, COUNT( comment_ID ) AS ccount
            FROM $wpdb->posts
            LEFT JOIN $wpdb->comments ON ( comment_post_ID = ID AND comment_approved = '1' AND comment_type='$type' )
            WHERE post_status = 'publish' AND ID IN ($post_id_list)
            GROUP BY ID");

            if ( $counts ) {
                if ( '' == $type )
                    $type = 'comment';
                foreach ( $counts as $count )
                    $cjd_comment_count_cache[$count->ID][$type] = $count->ccount;
            }
        }
    }
    return $queried_posts;
}

add_filter('the_posts', 'update_comment_type_cache'); 


// ===== Widgets ======================================================
if ( function_exists('register_sidebar') )
    register_sidebar(array(
        'before_widget' => '<ul><li>',
        'after_widget' => '</li></ul>',
        'before_title' => '<h3>',
        'after_title' => '</h3>',
	));


// ===== Code Markup ==================================================
add_filter('the_content', 'tguy_cmu_encode_xml', '1');
add_filter('the_content', 'tguy_cmu_tidy_code', '11');
function tguy_cmu_encode_xml($content) {
global $wp_version;
// $content = preg_replace('%(?<!<pre[^>]*>[^>]*)(<code[^>]*>.*?</code>)%ims', '<pre class="code-markup">\n$1\n</pre>', $content);
if ($wp_version < '2.3') {
$content = preg_replace_callback('!<pre([^>]*)>(.*?)</pre>!ims', 'tguy_cmu_escape_backslash_callback', $content);
}
$content = preg_replace_callback('!<code([^>]*)>(?:\r\n|\n|\r|)(.*?)(?:\r\n|\n|\r|)</code>!ims', 'tguy_cmu_encode_xml_callback', $content);
	return $content;
}
function tguy_cmu_tidy_code($content) {
$content = preg_replace_callback('!<pre([^>]*)>(.*?)</pre>!ims', 'tguy_cmu_unescape_qq_callback', $content);
$content = preg_replace_callback('!<code([^>]*)>(.*?)</code>!ims', 'tguy_cmu_untexturize_code_callback', $content);
	return $content;
}
function tguy_cmu_encode_xml_callback($matches) {
$attributes = $matches[1];
$escapedContent = $matches[2];
$attrMatches = array();
$markup = 'default';
if (0 < preg_match('!^(.*?)\s+(?:markup|allow)="([^"]*)"(.*)$!i', $attributes, $attrMatches)) {
$markup = strtolower($attrMatches[2]);
$attributes = $attrMatches[1] . $attrMatches[3];
}
if ($markup == 'default') {
if (0 < preg_match('!^(.*)lang="([^"]*)"(.*)$!i', $attributes, $attrMatches)) {
$lang = strtolower($attrMatches[2]);
$attributes = $attrMatches[1] . $attrMatches[3];
if ($lang == 'html' || $lang == 'xhtml') {
$markup = 'none';
			}
		}
	}
if ($markup == 'all') {
} else {
if ($markup == 'none' || $markup == '') {
$allowedTags = '';
} else if ($markup == 'default' || $markup == 'tags') { // 'tags' allowed for backward compatibility
$allowedTags = 'em|strong|b|i|ins|del|a|span|comment';
} else {
$allowedTags = preg_replace('!\s+!', '|', trim($markup));
}
$escapedContent = htmlspecialchars($escapedContent, ENT_NOQUOTES);
if ($allowedTags != '') {
$escapedContent = preg_replace_callback('!&lt;/?('.$allowedTags.')( .*?)?&gt;!is',
'tguy_cmu_unescape_tag', $escapedContent);
if (false !== strpos($allowedTags, 'comment')) {
$escapedContent = preg_replace_callback('|&lt;!--.*?--&gt;|is',
'tguy_cmu_unescape_tag', $escapedContent);
			}
		}
	}
return "<code$attributes>$escapedContent</code>";
}
function tguy_cmu_unescape_tag($matches) {
return str_replace(
array("&gt;", "&lt;", "&quot;", "&amp;"),
array(">", "<", "\"", "&"),
$matches[0]);
}
function tguy_cmu_escape_backslash_callback($matches) {
return "<pre{$matches[1]}>".str_replace('\\', '\\\\', $matches[2])."</pre>";
}
function tguy_cmu_unescape_qq_callback($matches) {
return "<pre{$matches[1]}>".str_replace('\"', '"', $matches[2])."</pre>";
}
function tguy_cmu_untexturize_code_callback($matches) {
$fancy = array('&#215;', '&#8216;', '&#8217;', '&#8242;', '&#8220;', '&#8221;', '&#8243;', '&#8212;', '&#8211;', '&#8230;', '&#8220;');
$plain = array('x'     ,'\''     , '\''     , '\''     , '"'      , '"'      , '"'      , '--'     , '--'     , '...'    , '``'     );
return "<code{$matches[1]}>".str_replace($fancy, $plain, $matches[2])."</code>";
}


// ===== Add Meta Noindex Rules on Singular Comment Page Section ======
function wpi_comment_paging_noindex_meta()
{	global $wp_query;
if (version_compare( (float) get_bloginfo('version'), 2.7, '>=') ){
if ($wp_query->is_singular && get_option('page_comments')){ // comments paging enabled
if (isset($wp_query->query['cpage'])
&& absint($wp_query->query['cpage']) >= 1 ){
echo '<meta name="robots" content="noindex" />'.PHP_EOL;
			}
		}
	}
}
add_action('wp_head','wpi_comment_paging_noindex_meta');	


// ===== Add a Microid to all Comments ================================
function comment_add_microid($classes) {
	$c_email=get_comment_author_email();
	$c_url=get_comment_author_url();
	if (!empty($c_email) && !empty($c_url)) {
		$microid = 'microid-mailto+http:sha1:' . sha1(sha1('mailto:'.$c_email).sha1($c_url));
		$classes[] = $microid;
	}
	return $classes;
}
add_filter('comment_class','comment_add_microid');


// ===== Seperate Pings ===============================================
function list_pings($comment, $args, $depth) {
       $GLOBALS['comment'] = $comment;
?>
<li id="comment-<?php comment_ID(); ?>">
  <?php comment_author_link(); ?>
  <?php }


// ===== Correct Comment Count ========================================
add_filter('get_comments_number', 'comment_count', 0);
function comment_count( $count ) {
        if ( ! is_admin() ) {
                global $id;
                $comments_by_type = &separate_comments(get_comments('status=approve&post_id=' . $id));
                return count($comments_by_type['comment']);
        } else {
                return $count;
        }
}


// ===== Comments Loop ===============================================
function mytheme_comment($comment, $args, $depth) {
   $GLOBALS['comment'] = $comment; ?>
<li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
  <div id="comment-<?php comment_ID(); ?>">
    <div class="comment-author vcard"> <?php echo get_avatar($comment,$size='32',$default='<path_to_url>' ); ?> <?php printf(__('<cite class="fn">%s</cite> <span class="says">says:</span>', 'r755'), get_comment_author_link()) ?> </div>
    <?php if ($comment->comment_approved == '0') : ?>
    <em>
    <?php _e('Your comment is awaiting moderation.', 'r755') ?>
    </em> <br />
    <?php endif; ?>
    <div class="comment-meta commentmetadata"><a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ) ?>"><?php printf(__('%1$s at %2$s', 'r755'), get_comment_date('d.m.y'),  get_comment_time('H:i')) ?></a>
      <?php edit_comment_link(__('Edit','r755'), '[ ', ' ]'); ?>
    </div>
    <?php comment_text() ?>
    <div class="reply">  
	  <?php comment_reply_link(array_merge( $args, array('reply_text' => __('Reply', 'r755'), 'depth' => $depth, 'max_depth' => $args['max_depth']))); ?>
    </div>
  </div>
  <?php
        }
?>