<?php
/**
 * Custom template tags for this theme.
 *
 * Eventually, some of the functionality here could be replaced by core features.
 *
 * @package daohang
 */


/**
 * Get Post Views.
 */
if ( ! function_exists( 'daohang_get_post_views' ) ) :

function daohang_get_post_views($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 '阅读<span class="view-count">(0)</span>';
    }
    return __('阅读', 'daohang') . '<span class="view-count">(' . ($count) . ')</span> ';
}

endif;

/**
 * Set Post Views.
 */
if ( ! function_exists( 'daohang_set_post_views' ) ) :

function daohang_set_post_views($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);
    }
}

endif;

/**
 * Search Filter 
 */
if ( ! function_exists( 'daohang_search_filter' ) && ( ! is_admin() ) ) :


function daohang_search_filter($query) {
	if ($query->is_search) {
		$query->set('post_type', 'post');
	}
	return $query;
}

add_filter('pre_get_posts','daohang_search_filter');

endif;

/**
 * Add custom meta box.
 */
if ( ! function_exists( 'daohang_add_custom_meta_box' ) ) :

function daohang_add_custom_meta_box()
{
    add_meta_box("demo-meta-box", "文章选项", "daohang_custom_meta_box_markup", "post", "side", "high", null);
}

add_action("add_meta_boxes", "daohang_add_custom_meta_box");

endif;
/**
 * Displaying fields in a custom meta box.
 */
if ( ! function_exists( 'daohang_custom_meta_box_markup' ) ) :

function daohang_custom_meta_box_markup($object)
{
    wp_nonce_field(basename(__FILE__), "meta-box-nonce");

    ?>
        <div>
            <p>
            <label for="entry_source"><?php echo __('文章来源', 'daohang'); ?></label>
            <input name="entry_source" type="text" value="<?php echo get_post_meta($object->ID, "entry_source", true); ?>" style="width: 100%;">
            </p>
            <p>
            <label for="entry_source_link"><?php echo __('文章来源链接', 'daohang'); ?></label>
            <input name="entry_source_link" type="text" value="<?php echo get_post_meta($object->ID, "entry_source_link", true); ?>" placeholder="http://" style="width: 100%;">
            </p>            
            <p>
            <label for="single_credit"><?php echo __('文章来源详情', 'daohang'); ?></label>
            <textarea name="single_credit" type="text" value="<?php echo get_post_meta($object->ID, "single_credit", true); ?>" style="width: 100%;"><?php echo get_post_meta($object->ID, "single_credit", true); ?></textarea>
            </p>            
        </div>
    <?php  
}

endif;

/**
 * Storing Meta Data.
 */
if ( ! function_exists( 'daohang_save_custom_meta_box' ) ) :

function daohang_save_custom_meta_box($post_id, $post, $update)
{
    if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__)))
        return $post_id;

    if(!current_user_can("edit_post", $post_id))
        return $post_id;

    if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
        return $post_id;

    $slug = "post";
    if($slug != $post->post_type)
        return $post_id;

    $meta_box_text_value = "";
    $meta_box_textarea_value = "";
    $meta_box_textarea_value2 = "";
    $meta_box_source_link_value = "";    
    $meta_box_checkbox_value = "";

    if(isset($_POST["is_featured"]))
    {
        $meta_box_checkbox_value = $_POST["is_featured"];
    }   
    update_post_meta($post_id, "is_featured", $meta_box_checkbox_value);


    if(isset($_POST["custom_title"]))
    {
        $meta_box_textarea_value = $_POST["custom_title"];
    }   
    update_post_meta($post_id, "custom_title", $meta_box_textarea_value);

    if(isset($_POST["entry_source"]))
    {
        $meta_box_text_value = $_POST["entry_source"];
    }   
    update_post_meta($post_id, "entry_source", $meta_box_text_value);

    if(isset($_POST["entry_source_link"]))
    {
        $meta_box_source_link_value = $_POST["entry_source_link"];
    }   
    update_post_meta($post_id, "entry_source_link", $meta_box_source_link_value);


    if(isset($_POST["single_credit"]))
    {
        $meta_box_textarea_value2 = $_POST["single_credit"];
    }   
    update_post_meta($post_id, "single_credit", $meta_box_textarea_value2);
}

add_action("save_post", "daohang_save_custom_meta_box", 10, 3);

endif;

/**
 * Filter the except length to 100 characters.
 *
 * @param int $length Excerpt length.
 * @return int (Maybe) modified excerpt length.
 */
if ( ! function_exists( 'zimeiti_1_custom_excerpt_length' ) ) :

