<?php
/* test */
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_print_styles', 'print_emoji_styles' );

/* enqueue scripts and style from parent theme */
function twentytwentyone_styles() {
    wp_enqueue_style( 'child-style', get_stylesheet_uri(),
                      array( 'twenty-twenty-one-style' ), wp_get_theme()->get('Version') );
}

add_action( 'wp_enqueue_scripts', 'twentytwentyone_styles', 99);

include 'postie-helper.php';

add_filter(
    'wp_sitemaps_posts_entry',
    function( $entry, $post ) {
        $entry['lastmod'] = $post->post_modified_gmt;
        return $entry;
    },
    10,
    2
);
// disable taxonomy sitemap
function shapeSpace_disable_sitemap_taxonomy($taxonomies) {
	unset($taxonomies['post_tag']); // can be post_tag, category, post_format, or any taxonomy
	unset($taxonomies['post_format']); // can be post_tag, category, post_format, or any taxonomy
	return $taxonomies;
}
add_filter('wp_sitemaps_taxonomies', 'shapeSpace_disable_sitemap_taxonomy');

// disable users sitemap
function shapeSpace_disable_sitemap_users($provider, $name) {
	return ($name == 'users') ? false : $provider;
}
add_filter('wp_sitemaps_add_provider', 'shapeSpace_disable_sitemap_users', 10, 2);

// disable post type sitemap
function shapeSpace_disable_sitemap_post_types($post_types) {
	unset($post_types['page']); // can be post, page, or any post type
	
	return $post_types;
}
add_filter('wp_sitemaps_post_types', 'shapeSpace_disable_sitemap_post_types');

/* https://firstsiteguide.com/wordpress-titles/ */
function wploop_change_separator() {
    return '//';
}
add_filter('document_title_separator', 'wploop_change_separator');

/* -- https://wordpress.stackexchange.com/questions/240221/modify-page-title-format-when-using-title-tag */
add_filter( 'document_title_parts', function( $title_parts_array ) {
    if ( get_the_ID() == 31286 ) {
        $title_parts_array['title'] = 'Markus Spring Photography';
    } else {
        $title_parts_array['site'] = str_replace('spring2life', 'Markus Spring Photography',
                                                  $title_parts_array['site']);
    }
    return $title_parts_array;
}, 10, 2 );

/* Basic WP SEO
	Usage: 
		1. add this code to functions.php
		2. replace the $default_keywords with your own
		3. add <?php echo basic_wp_seo(); ?> to header.php
		4. test well and fine tune as needed

	Optional: add custom description, keywords, and/or title
	to any post or page using these custom field keys:

		mm_seo_desc
		mm_seo_keywords
		mm_seo_title

	To migrate from any SEO plugin, replace its custom field 
	keys with those listed above. More information:

		@ https://digwp.com/2013/08/basic-wp-seo/
 */
function wp_seo_get_description ($post) {
    // description
    $seo_desc = get_post_meta($post->ID, 'mm_seo_desc', true);
    $description = get_bloginfo('description', 'display');
    $pagedata = get_post($post->ID);
    if (is_singular()) {
	if (!empty($seo_desc)) {
	    $content = $seo_desc;
	} else if (!empty($pagedata)) {
	    $content = apply_filters('the_excerpt_rss', $pagedata->post_content);
	    $content = substr(trim(strip_tags($content)), 0, 155);
	    $content = preg_replace('#\n#', ' ', $content);
	    $content = preg_replace('#\s{2,}#', ' ', $content);
	    $content = trim($content);
	} 
    } else {
	$content = $description;	
    }
    return esc_attr($content);
}

function wp_seo_get_keywords ($post) {
    // keywords
    $default_keywords = 'Markus Spring, spring2life, Fotografie, photography, fotoblog, photoblog'; // customize
    $keys = get_post_meta($post->ID, 'mm_seo_keywords', true);
    $cats = get_the_category();
    $tags = get_the_tags();
    if (empty($keys)) {
	if (!empty($cats)) foreach($cats as $cat) $keys .= $cat->name . ', ';
	if (!empty($tags)) foreach($tags as $tag) $keys .= $tag->name . ', ';
	$keys .= $default_keywords;
    }
    return esc_attr($keys);
}

