<?php
/*	$Id: postie-helper.php,v 1.2 2018/04/17 11:43:22 springm Exp springm $	*/

/*	$Log: postie-helper.php,v $
 *	Revision 1.2  2018/04/17 11:43:22  springm
 *	Summary: Funktioniert
 *	*/


/* ------------------- postie helper function for leftover categories --- */
/* postie removes categories given in the mail subject if it finds them in the
*  wordpress categories.
*  all other categories will be made tags of the created post

for this to work, postie-settings->message->remove matched categories has to be set to no

*/

add_filter('postie_post_before', 'mws_auto_tag');

function mws_auto_tag($post) {
    DebugEcho('============================== mws_auto_tag ' . print_r($post, true));
    // DebugEcho('    test for "common places" category');
    // if (in_category( 'Common Places', $post )) {
    //     DebugEcho('    post has "common places" category');
    // }
    $post = evaluate_image_exif($post, $post['post_category']);
    $post['post_name'] = $post['post_title'];
    DebugEcho('========================== end mws_auto_tag');
    DebugEcho("========================== post_content before massage\n" . $post['post_content']);
    $post['post_content'] = preg_replace('!<div class="postie-attachments">!','', $post['post_content']);
    $post['post_content'] = preg_replace('!</div>!','', $post['post_content']);
    $post['post_content'] = preg_replace('!<p></p>!','', $post['post_content']);
    $post['post_content'] = preg_replace('!<br />!','', $post['post_content']);
    $post['post_content'] = preg_replace('!\n!','', $post['post_content']);
    $post['post_content'] = preg_replace('!&lt;!','<', $post['post_content']);
    $post['post_content'] = preg_replace('!&gt;!','>', $post['post_content']);
    DebugEcho("========================== post_content after massage\n" . $post['post_content']); 
    $post = make_landscape_photos_large($post);
    return $post;
}

/* extract information from the exif metadata of the first image in the post.
*  if applicable create the title, categories and location information from this */ 
function evaluate_image_exif( $post, $categories ) {
    DebugEcho('MWS =====> begin  evaluate_image_exif');
    $common_places_found = 0;
    DebugEcho('    test for "common places" category');
    if (in_category( 'common places', $post )) {
        DebugEcho('    post has "common places" category');
        $common_places_found = 1;
    }
    $iimgs = get_attached_media('image', $post['ID']);
    $upload_dir = wp_upload_dir();
    foreach ( $iimgs as $iimg ) {
        $imagefile = $upload_dir['basedir'] . '/' .
                     wp_get_attachment_metadata( get_post_thumbnail_id( $post['ID'] ) )['file'];
        break;
    }
    $meta = miech_wp_read_image_metadata( get_post_meta($post['ID']), $imagefile, $sourceImageType );
    if ( ! empty( $meta['title'] ) )
        $post['post_title'] = $meta['title'];
    DebugEcho('~~~~~~~~~~ ' . $post['post_title'] );
    preg_match_all('/\[(.*?)\]/', $post['post_title'], $leftovercats);
    print_r($leftovercats[1]); 
    foreach ( array_merge( array( $meta['country'], $meta['state'], $meta['city'] ),
                           explode(',', $meta['keywords']), $leftovercats[1] ) as $k) {
        /* DebugEcho('     category/tag: ' . $k); */
        $in_blacklist = 0;
        foreach ( array('wp', 'blog', 'status', 'genre', 'published', 'printed', 'lens', 'treatment' ) as $b ) {
            if ( strcasecmp( "$k", "$b" ) == 0 ) {
                $in_blacklist = 1;
            }
        }
        /* if ( $in_blacklist < 1 ) { */
        if ( $in_blacklist < 1 and strlen($k) > 0) {
            DebugEcho("     Examining '$k' " );
            if ( strcasecmp('common places', "$k") == 0) {
                DebugEcho("     '$k' GEFUNDEN!" );
                $common_places_found = 1;
            }
            $cat = get_term_by('name', (string) "$k", 'category');
            if ( isset($cat) ) {
                if ( $cat->term_id > 1 ) {
                    DebugEcho("     Category '$k' exists with id " . $cat->term_id );
                    array_push( $categories, $cat->term_id );
                } else {
                    DebugEcho("     Category '$k' does not exist ==> '$k' becomes tag" );
                    array_push($post['tags_input'], "$k");
                }
            }
        }
    }
    DebugEcho("     \$common_places_found ist $common_places_found: " . print_r($categories, true) );
    if ( $common_places_found == 0 ) {
        array_push( $categories,  get_term_by('name', (string) "Vernacular", 'category')->term_id );
    } else {
        $c2 = \array_diff($categories, [1964]);
        $categories = $c2;
        DebugEcho("     'vernacular' removed: " . print_r($categories, true) );
    }
    $post['post_category'] = $categories;
    if ( $meta['city'] )
        $post['post_content'] = mws_add_caption( $post['post_content'], $meta );
    /* remove leftover category strings from title */
    $post['post_title'] = preg_replace('/\[.*\]\s*/', '', $post['post_title']);
    DebugEcho( "MWS ===> end evaluate_image_exif " .  $imagefile);
    return $post;
}