function zimeiti_1_custom_excerpt_length( $length ) {
    return get_theme_mod('loop-excerpt-length', get_theme_mod('loop-excerpt-length', '90'));
}
add_filter( 'excerpt_length', 'zimeiti_1_custom_excerpt_length', 999 );

endif;

/**
 * Custom Excerpt
 */
if ( ! function_exists( 'daohang_custom_excerpt' ) ) :

function daohang_custom_excerpt($limit) {

    $excerpt = explode(' ', get_the_excerpt(), $limit);

    if (count($excerpt)>=$limit) {
        array_pop($excerpt);
        $excerpt = implode(" ",$excerpt).'...';
    } else {

    $excerpt = implode(" ",$excerpt);

    }
    $excerpt = preg_replace('`[[^]]*]`','',$excerpt);
    return $excerpt;
}
endif;

/**
 * Customize excerpt more.
 */
if ( ! function_exists( 'daohang_excerpt_more' ) ) :

function daohang_excerpt_more( $more ) {
   return '&hellip;';
}
add_filter( 'excerpt_more', 'daohang_excerpt_more' );

endif;

/**
 * Custom post title
 */
if ( ! function_exists( 'daohang_custom_title' ) ) :
    function daohang_custom_title() {
        global $post;
        $custom_title = get_post_meta($post->ID, 'custom_title', true); 
        if( empty($custom_title) ) {
            echo wp_trim_words( get_the_title(), get_theme_mod('home-words-num','30'), '...' ); 
        } else {
            echo $custom_title;
        }
    }
endif;
/**
 * Custom post title for posts with thumbnails on homepage
 */
if ( ! function_exists( 'daohang_home_post_title' ) ) :
    function daohang_home_post_title() {
        global $post;
        $custom_title = get_post_meta($post->ID, 'custom_title', true); 
        if( empty($custom_title) ) {
            echo get_the_title(); 
        } else {
            echo $custom_title;
        }
    }
endif;

/*
 * First Image 
 */
if ( ! function_exists( 'daohang_custom_thumb' ) ) :

function daohang_custom_thumb($width,$height,$default) {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    
    for ( $i = 0; $i <= sizeof($matches[0])-1; $i++){
        $first_img = $matches[1][0];
    }

    if( empty($first_img) ) {
        if( $default == true ) {
        
            $random = mt_rand(1, 10);
            $first_img = get_template_directory_uri() . '/images/'.$random.'.jpg';

            echo '<a target="_blank" class="thumbnail-link" href="' . get_the_permalink() .'"><div class="thumbnail-wrap">';
            echo '<img src="' . get_template_directory_uri() . '/thumb.php?src=' . $first_img . '&w=' . $width . '&h=' .$height. '" alt="' . get_the_title() . '"/>';
            echo '</div></a>';  
        }      
    } else {
        echo '<a target="_blank" class="thumbnail-link" href="' . get_the_permalink() .'"><div class="thumbnail-wrap">';
        echo '<img src="' . get_template_directory_uri() . '/thumb.php?src=' . $first_img . '&w=' . $width . '&h=' .$height. '" alt="' . get_the_title() . '"/>';
        echo '</div></a>';

    }
    //return $first_img;
}

endif;

/**
 * Display the first (single) category of post.
 */
if ( ! function_exists( 'daohang_first_category' ) ) :
function daohang_first_category() {
    $category = get_the_category();
    if ($category) {
      echo '<a target="_blank" href="' . get_category_link( $category[0]->term_id ) . '" title="' . sprintf( __( "浏览所有%s文章", 'daohang' ), $category[0]->name ) . '" ' . '>' . $category[0]->name.'</a> ';
    }    
}
endif;

/**
 * Returns true if a blog has more than 1 category.
 *
 * @return bool
 */
if ( ! function_exists( 'daohang_categorized_blog' ) ) :

function daohang_categorized_blog() {
    if ( false === ( $all_the_cool_cats = get_transient( 'daohang_categories' ) ) ) {
        // Create an array of all the categories that are attached to posts.
        $all_the_cool_cats = get_categories( array(
            'fields'     => 'ids',
            'hide_empty' => 1,
            // We only need to know if there is more than one category.
            'number'     => 2,
        ) );

        // Count the number of categories that are attached to the posts.
        $all_the_cool_cats = count( $all_the_cool_cats );

        set_transient( 'daohang_categories', $all_the_cool_cats );
    }

    if ( $all_the_cool_cats > 1 ) {
        // This blog has more than 1 category so daohang_categorized_blog should return true.
        return true;
    } else {
        // This blog has only 1 category so daohang_categorized_blog should return false.
        return false;
    }
}