function basic_wp_seo() {
    global $page, $paged, $post;
    $default_keywords = 'Markus Spring, spring2life, Fotografie, photography, fotoblog, photoblog'; // customize
    $output = '';
    $output .= '<meta name="description" content="' . wp_seo_get_description($post) . '">' . "\n";
    $output .= "\t\t" . '<meta name="keywords" content="' . wp_seo_get_keywords($post) . '">' . "\n";
    // robots
    if (is_category() || is_tag()) {
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        if ($paged > 1) {
            $output .=  "\t\t" . '<meta name="robots" content="noindex,follow">' . "\n";
        } else {
            $output .=  "\t\t" . '<meta name="robots" content="index,follow">' . "\n";
        }
    } else if (is_home() || is_singular()) {
        $output .=  "\t\t" . '<meta name="robots" content="index,follow">' . "\n";
    } else {
        $output .= "\t\t" . '<meta name="robots" content="noindex,follow">' . "\n";
    }
    
    // title
    $title_custom = get_post_meta($post->ID, 'mm_seo_title', true);
    $url = ltrim(esc_url($_SERVER['REQUEST_URI']), '/');
    $name = get_bloginfo('name', 'display');
    $title = trim(wp_title('', false));
    $cat = single_cat_title('', false);
    $tag = single_tag_title('', false);
    $search = get_search_query();
    
    if (!empty($title_custom)) $title = $title_custom;
    if ($paged >= 2 || $page >= 2) $page_number = ' | ' . sprintf('Page %s', max($paged, $page));
    else $page_number = '';
    
    if (is_home() || is_front_page()) $seo_title = $name . ' | ' . $description;
    elseif (is_singular())            $seo_title = $title . ' | ' . $name;
    elseif (is_tag())                 $seo_title = 'Tag Archive: ' . $tag . ' | ' . $name;
    elseif (is_category())            $seo_title = 'Category Archive: ' . $cat . ' | ' . $name;
    elseif (is_archive())             $seo_title = 'Archive: ' . $title . ' | ' . $name;
    elseif (is_search())              $seo_title = 'Search: ' . $search . ' | ' . $name;
    elseif (is_404())                 $seo_title = '404 - Not Found: ' . $url . ' | ' . $name;
    else                              $seo_title = $name . ' | ' . $description;

    
    $output .= "\t\t" . '<title>' . esc_attr($seo_title . $page_number) . '</title>' . "\n";
    
    // OpenGraph
    $permalink = get_permalink($post->ID);  
    $output .= '<meta property="og:locale" content="en_GB" />' . "\n";
    $output .= "<meta property='og:url' content='$permalink'>\n";
    $output .= "<meta property='og:type' content='article'> \n";
    $output .= "<meta property='og:title' content='$title'> \n";
    $output .= "<meta property='og:site_name' content='Markus Spring Photography // spring2life'> \n";
    $output .= "<meta property='og:description' content='$title | Markus Spring Photography'>\n";
    $output .= "<meta property='og:image' content='" . get_post_image($post->ID) . "'> \n";
    // <meta property="article:modified_time" content="2021-03-16T20:48:44+00:00" />
    /*             echo "<!-- " . print_r($image_attributes) . " -->\n"; */
    
    return $output;
}

function get_post_image ($postID)
{                   
    $args = array(
    'numberposts' => 1,
    'order'=> 'ASC',
    'post_mime_type' => 'image',
    'post_parent' => $postID,
    'post_status' => null,
    'post_type' => 'attachment'
    );
    $attachments = get_children( $args );
    //print_r($attachments);
    if ($attachments) {
        foreach($attachments as $attachment) {
            $image_attributes = wp_get_attachment_image_src( $attachment->ID, 'full' );
            /*             echo "<!-- " . print_r($image_attributes) . " -->\n"; */
            return $image_attributes[0];
        }
    }
}

/* -------------------------------------------------- further cleanup --- */
/* Disable emojicons introduced with WP 4.2 */
/* from http://wordpress.stackexchange.com/questions/185577/disable-emojicons-introduced-with-wp-4-2 */
function disable_wp_emojicons() {
  // all actions related to emojis
  remove_action( 'admin_print_styles', 'print_emoji_styles' );
  remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
  remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
  remove_action( 'wp_print_styles', 'print_emoji_styles' );
  remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
  remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
  remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
  // filter to remove TinyMCE emojis
  // add_filter( 'tiny_mce_plugins', 'disable_emojicons_tinymce' );
}
add_action( 'init', 'disable_wp_emojicons' );

/* from https://wordpress.org/support/topic/remove-googlewebfonts */
function remove_open_sans() {
	wp_dequeue_style( 'open-sans-web-font' );
	wp_deregister_style( 'open-sans-web-font' );
}
add_action( 'wp_enqueue_scripts', 'remove_open_sans', 25 );

add_image_size( 'semilarge', 602, 0, false );
add_image_size( 'old_old_large', 1100, 1100, false );
add_filter( 'image_size_names_choose','miech_custom_image_sizes' );
function miech_custom_image_sizes( $sizes ) {
    return array_merge( $sizes, array(
        'semilarge' => 'SemiLarge',
        'old_old_large' => 'Old_old_Large',
    ) );
}

/*-- ------------------------------ run postie get posts from admin bar --- --*/
// https://markus-spring.info/wp-admin/admin.php?page=postie-settings&action=runpostie&Submit=Process+Email
function webriti_toolbar_link($wp_admin_bar) {
    $args = array(
        'id' => 'customlink',
        'title' => 'Run Postie',
        'href' => 'https://markus-spring.info/wp-admin/admin.php?page=postie-settings&action=runpostie&Submit=Process+Email',
        'meta' => array(
            'class' => 'customlink',
            'title' => 'run Postie'
        )
    );
    $wp_admin_bar->add_node($args);
}
add_action('admin_bar_menu', 'webriti_toolbar_link', 999);

