Index: extensions/ConcoursPhoto/include/Concours.class.php
===================================================================
--- extensions/ConcoursPhoto/include/Concours.class.php	(revision 9370)
+++ extensions/ConcoursPhoto/include/Concours.class.php	(revision 32457)
@@ -12,26 +12,16 @@
 	var $concours_infos = array();
 	
-/*	var $create_date = null;
-	var $name = null;
-	var $descr = null;
-	var $begin_date = null;
-	var $end_date = null;
-	var $category = null;
-	var $groups = null;
-*/	
-
 	// General configuration parameters
 	var $my_config = array();
-/*
-	active_menubar
-	nbconcours_menubar
-*/
 	var $user_groups = array();
 	var $debug = false;
-	
-	// Class constructor with concours id. Return NULL if not existing or create it
-	function Concours($concours_id = null, $force_creation = NULL)
-	{
-//	    $this->get_user_groups();
+
+
+	/**
+	 * Class constructor with concours id. 
+	 * Return NULL if not existing or create it
+	 */
+	function __construct($concours_id = null, $force_creation = NULL) 
+	{
 		if ($concours_id !== null)
 		{		
@@ -44,28 +34,30 @@
 
 	
-	// Load general configuration from config_database
-	function load_config() 
-	{
-
-		$query = '
-		  SELECT value
-		  FROM '.CONFIG_TABLE.'
-		  WHERE param = \'concoursphoto\'
-		;';
-
+	/**
+	 * Load configuration from database
+	 * Assign value to the variable $config
+	 */
+	function load_config() {
+		$query = 'SELECT value FROM '.CONFIG_TABLE.' WHERE param="concoursphoto";';
 		$result = pwg_query($query);
 
-	    if($result) 
-		{
-		     $row = mysql_fetch_row($result);
-		     if(is_string($row[0])) 
-			 {
-		        $this->my_config = unserialize(($row[0]));
-		     }
+	    if(isset($result)) {
+			$row = pwg_db_fetch_row($result);
+			if(is_string($row[0])) {
+				$this->my_config = unserialize(($row[0]));
+			}
 	    }
-		$this->load_default_config();
-	}
-	
-	// Initialize default values of params
+	if ($this->debug)  
+	    foreach ($this->my_config as $key => $value) 
+		{
+		    echo "my_config[".$key."] = ".$value."\n";
+		}    
+	    $this->load_default_config();
+	}
+	
+	
+	/**
+	 * Load default configuration, initialize default values of params
+	 */
 	private function load_default_config()
 	{
@@ -96,4 +88,11 @@
 	}
 	
+	/**
+	 * Save the current configuration (ie the value of $config) to the database
+	 */
+	function set_config() {
+		conf_update_param('concoursphoto', pwg_db_real_escape_string(serialize($this->my_config)));
+	}
+	
 	
 	// Retrieve user groups 
@@ -101,25 +100,11 @@
 	{
 		global $user;
-if ($this->debug)
-foreach ($user as $id=>$val)
-{
-	if (is_array($val))
-		foreach ($val as $id2=>$val2)
-			echo "user[".$id."][".$id2."]=".$val2."\n";
-	else
-		echo "user[".$id."]=".$val."\n";
-}
-
 		$query = 'SELECT group_id FROM ' . USER_GROUP_TABLE . ' WHERE user_id = ' . $user['id'] . ';';
-if ($this->debug)		echo $query."\n";
+
 		$result = pwg_query($query);
-		while ($row = mysql_fetch_assoc($result))
+		while ($row = pwg_db_fetch_array($result))
 		{
 		  array_push($this->user_groups, $row['group_id']);
 		}
-		
-if ($this->debug)
-foreach ($this->user_groups as $gr)
-	echo "Group=".$gr."\n";
 
 	}
@@ -144,8 +129,9 @@
 			$result = pwg_query($query);
 			if ($result)
-				$this->concours_infos = mysql_fetch_assoc($result);
-		}
-
-	}
+				$this->concours_infos = pwg_db_fetch_array($result);
+		}
+
+	}
+
 
 	// save informations on database for a concours_id
@@ -165,5 +151,6 @@
 						`groups`,
 						`method`,
-						`guest`
+						`guest`,
+						`admin`
                         
 						)
@@ -172,5 +159,6 @@
 							\"".$this->concours_infos['begin_date']."\", \"".$this->concours_infos['end_date']."\", 
 							".$this->concours_infos['category'].", ".$this->concours_infos['groups'].",
-							".$this->concours_infos['method'].", ".($this->concours_infos['guest'] ? "TRUE" : "FALSE")."
+							".$this->concours_infos['method'].", ".($this->concours_infos['guest'] ? "TRUE" : "FALSE").",
+							".($this->concours_infos['admin'] ? "TRUE" : "FALSE")."
 							);";
 			if (pwg_query($query) != null)
@@ -199,5 +187,6 @@
 						groups = ".$this->concours_infos['groups'].",
 						method = ".$this->concours_infos['method'].",
-						guest = ".($this->concours_infos['guest'] ? "TRUE" : "FALSE")."
+						guest = ".($this->concours_infos['guest'] ? "TRUE" : "FALSE").",
+						admin = ".($this->concours_infos['admin'] ? "TRUE" : "FALSE")."
 						
 						WHERE id = ".($concours_id !== NULL ? $concours_id : $this->concours_id)."
@@ -245,6 +234,12 @@
 			$query = '
 				DELETE
-				FROM ' . CONCOURS_TABLE .' 
-				WHERE id =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
+				FROM ' . CONCOURS_RESULT_TABLE .' 
+				WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
+				';
+			pwg_query($query);
+			$query = '
+				DELETE
+				FROM ' . CONCOURS_DATA_TABLE .' 
+				WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
 				';
 			pwg_query($query);
@@ -257,18 +252,30 @@
 			$query = '
 				DELETE
-				FROM ' . CONCOURS_DATA_TABLE .' 
-				WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
+				FROM ' . CONCOURS_TABLE .' 
+				WHERE id =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
 				';
 			pwg_query($query);
-			$query = '
-				DELETE
-				FROM ' . CONCOURS_RESULT_TABLE .' 
-				WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
-				';
-			pwg_query($query);
 		}
 		else
 			return false;
 		
+	}
+
+	
+	// delete all closed concours from db 
+	function delete_allclosed_concours()
+	{
+		$concours_list=array();
+		$query = '
+			SELECT id
+			FROM ' . CONCOURS_TABLE .' 
+			WHERE time_to_sec(TIMEDIFF(now(), end_date)) > 0 
+			AND  id>0;';
+
+		$result = pwg_query($query);
+		while ($row = pwg_db_fetch_assoc($result))
+		{
+			$this->delete_concours($row['id']);
+		}
 	}
 
@@ -288,5 +295,4 @@
 
 			$result = pwg_query($query);
-if ($this->debug) echo $query."\n";
 			if ($result != NULL)
 				return true;
@@ -311,5 +317,4 @@
 
 			$result = pwg_query($query);
-if ($this->debug) echo $query."\n";
 			if ($result != NULL)
 				return true;
@@ -321,5 +326,25 @@
 	}
 
-
+	// Get high value of concours (max score for each criterias)
+	function get_MaxScore_concours($concours_id = null)
+	{
+		$max = 0;
+		$query = '
+			SELECT criteria_id, max_value, ponderation, uppercriteria
+			FROM ' . CONCOURS_DETAIL_TABLE .' 
+			WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
+			ORDER BY criteria_id
+			';
+		$result = pwg_query($query);
+		while ($row = pwg_db_fetch_array($result))
+		{
+			if ($row['uppercriteria'] != NULL || !$this->is_criterias_contains_sub($row['criteria_id'])) // subcriteria or uppercriteria without sub
+				$max += $row['max_value']*$row['ponderation'];
+		}
+		return $max;
+
+
+	}	
+	
 	// Get criterias that are stored on db for default mode (concours_id = 0)
 	function get_default_criterias()
@@ -328,9 +353,9 @@
 		$query = 'SELECT IF(MAX(id)+1 IS NULL, 1, MAX(id)+1) AS next_element_id
 					FROM ' . CONCOURS_DETAIL_TABLE . ' ;';
-		list($next_element_id) = mysql_fetch_array(pwg_query($query));
+		list($next_element_id) = pwg_db_fetch_array(pwg_query($query));
 
 		foreach ($criterias as $criteria)
 		{		
-if ($this->debug)			echo "NEXT =".$next_element_id."\n";
+			
 			$query = 'INSERT INTO '.CONCOURS_DETAIL_TABLE.'
 						(id, id_concours, criteria_id, name, descr, min_value, max_value, ponderation, uppercriteria)'
@@ -343,5 +368,5 @@
 			
 				$result = pwg_query($query);
-if ($this->debug)	echo $query;			
+
 			$next_element_id = $next_element_id +1;
 		}
@@ -361,6 +386,5 @@
 				';
 			$result = pwg_query($query);
-if ($this->debug) echo $query."\n";
-			while ($row = mysql_fetch_assoc($result))
+			while ($row = pwg_db_fetch_array($result))
 			{
 				array_push($criteria_list, $row);
@@ -386,10 +410,7 @@
 				';
 			$result = pwg_query($query);
-if ($this->debug) echo $query."\n";
-			while ($row = mysql_fetch_assoc($result))
-			{
-if ($this->debug)			echo "criteria_id=".$row['criteria_id']."\n";
+			
+			while ($row = pwg_db_fetch_array($result))
 				array_push($criteria_list, $row);
-			}
 			return $criteria_list;
 		}
@@ -410,7 +431,5 @@
 				';
 			$result = pwg_query($query);
-if ($this->debug) echo $query."\n";
-			// mini 1 line 
-			if(mysql_fetch_assoc($result))
+			if(pwg_db_fetch_array($result))
 				return true;
 			else
@@ -435,6 +454,5 @@
 				';
 			$result = pwg_query($query);
-if ($this->debug) echo $query."\n";
-			while ($row = mysql_fetch_assoc($result))
+			while ($row = pwg_db_fetch_array($result))
 			{
 				array_push($criteria_list, $row);
@@ -460,11 +478,6 @@
 				';
 			$result = pwg_query($query);
-	if ($this->debug) echo $query."\n";
-            $criteria = mysql_fetch_assoc($result);
-	/*		while ($row = mysql_fetch_assoc($result))
-			{
-				array_push($criteria, $row);
-			}
-*/		
+			
+            $criteria = pwg_db_fetch_array($result);
 		}
 		return $criteria;