endif;

/**
 * Flush out the transients used in daohang_categorized_blog.
 */
if ( ! function_exists( 'daohang_category_transient_flusher' ) ) :

function daohang_category_transient_flusher() {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    // Like, beat it. Dig?
    delete_transient( 'daohang_categories' );
}
add_action( 'edit_category', 'daohang_category_transient_flusher' );
add_action( 'save_post',     'daohang_category_transient_flusher' );

endif;

/**
 * Disable specified widgets.
 */
/**
 * Enqueues scripts and styles.
 */
if ( ! function_exists( 'daohang_disable_specified_widgets' ) ) :

function daohang_disable_specified_widgets( $sidebars_widgets ) {

    if ( isset($sidebars_widgets['homepage']) ) {
        if ( is_home() && is_array($sidebars_widgets['homepage']) ) {
            foreach($sidebars_widgets['homepage'] as $i => $widget) {
                if( (strpos($widget, 'zhutibaba-') === false) ) {
                    unset($sidebars_widgets['homepage'][$i]);
                }
                if( (strpos($widget, 'zhutibaba-home-bottom-') !== false) ) {
                    unset($sidebars_widgets['homepage'][$i]);
                }                
            }
        }
    }

    if ( isset($sidebars_widgets['sidebar-1']) ) {
        if ( is_array($sidebars_widgets['sidebar-1']) ) {
            foreach($sidebars_widgets['sidebar-1'] as $i => $widget) {
                if(strpos($widget, 'zhutibaba-home-') !== false) {
                    unset($sidebars_widgets['sidebar-1'][$i]);
                }
            }
        }    
    }  

    return $sidebars_widgets;
}
//add_filter( 'sidebars_widgets', 'daohang_disable_specified_widgets' );

endif;


/**
 * Disable WordPress admin bar.
 */
//add_filter('show_admin_bar', '__return_false');

/**
 * Check HTTPS.
 */
if ( ! function_exists( 'daohang_check_https' ) ) :

function daohang_check_https() {
    
    if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) {
        
        return true; 
    }
    return false;
}

endif;

/**
 * Category Layout
 */
add_action ( 'edit_category_form_fields', function( $tag ){
    $is_img = get_term_meta( $tag->term_id, '_is_img', true ); ?>

    <tr class='form-field'>
        <th scope='row'><label for='cat_page_title'><?php _e('文章列表样式', 'daohang'); ?></label></th>
        <td>
                
            <input class="checkbox" type="checkbox" name='is_img' id='is_img' <?php if (!empty($is_img)) { echo "checked"; }?> />
            <label for="is_img">图片模式</label>
            
        </td>
    </tr> <?php
});
add_action ( 'edited_category', function() {
    if ( isset( $_POST['is_img'] ) ) {
        update_term_meta( $_POST['tag_ID'], '_is_img', $_POST['is_img'] );
    } else {
        update_term_meta( $_POST['tag_ID'], '_is_img', null );
    }
});

/*
 * First Image 
 */
if ( ! function_exists( 'catch_that_image' ) ) :

function catch_that_image() {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    
    for ( $i = 0; $i <= sizeof($matches[0])-1; $i++){
        $first_img = $matches[1][0];
    }

    if(empty($first_img)) {
        $random = mt_rand(1, 10);
        $first_img = get_template_directory_uri() . '/images/'.$random.'.jpg';
    }
    return $first_img;
}

endif;

/*
 * Limit Tags Count 
 */
//Register tag cloud filter callback
add_filter('widget_tag_cloud_args', 'daohang_tag_widget_limit');
 
//Limit number of tags inside widget
function daohang_tag_widget_limit($args){
 
//Check if taxonomy option inside widget is set to tags
if(isset($args['taxonomy']) && $args['taxonomy'] == 'post_tag'){
  $args['number'] = 30; //Limit number of tags
}
 
return $args;
}

// Enable Link Mannager
//add_filter( 'pre_option_link_manager_enabled', '__return_true' );

