<?php

/*-----------------------------------------------------------------------------------

TABLE OF CONTENTS

- Woo Helper Functions
-- woo_tumblog_image()
-- woo_tumblog_cleanSource()
-- woo_tumblog_embed()
-- woothemes_tumblog_uploader_custom_fields()

-----------------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------------*/
/* Woo Helper Functions  */
/*-----------------------------------------------------------------------------------*/
	

if (!(function_exists('woo_tumblog_image'))) {
	
	/*------------------------------------------------------------------------------------------------------*/
	/* NOTE - THIS VERSION OF woo_image() IS CUSTOMIZED AND NOT SWOPPABLE WITH THE VERSION IN WOOFRAMEWORK  */
	/*------------------------------------------------------------------------------------------------------*/
	
	/*-----------------------------------------------------------------------------------*/
	/* woo_tumblog_image - Get Image from custom field  */
	/*-----------------------------------------------------------------------------------*/

	/*
	This function gets the custom field image and uses thumb.php to resize it
	Parameters: 
        	$key = Custom field key eg. "image"
        	$width = Set width manually without using $type
        	$height = Set height manually without using $type
   	 	   	$class = CSS class to use on the img tag eg. "alignleft". Default is "thumbnail"
   	    	$quality = Enter a quality between 80-100. Default is 90
	        $id = Assign a custom ID, if alternative is required.
	        $link = Echo with image links ('src') or just echo as image ('img').
	        $repeat = Auto Img Function. Adjust amount of images to return for the post attachments.
	        $offset = Auto Img Function. Offset the $repeat with assigned amount of objects.
	        $before = Auto Img Function. Add Syntax before image output.
	        $after = Auto Img Function. Add Syntax after image output.
	        $single = Auto Img Function Only. Forces "img" return on images, like on single.php template
	        $force = Force smaller images to not be effected with image width and height dimentions (proportions fix)
	        $return = Return results instead of echoing out.
			$src = A parameter that accepts a img url for resizing. (No anchor)
			$auto_meta = Disables meta generated by the post_id. When src is used, this setting is automatically set to false.
			$meta = Add a custom meta text to the image and anchor of the image.
			$alignment = Crop alignment
	*/
	
	function woo_tumblog_image($args) {
		global $post;
		global $woo_options;
		
		//Defaults
		$key = 'image';
		$width = null;
		$height = null;
		$class = '';
		$quality = 90;
		$id = null;
		$link = 'src';
		$repeat = 1;
		$offset = 0;
		$before = '';
		$after = '';
		$single = false;
		$force = false;
		$return = false;
		$is_auto_image = false;
		$src = '';
		$auto_meta = true;
		$meta = '';
		$alignment = '';
		
		$alt = 'alt=""';
		$img_link = '';
		
		$attachment_id = array();
		$attachment_src = array();
		$thumb_id = get_post_meta($post->ID,'_thumbnail_id',true);
			
		if ( !is_array($args) ) 
			parse_str( $args, $args );
		
		extract($args);
		
	    // Set post ID
	    if ( empty($id) ) {
			$id = $post->ID;
	    }
	    
		// Set alignment 
		if ( $alignment == '') 
			$alignment = get_post_meta($id, '_image_alignment', $single = true);
	    
		if ( $src != '' ) { // When a custom image is sent through
			$custom_field = $src;
			$link = 'img';
			$auto_meta = false;
			
		} elseif ( get_option('woo_post_image_support') == 'true' AND !empty($thumb_id) ) {
		
			if(is_singular() && $single == false){
				$img_link = get_the_post_thumbnail($id,'single-post-thumbnail',array('class' => 'woo-image ' . $class));	
			} else if(is_singular() && $single == true){
				$img_link = get_the_post_thumbnail($id,array($width,NULL),array('class' => 'woo-image ' . $class));
			} else {
				if(!empty($width)){
					$img_link = get_the_post_thumbnail($id,array($width,NULL),array('class' => 'woo-image ' . $class));
				} else {
					$img_link = get_the_post_thumbnail($id,array(),array('class' => 'woo-image ' . $class));
				}
			}
		
		} else {
	    	$custom_field = get_post_meta($id, $key, true);
		} 
	
		if ( empty($custom_field) && get_option('woo_auto_img') == 'true' && empty($img_link) && !is_singular() ) { // Get the image from post attachments
	        
	        if( $offset >= 1 ) 
				$repeat = $repeat + $offset;
	    
	        $attachments = get_children( array(	'post_parent' => $id,
												'numberposts' => $repeat,
												'post_type' => 'attachment',
												'post_mime_type' => 'image',
												'order' => 'DESC', 
												'orderby' => 'menu_order date')
												);
	
			if ( !empty($attachments) ) { // Search for and get the post attachment
	       
				$counter = -1;
				$size = 'large';
				foreach ( $attachments as $att_id => $attachment ) {            
					$counter++;
					if ( $counter < $offset ) 
						continue;
				
					$src = wp_get_attachment_image_src($att_id, $size, true);
					$custom_field = $src[0];
					$is_auto_image = true;
					$attachment_id[] = $att_id;
					$src_arr[] = $custom_field;
				}
	
			} else { // Get the first img tag from content
	
				$first_img = '';
				$post = get_post($id); 
				ob_start();
				ob_end_clean();
				$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
				if ( !empty($matches[1][0]) )
					$custom_field = $matches[1][0];
	
			}
			
		} 
			
		// Return if there is no attachment or custom field set
		if ( empty($custom_field) && empty($img_link) ) {
			
			// Check if default placeholder image is uploaded
			$placeholder = get_option('framework_woo_default_image');
			if ( $placeholder )
				$custom_field = $placeholder;	
			else
		       return;
		
		}
		
		if(empty($src_arr) && empty($img_link)){ $src_arr[] = $custom_field; }
		
	    $output = '';
	
		// Get standard sizes
		if ( !$width && !$height ) {
			$width = '100';
			$height = '100';
		}
		
	    $set_width = ' width="' . $width .'" ';
	    $set_height = ' height="' . $height .'" '; 
	    
	    if($height == null OR $height == '')
	        $set_height = '';
			
		// Set standard class
		if ( $class )
			$class = 'woo-image ' . $class;
		else 
			$class = 'woo-image';
	
		// Do check to verify if images are smaller then specified.
		$force_all = get_option('woo_force_all');
		$force_single = get_option('woo_force_single');
		if($force == true OR $force_all == true OR ($force_single == true AND is_single())){  
			$set_width = '';
			$set_height = '';
		}
		// WordPress's the_post_thumbnail
		if(!empty($img_link)){
		
					
			if( $link == 'img' ) {  // Just output the image
				$output .= $before; 
				$output .= $img_link;
				$output .= $after;  
				
			} else {  // Default - output with link				
	
				if ( ( is_single() OR is_page() ) AND $single == false ) {
					$rel = 'rel="lightbox"';
					$href = false;  
				} else { 
					$href = get_permalink($id);
					$rel = '';
				}
				
				$title = 'title="' . get_the_title($id) .'"';
			
				$output .= $before; 
				if($href == false){
					$output .= $img_link;
				} else {
					$output .= '<a '.$title.' href="' . $href .'" '.$rel.'>' . $img_link . '</a>';
				}
				
				$output .= $after;  
			}	
		}
		elseif ( get_option('woo_resize') == 'true') { 
			
			foreach($src_arr as $key => $custom_field){
		
				// Clean the image URL
				$href = $custom_field; 		
				$custom_field = woo_tumblog_cleanSource( $custom_field );
	
				// Check if WPMU and set correct path AND that image isn't external
				if ( function_exists('get_current_site') && strpos($custom_field,"http://") !== 0 ) {
					get_current_site();
					//global $blog_id; Breaks with WP3 MS
					if ( !$blog_id ) {
						global $current_blog;
						$blog_id = $current_blog->blog_id;				
					}
					if ( isset($blog_id) && $blog_id > 0 ) {
						$imageParts = explode( 'files/', $custom_field );
						if ( isset($imageParts[1]) ) 
							$custom_field = '/blogs.dir/' . $blog_id . '/files/' . $imageParts[1];
					}
				}
				
				// Set alignment if any
				
			
				//Set the ID to the Attachent's ID if it is an attachment
				if($is_auto_image == true){	
					$quick_id = $attachment_id[$key];
				} else {
				 	$quick_id = $id;
				}
				
				if($auto_meta == true) {
					$alt = 'alt="'. get_the_title($quick_id) .'"';
					$title = 'title="'. get_the_title($quick_id) .'"';
				}
				elseif($auto_meta == false) {
					$alt = 'alt="'. $meta.'"';
					$title = 'title="'. $meta .'"';
				}
				else {
					$alt = 'alt=""';
					$title = '';
				}
				
				// Set alignment parameter
				if ($alignment <> '')
					$alignment = '&a='.$alignment;
					
				//CUSTOMIZATION FOR TUMBLOG PLUGIN	
				$pluginpath = dirname( __FILE__ );					
				$img_link = '<img src="'. get_bloginfo('stylesheet_directory') . '/admin/woo-tumblog/functions'. '/thumb.php?src='. $custom_field .'&amp;w='. $width .'&amp;h='. $height .'&amp;zc=1&amp;q='. $quality . $alignment . '" '.$alt.' class="'. stripslashes($class) .'" '. $set_width . $set_height . ' />';
				
				if( $link == 'img' ) {  // Just output the image
					$output .= $before; 
					$output .= $img_link;
					$output .= $after;  
					
				} else {  // Default - output with link				
	
					if ( ( is_single() OR is_page() ) AND $single == false ) {
						$rel = 'rel="lightbox"';
					} else { 
						$href = get_permalink($id);
						$rel = '';
					}
				
					$output .= $before; 
					$output .= '<a '.$title.' href="' . $href .'" '.$rel.'>' . $img_link . '</a>';
					$output .= $after;  
				}
			}
			
		} else {  // Not Resize
			
			foreach($src_arr as $key => $custom_field){
			
				//Set the ID to the Attachent's ID if it is an attachment
				if($is_auto_image == true){	
					$quick_id = $attachment_id[$key];
				} else {
				 	$quick_id = $id;
				}
				
				if($auto_meta == true) {
					$alt = 'alt="'. get_the_title($quick_id) .'"';
					$title = 'title="'. get_the_title($quick_id) .'"';
				}
				elseif($auto_meta == false) {
					$alt = 'alt="'. $meta.'"';
					$title = 'title="'. $meta .'"';
				}
				else {
					$alt = 'alt=""';
					$title = '';
				}
			
				$img_link =  '<img src="'. $custom_field .'" '. $alt .' '. $set_width . $set_height . ' class="'. stripslashes($class) .'" />';
			
				if ( $link == 'img' ) {  // Just output the image 
					$output .= $before;                   
					$output .= $img_link; 
					$output .= $after;  
					
				} else {  // Default - output with link
				
					if ( ( is_single() OR is_page() ) AND $single == false ) { 
						$href = $custom_field;
						$rel = 'rel="lightbox"';
					} else { 
						$href = get_permalink($id);
						$rel = '';
					}
					 
					$output .= $before;   
					$output .= '<a href="' . $href .'" '. $rel .'>' . $img_link . '</a>';
					$output .= $after;   
				}
			}
		}
		
		// Return or echo the output
		if ( $return == TRUE )
			return $output;
		else 
			echo $output; // Done  
	
	}
	
}