@@ -483,12 +496,7 @@
 			';
 		$result = pwg_query($query);
-if ($this->debug) echo $query."\n";
-$criteria = mysql_fetch_assoc($result);
-/*		while ($row = mysql_fetch_assoc($result))
-		{
-			array_push($criteria, $row);
-		}
-*/		
-	return $criteria;
+		
+		$criteria = pwg_db_fetch_array($result);
+		return $criteria;
 	
 	}
@@ -504,9 +512,10 @@
 			$query = 'SELECT IF(MAX(id)+1 IS NULL, 1, MAX(id)+1) AS next_element_id
 						FROM ' . CONCOURS_DETAIL_TABLE . ' ;';
-			list($next_element_id) = mysql_fetch_array(pwg_query($query));
+			list($next_element_id) = pwg_db_fetch_array(pwg_query($query));
+
 			$query = 'SELECT IF(MAX(criteria_id)+1 IS NULL, 1, MAX(criteria_id)+1) AS next_criteria_id
 						FROM ' . CONCOURS_DETAIL_TABLE . '
 					  WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id ) . ' ;';
-			list($next_criteria_id) = mysql_fetch_array(pwg_query($query));
+			list($next_criteria_id) = pwg_db_fetch_array(pwg_query($query));
 			
 			$query = '
@@ -553,7 +562,4 @@
 
 			pwg_query($query);
-
-			if ($this->debug) echo $query."\n";
-
 		}		
 	}
@@ -573,5 +579,5 @@
 				';
 			$result = pwg_query($query);
-	if ($this->debug) echo $query."\n";
+			
 			if($result)
 				return true;
@@ -594,5 +600,4 @@
 			';
 		$result = pwg_query($query);
-if ($this->debug) echo $query."\n";
 
 	}	
@@ -608,5 +613,5 @@
 		$result = pwg_query($query);
 		// For each images
-		if (mysql_fetch_assoc($result))
+		if (pwg_db_fetch_array($result))
 			return true;
 		else
@@ -614,4 +619,7 @@
 	
 	}
+	
+
+
 	
 	// function to return the number of votes for a concours by images
@@ -628,5 +636,5 @@
 		$result = pwg_query($query);
 		$nbvotes = array();
-		while ($row = mysql_fetch_assoc($result))
+		while ($row = pwg_db_fetch_array($result))
 		{
 			$nbvotes[$row['img_id']] = $row['NBVOTE'];
@@ -634,5 +642,5 @@
         
         // Add guest infos
-        $query = 'SELECT img_id, COUNT(DISTINCT user_id, ipguest) AS NBVOTE FROM ' . CONCOURS_DATA_TABLE 
+        $query = 'SELECT img_id, COUNT(DISTINCT ipguest) AS NBVOTE FROM ' . CONCOURS_DATA_TABLE 
         .' WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id )
         .' AND ipguest IS NOT NULL'
@@ -641,17 +649,46 @@
                 
         $result = pwg_query($query);
-    if ($this->debug)		echo "NBVOTE = ".$query."\n";
-        while ($row = mysql_fetch_assoc($result))
+        while ($row = pwg_db_fetch_array($result))
+	
             if (!isset($nbvotes[$row['img_id']]))
                 $nbvotes[$row['img_id']] = $row['NBVOTE'];
             else
                 $nbvotes[$row['img_id']] += $row['NBVOTE'];
-        
+			
 		return $nbvotes;
 	}
 
+	
+	
+	// Get All user that are vote  for guest who have vote (IP Stores in db) in a concours
+	function get_user_list($concours_id = NULL)
+	{
+		global $conf;
+        $userid = array();
+		if ($concours_id!== null or $this->concours_id !== null)
+		{
+			$query = '
+				SELECT distinct(user_id)
+				FROM ' . CONCOURS_DATA_TABLE .' 
+				WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
+                AND ipguest IS  NULL
+				AND user_id !='.$conf['guest_id']
+
+				.' ORDER BY user_id
+				';
+			$result = pwg_query($query);
+			while ($row = pwg_db_fetch_array($result))
+			{
+				array_push($userid, $row['user_id']);
+			}
+		}
+		return $userid;
+	}
+	
+	
 	// Get All iaddr for guest who have vote (IP Stores in db) in a concours
 	function get_guest_list($concours_id = NULL)
 	{
+		global $conf;
         $ipguest = array();
 		if ($concours_id!== null or $this->concours_id !== null)
@@ -660,11 +697,11 @@
 				SELECT distinct(ipguest)
 				FROM ' . CONCOURS_DATA_TABLE .' 
-				WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
-                AND ipguest IS NOT NULL
+				WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id )
+                .' AND user_id = '.$conf['guest_id']
+                .' AND ipguest IS NOT NULL
 				ORDER BY ipguest
 				';
 			$result = pwg_query($query);