// Register the Clients custom post type
function daohang_toolbox_register_links() {

    $slug = apply_filters( 'daohang_links_rewrite_slug', 'links' );

    $labels = array(
        'name'                  => _x( '链接', 'Post Type General Name', 'daohang' ),
        'singular_name'         => _x( '链接', 'Post Type Singular Name', 'daohang' ),
        'menu_name'             => __( '链接', 'daohang' ),
        'name_admin_bar'        => __( '链接', 'daohang' ),
        'archives'              => __( '链接归档', 'daohang' ),
        'parent_item_colon'     => __( 'Parent Item:', 'daohang' ),
        'all_items'             => __( '所有链接', 'daohang' ),
        'add_new_item'          => __( '添加新链接', 'daohang' ),
        'add_new'               => __( '添加新链接', 'daohang' ),
        'new_item'              => __( '新链接', 'daohang' ),
        'edit_item'             => __( '编辑链接', 'daohang' ),
        'update_item'           => __( '更新链接', 'daohang' ),
        'view_item'             => __( '查看链接', 'daohang' ),
        'search_items'          => __( '搜索链接', 'daohang' ),
        'not_found'             => __( '未找到链接', 'daohang' ),
        'not_found_in_trash'    => __( '回收站中没有链接', 'daohang' ),
        'featured_image'        => __( '特色图片', 'daohang' ),
        'set_featured_image'    => __( '设置特色图片', 'daohang' ),
        'remove_featured_image' => __( '取消特色图片', 'daohang' ),
        'use_featured_image'    => __( '设为特色图片', 'daohang' ),
        'insert_into_item'      => __( '插入至链接内容', 'daohang' ),
        'uploaded_to_this_item' => __( '更新链接内容', 'daohang' ),
        'items_list'            => __( '链接列表', 'daohang' ),
        'items_list_navigation' => __( '链接列表导航', 'daohang' ),
        'filter_items_list'     => __( '过滤链接列表', 'daohang' ),
    );
    $args = array(
        'label'                 => __( 'Link', 'daohang' ),
        'description'           => __( 'A post type for your links', 'daohang' ),
        'labels'                => $labels,
        'supports'              => array( 'title', ),
        //'taxonomies'            => array( 'link_cat' ),
        'hierarchical'          => true,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 3,
        'menu_icon'             => 'dashicons-admin-links',
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,        
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'page',
        'rewrite'               => array( 'slug' => $slug ),
    );
    register_post_type( 'links', $args );

}

add_action( 'init', 'daohang_toolbox_register_links', 0 );

// Register Client Category
function daohang_toolbox_register_links_taxonomy(){
    
    $args = array(
        "hierarchical" => true, 
        "label" => __( "链接分类目录", 'daohang' ), 
        "singular_label" => __( "Category", 'daohang' ), 
        "rewrite" => array('slug' => 'link_cat', 'hierarchical' => true), 
        "public" => true,
        'show_ui'           => true,
        'show_in_menu'      => true,
        'show_in_nav_menus' => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'show_in_quick_edit' => true, 
    );
    
    register_taxonomy(__( "link_cat", 'daohang' ), array(__( "links", 'daohang' )), $args); 
}

add_action( 'init', 'daohang_toolbox_register_links_taxonomy', 0 );

/**
 * Update messages for the Theme admin.
 */
function daohang_links_type_updated_messages( $messages ) {
    global $post;

    $messages['links'] = array(
        0  => '', // Unused. Messages start at index 1.
        1  => sprintf( __( '链接已更新。 <a href="%s">查看链接</a>', 'daohang'), esc_url( get_permalink( $post->ID ) ) ),
        2  => esc_html__( '自定义字段已更新', 'daohang' ),
        3  => esc_html__( '自定义字段已删除', 'daohang' ),
        4  => esc_html__( '链接已更新', 'daohang' ),
        /* translators: %s: date and time of the revision */
        5  => isset( $_GET['revision'] ) ? sprintf( esc_html__( '链接已复原为版本 %s', 'daohang'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
        6  => sprintf( __( '链接已发布。 <a href="%s">查看链接</a>', 'daohang' ), esc_url( get_permalink( $post->ID ) ) ),
        7  => esc_html__( '链接已保存', 'daohang' ),
        8  => sprintf( __( '链接已提交。 <a target="_blank" href="%s">预览链接</a>', 'daohang'), esc_url( add_query_arg( 'preview', 'true', get_permalink( $post->ID ) ) ) ),
        9  => sprintf( __( '链接计划发布: <strong>%1$s</strong>. <a target="_blank" href="%2$s">预览链接</a>', 'daohang' ),
        // translators: Publish box date format, see http://php.net/date
        date_i18n( __( 'M j, Y @ G:i', 'daohang' ), strtotime( $post->post_date ) ), esc_url( get_permalink( $post->ID ) ) ),
        10 => sprintf( __( '链接草稿已更新。 <a target="_blank" href="%s">预览链接</a>', 'daohang' ), esc_url( add_query_arg( 'preview', 'true', get_permalink( $post->ID ) ) ) ),
    );

    return $messages;
}
add_filter( 'post_updated_messages', 'daohang_links_type_updated_messages' );
