<?php
//页码函数
function pagenavi() {
    global $wp_query, $wp_rewrite;
    $wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;
    $pagination = array(
        'base' => @add_query_arg('paged','%#%'),
        'format' => '',
        'total' => $wp_query->max_num_pages,
        'current' => $current,
        'show_all' => false,
		'end_size'=>'1',   
        'mid_size'=>'10',
        'type' => 'plain',
        'prev_next' => false
    );
    if( $wp_rewrite->using_permalinks() )
        $pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg('s',get_pagenum_link(1) ) ) . 'page/%#%/', 'paged');
    if( !empty($wp_query->query_vars['s']) )
        $pagination['add_args'] = array('s'=>get_query_var('s'));
	previous_posts_link('上一页','');
    echo paginate_links($pagination);
	next_posts_link('下一页','');
	if( $pagination['total']>1 ){
	}
}

//获取缩略图
function get_post_img( $id = null,$width="150",$height="100") {
	if( $id ){
		$post = get_post($id);
		$post_id = $id;
	}else{
		global $post;
		$post_id = $post->ID;
	}
	
	if(get_post_meta($post_id,'_post_pic',true)&&(get_post_meta($post_id,'_post_pic',true)!='')){
		return get_post_meta($post_id,'_post_pic',true);
	}else{
		$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
	
		if( !empty( $matches[1][0] ) ){
			return $matches[1][0];
		}else{
			return '';
		}
	}
}

//计算字符
if ( !function_exists('mb_strlen') ) {
	function mb_strlen ($text, $encode) {
		if ($encode=='UTF-8') {
			return preg_match_all('%(?:
					  [\x09\x0A\x0D\x20-\x7E]           # ASCII
					| [\xC2-\xDF][\x80-\xBF]            # non-overlong 2-byte
					|  \xE0[\xA0-\xBF][\x80-\xBF]       # excluding overlongs
					| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
					|  \xED[\x80-\x9F][\x80-\xBF]       # excluding surrogates
					|  \xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
					| [\xF1-\xF3][\x80-\xBF]{3}         # planes 4-15
					|  \xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
					)%xs',$text,$out);
		}else{
			return strlen($text);
		}
	}
}

/*截取字符串函数*/
if (!function_exists('mb_substr')) {
    function mb_substr($str, $start, $len = '', $encoding="UTF-8"){
        $limit = strlen($str);
        for ($s = 0; $start > 0;--$start) {// found the real start
            if ($s >= $limit)
                break;
            if ($str[$s] <= "\x7F")
                ++$s;
            else {
                ++$s; // skip length
                while ($str[$s] >= "\x80" && $str[$s] <= "\xBF")
                    ++$s;
            }
        }
       if ($len == '')
            return substr($str, $s);
        else
            for ($e = $s; $len > 0; --$len) {//found the real end
                if ($e >= $limit)
                    break;
                if ($str[$e] <= "\x7F")
                    ++$e;
                else {
                    ++$e;//skip length
                    while ($str[$e] >= "\x80" && $str[$e] <= "\xBF" && $e < $limit)
                        ++$e;
                }
            }
        return substr($str, $s, $e - $s);
    }
}

//获取浏览数
function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0";
    }
    return $count;
}
//设置浏览数
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}