-if ($this->debug) echo $query."\n";
-			while ($row = mysql_fetch_assoc($result))
+			while ($row = pwg_db_fetch_array($result))
 			{
 				array_push($ipguest, $row['ipguest']);
@@ -689,4 +726,13 @@
 		// var which contains id=img_id and val =global note
 		$global_note = array();
+		// FOR MODERATION
+		// var which contains id=user_id and val =global note
+		$vote_by_user = array();
+		$amplitiudeMINmax = 999; // MIN of all max score (for each users)
+		$amplitiudeMAXmin = -999; // MIN of all max score (for each users)
+		$REFaverage = 0; 	// reference average (average between amplitiudeMINmax and amplitiudeMAXmin)
+		$global_note_mod1 = array();
+		$global_note_mod2 = array();
+		
 		if ($concours_id!== null or $this->concours_id !== null)
 		{
@@ -698,4 +744,5 @@
 				$nbvotes = $this->nb_votes_by_img($concours_id);
 				
+		
 				$user_id = array();
 				// vars not initialized
@@ -703,7 +750,5 @@
 					$this->get_concours();
 				$category = $this->concours_infos['category'];
-
-if ($this->debug)
-	echo "CAT=".$category;
+				
 				// Get all user_id from a concours
 				$query = 'SELECT DISTINCT user_id'
@@ -713,21 +758,17 @@
 				.';';
 				$result = pwg_query($query);
-if ($this->debug)
-echo $query;
-				while ($row = mysql_fetch_assoc($result))
+
+				while ($row = pwg_db_fetch_array($result))
 					array_push($user_id, $row['user_id']);
 
                 // Add guest info is present
                 $ipguest = array();
-                if ($concours_id!== null)
+                if ($concours_id!== null or $this->concours_id !== null)
+				{
+					if ($this->debug)
+						echo "Check IPGUEST";
                     $ipguest = $this->get_guest_list(($concours_id !== null ? $concours_id : $this->concours_id ));
-
-if ($this->debug)
-{
-	foreach ($user_id as $userid)
-			echo "USER = ".$userid;
-	foreach ($ipguest as $userid)
-			echo "IPGUEST = ".$userid;
-}				
+				}
+
 				
 				// recover all img_id from the category
@@ -736,39 +777,206 @@
 				.' WHERE category_id = '.$category.';';
 				
+				$nb_image_concours = 0;
 				$result = pwg_query($query);
 				// For each images
-				while ($row = mysql_fetch_assoc($result))
+				while ($row = pwg_db_fetch_array($result))
 				{
-		if ($this->debug)	echo "IMG_ID=".$row['image_id']."\n";
+					$nb_image_concours++;
+		
 					foreach ($user_id as $i => $userid)
 					{
+						$img_note_user = $this->get_img_globalnote_user($row['image_id'], null, $userid);
+						
 						if (!isset($global_note[$row['image_id']]))
 							$global_note[$row['image_id']] = 0;
-						$global_note[$row['image_id']] +=  $this->get_img_globalnote_user($row['image_id'], null, $userid);			
+					// FOR MODERATION
+					// store the nb of vote for each user
+						if ($img_note_user >= 0) // user has made a vote
+						{
+							if (!isset($vote_by_user[$userid]['nbvote']))
+								$vote_by_user[$userid]['nbvote'] = 0;
+							
+							$vote_by_user[$userid]['nbvote'] ++;	// update vote counter
+						
+							$global_note[$row['image_id']] +=  $img_note_user	;		
+						
+
+						// FOR MODERATION
+							// store the total of note for the same user
+							if (!isset($vote_by_user[$userid]['totalvote']))
+								$vote_by_user[$userid]['totalvote'] = 0;
+							$vote_by_user[$userid]['totalvote'] +=  $img_note_user;
+							// FOR MODERATION
+							// store min/max for each user
+							if (!isset($vote_by_user[$userid]['min'])) 	$vote_by_user[$userid]['min'] = 999;
+							if (!isset($vote_by_user[$userid]['max'])) 	$vote_by_user[$userid]['max'] = 0;
+							
+							
+							if ($vote_by_user[$userid]['min'] > $img_note_user) $vote_by_user[$userid]['min'] = $img_note_user;
+							if ($vote_by_user[$userid]['max'] < $img_note_user) $vote_by_user[$userid]['max'] = $img_note_user;
+						}						
+					
 					}
                     // Add guest scores if present
-					foreach ($ipguest as $i => $ipguestt)
+					foreach ($ipguest as $i => $userid)
 					{
+						
+						$img_note_user = $this->get_img_globalnote_user($row['image_id'], null, null, $userid);	// $userid contains the ip address for the guest!
 						if (!isset($global_note[$row['image_id']]))
 							$global_note[$row['image_id']] = 0;
-						$global_note[$row['image_id']] +=  $this->get_img_globalnote_user($row['image_id'], null, null, $ipguestt);			
+
+					// FOR MODERATION
+					// store the nb of vote for each guest (with ipaddr)
+						if ($img_note_user >= 0) // user has made a vote
+						{
+							if (!isset($vote_by_user[$userid]['nbvote']))
+								$vote_by_user[$userid]['nbvote'] = 0;
+							
+							$vote_by_user[$userid]['nbvote'] ++;	// update vote counter
+						
+							$global_note[$row['image_id']] +=  $img_note_user	;		
+						
+
+						// FOR MODERATION
+							// store the total of note for the same user
+							if (!isset($vote_by_user[$userid]['totalvote']))
+								$vote_by_user[$userid]['totalvote'] = 0;
+							$vote_by_user[$userid]['totalvote'] +=  $img_note_user;
+							// FOR MODERATION
+							// store min/max for each user
+							if (!isset($vote_by_user[$userid]['min'])) 	$vote_by_user[$userid]['min'] = 999;
+							if (!isset($vote_by_user[$userid]['max'])) 	$vote_by_user[$userid]['max'] = 0;
+							
+							
+							if ($vote_by_user[$userid]['min'] > $img_note_user) $vote_by_user[$userid]['min'] = $img_note_user;
+							if ($vote_by_user[$userid]['max'] < $img_note_user) $vote_by_user[$userid]['max'] = $img_note_user;
+						}						
+
 					}
 				}
-				if ($this->debug)
+
+				// FOR MODERATION
+				// calcul the average by user and min/max global
+				foreach ($user_id as $i => $userid)
 				{
-					foreach ($global_note as $id => $val)
-						echo "Note img ( ".$id.") = ".$val."\n";
+					$vote_by_user[$userid]['average'] = $vote_by_user[$userid]['totalvote']/$vote_by_user[$userid]['nbvote'];
+					$vote_by_user[$userid]['lowerAmp'] = $vote_by_user[$userid]['min'];
+					// calcul the max value of the concours (for the moderation)
+					$vote_by_user[$userid]['upperAmp'] = $this->get_MaxScore_concours() - $vote_by_user[$userid]['max'];
+					
+					$vote_by_user[$userid]['minLevel'] = $vote_by_user[$userid]['average'] - $vote_by_user[$userid]['lowerAmp'];
+					$vote_by_user[$userid]['maxLevel'] = $vote_by_user[$userid]['average'] + $vote_by_user[$userid]['upperAmp'];
+					if ($amplitiudeMINmax > $vote_by_user[$userid]['maxLevel']) $amplitiudeMINmax = $vote_by_user[$userid]['maxLevel'];
+					if ($amplitiudeMAXmin < $vote_by_user[$userid]['minLevel']) $amplitiudeMAXmin = $vote_by_user[$userid]['minLevel'];				
 				}
+
+				// calcul the average by guest and min/max global
+				foreach ($ipguest as $i => $userid)
+				{
+					$vote_by_user[$userid]['average'] = $vote_by_user[$userid]['totalvote']/$vote_by_user[$userid]['nbvote'];
+					$vote_by_user[$userid]['lowerAmp'] = $vote_by_user[$userid]['min'];
+					// calcul the max value of the concours (for the moderation)
+					$vote_by_user[$userid]['upperAmp'] = $this->get_MaxScore_concours() - $vote_by_user[$userid]['max'];
+					
+					$vote_by_user[$userid]['minLevel'] = $vote_by_user[$userid]['average'] - $vote_by_user[$userid]['lowerAmp'];
+					$vote_by_user[$userid]['maxLevel'] = $vote_by_user[$userid]['average'] + $vote_by_user[$userid]['upperAmp'];
+					if ($amplitiudeMINmax > $vote_by_user[$userid]['maxLevel']) $amplitiudeMINmax = $vote_by_user[$userid]['maxLevel'];
+					if ($amplitiudeMAXmin < $vote_by_user[$userid]['minLevel']) $amplitiudeMAXmin = $vote_by_user[$userid]['minLevel'];				
+
+				}
+
+
+				// FOR MODERATION
+				// calcul the reference average 
+				$calcultemp = (int)($amplitiudeMINmax+$amplitiudeMAXmin)/2+0.5;
+				if ((int)(($amplitiudeMINmax+$amplitiudeMAXmin)/2+0.5) > $amplitiudeMAXmin)
+				{
+					if ((int)(($amplitiudeMINmax+$amplitiudeMAXmin)/2+0.5) < $amplitiudeMINmax)
+						$REFaverage = (int)(($amplitiudeMINmax+$amplitiudeMAXmin)/2+0.5);
+					else
+						$REFaverage = $amplitiudeMINmax;
+				}
+				else
+					$REFaverage = $amplitiudeMAXmin;
+				
+					
+				// FOR MODERATION
+				// calcul the moderation scopr for each users
+				foreach ($user_id as $i => $userid)
+					$vote_by_user[$userid]['moderation'] = $REFaverage - $vote_by_user[$userid]['average'];
+
+				// FOR MODERATION
+				// calcul the moderation scopr for each guest ($ipguest)
+				foreach ($ipguest as $i => $userid)
+					$vote_by_user[$userid]['moderation'] = $REFaverage - $vote_by_user[$userid]['average'];
+					
+				// FOR MODERATION
+				// need to parse again image for new calcul with moderation
+				// moderation 1 => For each photo without note (user = author or user != author but no vote) add each user avaerage to the total of note and calcul the average 
+				// moderation 2 => For each photo with note, adapt/change all the value with the moderation value : user note + moderation. 
+
+				// parse again all img_id from the category
+				$query = 'SELECT DISTINCT(image_id)'
+				.' FROM ' .IMAGE_CATEGORY_TABLE
+				.' WHERE category_id = '.$category.';';
+				
+				$result = pwg_query($query);
+				// For each images
+				while ($row = pwg_db_fetch_array($result))
+				{
+					// for each user
+					foreach ($user_id as $i => $userid)
+					{
+						if (!isset($global_note_mod1[$row['image_id']]))
+							$global_note_mod1[$row['image_id']] = 0;
+						$globalnote_user = $this->get_img_globalnote_user($row['image_id'], null, $userid, null, 1, $vote_by_user[$userid]['average']);
+
+						$global_note_mod1[$row['image_id']] += ($globalnote_user >= 0 ? $globalnote_user : 0) 	;
+
+						if (!isset($global_note_mod2[$row['image_id']]))
+							$global_note_mod2[$row['image_id']] = 0;
+						$globalnote_user = $this->get_img_globalnote_user($row['image_id'], null, $userid, null, 2, $vote_by_user[$userid]['moderation']);
+
+						$global_note_mod2[$row['image_id']] +=  ($globalnote_user >= 0 ? $globalnote_user : 0) 	;		
+					}
+					
+					// for each guest
+					foreach ($ipguest as $i => $userid)
+					{
+						if (!isset($global_note_mod1[$row['image_id']]))
+							$global_note_mod1[$row['image_id']] = 0;
+						$globalnote_user = $this->get_img_globalnote_user($row['image_id'], null, null, $userid, 1, $vote_by_user[$userid]['average']);	// userid contains the ip addr for the guest
+
+						$global_note_mod1[$row['image_id']] += ($globalnote_user >= 0 ? $globalnote_user : 0) 	;
+
+						if (!isset($global_note_mod2[$row['image_id']]))
+							$global_note_mod2[$row['image_id']] = 0;
+						$globalnote_user = $this->get_img_globalnote_user($row['image_id'], null, null, $userid, 2, $vote_by_user[$userid]['moderation']);
+
+						$global_note_mod2[$row['image_id']] +=  ($globalnote_user >= 0 ? $globalnote_user : 0) 	;		
+					}
+
+					
+				}
+					
 				
 				// update database and store result into RESULT table
 				// note = global note
 				$IMGmoyenne = 0;
+				$IMGmoyenneModeration1 = 0;
+				$IMGmoyenneModeration2 = 0;
+				
 				foreach ($global_note as $id => $val)
 				// id contains the image id
 				{
-if ($this->debug)		echo $nbvotes[$id];
 					$IMGmoyenne = (isset($nbvotes[$id]) && $nbvotes[$id] != 0 ? $val/$nbvotes[$id] : 0);
+					// Moderation
+
+					$IMGmoyenneModeration1 = ($nb_image_concours != 0 ? $global_note_mod1[$id]/$this->nb_user_by_concours() : 0);	// all photos have note 
+					$IMGmoyenneModeration2 = (isset($nbvotes[$id]) && $nbvotes[$id] != 0 ? $global_note_mod2[$id]/$nbvotes[$id] : 0);	// only voted photos are used
 					
-					$query = 'INSERT INTO  ' . CONCOURS_RESULT_TABLE .'(`id_concours`, `img_id`, `date` , `note`, `moyenne`, `nbvotant` )
+					$query = 'INSERT INTO  ' . CONCOURS_RESULT_TABLE .'(`id_concours`, `img_id`, `date` , `note`, `moyenne`, 
+					`moderation1`, `moderation2`,
+					`nbvotant` )
 							VALUES ('.($concours_id !== null ? $concours_id : $this->concours_id )
 									 .', '.$id 
@@ -776,14 +984,11 @@
 									 .', '.$val
 									 .', '.$IMGmoyenne
+									 .', '.$IMGmoyenneModeration1
+									 .', '.$IMGmoyenneModeration2
 									 .', '.(isset($nbvotes[$id]) ? $nbvotes[$id] : 0)
 									 .');';
-				$result = pwg_query($query);
-						 
+				$result = pwg_query($query);	 
 					
 				}
-            
-				
-
-				
 			}
 			else
@@ -794,11 +999,45 @@
 	}
 	
