<?php
	/*
		Plugin Name: FaceThumb
		Plugin URI: http://www.mnt-tech.fr/blog/
		Description: The plugin allows your visitors to post thumbnails on your blog.
		Version: 0.0.4
		Author: MNT-Tech S.A.R.L.
		Author URI: http://www.mnt-tech.fr/
	*/
	
	$plugin_dir = basename(dirname(__FILE__));
	load_plugin_textdomain( 'facethumb', 'wp-content/plugins/' . $plugin_dir, $plugin_dir . '/languages' );

	function calculate_gallery($admin) {
		global $wpdb;
		$post = $wpdb->prefix . "posts";
		$plugin = $wpdb->prefix . "facethumb";
		$column = get_option( 'facethumb_column' );
		$line = get_option( 'facethumb_line' );
		$photo_per_page = $line * $column;
		$number_of_photo = $wpdb->get_var( "SELECT COUNT(*) FROM $plugin" );
		$number_of_page = ceil( $number_of_photo / $photo_per_page );  //ceil : entier supérieur
		if ( isset( $_GET['ppmnt']) AND $_GET['ppmnt'] != NULL AND $_GET['ppmnt'] > 0 AND $_GET['ppmnt'] <= $number_of_page ) {
			$number_of_current_page = $_GET['ppmnt'];
			$start = ( $photo_per_page * ( $number_of_current_page - 1 ) ) + 1;
		}
		else {
			$number_of_current_page = 1;
			$start = 1;
		}
		$stop = $number_of_current_page * $photo_per_page;
		$photo_to_display = $number_of_photo - ($start - 1);
		$display = '';
		if ( $number_of_photo == 0 ) {
			$display .= '<p>'. __('Sorry, no photos have been taken yet!', 'facethumb') .'</p><br/>';
		}
		elseif ( $photo_to_display < $photo_per_page ) {
			$stop_display = 1;   // Permet de ne pas afficher des cases vides dans le tableau, s'il n'y a pas assez de photo pour remplir la page
			if ( $admin == 1 AND $number_of_photo != 0) {
				$cible = str_replace( '%7E', '~', $_SERVER['REQUEST_URI']);
				$display .= '<form name="form1" method="post" action="'.$cible.'">';
				$display .= '<input type="hidden" name="delete_hidden" value="Y">';
				$display .= '<input type="hidden" name="start_hidden" value="'.$start.'">';
			}
			$display .= '<table>';
			for ( $line_count = 1; $line_count <= $line AND $photo_to_display >= $stop_display; $line_count++ ) {
				$display .= '<tr>';
				for ($compteur_colonne = 1; $compteur_colonne <= $column AND $photo_to_display >= $stop_display; $compteur_colonne++) {
					$display .= '<td>';
					$id_photo = $number_of_photo - $start;
					$current_photo = $wpdb->get_row( "SELECT * FROM $plugin ORDER BY id LIMIT $id_photo, 1" );
					while ( $current_photo->url == NULL AND $start <= $stop ) {  // Elimine les id des éléments supprimés de la BDD.
						$start ++;
						$current_photo = $wpdb->get_row( "SELECT * FROM $plugin ORDER BY id LIMIT $id_photo, 1" );
					}
					if ( (get_option('facethumb_link') == 'gallery' OR get_option('facethumb_link') == 'both') AND $current_photo->link != "none") {
						$display .= '<a href="' . htmlspecialchars($current_photo->link) . '">';
					}
					$display .= '<img src="' . htmlspecialchars($current_photo->url) . '" alt="' . htmlspecialchars($current_photo->name) . '" />';
					if ( (get_option('facethumb_link') == 'gallery' OR get_option('facethumb_link') == 'both') AND $current_photo->link != "none") {
						$display .= '</a>';
					}
					$timestamp = $current_photo->time;
					$display .= '<br/> '. __('the ', 'facethumb') . date( 'Y-m-d', $timestamp ). __(' at ','facethumb') .date( 'H:i', $timestamp ) . '<br/>'. __('by ', 'facethumb') . htmlspecialchars($current_photo->name);
					if ( $admin == 1) {	
						$display .= '<br/><input type="checkbox" name="delete_'.$current_photo->id.'" />';
					}
					$display .= '</td>';
					$start ++;
					$stop_display ++;
				}
				$display .= '</tr>';
			}
			$display .= '</table><br/>';
		}
		else {
			if ( $admin == 1 AND $number_of_photo != 0) {
				$cible = str_replace( '%7E', '~', $_SERVER['REQUEST_URI']);
				$display .= '<form name="form1" method="post" action="'.$cible.'">';
				$display .= '<input type="hidden" name="delete_hidden" value="Y">';
				$display .= '<input type="hidden" name="start_hidden" value="'.$start.'">';
			}
			$display .= '<table>';
			for ( $line_count = 1; $line_count <= $line; $line_count++ ) {
				$display .= '<tr>';
				for ($compteur_colonne = 1; $compteur_colonne <= $column; $compteur_colonne++) {
					$display .= '<td>';
					$id_photo = $number_of_photo - $start;
					$current_photo = $wpdb->get_row( "SELECT * FROM $plugin ORDER BY id LIMIT $id_photo, 1" );
					while ( $current_photo->url == NULL AND $start <= $stop ) {  // Elimine les id des éléments supprimés de la BDD.
						$start ++;
						$current_photo = $wpdb->get_row( "SELECT * FROM $plugin ORDER BY id LIMIT $id_photo, 1" );
					}
					if ( (get_option('facethumb_link') == 'gallery' OR get_option('facethumb_link') == 'both') AND $current_photo->link != "none") {
						$display .= '<a href="' . htmlspecialchars($current_photo->link) . '">';
					}
					$display .= '<img src="' . htmlspecialchars($current_photo->url) . '" alt="' . htmlspecialchars($current_photo->name) . '" />';
					if ( (get_option('facethumb_link') == 'gallery' OR get_option('facethumb_link') == 'both') AND $current_photo->link != "none") {
						$display .= '</a>';
					}
					$timestamp = $current_photo->time;
					$display .= '<br/> '. __('the ', 'facethumb') . date( 'Y-m-d', $timestamp ). __(' at ','facethumb') .date( 'H:i', $timestamp ) . '<br/>'. __('by ', 'facethumb') . htmlspecialchars($current_photo->name);
					if ( $admin == 1) {
						$display .= '<br/><input type="checkbox" name="delete_'.$current_photo->id.'" />';
					}
					$display .= '</td>';
					$start ++;
				}
				$display .= '</tr>';
			}
			$display .= '</table><br/>';
		}
		//  Affichage de la pagination
		$id_page = $wpdb->get_var( "SELECT ID FROM $post WHERE post_content='[FaceThumb WordPress MNTT]' AND post_title='FaceThumb Gallery'" );
		$start_float = $number_of_current_page - 2;
		$stop_float = $number_of_current_page + 2;
		if ( $start_float <= 0 ) {
			$start_float = 1;
		}
		if ( $stop_float > $number_of_page ) {
			$stop_float = $number_of_page;
		}
		if ( $admin == 1) {
			$url = get_bloginfo( 'url' ) . '/wp-admin/admin.php?page=manage-gallery';
		}
		else {
			$url = get_bloginfo( 'url' ). '/?page_id=' . $id_page;
		}
		if ( $start_float == 1 AND $stop_float == 1 ) {
			$display .= __('Pages', 'facethumb'). ' : 1';
		}
		elseif ( $start_float > 1 AND $stop_float < $number_of_page ) {
			$display .= __('Pages', 'facethumb').' : ';
			$display .= '<a href="' . $url . '&amp;ppmnt=1">1</a> ... ';
			for ( $i = $start_float; $i <= $number_of_current_page - 1; $i ++) {
				$display .= '<a href="' . $url . '&amp;ppmnt=' . $i . '">' . $i . '</a> ';
			}
			$display .= $i . ' ';
			for ( $i = $number_of_current_page + 1; $i <= $stop_float; $i ++) {
				$display .= '<a href="' . $url . '&amp;ppmnt=' . $i . '">' . $i . '</a> ';
			}
			$display .= '... <a href="' . $url . '&amp;ppmnt=' . $number_of_page . '">' . $number_of_page . '</a>';
		}
		elseif ( $start_float == 1 AND $stop_float == $number_of_page ) {
			$display .= __('Pages', 'facethumb').' : ';
			for ( $i = $start_float; $i <= $number_of_current_page - 1; $i ++) {
				$display .= '<a href="' . $url . '&amp;ppmnt=' . $i . '">' . $i . '</a> ';
			}
			$display .= $i . ' ';
			for ( $i = $number_of_current_page + 1; $i <= $stop_float; $i ++) {
				$display .= '<a href="' . $url . '&amp;ppmnt=' . $i . '">' . $i . '</a> ';
			}
		}
		elseif ( $start_float == 1 AND $stop_float != $number_of_page ) {
			$display .= __('Pages', 'facethumb').' : ';
			for ( $i = $start_float; $i <= $number_of_current_page - 1; $i ++) {
				$display .= '<a href="' . $url . '&amp;ppmnt=' . $i . '">' . $i . '</a> ';
			}
			$display .= $i . ' ';
			for ( $i = $number_of_current_page + 1; $i <= $stop_float; $i ++) {
				$display .= '<a href="' . $url . '&amp;ppmnt=' . $i . '">' . $i . '</a> ';
			}
			$display .= '... <a href="' . $url . '&amp;ppmnt=' . $number_of_page . '">' . $number_of_page . '</a>';
		}
		elseif ( $start_float != 1 AND $stop_float == $number_of_page ) {
			$display .= __('Pages', 'facethumb').' : ';
			$display .= '<a href="' . $url . '&amp;ppmnt=1">1</a> ... ';
			for ( $i = $start_float; $i <= $number_of_current_page - 1; $i ++) {
				$display .= '<a href="' . $url . '&amp;ppmnt=' . $i . '">' . $i . '</a> ';
			}
			$display .= $i . ' ';
			for ( $i = $number_of_current_page + 1; $i <= $stop_float; $i ++) {
				$display .= '<a href="' . $url . '&amp;ppmnt=' . $i . '">' . $i . '</a> ';
			}
		}
		// Fin de pagination
		
		if ( $admin == 1 AND $number_of_photo != 0) {	
			$display .= '<p class="submit">';
				$display .= '<input type="submit" name="Submit" value="' . __('Delete Thumbnails', 'facethumb') . '" />';
			$display .= '</p>';
			$display .= '</form>';
		}
				
		return $display;
	}
	
	
	add_action("widgets_init", array('FaceThumb', 'register'));
	register_activation_hook( __FILE__, array('FaceThumb', 'plugin_install'));

	class FaceThumb {
		function plugin_install(){
			global $wpdb;
			global $plugin_db_version;
			
			$table_name = $wpdb->prefix . "facethumb";
			if( $wpdb->get_var("show tables like '$table_name'") != $table_name ) {
				$sql1 = "CREATE TABLE " . $table_name . " (
					id mediumint(9) NOT NULL AUTO_INCREMENT,
					time bigint(11) DEFAULT '0' NOT NULL,
					name tinytext NOT NULL,
					url VARCHAR(100) NOT NULL,
					link VARCHAR(100) NOT NULL,
					UNIQUE KEY id (id)
				);";
				
				$wpdb->query($sql1);
				add_option("plugin_db_version", $plugin_db_version);
			}
			
			$post = $wpdb->prefix . "posts";
			$date = date( 'Y-m-d H:i:s' );
			$first_install = $wpdb->get_var( "SELECT ID FROM $post WHERE post_content='[FaceThumb WordPress MNTT]' AND post_title='FaceThumb Gallery'" );
			if ( !($first_install > 0) ) {
				$id = $wpdb->get_var( "SELECT ID FROM $post ORDER BY ID DESC LIMIT 0, 1" );
				$id ++;
				$adress = get_bloginfo('url') . '/?page_id=' . $id;
				$wpdb->query( "INSERT INTO $post VALUES ('$id', '1', '$date', '$date', '[FaceThumb WordPress MNTT]', 'FaceThumb Gallery', '','publish', 'closed', 'closed', '', 'facethumb-gallery', '', '', '$date', '$date' , '', '0', '$adress', '0', 'page', '', '0' )");	
				$time = time();
				$base = get_bloginfo('url') . '/wp-content/plugins/facethumb/uploads/mnt-tech.jpg';
				$wpdb->query( "INSERT INTO $table_name VALUES ('', '$time', 'MNT-Tech', '$base', 'http://www.mnt-tech.fr/blog/')" );
			}
			$options = $wpdb->prefix . "options";
			$is_set = $wpdb->get_var( "SELECT ID FROM $options WHERE option_name='facethumb_column'" );
			if ( !($is_set > 0) ) {
				$wpdb->query( "INSERT INTO $options VALUES ('', '0', 'facethumb_column', '3', 'yes')" );
				$wpdb->query( "INSERT INTO $options VALUES ('', '0', 'facethumb_line', '5', 'yes')" );
				$wpdb->query( "INSERT INTO $options VALUES ('', '0', 'facethumb_widget', 'last', 'yes')" );
			}
		}	
		
		function display_plugin($args) {
			global $wpdb;
			$table_name = $wpdb->prefix . "facethumb";
			$post = $wpdb->prefix . "posts";
			$url = get_bloginfo('url') . '/wp-content/plugins/facethumb/flash.php';
			$thumb_url = $wpdb->get_var( "SELECT guid FROM $post WHERE post_content='[FaceThumb WordPress MNTT]' AND post_title='FaceThumb Gallery'" );
			$facethumb_widget = get_option('facethumb_widget');
			if ( $facethumb_widget == 'random' ) {
				$number_of_photo = $wpdb->get_var( "SELECT COUNT(*) FROM $table_name" );
				$photo_number = rand(0, $number_of_photo-1);
			}
			else {
				$number_of_photo = $wpdb->get_var( "SELECT COUNT(*) FROM $table_name" );
				$photo_number = $number_of_photo - 1;
			}	
			$pic_info = $wpdb->get_row( "SELECT * FROM $table_name ORDER BY id LIMIT $photo_number, 1 " );
			echo $args['before_widget'];
			echo $args['before_title'] . '<a href="http://www.mnt-tech.fr/blog/tag/facethumb/" title="FaceThumb 0.0.4">FaceThumb</a>' . $args['after_title'];
			if ( $pic_info->url != NULL ) {
				if ( (get_option('facethumb_link') == 'widget' OR get_option('facethumb_link') == 'both') AND $pic_info->link != "none") {
					echo '<a href="' . htmlspecialchars($pic_info->link) . '" style="margin: auto;">';
				}
				echo '<img src="' . $pic_info->url . '" alt="' . htmlspecialchars($pic_info->name) . '" style="margin-left: 10px; margin-top: 10px;" />';
				if ( (get_option('facethumb_link') == 'widget' OR get_option('facethumb_link') == 'both') AND $pic_info->link != "none") {
					echo '</a>';
				}
				echo '<script language="Javascript">
				 <!--
				 function PopupCenter(page, width, height, options) {
				 	var top=(screen.height-height)/2;
				 	var left=(screen.width-width)/2;
				 	window.open(page,\'Take a Thumbnail\',\'top=\'+top+\',left=\'+left+\',width=\'+width+\',height=\'+height+\',\'+options);
				 }
				// -->
				</script>';
					echo '<ul style="margin-top: 0px"><li>' . htmlspecialchars($pic_info->name). '</li>
					
					<li><a href="#" onclick="PopupCenter(\'' . $url . '\', 500, 400, \'toolbar=no, menubar=no, location=no, status=no\');" >'.__('Take a Thumbnail', 'facethumb').'</a></li>
					<li><a href="'. $thumb_url. '">'.__('Thumb Gallery', 'facethumb').'</a></li>
					</ul>';
			}
			else {
				echo '<ul>
					<li><a href="#" onclick="PopupCenter(\'' . $url . '\', 500, 400, \'toolbar=no, menubar=no, location=no, status=no\');" >'.__('Take a Thumbnail', 'facethumb').'</a></li>
					<li><a href="'. $thumb_url . '">'.__('Thumb Gallery', 'facethumb').'</a></li>
					</ul>';
			}
			echo $args['after_widget'];
		}
		
		function register(){
			register_sidebar_widget('FaceThumb', array('FaceThumb', 'display_plugin'));
		}
	}
	
	// Panel Admin 
	
	function facethumb_menu() {
		add_menu_page('FaceThumb Options', 'FaceThumb', 10, __FILE__, 'facethumb_option');
		add_submenu_page(__FILE__,'FaceThumb Options',__('Options', 'facethumb'), 10, __FILE__,'facethumb_option');
		add_submenu_page(__FILE__,'Manage Gallery', __('Manage Gallery', 'facethumb'), 10, 'manage-gallery','manage_gallery');
	}
	
	add_action('admin_menu', 'facethumb_menu');
	
	function facethumb_option() {
		global $wpdb;
		
		$post = $wpdb->prefix . "posts";
		$opt_val = get_option('facethumb_column');
		$opt_val2 = get_option('facethumb_line');
		$opt_val3 = get_option('facethumb_widget');
		$opt_val4 = get_option('facethumb_link');

		if( $_POST[ 'submit_hidden' ] == 'Y' ) {
			function isInt($x) {  
				return(is_numeric($x) ? intval(0+$x) == $x : false);  
			} 
			
			if ( isInt($_POST['facethumb_column']) AND $_POST['facethumb_column'] > 0 AND isInt($_POST['facethumb_line']) AND $_POST['facethumb_line'] > 0 ) {
				$opt_val = $_POST['facethumb_column'];
				update_option('facethumb_column', $opt_val);
			
				$opt_val2 = $_POST['facethumb_line'];
				update_option('facethumb_line', $opt_val2);
				
				$opt_val3 = $_POST['facethumb_widget'];
				update_option('facethumb_widget', $opt_val3);
				
				$opt_val4 = $_POST['facethumb_link'];
				update_option('facethumb_link', $opt_val4);

				?>
				<div class="updated"><p><strong><?php _e('Option saved', 'facethumb'); ?></strong></p></div>
				<?php
			}
			else {
				?>
				<div class="updated"><p><strong><?php _e('Warning: Number of column and line are integer greater than 0.', 'facethumb'); ?></strong></p></div>
				<?php
			}
			
		}
		
    		echo '<div class="wrap">';
    		echo "<h2>" . __('FaceThumb Options', 'facethumb') . "</h2>";
    		?>

		<form name="form1" method="post" action="<?php echo str_replace( '%7E', '~', $_SERVER['REQUEST_URI']); ?>">
			<input type="hidden" name="submit_hidden" value="Y">
			
			<h3><?php _e('Gallery properties', 'facethumb'); ?></h3>

			<p>
				<label for="facethumb_column" /><?php _e('Number of column for the gallery:', 'facethumb'); ?></label>
				<input type="text" name="facethumb_column" id="facethumb_column" value="<?php echo $opt_val; ?>" size="10" />
			</p>
			
			<p>
				<label for="facethumb_line" /><?php _e('Number of line for the gallery:', 'facethumb'); ?></label>
				<input type="text" name="facethumb_line" id="facethumb_line" value="<?php echo $opt_val2; ?>" size="10" />
			</p>
			
			<h3><?php _e('Other Options', 'facethumb'); ?></h3>
			
			<p>
				<label for="facethumb_widget" /><?php _e('Photo to display in widget:', 'facethumb'); ?></label>
				<select name="facethumb_widget" id="facethumb_widget">
					<option value="last" <?php if($opt_val3 == "last") { echo 'selected="selected"'; } ?>><?php _e('The last one', 'facethumb'); ?></option>
					<option value="random" <?php if($opt_val3 == "random") { echo 'selected="selected"'; } ?>><?php _e('A random one', 'facethumb'); ?></option>
				</select>

			</p>
			
			<p>
				<label for="facethumb_link" /><?php _e('Display user\'s link with photos:', 'facethumb'); ?></label>
				<select name="facethumb_link" id="facethumb_link">
					<option value="gallery" <?php if($opt_val4 == "gallery") { echo 'selected="selected"'; } ?>><?php _e('Gallery', 'facethumb'); ?></option>
					<option value="widget" <?php if($opt_val4 == "widget") { echo 'selected="selected"'; } ?>><?php _e('Widget', 'facethumb'); ?></option>
					<option value="both" <?php if($opt_val4 == "both") { echo 'selected="selected"'; } ?>><?php _e('Both', 'facethumb'); ?></option>
					<option value="none" <?php if($opt_val4 == "none") { echo 'selected="selected"'; } ?>><?php _e('None', 'facethumb'); ?></option>
				</select>

			</p>

			<p class="submit">
				<input type="submit" name="Submit" value="<?php _e('Update Options', 'facethumb'); ?>" />
			</p>

		</form>
		</div>

		<?php

	}
	
	function manage_gallery() {
		global $wpdb;
		$plugin = $wpdb->prefix . "facethumb";
		if ( $_POST['delete_hidden'] == 'Y' ) {
			$startH = $_POST['start_hidden'] - 1; // les limit des BDD commencent à 0 donc on retire 1
			$number_of_photo = $wpdb->get_var( "SELECT COUNT(*) FROM $plugin" );
			$photo_per_page = get_option( 'facethumb_column' ) * get_option( 'facethumb_line' );
			if ( $number_of_photo < $photo_per_page ) {
				$stopH = $number_of_photo - 1;
			}
			else {
				$stopH = $startH + $photo_per_page - 1;  // les limit des BDD commencent à 0 donc 1 pour $photo_per_page (pour $startH c'est deja fait)
			}		// Attention les photos de la gallerie sont affichées dans l'ordre décroissant
			$idStartH = $wpdb->get_var( "SELECT id FROM $plugin ORDER BY id DESC LIMIT $startH, 1" );
			$idStopH = $wpdb->get_var( "SELECT id FROM $plugin ORDER BY id DESC LIMIT $stopH, 1" );
			$count = 0; 
			for ( $i = $idStopH; $i <= $idStartH; $i++ ) {   
				$dir = '../wp-content/plugins/facethumb/uploads/';
				if ( $i == 1 AND $_POST['delete_1'] ) {
					if(file_exists($dir.'mnt-tech.jpg')){
						if (unlink($dir.'mnt-tech.jpg')) {
							$wpdb->query( "DELETE FROM $plugin WHERE id='$i'" );
							$count++;
						}
					}
				}
				elseif ( $_POST['delete_'. $i] ) {
					$thumb_to_delete = $wpdb->get_row( "SELECT * FROM $plugin WHERE id='".$i."'" );
					if(file_exists($dir.$thumb_to_delete->time.'.jpg')){
						if (unlink($dir.$thumb_to_delete->time.'.jpg')) {
							$wpdb->query( "DELETE FROM $plugin WHERE id='$i'" );
							$count++;
						}
					} 
					else { 
						$wpdb->query( "DELETE FROM $plugin WHERE id='$i'" ); 
						$count++; 
					}
				}
			}	
		}
		echo '<div class="wrap">';
    		echo "<h2>" . __('Manage Gallery', 'facethumb') . "</h2>";
    		if ($count > 0) {
				echo '<div class="updated"><p><strong>' . $count . __(' thumbnail(s) deleted.', 'facethumb') . '</strong></p></div>';
			}	
		echo calculate_gallery(1);
		echo '</div>';
	}
	
	// Fin pannel Admin
	
	function public_display_gallery() {
		return calculate_gallery(0);
	}
	
	function modify_gallery_title($a) {
		if ( $a == 'FaceThumb Gallery' ) {
			return __('FaceThumb Gallery', 'facethumb');
		}
		else {
			return $a;
		}
	}
	
	function display_gallery () {
		add_filter('the_title', 'modify_gallery_title');
		if ( is_page('FaceThumb Gallery') ) {
			add_filter('the_content', 'public_display_gallery' );
		}
	}
	
	add_action( 'loop_start', 'display_gallery' );
	
	if ( isset( $_GET['name']) AND isset( $_GET['link']) AND isset( $_GET['url']) AND isset( $_GET['time'])) {
		global $wpdb;
		$table_name = $wpdb->prefix . "facethumb";
		$link = mysql_real_escape_string(htmlspecialchars($_GET['link']));
		$name = mysql_real_escape_string(htmlspecialchars($_GET['name']));
		$time = mysql_real_escape_string(htmlspecialchars($_GET['time']));
		$url = mysql_real_escape_string(htmlspecialchars($_GET['url']));
		$wpdb->query( "INSERT INTO $table_name VALUES ('', '$time', '$name', '$url', '$link')");
	}
	
?>