if (!(function_exists('woo_tumblog_cleanSource'))) {

	/*-----------------------------------------------------------------------------------*/
	/* Tidy up the image source url */
	/*-----------------------------------------------------------------------------------*/
	function woo_tumblog_cleanSource($src) {

		// remove slash from start of string
		if(strpos($src, "/") == 0) {
			$src = substr($src, -(strlen($src) - 1));
		}

		// Check if same domain so it doesn't strip external sites
		$host = str_replace('www.', '', $_SERVER['HTTP_HOST']);
		if ( !strpos($src,$host) )
			return $src;


		$regex = "/^((ht|f)tp(s|):\/\/)(www\.|)" . $host . "/i";
		$src = preg_replace ($regex, '', $src);
		$src = htmlentities ($src);
    
    	// remove slash from start of string
    	if (strpos($src, '/') === 0) {
    	    $src = substr ($src, -(strlen($src) - 1));
    	}
	
		return $src;
	}

}

if (!(function_exists('woo_tumblog_embed'))) {

	/*------------------------------------------------------------------------------------------------------*/
	/* NOTE - THIS VERSION OF woo_embed() IS CUSTOMIZED AND NOT SWOPPABLE WITH THE VERSION IN WOOFRAMEWORK  */
	/*------------------------------------------------------------------------------------------------------*/
	
	/*-----------------------------------------------------------------------------------*/
	/* woo_tumblog_embed - Get Video embed code from custom field */
	/*-----------------------------------------------------------------------------------*/
	
	/*
	Get Video
	This function gets the embed code from the custom field
	Parameters: 
	        $key = Custom field key eg. "embed"
	        $width = Set width manually without using $type
	        $height = Set height manually without using $type
			$class = Custom class to apply to wrapping div
			$id = ID from post to pull custom field from
	*/
	
	function woo_tumblog_embed($args) {
	
		//Defaults
		$key = 'embed';
		$width = null;
		$height = null;
		$class = 'video';
		$id = null;	
		
		if ( !is_array($args) ) 
			parse_str( $args, $args );
		
		extract($args);
	
	  	if(empty($id)) {
	    	global $post;
	    	$id = $post->ID;
	    } 
	    
	
		$custom_field = get_post_meta($id, $key, true);
	
		if ($custom_field) : 
	
	    	$org_width = $width;
	    	$org_height = $height;
	    
	    	// Get custom width and height
	    	$custom_width = get_post_meta($id, 'width', true);
	    	$custom_height = get_post_meta($id, 'height', true);    
	    
	    	//Dynamic Height Calculation
	    	if ($org_height == '' && $org_width != '') {
	    		$raw_values = explode(" ", $custom_field);
	    
	    		foreach ($raw_values as $raw) {
	    			$embed_params = explode("=",$raw);
	    			if ($embed_params[0] == 'width') {
	   			 		$embed_width = ereg_replace("[^0-9]", "", $embed_params[1]);
	    			}
	    			elseif ($embed_params[0] == 'height') {
	    				$embed_height = ereg_replace("[^0-9]", "", $embed_params[1]);
	    			} 
	    		}
	    
	    		$float_width = floatval($embed_width);
				$float_height = floatval($embed_height);
				$float_ratio = $float_height / $float_width;
				$calculated_height = intval($float_ratio * $width);
	    	}
	    
	    	// Set values: width="XXX", height="XXX"
	    	if ( !$custom_width ) $width = 'width="'.$width.'"'; else $width = 'width="'.$custom_width.'"';
	    	if ( $height == '' ) { $height = 'height="'.$calculated_height.'"'; } else { if ( !$custom_height ) { $height = 'height="'.$height.'"'; } else { $height = 'height="'.$custom_height.'"'; } }
	    	$custom_field = stripslashes($custom_field);
	    	$custom_field = preg_replace( '/width="([0-9]*)"/' , $width , $custom_field );
	    	$custom_field = preg_replace( '/height="([0-9]*)"/' , $height , $custom_field );    
	
	    	// Set values: width:XXXpx, height:XXXpx
	    	if ( !$custom_width ) $width = 'width:'.$org_width.'px'; else $width = 'width:'.$custom_width.'px';
	    	if (  $height == '' ) { $height = 'height:'.$calculated_height.'px'; } else { if ( !$custom_height ) { $height = 'height:'.$org_height.'px'; } else { $height = 'height:'.$custom_height.'px'; } }
	    	$custom_field = stripslashes($custom_field);
	    	$custom_field = preg_replace( '/width:([0-9]*)px/' , $width , $custom_field );
	    	$custom_field = preg_replace( '/height:([0-9]*)px/' , $height , $custom_field );     
	
			// Suckerfish menu hack
			$custom_field = str_replace('<embed ','<param name="wmode" value="transparent"></param><embed wmode="transparent" ',$custom_field);
	
			$output = '';
	    	$output .= '<div class="'. $class .'">' . $custom_field . '</div>';
	    
	    	return $output; 
		
		else :
	
			return false;
	    
		endif;
	
	}

}

/*-----------------------------------------------------------------------------------*/
// woothemes_uploader_custom_fields
/*-----------------------------------------------------------------------------------*/

function woothemes_tumblog_uploader_custom_fields($pID,$id,$std,$desc){

    // Start Uploader
    $upload = get_post_meta( $pID, $id, true);
	$href = woo_tumblog_cleanSource($upload);
	$uploader = '';
    $uploader .= '<input class="woo_input_text" name="'.$id.'" type="text" value="'.$upload.'" />';
    $uploader .= '<div class="clear"></div>'."\n";
    $uploader .= '<input type="file" name="attachement_'.$id.'" />';
    $uploader .= '<input type="submit" class="button button-highlighted" value="Save" name="save"/>';
    if ( $href ) 
		$uploader .= '<span class="woo_metabox_desc">'.$desc.'</span></td>'."\n".'<td class="woo_metabox_image"><a href="'. $upload .'"><img src="'.get_bloginfo('template_url').'/thumb.php?src='.$href.'&w=150&h=80&zc=1" alt="" /></a>';

	return $uploader;
}

?>