-
-	// Check if an image's author is the same as the actual user 
+	
+	// Get array with nb of vote for each user of a concours_id
+	function nb_user_by_concours($concours_id = NULL)
+	{
+		$nbusertotal = 0;
+		// user 
+		$query = 'SELECT count(distinct(user_id)) as nb_user FROM ' . CONCOURS_DATA_TABLE .'
+				WHERE id_concours =' . ($concours_id !== NULL ? $concours_id : $this->concours_id).'
+				AND ipguest IS NULL
+			  ;';
+		$result = pwg_query($query);
+		if ($result)
+		{
+			$row = pwg_db_fetch_array($result);
+			$nbusertotal += $row['nb_user'];
+		}
+		// guest
+		$query = 'SELECT count(distinct(ipguest)) as nb_user FROM ' . CONCOURS_DATA_TABLE .'
+				WHERE id_concours =' . ($concours_id !== NULL ? $concours_id : $this->concours_id).'
+				AND ipguest IS NOT NULL
+			  ;';
+		$result = pwg_query($query);
+		if ($result)
+		{
+			$row = pwg_db_fetch_array($result);
+			$nbusertotal +=  $row['nb_user'];
+		}
+		return $nbusertotal;
+		
+	}
+	
+	
+	// Check if an image's author OR addebBy is the same as the actual user
+	// depending the config param 
 	function check_img_user($img_id)
 	{
 		global $user;
+
+
 		$query = '
-			SELECT author
+			SELECT author, added_by
 			FROM ' . IMAGES_TABLE .' 
 			WHERE id =' . $img_id . '
@@ -809,13 +1048,68 @@
 		if ($result)
 		{
-			$row = mysql_fetch_assoc($result);
+			$row = pwg_db_fetch_array($result);
 			$authorid = get_userid($row['author']);
-			if ($authorid and ($authorid == $user['id']))
-				return true;
-			else
-				return false;
+			$addedbyid = $row['added_by'];
+
+			switch ($this->my_config['author_vote_available'])
+			{
+			
+				case 0 : // no check (allow to vote for all photos)
+					return false;
+					
+				case 1 : // check between author and user
+					if ($authorid)	// Author name present as username
+					{
+						if ($authorid == $user['id'])
+							return true;
+						else
+							return false;
+					}
+					else
+					{
+						// check if author name = user name 
+						$AuthorArray = strip_punctuation2($row['author']);
+						$UserArray = strip_punctuation2($user['username']);
+						// Patch if author is empty
+						if (empty($AuthorArray))
+							return false;
+				
+						if (count(array_intersect($AuthorArray, $UserArray)) == count ($AuthorArray)) // found 				
+							return true;
+						else
+							return false;
+					}
+	
+					
+				case 2 : // check between author and user
+					if (isset($addedbyid) AND $addedbyid == $user['id'])
+						return true;
+					else
+						return false;
+				case 3 : // check between author OR addedby and user
+					// Check Author 
+					if ($authorid AND $authorid == $user['id'])	// Author name present as username
+							return true;
+					else
+					{
+						// check if author name = user name 
+						$AuthorArray = strip_punctuation2($row['author']);
+						$UserArray = strip_punctuation2($user['username']);								
+						if (empty($AuthorArray) AND (count(array_intersect($AuthorArray, $UserArray)) == count ($AuthorArray))) // found 				
+							return true;
+					}			
+					// check addebBy
+					if (isset($addedbyid) AND $addedbyid == $user['id'])
+						return true;
+	
+					return false;
+
+				default :
+					return false;
+				
+			}
+
 		}
 		return false;
-	
 	}
 	
@@ -826,5 +1120,5 @@
 		// Step0 : if user = guest, check the concours param and store ip address to user name.
 		// Step1 : concours is defined to this category AND concours is open AND user is authorized to access to this category (thru group)
-		// Step1 bis : dont show concours if img_author = user_id
+		// Step1 bis : dont show concours if check author or added_by id is the samie as used_id (depending the param)
 		// Step 2 : Recover stored informations in db for this user
 		// Step 3 : Complete tpl information
@@ -839,58 +1133,23 @@
 
         // STEP 0 