/* ------------------------------------------- exif related functions --- */
function miech_wp_read_image_metadata( $meta, $file, $sourceImageType ) {
    DebugEcho('MWS ===> beginning  miech_wp_read_image_metadata');
    $newmeta = array();
    
    // read iptc first, since it might contain data not available in exif such
    // as caption, description etc
    getimagesize( $file, $info );
    if ( ! empty( $info['APP13'] ) ) {
        $iptc = iptcparse( $info['APP13'] );
        $newmeta['title']    = trim( $iptc['2#105'][0] );
        $newmeta['country']  = trim( $iptc['2#101'][0] );
        $newmeta['state']    = trim( $iptc['2#095'][0] );
        $newmeta['city']     = trim( $iptc['2#090'][0] );
        $newmeta['location'] = trim( $iptc['2#092'][0] );
        $keywordcount = count($iptc["2#025"]);
        for ( $i = 0; $i < $keywordcount; $i++ ) {
            if ( strlen($newmeta['keywords']) > 0 )
                $newmeta['keywords'] .= ',' ;
            $newmeta['keywords'] .= $iptc["2#025"][$i];
        }
    } 

    $exif = @exif_read_data( $file );
    /*     DebugEcho('Exif' . print_r($exif)); */
    DebugEcho('GPSLatitude is ' . $exif['GPSLatitude']);
    if ( is_numeric($exif['GPSLatitude']) )
        DebugEcho('GPSLatitude is numeric ' );
    else
        DebugEcho('GPSLatitude is not numeric ' );
        
    if ( ! empty($exif['GPSLatitude'])) 
        $newmeta['latitude'] = geo_single_fracs2dec($exif['GPSLatitude'] );
    if ( ! empty($exif['GPSLongitude']))
        $newmeta['longitude'] = geo_single_fracs2dec($exif['GPSLongitude']) ;
    if ( ! empty($exif['GPSLatitudeRef']))
        if ( $exif['GPSLatitudeRef'] == 'S' )
            $newmeta['latitude'] = '-' . $newmeta['latitude'];
    if ( ! empty($exif['GPSLongitudeRef']))
        if ( $exif['GPSLongitudeRef'] == 'W' )
            $newmeta['longitude'] = '-' . $newmeta['longitude'];

    foreach ( array( 'city', 'location') as $key ) {
        if ( $newmeta[ $key ] && ! seems_utf8( $newmeta[ $key ] ) )
            $newmeta[ $key ] = utf8_encode( $newmeta[ $key ] );
    }
    
    $meta = array_merge($meta, $newmeta);
    DebugEcho('MWS ===> end miech_wp_read_image_metadata');
    return $meta;
}

function geo_frac2dec($str) {
  @list( $n, $d ) = explode( '/', $str );
  if ( !empty($d) )
    return $n / $d;
  return $str;
}

function geo_single_fracs2dec($fracs) {
	return	geo_frac2dec($fracs[0]) +
		geo_frac2dec($fracs[1]) / 60 +
		geo_frac2dec($fracs[2]) / 3600;
}

function mws_add_caption( $s, $meta ) {
    DebugEcho('MWS ===> begin mws_add_caption');
    $alt = $meta['title'];
    $caption = "</div>\n<p class='mycaption'>";
    if ( $meta['location'] ) {
        $caption = $caption . $meta['location'] . ', ';
        $alt     = $alt . ', ' . $meta['location'];
    }
    $caption = $caption . $meta['city'];
    $alt = $alt . ', ' . $meta['city'];
    if ( $meta['longitude'] ) {
        $caption = $caption . ' (<a href="http://www.openstreetmap.org/?mlat=' . $meta['latitude'];
        $caption = $caption . ';&mlon=' . $meta['longitude'] . '&zoom=14&q=mapquest" target="_blank">OSM</a>)'; 
        $alt = $alt . ', geotagged';
    }
    $caption = $caption . "</p>\n";
    $keywords = $meta['keywords'];
    DebugEcho('Keywords: ' . $keywords);
    $keywords = preg_replace('/(WP|Lens,|Status,|Blog,|Published,|Treatment,|)/s', '', $keywords);
    $keywords = preg_replace('/"/s', "'", $keywords);
    $keywords = preg_replace('/,/s', ', ', $keywords);
    $keywords = preg_replace('/, $/', '', $keywords);
    DebugEcho($keywords);
    $alt = $alt . ', ' . $keywords;
    DebugEcho($alt);
    $s = preg_replace('/<br \/>\s*<\/div>/ims', $caption, $s, 1);
    $s = preg_replace('/alt=""/ims', 'alt="' . $alt . '"', $s, 1);
    DebugEcho($s); 
    DebugEcho('MWS ===> end mws_add_caption');
    return $s;
}