add_action( 'pre_get_posts', 'prefix_category_query' );
/**
 * Customize category query using pre_get_posts.
 * 
 * @author     FAT Media <http://youneedfat.com>
 * @copyright  Copyright (c) 2013, FAT Media, LLC
 * @license    GPL-2.0+
 * @todo       Change prefix to theme or plugin prefix
 *
 */
function prefix_category_query( $query ) {
    /* if ( $query->is_main_query() && ! $query->is_feed() && ! is_admin() && is_category() ) { */
	if ( $query->is_main_query() && ! $query->is_feed() && ! is_admin() && is_archive() ) {
		$query->set( 'posts_per_page', '40' ); //Change this number to anything you like.
	}

}

/* ----------------------------------- for manipulating the main loop --- */
$miech_active_cat;

function miech_get_active_cat ($id) {
    //_log("Querying active cat for $id");
    $my_query = new WP_Query('posts_per_page=1');
    while ( $my_query->have_posts() )
        $my_query->the_post();
    $featured_category_1 = get_theme_mod( 'featured_category_1', 'default_value' );
    $featured_category_2 = get_theme_mod( 'featured_category_2', 'default_value' );
    $do_not_duplicate = $id; //This is the magic line
    if (has_category ( $featured_category_1, $id)) { /* Featured Category 1 */
        $active_cat = $featured_category_1;
    } else {
        $active_cat = $featured_category_2;          /* Featured Category 2 */
    }
    wp_reset_query();
    //_log("miech_get_active_cat: Active cat is $active_cat");
    return $active_cat;
}

function miech_set_active_cat ( $this_cat ) {
    global $miech_active_cat;
    if (have_posts()) {
        if ( $this_cat ) {
            $miech_active_cat = $this_cat;
        } else {
            $miech_active_cat = miech_get_active_cat($post->ID);
        }
        //error_log("miech_set_active_cat: miech_active_cat is $miech_active_cat");
        if ( get_query_var('paged') )
           { $paged = get_query_var('paged'); }
        elseif ( get_query_var('page') )
           { $paged = get_query_var('page'); }
        else
           { $paged = 1; }
        //error_log("paged: $paged");
        if ( is_single() )
            $posts_per_page = 1;
        else
            $posts_per_page = 25;

        query_posts( array(
            'order' => 'DESC',
            'paged' => $paged,
            'cat'   => $miech_active_cat,
            'posts_per_page' => $posts_per_page
        ) );
    }
}

// turn Photon off so we can get the correct image
$photon_removed = '';
if ( class_exists( 'Jetpack' ) && Jetpack::is_module_active( 'photon' ) ) { // check that we are, in fact, using Photon in the first place
    $photon_removed = remove_filter( 'image_downsize', array( Jetpack_Photon::instance(), 'filter_image_downsize' ) );
}

/*
Diverse Einstellungen für die functions.php (dort am Ende einfügen)
von https://faq.netzprisma.de/wordpress-html-ausmisten/
*/

// Diverse Einträge entfernen
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');

// Generator-Angaben, z.B. im Feed, entfernen
function remove_wp_generator() { return ''; }
add_filter('the_generator','remove_wp_generator');
// // prev+next Links in Beiträgen entfernen
// remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');

// // shortlink entfernen
// remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0);

// Post+Kommentar+Kategorie RSS Feed-Links entfernen (entfernt nicht die Feeds selbst)
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'feed_links_extra', 3);

// wp Versions-Parameter ?ver=... von Skripts entfernen, falls unsere WordPress-Version angegeben wird
function vc_remove_wp_ver_css_js( $src )
{
   if (  strpos($src, 'ver='. get_bloginfo('version') )  )
      $src = remove_query_arg('ver', $src);
   return $src;
}
add_filter('style_loader_src',  'vc_remove_wp_ver_css_js', 9999);
add_filter('script_loader_src', 'vc_remove_wp_ver_css_js', 9999);

// Emoji js, css und dns-preload entfernen
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
add_filter('emoji_svg_url', '__return_false');

// // REST Api Hinweise entfernen
// remove_action('wp_head', 'rest_output_link_wp_head');
// remove_action('wp_head', 'wp_oembed_add_discovery_links');
// remove_action('template_redirect', 'rest_output_link_header', 11, 0);

// function remove_json_api ()
// {
//    // REST API Zeilen aus dem HTML Header entfernen
//    remove_action('wp_head', 'rest_output_link_wp_head', 10);
//    remove_action('wp_head', 'wp_oembed_add_discovery_links', 10);
//    // REST API endpoint entfernen
//    remove_action('rest_api_init', 'wp_oembed_register_route');
//    // oEmbed auto discovery entfernen
//    add_filter('embed_oembed_discover', '__return_false');
//    // oEmbed results nicht filtern
//    remove_filter('oembed_dataparse', 'wp_filter_oembed_result', 10);
//    // oEmbed discovery links entfernen
//    remove_action('wp_head', 'wp_oembed_add_discovery_links');
//    // oEmbed-JavaScript entfernen
//    remove_action('wp_head', 'wp_oembed_add_host_js');
//    // rewrite rules zum Einbetten entfernen
//    add_filter('rewrite_rules_array', 'disable_embeds_rewrites');
// }
// add_action('after_setup_theme', 'remove_json_api');