-if ($this->debug)	echo "STEP0\n";
-
-    $user['ipguest'] = null;
-
-    echo "user id=".$user['id'];
-    // Check if the user is a guest only
-    if (is_a_guest())
-    {
-        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
-            $IP = $_SERVER['HTTP_X_FORWARDED_FOR']; 
-        elseif(isset($_SERVER['HTTP_CLIENT_IP']))   
-            $IP = $_SERVER['HTTP_CLIENT_IP'];   
-        else
-            $IP = $_SERVER['REMOTE_ADDR'];  
-             
-        // store ip
-        $user['ipguest'] = $IP;
-if ($this->debug)	    
-    echo "user ip guest=".$user['ipguest'];
-
-}
-
-
-		
-// DEBUG
-if ($this->debug)
-{
-    foreach ($user as $id=>$val)
-    {
-        if (is_array($val))
-            foreach ($val as $id2=>$val2)
-                echo "user[".$id."][".$id2."]=".$val2."\n";
-        else
-            echo "user[".$id."]=".$val."\n";
-    }
-}
-
-//  END DEBUG
+		$user['ipguest'] = null;
+
+		// Check if the user is a guest only
+		if (is_a_guest())
+		{
+			if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
+				$IP = $_SERVER['HTTP_X_FORWARDED_FOR']; 
+			elseif(isset($_SERVER['HTTP_CLIENT_IP']))   
+				$IP = $_SERVER['HTTP_CLIENT_IP'];   
+			else
+				$IP = $_SERVER['REMOTE_ADDR'];  
+				 
+			// store ip
+			$user['ipguest'] = $IP;
+		}
         
         
-// DEBUG
-if ($this->debug)
-foreach ($page as $id=>$val)
-{
-	if (is_array($val))
-		foreach ($val as $id2=>$val2)
-			echo "page[".$id."][".$id2."]=".$val2."\n";
-	else
-		echo "page[".$id."]=".$val."\n";
-}
-//  END DEBUG
-
-	// disable author name  on image which are present in a concours.
-	// check the categories where the current image is present and disable the author name 
+		// disable author name  on image which are present in a concours.
+		// check the categories where the current image is present and disable the author name 
 		if (isset($this->my_config['mask_author']) && $this->my_config['mask_author'] == true)
 		{
@@ -902,8 +1161,7 @@
 			  WHERE image_id = '.$page['image_id'].'
 			  ;';
-//	               echo $query;
 			$result = pwg_query($query);
 			$related_categories = array();
-			while ($row = mysql_fetch_array($result))
+			while ($row = pwg_db_fetch_array($result))
 			{
 			  array_push($related_categories, $row['category_id']);
@@ -920,39 +1178,17 @@
                     AND time_to_sec(TIMEDIFF(now(), end_date)) < 0
                 ';
-        //                echo $query;
                 $result = pwg_query($query);
                 // If one or more concours are found, the author name is masked 
-                if ($result && mysql_fetch_assoc($result))
-                {
-                    $template->assign('INFO_AUTHOR',l10n('concours_img_author'));
-                }
-            }
-		}
-
-	// End disable author name
-
-
-		if (($page['section']) == 'categories' AND !empty($page['category']))
-		{
-if ($this->debug)	echo "STEP1\n";
-			//------------
-			// Step 1
-
-/*            
-            if ($this->my_config['mask_author'] && $this->my_config['mask_author'] == true)
-            {
-                // Request for all concours prepared & actived
-                $query = '
-                    SELECT *
-                    FROM ' . CONCOURS_TABLE .' 
-                    WHERE category =' . $page['category']['id'] . '
-                    AND time_to_sec(TIMEDIFF(now(), end_date)) < 0
- 				';
-//                echo $query;
-                $result = pwg_query($query);
-                if ($result && mysql_fetch_assoc($result))
+                if ($result && pwg_db_fetch_array($result))
                     $template->assign('INFO_AUTHOR',l10n('concours_img_author'));
             }
-*/
+		}
+
+	// End disable author name
+
+
+		if (($page['section']) == 'categories' AND !empty($page['category']))
+		{
+			// Step 1
             
 			$query = '
@@ -965,35 +1201,39 @@
 
 			$result = pwg_query($query);
-if ($this->debug) echo $query."\n";
-			while ($row = mysql_fetch_assoc($result))
+
+			while ($row = pwg_db_fetch_array($result))
 			{
-				if (!empty($row['groups']))
+				if (!is_a_guest() AND !empty($row['groups']))
 				{
-if ($this->debug)	echo "GROUPS=".$row['groups'];				
-					$authorized_groups = explode(',', $row['groups']);
-					if (array_intersect($this->user_groups, $authorized_groups) == array()) 
-					{
-if ($this->debug)	echo "ERROR GROUPS";
-						continue;
+
+					if (is_admin() AND $row['admin'])	// allow admin 
+						$concours = $row;
+					else
+					{		
+						$authorized_groups = explode(',', $row['groups']);
+						if (array_intersect($this->user_groups, $authorized_groups) == array())
+							continue;
+						// If no group is parameter for that concours  ==> available for all registered users
+						$concours = $row;
 					}
-                    // If no group is parameter for that concours  ==> available for all registered users
-					$concours = $row;
 				}
-                else
+                else 
+					
    					$concours = $row;
-
-
 			}
-
-if ($this->debug)	echo "STEP1 bis\n";
 			//------------
 			// Step 1 bis
 			// Actual user is  the author of the picture ==>end
-			if ( !$this->my_config['author_vote_available']
-                AND $this->check_img_user($page['current_item']))
+			// for the image, check (depending the config) if user = author or addedby or none
+			if ($this->check_img_user($page['current_item']))
 				return;
-			
-
-if ($this->debug)	echo "STEP2\n";
+				
+			// Check if user is guest and if guest is allowed
+			if (is_a_guest() AND array_key_exists('guest', $concours) AND !$concours['guest'])
+				return;
+			// Check if user is admin and if admin is allowed
+			if (is_admin() AND (!isset($concours['admin']) OR (isset($concours['admin']) AND !$concours['admin'])))
+				return;
+			
 			//------------
 			// Step 2
@@ -1003,20 +1243,18 @@
 				if (isset($_POST['concours_submit']))
 				{
-                
+         
 //                    array_push($page['infos'] , l10n('concours_vote_saved'));
                     
 					$user_note = "";
-		if ($this->debug)			echo "SUBMIT";
-				// concat all the notes to save on db
-				
+					
+					// concat all the notes to save on db
 					$firstcriterias = $this->get_firstlevel_criterias($concours['id']);
 					foreach ($firstcriterias as $criteria)
 					{
-						
 						// First without sub criterias
 						if (!$this->is_criterias_contains_sub($criteria['criteria_id'],$concours['id'] ))
 						{
 							// Check value 
-							$value = str_replace(",",".",$_POST[$criteria['criteria_id']]);
+							$value = str_replace(",",".",(isset($_POST[$criteria['criteria_id']]) ? $_POST[$criteria['criteria_id']] : floatval($criteria['min_value'])));
 							$value = str_replace(" ","",$value);
 							$value = floatval($value);
@@ -1034,5 +1272,5 @@
 							{
 								// Check value 
-								$value = str_replace(",",".",$_POST[$subcriteria['criteria_id']]);
+								$value = str_replace(",",".",(isset($_POST[$subcriteria['criteria_id']]) ? $_POST[$subcriteria['criteria_id']] : floatval($subcriteria['min_value'] )));
 								$value = str_replace(" ","",$value);
 								$value = floatval($value);
@@ -1047,7 +1285,5 @@
 					}
 				
-//				$datas = "0=0";
 					$this->store_img_note_user($page['current_item'], $user_note, $concours['id'], $user['ipguest']);
-if ($this->debug)	echo "COMMENT=".$_POST['CONCOURS_COMMENT'];
 					$this->store_img_comment_user($page['current_item'], $_POST['concours_comment'], $concours['id'], $user['ipguest']);
 				}
@@ -1056,6 +1292,6 @@
 				if (isset($_POST['concours_raz']))
 				{
-if ($this->debug)			echo "RAZ";				
-					$this->RAZ_img_note_user($page['current_item'], $concours['id'], $user['ipguest']);
+					$this->delete_img_note_user($page['current_item'], $concours['id'], $user['ipguest']);
+					$user_notes = array();
 				}
 				else
@@ -1068,5 +1304,4 @@
 				$comment = $this->get_img_comment_user($page['current_item'], $concours['id'], $user['id'], $user['ipguest']);
 
-if ($this->debug)	echo "STEP3\n";
 				//------------
 				// Step 3
@@ -1075,5 +1310,4 @@
 				foreach ($firstcriterias as $criteria)
 				{
-if ($this->debug)					echo "criteriaID=".$criteria['criteria_id']."\n";
 					// First without sub criterias
 					if (!$this->is_criterias_contains_sub($criteria['criteria_id'],$concours['id'] ))
@@ -1102,5 +1336,4 @@
 						foreach ($secondcriterias as $subcriteria)
 						{
-if ($this->debug)							echo "subcriteriaID=".$criteria['criteria_id']."\n";
 							$template->append( 'concours_criteria', array(
 									'nosub'	=> true,
@@ -1123,5 +1356,5 @@
 				// if a user has already vote for this photo, check if the score change is allowed
 
-if ($this->debug)           echo "change=".($this->my_config['concours_change_score'] ? "OK" : "KO");
+
                 if ($user_notes == array() OR $this->my_config['concours_change_score'])  // Allow user to change his vote after a validation
                     $template->assign( 'CONCOURS_CHANGE_SCORE', true);
@@ -1129,18 +1362,24 @@
                     $template->assign( 'CONCOURS_CHANGE_SCORE', false);
                 
-				
+				$noteuser = $this->get_img_globalnote_user($page['current_item'], $concours['id'], null, $user['ipguest']);
 				// Add concours informations on template
 				$template->assign( 'concours_infos', array(
 							'name'	=> $concours['name'],
 							'descr'	=> $concours['descr'],
-                            'note'  => $this->get_img_globalnote_user($page['current_item'], $concours['id'], null, $user['ipguest'])
+                            'note'  => ($noteuser >= 0 ? $noteuser : 0 ),
+							'begin_date' => $concours['begin_date'],
+							'end_date' => $concours['end_date'],
+							'end_concours_min' => (strtotime($concours['end_date'])-time())	,
+							'max_note' => $this->get_concours_maxnote($concours['id']),
+							'deadline_type' => $this->my_config['concours_deadline']
 								));
 				
+
+				$template->assign( 'SCORE_MODE', $this->my_config['score_mode']);
+				$template->assign( 'TEXT_OVERLAY', $this->my_config['text_overlay']);
 			
 				$template->set_filenames(array('concours' =>  CONCOURS_ROOT.'/template/concours.tpl'));
-//				$template->concat('PLUGIN_PICTURE_AFTER', $template->parse('concours', true));
 				$template->concat('COMMENT_IMG', $template->parse('concours', true));
 
-				// 
 				$template->assign('INFO_AUTHOR',l10n('concours_img_author'));
 			}
@@ -1148,4 +1387,31 @@
 	}
 
+	
+	// RAZ notation from user to db
+	// fill criterias notes to 0 in DB
+	// return false if error
+	function delete_img_note_user($img_id, $concours_id = NULL, $ipguest = null, $userid=null)
+	{
+		global $user;
+		
+		if ($concours_id === null)
+			if ($this->concours_id !== null)
+				$concours_id = $this->concours_id;
+			else
+				return false;
+				
+		$query = '
+		DELETE FROM ' . CONCOURS_DATA_TABLE .'
+		WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id ).'
+		AND user_id = '.($userid == null ? $user['id'] : $userid).' 
+		AND img_id = '.$img_id.
+		($ipguest ? ' AND ipguest = "'.$ipguest.'"' : '')            
+		.';';
+
+		return pwg_query($query);
+
+	}
+	
+	
 	// RAZ notation from user to db
 	// fill criterias notes to 0 in DB
@@ -1163,21 +1429,14 @@
 		foreach ($firstcriterias as $criteria)
 		{
-if ($this->debug)					echo "ID=".$criteria['criteria_id']."\n";
 			// First without sub criterias
 			if (!$this->is_criterias_contains_sub($criteria['criteria_id'],$concours_id ))
-			{
 				$user_note .= (strlen($user_note) != 0 ? ";" : "").$criteria['criteria_id']."=".$criteria['min_value'];
-			}
 			else
 			{
 				$secondcriterias = $this->get_subcriterias($criteria['criteria_id'], $concours_id );
 				foreach ($secondcriterias as $subcriteria)
-				{
-if ($this->debug)							echo "ID=".$criteria['criteria_id']."\n";
 					$user_note .= (strlen($user_note) != 0 ? ";" : "").$subcriteria['criteria_id']."=".$subcriteria['min_value'];
-				}
 			}
 		}
-if ($this->debug)	echo "RAZ=>".$user_note."\n";
 		if (strlen($user_note) != 0)
 		{
@@ -1187,6 +1446,4 @@
 		else
 			return false;
-				
-
 	}
 
@@ -1199,6 +1456,6 @@
 		{
 			$query = 'SELECT IF(MAX(id)+1 IS NULL, 1, MAX(id)+1) AS next_element_id  FROM ' . CONCOURS_DATA_TABLE . ' ;';
-			list($next_element_id) = mysql_fetch_array(pwg_query($query));
-if ($this->debug)	echo "Next_element=".$next_element_id."\n";
+			list($next_element_id) = pwg_db_fetch_array(pwg_query($query));
+
 			$query = '
 			INSERT INTO ' . CONCOURS_DATA_TABLE .'
@@ -1229,6 +1486,5 @@
             .';';
 		}
-if ($this->debug) 			echo $query."\n";
-			pwg_query($query);
+		pwg_query($query);
 	
 	}
@@ -1240,5 +1496,5 @@
 	function get_img_note_user($img_id, $concours_id = NULL, $user_id = null, $ipguest = null)
 	{
-		global $user;
+		global $user, $conf;
 		$img_note = array();
 		if ($concours_id!== null or $this->concours_id !== null)
@@ -1247,63 +1503,15 @@
 			SELECT datas
 			FROM ' . CONCOURS_DATA_TABLE .' 
-			WHERE id_concours =' . ($concours_id !== NULL ? $concours_id : $this->concours_id) . '
-			AND user_id = '. ($user_id !== null ? $user_id : $user['id']).'
-			AND img_id = '. $img_id .
-            ($ipguest ? ' AND ipguest = "'.$ipguest.'"' : '')
+			WHERE id_concours =' . ($concours_id !== NULL ? $concours_id : $this->concours_id) 
+			. ($ipguest == null ? ' AND user_id = '. ($user_id !== null ? $user_id : $user['id'])
+			   : ' AND user_id = '.$conf['guest_id'] .' AND ipguest = "'.$ipguest.'"')
+			.' AND img_id = '. $img_id 
 			.';';
-if ($this->debug) 			echo $query."\n";
-			$result = pwg_query($query);
-			
-			while ($row = mysql_fetch_assoc($result))
-			{
-if ($this->debug)				echo "row[data]=".$row['datas']."\n";
-				$datas = explode(";",$row['datas']);
-				foreach ($datas as $val)
-				{
-					if (strpos($val, '=') !== FALSE)
-						$img_note[substr($val, 0, strpos($val, '='))]=substr($val, strpos($val, '=')+1);
-				}
-			}
-// DEBUG
-if ($this->debug)
-foreach ($img_note as $id=>$val)
-{
-	if (is_array($val))
-		foreach ($val as $id2=>$val2)
-			echo "img_note[".$id."][".$id2."]=".$val2."\n";
-	else
-		echo "img_note[".$id."]=".$val."\n";
-}
-//  END DEBUG
-			
-			return $img_note;
-		}
-		else
-			return array();
-		
-		
-	}
-
-	
-	// get notation's user from db
-	// Return the global note for a picture id from a user
-	function get_img_globalnote_user($img_id, $concours_id = NULL, $user_id = null, $ipguest = null)
-	{
-		global $user;
-		$img_note = array();
-		$global_user_note = 0;
-		if ($concours_id!== null or $this->concours_id !== null)
-		{
-			$query = '
-			SELECT datas
-			FROM ' . CONCOURS_DATA_TABLE .' 
-			WHERE id_concours =' . ($concours_id !== NULL ? $concours_id : $this->concours_id) . '
-			AND user_id = '. ($user_id !== null ? $user_id : $user['id']).'
-			AND img_id = '. $img_id .
             ($ipguest ? ' AND ipguest = "'.$ipguest.'"' : '')
 			.';';
 			$result = pwg_query($query);
 			
-			while ($row = mysql_fetch_assoc($result))
+			while ($row = pwg_db_fetch_array($result))
+
 			{
 				$datas = explode(";",$row['datas']);
@@ -1315,8 +1523,81 @@
 			}
 			
+			return $img_note;
+		}
+		else
+			return array();
+	}
+
+
+
+	// Return the max note for a concours 
+	function get_concours_maxnote($concours_id = NULL)
+	{
+
+		if ($concours_id!== null or $this->concours_id !== null)
+		{
+			$query = '
+			SELECT SUM(max_value) AS TOTAL
+			FROM ' . CONCOURS_DETAIL_TABLE .' 
+			WHERE id_concours =' . ($concours_id !== NULL ? $concours_id : $this->concours_id)
+			.' AND uppercriteria IS NULL' 
+			.';';
+			
+			$result = pwg_query($query);
+			if ($this->debug)					echo "query=".$query."<br>\n";
+			
+			if ($row = pwg_db_fetch_array($result))
+			{
+				return $row['TOTAL'];
+			}
+			else 
+			return -1;
+			
+		}
+
+	
+	}
+
+
+	
+	// get notation's user from db
+	// Return the global note for a picture id from a user
+	// if moderationMode = 1, the 'moderation' contains the GlobalAverage for all the concours
+	// if moderationMode = 2, the 'moderation' contains the user moderation for all image that are voted by
+	// return -1 if there is no vote for that user
+	function get_img_globalnote_user($img_id, $concours_id = NULL, $user_id = null, $ipguest = null, $moderationMode = 0, $moderation = 0)
+	{
+		global $user, $conf;
+		$img_note = array();
+		$global_user_note = -1;
+		$note_found = false;
+		if ($concours_id!== null or $this->concours_id !== null)
+		{
+			$query = '
+			SELECT datas
+			FROM ' . CONCOURS_DATA_TABLE .' 
+			WHERE id_concours =' . ($concours_id !== NULL ? $concours_id : $this->concours_id) 
+			. ($ipguest == null ? ' AND user_id = '. ($user_id !== null ? $user_id : $user['id'])
+			   : ' AND user_id = '.$conf['guest_id'] .' AND ipguest = "'.$ipguest.'"')
+			.' AND img_id = '. $img_id 
+			.';';
+			$result = pwg_query($query);
+			if ($this->debug)					echo "query=".$query."<br>\n";
+			
+			while ($row = pwg_db_fetch_array($result))
+			{
+				$global_user_note = 0; // init note if one vote is present
+				$note_found = true;
+				$datas = explode(";",$row['datas']);
+				foreach ($datas as $val)
+				{
+					if (strpos($val, '=') !== FALSE)
+						$img_note[substr($val, 0, strpos($val, '='))]=substr($val, strpos($val, '=')+1);
+				}
+			}
+			
 			$firstcriterias = $this->get_firstlevel_criterias($concours_id);
 			foreach ($firstcriterias as $criteria)
 			{
-if ($this->debug)					echo "criteriaID=".$criteria['criteria_id']."\n";
 				// First without sub criterias
 				if (!$this->is_criterias_contains_sub($criteria['criteria_id'],$concours_id ))
@@ -1327,16 +1608,30 @@
 				else
 				{
-
 					$secondcriterias = $this->get_subcriterias($criteria['criteria_id'], $concours_id );
 					foreach ($secondcriterias as $subcriteria)
 					{
-if ($this->debug)							echo "subcriteriaID=".$subcriteria['criteria_id']."\n";
 						if (isset($img_note[$subcriteria['criteria_id']]))
 						$global_user_note += (int)$subcriteria['ponderation'] * (float)$img_note[$subcriteria['criteria_id']];
 					}
 				}
-
 			}
 			
+			// MODERATION 
+				// moderation 1 => For each photo without note (user = author or user != author but no vote) add each user avaerage to the total of note and calcul the average 
+				// moderation 2 => For each photo with note, adapt/change all the value with the moderation value : user note + moderation. 
+			
+			if ($user_id !== null) // only for user 
+			{
+				if ($moderationMode == 1 && !$note_found)
+				{		// Moderation1
+					$global_user_note = $moderation;
+				}
+				elseif ($moderationMode == 2 && $note_found)
+				{	// Moderation2
+					$global_user_note += $moderation;
+				}		
+				
+				
+			}
 			return $global_user_note;
 		}
@@ -1354,6 +1649,6 @@
 		{
 			$query = 'SELECT IF(MAX(id)+1 IS NULL, 1, MAX(id)+1) AS next_element_id  FROM ' . CONCOURS_DATA_TABLE . ' ;';
-			list($next_element_id) = mysql_fetch_array(pwg_query($query));
-if ($this->debug)	echo "Next_element=".$next_element_id."\n";
+			list($next_element_id) = pwg_db_fetch_array(pwg_query($query));
+
 			$query = '
 			INSERT INTO ' . CONCOURS_DATA_TABLE .'
@@ -1381,7 +1676,5 @@
             .';';
 		}
-if ($this->debug) 			echo $query."\n";
 			pwg_query($query);
-	
 	}
 	
@@ -1402,12 +1695,9 @@
             ($ipguest ? ' AND ipguest = "'.$ipguest.'"' : '')
 			.';';
-if ($this->debug) 			echo $query."\n";
+
 			$result = pwg_query($query);
 			
-			while ($row = mysql_fetch_assoc($result))
-			{
-if ($this->debug)				echo "row[comment]=".$row['comment']."\n";
+			while ($row = pwg_db_fetch_array($result))
 				$datas = $row['comment'];
-			}
 		}
 		return $datas;
@@ -1441,5 +1731,5 @@
 		// For each images
 		$rang = 1;
-		while ($row = mysql_fetch_assoc($result))
+		while ($row = pwg_db_fetch_array($result))
 		{
 			$file .= ($row['nbvotant'] != 0 ? $rang : 'N/A').', '
@@ -1467,4 +1757,5 @@
 	{
         global $conf;
+		$MethodType = "0";
 		if ($concours_id === null)
 			$concours_id = $this->concours_id;
@@ -1495,5 +1786,4 @@
 			$ident1++;
 		}
-if ($this->debug)	echo "CRITERIA_LIST=".$criteria_list."\n";	
 		$user_list = array();
 		$users_criteria = "";
@@ -1511,9 +1801,8 @@
 		$result = pwg_query($query);
 		// For each user
-		while ($row = mysql_fetch_assoc($result))
+		while ($row = pwg_db_fetch_array($result))
 		{
 			array_push($user_list, $row);
 			$users_criteria .= (strlen($users_criteria) ? "," : "")."user, user_global_note, comment, ".$criteria_list;
-			
 		}
         
@@ -1530,8 +1819,7 @@
         }
 
-if ($this->debug)	echo "users_criteria=".$users_criteria."\n";	
 		
 		// All informations in csv format
-		$file = "rang, id_concours, method, nom_concours, date_debut, date_fin, date_export, img_id, img_name, img_file, img_author, note, moyenne, nbvotant, datas,"
+		$file = "rang, id_concours, method, nom_concours, date_debut, date_fin, date_export, img_id, img_name, img_file, img_author, note, moyenne, moderation1, moderation2, nbvotant, datas,"
 		.$users_criteria 
 		."\r\n";
@@ -1542,9 +1830,8 @@
 		$nbvotes = $this->nb_votes_by_img($concours_id);
 
-		
 		// recover all img_id from the category
 		if (!(isset($this->concours_infos['method'])))
 			$this->concours_infos['method'] = 1;
-		$query = 'SELECT id_concours, method, img_id, IMG.name, IMG.file, IMG.author, date, note, moyenne, nbvotant, datas, comment'
+		$query = 'SELECT id_concours, method, img_id, IMG.name, IMG.file, IMG.author, date, note, moyenne, moderation1, moderation2, nbvotant, datas, comment'
 		.' FROM ' .CONCOURS_RESULT_TABLE
 		.' INNER JOIN ' . CONCOURS_TABLE.' AS CONC on CONC.id = id_concours'
@@ -1552,12 +1839,26 @@
 		.' WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id );
 		
-		if ($this->concours_infos['method'] == 1)	// total
+		switch ($this->concours_infos['method'])
+		{
+		case 1 :	// total
 			$query .= ' ORDER BY note DESC';
-		elseif ($this->concours_infos['method'] == 2)	// moyenne
+			$MethodType = "1-Sum";
+			break;
+		case  2 :	// moyenne
 			$query .= ' ORDER BY moyenne DESC';
-		
+			$MethodType = "2-Average";
+			break;
+		case  3 :	// moderation1
+			$query .= ' ORDER BY moderation1 DESC';
+			$MethodType = "3-Average(Mod1)";
+			break;
+		case  4 :	// moderation2
+			$query .= ' ORDER BY moderation2 DESC';
+			$MethodType = "4-Average(Mod2)";
+			break;
+		}
+				
 		$query .=';';
 		
-if ($this->debug)		echo $query;
 		$result = pwg_query($query);
 		// For each images
@@ -1565,5 +1866,5 @@
         $previousNote = $previousMoy = 0;
 
-		while ($row = mysql_fetch_assoc($result))
+		while ($row = pwg_db_fetch_array($result))
 		{
             // Check and verify for exaequo
@@ -1575,6 +1876,5 @@
                           AND ($row['moyenne'] == $previousMoy)))
                 {
-                    $rang --;
-                    
+                    $rang --;          
                 }
             }