/* add the categories of the postie post to all attached images */
add_filter('postie_post_after', 'mws_postie_add_cats_to_images'); /* MWS now */

function mws_postie_add_cats_to_images( $post ) {
    $cats = $post['post_category'];
    $imgs = get_attached_media('image', $post['ID']);
    $flag = 0;
    foreach ($cats as $c) {
        /* DebugEcho( $c ); */
        $cat = get_category($c);
        /* DebugEcho( print_r($cat) ); */
        if ( $cat->cat_ID > 1 ) {
            foreach ( $imgs as $img ) {
                wp_set_post_categories( $img->ID, $cat->cat_ID, true );
            }
        }
        $flag = 1;
    }
    if ( $flag > 0 ) {
        wp_set_post_categories( $img->ID,  get_cat_ID('no_user'), true );
    }
    return $post;
}

function make_landscape_photos_large( $post ) {
    DebugEcho("make_landscape_photos_large 1  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" . $post['post_content'] . "\n");
    preg_match('/ postie_dunit (\d+)pxx(\d+)px /', $post['post_content'], $size);
    DebugEcho( print_r($size) );
    if ( $size[1] > $size[2] ) {
        DebugEcho( "Landscape\n" );
        #<!-- postie_dunit 750pxx422px --><!-- wp:image {"id":36954,"sizeSlug":"large","linkDestination":"media"} --><figure class="wp-block-image size-large"><a href="https://markus-spring.info/wp-content/uploads/sites/2/2021/03/Ripples-6.jpg"><img src="https://markus-spring.info/wp-content/uploads/sites/2/2021/03/Ripples-6-1200x675.jpg" alt="Ripples.jpg" class="wp-image-36954"/></a><figcaption>Saalachau, Bad Reichenhall</figcaption></figure><!-- /wp:image -->
        #
        # <!-- wp:image {"align":"wide","id":36936,"sizeSlug":"large","linkDestination":"media"} --><figure class="wp-block-image alignwide size-large">

        $post['post_content'] = preg_replace('/{/', '{"align":"wide",', $post['post_content']);
        $post['post_content'] = preg_replace('/wp-block-image /','wp-block-image alignwide ', $post['post_content']);
        $post['post_content'] = preg_replace('/<!-- postie_dunit.*? -->\n*/', '', $post['post_content']);
        DebugEcho($post['post_content']);
    }
    return $post;
}


/* add_filter('postie_post_after', 'mws_postie_rotate_ios_images');

function mws_postie_rotate_ios_images ( $post ) {
    $upload_dir = wp_upload_dir();
    foreach ( $iimgs as $iimg ) {
        $imagefile = $upload_dir['basedir'] . '/' .
                     wp_get_attachment_metadata( get_post_thumbnail_id( $post['ID'] ) )['file'];
        DebugEcho("1. Image to rotate: " .$imagefile);
        correctImageOrientation($imagefile);
    }
   } */

/* add_action('postie_file_added', 'mws_postie_fileadded', 10, 3); */ /* MWS now */

/* function mws_postie_fileadded($postid, $attachmentid, $file_array) {
   DebugEcho('MWS ========> begin mws_postie_fileadded');
   $fileinfo = wp_check_filetype(get_attached_file($attachmentid));
   $upload_dir = wp_upload_dir()['basedir'];
   $meta = wp_get_attachment_metadata( $attachmentid );
   $mimetype = $fileinfo['type'];
   if (strpos($mimetype, 'image', 0) === 0) { //only if attachment is an image
   $file = $upload_dir . '/' . $meta['file'];
   set_title_from_exif_if_necessary($postid, $file, $meta);
   $subdir = dirname($meta['file']);
   $deg = correctImageOrientation($file);
   foreach ( array_keys($meta['sizes']) as $size ) {
   if ( $size != 'full' ) {
   $file = $upload_dir . '/' . $subdir . '/' . $meta['sizes'][$size]['file'];
   correctImageOrientation($file);
   }
   }
   }
   DebugEcho('MWS ========> end mws_postie_fileadded');
   }
 */


?>