function addhttp($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

function is_valid_int( $int ) {
    $int = isset( $int ) ? intval( $int ) : 0;
    return $int;
}
/**********编辑文章的连接*****************/
function user_edit_post_link( $url, $post_id ) {
    if ( is_admin() ) {
        return $url;
    }

    $override = wpuf_get_option( 'override_editlink', 'yes' );
    if ( $override == 'yes' ) {
        $url = '';
        if ( wpuf_get_option( 'enable_post_edit' ) == 'yes' ) {
            $edit_page = (int) wpuf_get_option( 'edit_page_id' );
            $url = get_permalink( $edit_page );

            $url = wp_nonce_url( $url . '?pid=' . $post_id, 'wpuf_edit' );
        }
    }

    return $url;
}

//add_filter( 'get_edit_post_link', 'user_edit_post_link', 10, 2 );


/******格式化错误*********/
function user_error_msg( $error_msg ) {
    $msg_string = '';
    foreach ($error_msg as $value) {
        if ( !empty( $value ) ) {
            $msg_string = $msg_string . '<div class="error">' . $msg_string = $value . '</div>';
        }
    }
    return $msg_string;
}
/*********整理标签**********/
function user_clean_tags( $string ) {
    $string = preg_replace( '/\s*,\s*/', ',', rtrim( trim( $string ), ' ,' ) );
    return $string;
}
/**************邮件通知管理员有来稿**************/
function user_notify_post_mail( $user, $post_id ) {
    $blogname = get_bloginfo( 'name' );
    $to = get_bloginfo( 'admin_email' );
    $permalink = get_permalink( $post_id );

    $headers = sprintf( "来自: %s <%s>\r\n", $blogname, $to );
    $subject = sprintf( '[%s] 有新投稿', $blogname );

    $msg = sprintf( '%s 上有人提交了新文章', $blogname ) . "\r\n\r\n";
    $msg .= sprintf( '作者 : %s', $user->display_name ) . "\r\n";
    $msg .= sprintf( '作者Email : %s', $user->user_email ) . "\r\n";
    $msg .= sprintf( '标题: %s', get_the_title( $post_id ) ) . "\r\n";
    $msg .= sprintf( '文章地址 : %s', $permalink ) . "\r\n";
    $msg .= sprintf( '编辑链接 : %s', admin_url( 'post.php?action=edit&post=' . $post_id ) ) . "\r\n";
	
    wp_mail( $to, $subject, $msg, $headers );
}


function user_get_avatar($uid, $w = 25, $h = 25){
	$av = get_user_meta($uid, 'avatar', true);
	if ($av) {
		return $av;
	}else{
		return bloginfo('template_directory').'/images/default-user.jpg';
	}
}

function ashu_wp_comment( $comment, $args, $depth ) {
	$GLOBALS['comment'] = $comment;
	switch ( $comment->comment_type ) :
		case '' :
	?>
	<div class="perComment"  id="li-comment-<?php comment_ID(); ?>">
		<div class="avatarImgBox">
			<?php
			if($comment->user_id){
				$user_info = get_userdata($comment->user_id);
			?>
				<a href="<?php  echo site_url().'/user-profile/'.$user_info->user_login; ?>">
				<?php echo get_avatar( $comment->user_id, 40 ); ?>
				</a>
			<?php }else{
				echo get_avatar( $comment, 40,'',$comment->comment_author );
			}
			?>
		</div>
		<div class="commentRight">
				<div class="commentName"><?php echo get_comment_author_link(); ?></div>
				<div class="commentTime"><?php	printf('%1$s %2$s', get_comment_date('m.d'),  get_comment_time('g:i') ); ?>&nbsp;<?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?></div>
				<div class="clear"></div>
				<div class="nrBox"><?php comment_text(); ?></div>
		</div>
		<div class="clear"></div>
		<div class="line"></div>
	<?php
			break;
		case 'pingback'  :
		case 'trackback' :
			break;
	endswitch;
}


/*********用户评论******/
function user_comments_list( $comment, $args, $depth ){
	$GLOBALS['comment'] = $comment;
	switch ( $comment->comment_type ) :
		case '' :
	?>
	<li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">
		<a href="<?php echo get_permalink($comment->comment_post_ID);?>">
		<?php comment_text(); ?>
		</a>
	<?php
			break;
		case 'pingback'  :
		case 'trackback' :
			break;
	endswitch;
}
/*********获取用户************/
function wpuf_list_users() {
    if ( function_exists( 'get_users' ) ) {
        $users = get_users();
    } else {
        ////wp 3.1 fallback
        $users = get_users_of_blog();
    }

    $list = array();

    if ( $users ) {
        foreach ($users as $user) {
            $list[$user->ID] = $user->display_name;
        }
    }

    return $list;
}

/**********用户菜单**************/
function user_get_users_links(){
	global $wpdb,$wp_rewrite,$wp_query,$current_user;
	get_currentuserinfo();
	if( isset($wp_query->query_vars['my_second_page']) && $wp_query->query_vars['my_second_page'] !='' )
		$current_page = $wp_query->query_vars['my_second_page'];
	else $current_page = 'home';
	?>
	<div class="page-info">
	<div class="main-container">
	<div id="breadcrumbs">
		<?php //dimox_breadcrumbs(); ?>
	</div>
	</div>
	<div class="uc_tabs">
	<ul>
		<li <?php	if($current_page == 'home') echo "class='active'"; ?>>
			<a href="<?php echo smzdm_my_account_link(); ?>">个人信息</a>
		</li>    
		<li <?php	if($current_page == 'my-settings') echo "class='active'"; ?>>
			<a href="<?php echo smzdm_my_account_link(); ?>/my-settings/">编辑资料</a>
		</li>
		<li <?php	if($current_page == 'my-posts') {echo "class='active'";}?>>
			<a href="<?php echo smzdm_my_account_link(); ?>/my-posts/">已发布文章</a>
		</li>
		<li <?php	if($current_page == 'my-comments') {echo "class='active'";}?>>
			<a href="<?php echo smzdm_my_account_link(); ?>/my-comments/">我的评论</a>
		</li>
		<li <?php	if($current_page == 'my-collects') {echo "class='active'";}?>>
			<a href="<?php echo smzdm_my_account_link(); ?>/my-collects/">我的收藏</a>
		</li>
		<li <?php	if($current_page == 'post-new') {echo "class='active last'";} else {echo "class='last'";} ?>>
			<a href="<?php echo site_url() ?>/post-new">发表新文章</a>
			<div class="last"></div>
		</li>
	</ul>
	</div>
	</div>
	<div class='clear'></div>
<?php 
}
/***********页码函数********/
function emm_paginate($args = null) {
	          $defaults = array(
		        'page' => null, 'pages' => null, 
		        'range' => 2, 'gap' => 1, 'anchor' => 1,
		        'before' => '<div class="emm-paginate">', 'after' => '</div>',
		        'title' => __(''),
		        'nextpage' => __('&raquo;'), 'previouspage' => __('&laquo'),
	          'echo' => 1
);
$r = wp_parse_args($args, $defaults);
	          extract($r, EXTR_SKIP);
	          if (!$page && !$pages) {
		        global $wp_query;
		        $page = get_query_var('paged');
		        $page = !empty($page) ? intval($page) : 1;
		        $posts_per_page = intval(get_query_var('posts_per_page'));
		        $pages = intval(ceil($wp_query->found_posts / $posts_per_page));
}
$output = "";
	          if ($pages > 1) {	
		        $output .= "$before<span class='emm-title'>$title</span>";
		        $ellipsis = "<span class='emm-gap'></span>";
		        if ($page > 1 && !empty($previouspage)) {
		    	  $output .= "<a href='" . get_pagenum_link($page - 1) . "' class='emm-prev'>$previouspage</a>";
}
            $min_links = $range * 2 + 1;
		        $block_min = min($page - $range, $pages - $min_links);
		        $block_high = max($page + $range, $min_links);
		        $left_gap = (($block_min - $anchor - $gap) > 0) ? true : false;
		        $right_gap = (($block_high + $anchor + $gap) < $pages) ? true : false;
if ($left_gap && !$right_gap) {
			      $output .= sprintf('%s%s%s', 
			    	emm_paginate_loop(1, $anchor), 
			    	$ellipsis, 
				    emm_paginate_loop($block_min, $pages, $page)
);
}
else if ($left_gap && $right_gap) {
			     $output .= sprintf('%s%s%s%s%s', 
				   emm_paginate_loop(1, $anchor), 
				   $ellipsis, 
				   emm_paginate_loop($block_min, $block_high, $page), 
				   $ellipsis, 
				   emm_paginate_loop(($pages - $anchor + 1), $pages)
);
}
else if ($right_gap && !$left_gap) {
			     $output .= sprintf('%s%s%s', 
			   	 emm_paginate_loop(1, $block_high, $page),
				   $ellipsis,
				   emm_paginate_loop(($pages - $anchor + 1), $pages)
);
}
else {
			     $output .= emm_paginate_loop(1, $pages, $page);
}
if ($page < $pages && !empty($nextpage)) {
			     $output .= "<a href='" . get_pagenum_link($page + 1) . "' class='emm-next'>$nextpage</a>";
}
		       $output .= $after;
}
if ($echo) {
		       echo $output;
}
return $output;
}

function add_fav($post_id,$user_id){
	global $wpdb;
	$user_id = (int)$user_id;
	$post_id = (int)$post_id;
	$check= "select * from ".$wpdb->prefix."userpost_fav where post='$post_id' and user='$user_id'";
	$coo = $wpdb->get_results($check);
	if(!count($coo) > 0){
		$tm = time();
		$s = "insert into ".$wpdb->prefix."userpost_fav (user,post,vote_date) values('$user_id','$post_id','$tm')";
		$wpdb->query($s);
		echo "y";
	}else{
		echo "h";
	}
}
function get_user_fav_posts($uid){
	global $wpdb;
	$uid = (int)$uid;
	$sql = "select count(*) from ".$wpdb->prefix."userpost_fav where user='$uid'";
	$coo = $wpdb->get_results($sql);
}
/*********获取用户收藏的文章总数**********/
function get_user_fav_count($user_id){
	global $wpdb;
	$user_id = (int)$user_id;
	$sql = "select count(*) from ".$wpdb->prefix."userpost_fav where user='$user_id'";
	$coo = $wpdb->get_var($sql);
	if($coo)
	return $coo;
	else
	return 0;
}
/**********获取收藏某文章的人数*********/
function get_post_fav_count($post_id){
	global $wpdb;
	$post_id = (int)$post_id;
	$sql = "select count(*) from ".$wpdb->prefix."userpost_fav where post='$post_id'";
	$coo = $wpdb->get_var($sql);
	if($coo)
	return $coo;
	else
	return 0;
}
/************获取文章评分数********************/
function get_post_rating($post_id,$vote='up'){
	global $wpdb;
	$post_id = (int)$post_id;
	if($vote == 'up'){
		$vote='up';
	}else{
		$vote='down';
	}
	$sql = "select count(*) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='$vote'";
	$coo = $wpdb->get_var($sql);
	if($coo)
	return $coo;
	else
	return 0;
}

/*************添加评分**************/
function add_vote($post_id,$user_id='',$ip='',$rating='up'){
	global $wpdb;
	$user_id = (int)$user_id;
	$post_id = (int)$post_id;
	if(($user_id=='')&&($ip=='')){
		return "e";
	}
	if($user_id!=''){
		$check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and user='$user_id'";
	}else{
	if($ip!=''){
		$check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and ip='$ip'";
	}
	}
	//$check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and user='$user_id'";
	$coo = $wpdb->get_results($check);
	if($rating=='up'){
		$rating='up';
	}else{
		$rating='down';
	}
	if(!count($coo) > 0){
		$tm = time();
		$s = "insert into ".$wpdb->prefix."post_vote (user,post,rating,ip) values('$user_id','$post_id','$rating','$ip')";
		$wpdb->query($s);
		return "y";
	}else{
		return "h";
	}
	return "e";
}
/*************获取用户的评论总数*******************/
function get_user_comments_count($user_id){
	global $wpdb;
	$user_id = (int)$user_id;
	$sql = "select count(*) from {$wpdb->comments} where user_id='$user_id' and comment_approved = 1";
	$coo = $wpdb->get_var($sql);
	if($coo)
	return $coo;
	else
	return 0;
}

/*******menu walker***********/
class SH_Last_Walker extends Walker_Nav_Menu{
   function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) {

        $id_field = $this->db_fields['id'];
       if( isset($children_elements[$element->$id_field]) ) { 
            $classes = empty( $element->classes ) ? array() : (array) $element->classes;
            $classes[] = 'haschildren';
            $element->classes =$classes;
       }
        if( 0 == $depth ){
			$classes = empty( $element->classes ) ? array() : (array) $element->classes;
            $classes[] = 'level1';
            $element->classes =$classes;
		}
		if( 1 == $depth ){
			$classes = empty( $element->classes ) ? array() : (array) $element->classes;
            $classes[] = 'level2';
            $element->classes =$classes;
		}
		if( 2 == $depth ){
			$classes = empty( $element->classes ) ? array() : (array) $element->classes;
            $classes[] = 'level3';
            $element->classes =$classes;
		}
        
        return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
    }
}