@@ -1582,5 +1882,5 @@
 			$file .= ($row['nbvotant'] != 0 ? $rang : 'N/A').', '
 					.$row['id_concours'].', '
-					.$row['method'].', '
+					.$MethodType.', '
 					.str_replace(",", "",$this->concours_infos['name']).', '
 					.$this->concours_infos['begin_date'].', '
@@ -1594,6 +1894,7 @@
 					.$row['note'].', '
 					.$row['moyenne'].', '
+					.$row['moderation1'].', '
+					.$row['moderation2'].', '
 					.$row['nbvotant'].', '
-//					.(isset($nbvotes[$row['img_id']]) ? $nbvotes[$row['img_id']] : 0).', '
 					.($row['datas'] != null ? $row['datas'] : '')
 					;
@@ -1605,6 +1906,6 @@
 				$user_note = $this->get_img_note_user($row['img_id'], $concours_id, $uuser['user_id']);
 				
-				$file .= ', '.$uuser['username'].', '.$this->get_img_globalnote_user($row['img_id'], $concours_id, $uuser['user_id'])
-//						.', '.($row['comment'] != null ? str_replace(",", "",$row['comment']) : '')
+				$user_global_note = $this->get_img_globalnote_user($row['img_id'], $concours_id, $uuser['user_id']);
+				$file .= ', '.$uuser['username'].', '.($user_global_note >= 0 ? $user_global_note  : 0)
 						.', '.($comment != false ? str_replace(array(",","\r\n", "\n", "\r"), " ",$comment) : '')
 						.', '
@@ -1642,11 +1943,10 @@
 			foreach ($ipguest as $ipguestt)
 			{
-//                echo "IP=".$ipguestt."\n";
 				$comment = $this->get_img_comment_user($row['img_id'], $concours_id, $conf['guest_id'], $ipguestt);
 			
 				$user_note = $this->get_img_note_user($row['img_id'], $concours_id, $conf['guest_id'], $ipguestt);
-				
-				$file .= ', Guest('.$ipguestt.'), '.$this->get_img_globalnote_user($row['img_id'], $concours_id, $conf['guest_id'], $ipguestt)
-//						.', '.($row['comment'] != null ? str_replace(",", "",$row['comment']) : '')
+				$user_global_note = $this->get_img_globalnote_user($row['img_id'], $concours_id, $conf['guest_id'], $ipguestt);
+				
+				$file .= ', Guest('.$ipguestt.'), '.($user_global_note >= 0 ? $user_global_note : 0)
 						.', '.($comment != false ? str_replace(array(",","\r\n", "\n", "\r"), " ",$comment) : '')
 						.', '
@@ -1687,10 +1987,8 @@
 
 		}
-if ($this->debug)		echo $file;
 		return utf8_decode($file);
 	
 		
 	}
-	
 	
 	
@@ -1722,5 +2020,4 @@
 						;";
 			pwg_query($query);
-if ($this->debug)		echo $query;
 			
 			return $filename;
@@ -1735,9 +2032,8 @@
 		.' WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id )
 		.';';
-if ($this->debug)	echo $query;
 		$result = pwg_query($query);
 		if ($result)
 		{
-			$row = mysql_fetch_assoc($result);		
+			$row = pwg_db_fetch_array($result);		
 			if ($row)
 				return $row['file_name'];
@@ -1762,8 +2058,8 @@
 			fpassthru($file);
 		}
-	
-	}
-	
-	// Activation page administration
+	}
+	
+	// DEPRECATED Piwigo 11 Activation page administration
+/*
 	function concours_admin_menu($menu)
 	{
@@ -1771,17 +2067,18 @@
 	       array(
 	            'NAME' => CONCOURS_NAME,
-	            'URL' => get_admin_plugin_menu_link(CONCOURS_ADMIN_PATH.'admin.php')
+	            'URL' => get_root_url().'admin.php?page=plugin-'.CONCOURS_DIR.'-manage'
 	        ) 
 	    );
 	    return $menu;
 	}
+*/
 	
 	// register Concours Menubar
 	public function register_blocks( $menu_ref_arr )
 	{
-	$menu = & $menu_ref_arr[0];
-	if ($menu->get_id() != 'menubar' OR $this->my_config['active_menubar'] == false)
-	  return;
-	$menu->register_block( new RegisteredBlock( 'CONCOURS_menu', 'concours', 'ConcoursPhoto'));
+		$menu = & $menu_ref_arr[0];
+		if ($menu->get_id() != 'menubar' OR $this->my_config['active_menubar'] == false)
+		  return;
+		$menu->register_block( new RegisteredBlock( 'CONCOURS_menu', 'concours', 'ConcoursPhoto'));
 	}
 
@@ -1789,5 +2086,5 @@
 	public function blockmanager_apply( $menu_ref_arr )
 	{
-  
+
 		global $user, $template;
 		$menu = & $menu_ref_arr[0];
@@ -1798,21 +2095,22 @@
 		if ( ($block = $menu->get_block( 'CONCOURS_menu' ) ) != null )
 		{
-
-		  $menu_list=array();
-
-		  if(is_admin())
-		  {
+			$menu_list=array();
+
+			if(is_admin())
+			{
+
 			array_push($menu_list,
 			  array(
-				'nfo' => "",
-				'text' => l10n('concours_admin_add'),
-				'link' => PHPWG_ROOT_PATH . 'admin.php?page=plugin&amp;section=' . CONCOURS_DIR . '%2Fadmin%2Fadd_concours.php&amp;action=new',
-				'edit' => ""
+				'NAME' => l10n('concours_admin_add'),
+				'TITLE' => l10n('concours_admin_add'),
+				'URL' => PHPWG_ROOT_PATH . 'admin.php?page=plugin&amp;section=' . CONCOURS_DIR . '%2Fadmin%2Fadd_concours.php&amp;action=new',
+				'REL' => ""
 			  )
 			);
-		  }
+ 			
+			}
 
 			// recover all img_id from the category
-			$query = 'SELECT distinct(id_concours), groups, guest, CONC.name'
+			$query = 'SELECT distinct(id_concours), groups, guest, admin, CONC.name'
 			.' FROM ' .CONCOURS_RESULT_TABLE
 			.' INNER JOIN '.CONCOURS_TABLE. ' AS CONC ON CONC.id = id_concours'
@@ -1822,6 +2120,8 @@
 			$result = pwg_query($query);
 			$nb_concours = 1;
+			
 			// For each concours
-			while ($row = mysql_fetch_assoc($result))
+			while ($row = pwg_db_fetch_assoc($result))
+
 			{
 				
@@ -1831,8 +2131,11 @@
                 $conc_to_show = false;  // Default ==> dont show
                 
-                // Guest
-				if (is_a_guest() AND $row['guest'])
+                // Guest OR admin
+				if ((is_a_guest() AND $row['guest'])
+					OR (is_admin() AND $row['admin']))
                     $conc_to_show = true;
                 // Group present
+				
+				
                 elseif (!empty($row['groups']))
 				{
@@ -1848,10 +2151,11 @@
 					{
 					$nb_concours ++;
+
 					array_push($menu_list,
 					  array(
-						'nfo' => "",
-						'text' => $row['name'],
-						'link' => './index.php?/concours/'.$row['id_concours'],
-						'edit' => (is_admin()? PHPWG_ROOT_PATH . 'admin.php?page=plugin&amp;section=' . CONCOURS_DIR . '%2Fadmin%2Fadd_concours.php&amp;concours=' . $row['id_concours'].'&amp;action=modify':"")
+						'NAME' => $row['name'],
+						'TITLE' => $row['name'],
+						'URL' => './index.php?/concours/'.$row['id_concours'],
+						'EDIT' => (is_admin()? PHPWG_ROOT_PATH . 'admin.php?page=plugin&amp;section=' . CONCOURS_DIR . '%2Fadmin%2Fadd_concours.php&amp;concours=' . $row['id_concours'].'&amp;action=modify':"")
 					  )
 					);
@@ -1861,6 +2165,4 @@
 		  if (count($menu_list))
 		  {
-
-			  $block->set_title(l10n('concoursphoto'));
 			  $block->template = CONCOURS_ROOT.'/template/concours_menu.tpl';
 			  $block->data = $menu_list;
@@ -1869,5 +2171,4 @@
 	}
 
-	
 	function section_init_concours()
 	{
@@ -1875,4 +2176,6 @@
 		if ($tokens[0] == 'concours')
 		  $page['section'] = 'concours';
+		elseif ($tokens[0] == 'concours_vote')
+		  $page['section'] = 'concours_vote';
 	}
 	
@@ -1880,6 +2183,4 @@
 	{
 		global $page;
-		
-		
 		if (isset($page['section']) and $page['section'] == 'concours')
 		{
@@ -1888,10 +2189,18 @@
 	}
 
+	function index_vote_concours()
+	{
+		global $page;
+		if (isset($page['section']) and $page['section'] == 'concours_vote')
+		{
+			include(CONCOURS_PATH . 'concours_vote.php');
+		}
+	}
+	
 	
   // Show the global note under the thumbnail
-  function thumbnail_note($tpl_var) 
+  function thumbnail_note($tpl_var, $pictures) 
   {
-
-	global $page, $user;
+	global $page, $user, $template;
 	$this->get_user_groups();
 
@@ -1909,65 +2218,241 @@
         $user['ipguest'] = $IP;
     }
-        
-    if ($this->my_config['thumb_note'] && $this->my_config['thumb_note'] == true)
-    {
-        $concours = array();
-        if (($page['section']) == 'categories' AND !empty($page['category']))
-        {
-            $query = '
-                SELECT *
-                FROM ' . CONCOURS_TABLE .' 
-                WHERE category =' . $page['category']['id'] . '
-                AND time_to_sec(TIMEDIFF(begin_date,now())) < 0
-                AND time_to_sec(TIMEDIFF(now(), end_date)) < 0
-                ';
-
-            $result = pwg_query($query);
-    if ($this->debug) echo $query."\n";
-            while ($row = mysql_fetch_assoc($result))
-            {
-                
-                if (!empty($row['groups']))
-                {
-    if ($this->debug)	echo "GROUPS=".$row['groups'];				
-                    $authorized_groups = explode(',', $row['groups']);
-                    if (array_intersect($this->user_groups, $authorized_groups) == array()) 
-                    {
-    if ($this->debug)	echo "ERROR GROUPS";
-                        continue;
-                    }
-                    $concours = $row;
-                }
-                
-                // If no group is parameter for that concours  ==> available for all registered users
-                else
-                    $concours = $row;
-                
-            }
-            if (count($concours))
-            {
-                // Check if user is guest and if guest is allowed
-                if ((is_a_guest() AND $concours['guest'])
-                    OR !is_a_guest())
-                {
-                    foreach($tpl_var as $cle=>$valeur) 
-                    {
-                        // show only if the author is not the active user
-                        if ($tpl_var[$cle]['FILE_AUTHOR'] != $user['username']
-                            OR $this->my_config['author_vote_available']    // Allow author to vote (and also show his score)
-                            )
-                        {
-                            $tpl_var[$cle]['NAME'] = $tpl_var[$cle]['NAME'].'<br>&nbsp;'.l10n('thumbnail_global_note').' : '.$this->get_img_globalnote_user($tpl_var[$cle]['ID'], $concours['id'], $user['id'], $user['ipguest']);
-                        }
-                    }
-                }
-            }
-        }
-    }
+
+	if (($page['section']) == 'categories' AND !empty($page['category']))
+	{
+		
+		$concours = array();
+
+		$query = '
+			SELECT *
+			FROM ' . CONCOURS_TABLE .' 
+			WHERE category =' . $page['category']['id'] 
+// comment to load prepared contests and opened contests				. ' AND time_to_sec(TIMEDIFF(begin_date,now())) < 0'
+			. ' AND time_to_sec(TIMEDIFF(now(), end_date)) < 0';
+
+		$result = pwg_query($query);
+		// DEBUG
+		if ($this->debug) echo $query."\n";
+		// END DEBUG
+		while ($row = pwg_db_fetch_array($result))
+		{				
+			if ((strtotime($row['begin_date'])-time() > 0) AND $this->my_config['mask_thumbnail'])
+			{
+			// disable picture if contest is prepared for all users
+			  $i=0;
+			  while ($i<count($tpl_var))
+			  {
+				  array_splice($tpl_var, $i, 1);
+				  array_splice($pictures, $i, 1);
+			  }	
+			$concours = $row;
+				
+			}
+			elseif (is_admin() AND $row['admin'])
+				$concours = $row;
+			elseif (!is_a_guest() AND !empty($row['groups']))
+			{
+				$authorized_groups = explode(',', $row['groups']);
+				if (array_intersect($this->user_groups, $authorized_groups) == array()) 
+					continue;
+				$concours = $row;
+			}
+			
+			// If no group is parameter for that concours  ==> available for all registered users
+			else
+				$concours = $row;		
+		}
+		
+
+		if (count($concours))
+		{		
+			// Add timeline for all users.
+			if (strtotime($concours['begin_date'])-time() > 0)
+			{
+				$template->assign('begin_concours_min', (strtotime($concours['begin_date'])-time()));
+				$template->assign('deadline_type',$this->my_config['concours_deadline']);
+				$template->assign('begin_concours', $concours['begin_date']);
+			}
+			else
+			{
+				// Check if user is guest and if guest is allowed
+				if ((is_a_guest() AND $concours['guest']) 
+					OR (is_admin() AND $concours['admin'])
+					OR !is_a_guest())
+				{
+			 
+					// check if contest is concours not already open (date begin > now)
+
+				
+					
+						foreach($tpl_var as $cle=>$valeur) 
+						{
+							// show only if the author is not the active user
+
+							$AuthorArray = strip_punctuation2($tpl_var[$cle]['author']);
+							$AddedByID = ($tpl_var[$cle]['added_by']);
+							$UserArray = strip_punctuation2($user['username']);
+
+							if ($this->my_config['author_vote_available']  == 0 // Allow to vote for all photos (and also show his score)
+							    OR ($this->my_config['author_vote_available'] == 1 // check between author and user
+							        AND (empty($AuthorArray) OR count(array_intersect($AuthorArray, $UserArray)) != count ($AuthorArray))  // Author is the same as user name 
+							        ) 	
+							    OR ($this->my_config['author_vote_available'] == 2 // check between author and user
+							        AND (!isset($AddedByID) OR ($user['id'] != $AddedByID))  // Addedby is the same as user name 
+							        ) 
+							    OR ($this->my_config['author_vote_available'] == 3 // check between author OR addedby and user
+							        AND (!isset($AddedByID) OR ($user['id'] != $AddedByID))  // Addedby is the same as user name 
+							        AND (empty($AuthorArray) OR count(array_intersect($AuthorArray, $UserArray)) != count ($AuthorArray))  // Author is the same as user name 
+							        ) 
+							   )
+
+							{
+								if ($this->my_config['thumb_note'])	 // display thumbnail note only if option is activated
+								{
+									$user_global_note = $this->get_img_globalnote_user($tpl_var[$cle]['id'], $concours['id'], $user['id'], $user['ipguest']);
+									$tpl_var[$cle]['NAME'] = $tpl_var[$cle]['NAME'].'('.l10n('thumbnail_global_note').': '.($user_global_note >= 0 ? $user_global_note : 0).')';
+								}
+							}
+						}
+						
+						// Add deadline on description page 	
+						$template->assign('end_concours', $concours['end_date']);
+						$template->assign('end_concours_min', (strtotime($concours['end_date'])-time()));
+						$template->assign('deadline_type',$this->my_config['concours_deadline']);
+						if (isset($this->my_config['active_global_score_page']) AND $this->my_config['active_global_score_page'])	// only if option is activated
+							$template->assign('global_vote_link', PHPWG_ROOT_PATH . 'index.php?/concours_vote/'.$concours['id']);
+				}
+				
+			}
+			$template->assign('IMG_URL', CONCOURS_IMG_PATH);
+			
+			$template->set_filenames(array('concours_description' =>  CONCOURS_ROOT.'/template/concours_description.tpl'));
+			$template->concat('CONTENT_DESCRIPTION', $template->parse('concours_description', true));
+
+		}
+	}
+	
     return $tpl_var;
   }
-	
+
+	function concours_stuffs_module($modules)
+	{
+		array_push($modules, array(
+		'path' => CONCOURS_PATH.'stuffs_module/',
+		'name' => l10n('concours_stuffs_name'),
+		'description' => l10n('concours_stuffs_description'),
+		)
+		);
+		return $modules;
+	}	
+	
+	
+	
+	function add_contest_desc($tpl_var)
+	{	
+		global $page, $user, $template;
+	// TO DO : Add contest information on subcategory 
+/*	
+	echo "ICI<br>";
+	echo "tpl_VAR".(is_array($tpl_var) ? "OK" : $tpl_var)."<br>";
+	foreach ($tpl_var as $id=>$val)
+	{
+		
+		if (is_array($val))
+			foreach ($val as $id2=>$val2)
+			if (is_array($val2))
+				foreach ($val2 as $id3=>$val3)
+				if (is_array($val3))
+					foreach ($val3	as $id4=>$val4)
+						echo "tpl_var[".$id."][".$id2."][".$id3."][".$id4."]=".$val4."<br>\n";
+				else
+					echo "tpl_var[".$id."][".$id2."][".$id3."]=".$val3."<br>\n";
+			else
+				echo "tpl_var[".$id."][".$id2."]=".$val2."<br>\n";
+		else
+			echo "tpl_var[".$id."]=".$val."<br>\n";
+	}
+	  $i=0;
+	  while ($i<count($tpl_var))
+	  {
+		$tpl_var[$i]['NAME'] = "TEST TEST";
+		$i++;
+		
+	  }
+	
+		$template->set_filenames(array('concours_description' =>  CONCOURS_ROOT.'/template/concours_description-cat.tpl'));
+		$template->concat('DESCRIPTION', $template->parse('concours_description', true));
+		
+		return  $tpl_var;
+*/		
+	}
+
+
+
+
+	// Check if a concours is present (prepared or actived) for the category and user group
+	function concours_present_cat($category = NULL)
+	{
+		global $page;
+		$concours_present = false;
+		if (!isset($category))	// param not present
+		{
+			if (($page['section']) == 'categories' AND !empty($page['category']))
+					$category = $page['category']['id'] ;
+		}
+
+		if (isset($category))
+		{
+			$query = '
+				SELECT *
+				FROM ' . CONCOURS_TABLE .' 
+				WHERE category =' . $category . '
+                AND time_to_sec(TIMEDIFF(now(), end_date)) < 0
+				';
+
+			$result = pwg_query($query);
+			while ($row = pwg_db_fetch_array($result))
+				return true;
+		}
+		return false;
+	}
+
+
+	// Disable Metatdata to picture for a prepared or active concours
+	function disable_meta_to_picture()
+	{
+		if (isset($this->my_config['mask_meta']) && $this->my_config['mask_meta'] == true)
+		{
+			if ($this->concours_present_cat())
+				pwg_set_session_var('show_metadata', 0 );
+		}
+	}
+
 	
 }
 
+function strip_punctuation($string) {
+    $string = strtolower($string);	// lower case
+    $string = preg_replace("/\p{P}+/", "", $string); // remove punctuation
+    $string = preg_replace("/\p{Nd}+/", "", $string); // remove numeric
+    $string = preg_replace("/[\p{Z}\t\r\n\v\f]+/", "", $string); // remove spaces
+    $string = str_replace(" +", "", $string);	// remove space
+//echo "stripPunct=".$string."!\n";
+    return $string;
+}
+
+// return array
+function strip_punctuation2($string) {
+    $string = strtolower($string);	// lower case
+    $string = preg_replace("/\p{P}+/", " ", $string); // remove punctuation by space
+    $string = preg_replace("/\p{Nd}+/", "", $string); // remove numeric
+    $string = preg_replace("/[\p{Z}\t\r\n\v\f]+/", " ", $string); // remove spaces by spaces (only 1)
+//    $string = str_replace(" +", "", $string);	// remove space
+	$stringArray = $returnValue = preg_split('/\\W/', $string, -1, PREG_SPLIT_NO_EMPTY);
+
+    return $stringArray;
+}
+
+
+
 ?>
Index: extensions/ConcoursPhoto/include/default_values.inc.php
===================================================================
--- extensions/ConcoursPhoto/include/default_values.inc.php	(revision 9370)
+++ extensions/ConcoursPhoto/include/default_values.inc.php	(revision 32457)
@@ -7,9 +7,21 @@
 $concours_default_values['active_menubar'] = true; // Activate menubar view
 $concours_default_values['nbconcours_menubar'] = 3;	// Nb of last published concours show on concours menubar
-$concours_default_values['mask_author'] =   true; // Mask author for prepared concours
+$concours_default_values['mask_author'] =   true; // Mask author for prepared concours or active concours
+$concours_default_values['mask_meta'] =     false; // Mask meta for prepared concours or active concours
 $concours_default_values['thumb_note'] = true; // Display global note (for user) under thumbnail
 $concours_default_values['check_exaequo'] = false; // Check exaequo and display the same rank
-$concours_default_values['author_vote_available'] = false; // Dont allow author to vote for his own photo
+//$concours_default_values['author_vote_available'] = false; // Dont allow author to vote for his own photo
+$concours_default_values['author_vote_available'] = 0; // 0: Disable check between curent user and Author/AddedBy info for a photo ==> All user cound vote  
+													   // 1: Check between "Author" (of photo) and "User" 
+													   // 2: Check between "AddedBy" (of photo) and "User" 
+													   // 3: Check between "Author" OR "AddedBy" and "User" 
+
 $concours_default_values['concours_change_score']   = true; // Allow a user to change his score afer a validation
+$concours_default_values['concours_deadline']   = 2; // 0: dont show deadline; 1: deadline version 1; 2: deadline version 2
+$concours_default_values['mask_thumbnail']   = true; // Mask thumbnail on category page before the contest start
+$concours_default_values['nb_concours_page']   = 10; // nb of contest by page (on admin page)
+$concours_default_values['active_global_score_page']   = false; // activate global page for vote/score (all image in 1 page)
+$concours_default_values['score_mode']   = 1; // score mode. 0: text box / 1: stars 
+$concours_default_values['text_overlay']   = "Vote déjà enregistré <br>"; // text to display when the score is already present and the option concours_change_score is false (allow the user to change the score after vote) 
 
 ?>
Index: extensions/ConcoursPhoto/include/index.php
===================================================================
--- extensions/ConcoursPhoto/include/index.php	(revision 9370)
+++ extensions/ConcoursPhoto/include/index.php	(revision 32457)
