<?php
/**
 * This file is part of ContestMX2
 * pragmaMx - Web Content Management System.
 * Copyright by TerraProject (c)2009
 *
 * pragmaMx is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * $Revision: 0.2 $
 * $Author: O.Herfurth $
 * $Date: 2009/05/01 $
 */

if (!defined("mxMainFileLoaded")) die ("You can't access this file directly...");

include ("modules/" . $module_name . "/inc/slimbox/mx_slimbox.php");
include_once ("modules/" . $module_name . "/inc/cmxUserpoints.php");
include_once ("modules/" . $module_name . "/version.php");

function getUserID($uname)
{
    $user=mxGetUserDataFromUsername($uname);
	return $user['uid'];
}

function isContestAdmin()
{
    global $module_name, $CONT_CFG;
	//$admindata=mxGetAdminData();
	$admin=mxGetAdminSession();
	$i=false;
	foreach ($CONT_CFG['ADMINS'] as $key => $element){
	  if ($element==$admin['aid']) {$i=true;}
	  //echo "[->$element-".$admin['aid']."-".$i."-]";
	}
    return $i;
}

function isSetCookie()
{
 
 setcookie("mx-contest2-test","test",time()+1000);
 
 if (isset($_COOKIE['mx-contest2-test'])) 
 { 
   return true;
   } else {
   return false;
  }
 
}

function isHome()
{  
   echo "<a name='home'></a>";
}

function goHome($cat=0)
{
    global $module_name, $CONT_CFG;
    $img2="<img src='modules/" . $module_name . "/style/images/toolbar/bullet_arrow_up.png' alt='"._GOHOME."' title='"._GOHOME."'/>";
	echo "<table width=100%><tr><td width=30%><p class='align-center'><a href=\"javascript:history.go(-1)\">["._BACK."]</a></p></td>";
	if ($cat==0) echo "<td>&nbsp;</td><td width=30%><p class='align-center'><a href='modules.php?name=Contest' >&raquo; ".readCategoryBaseName()." &laquo;</a></p></td>";
	echo "<td>&nbsp;</td><td width=30%><p class='align-center'><a href='#home'>["._GOHOME."]</a></p></td></tr></table><br/>";
	
}
function goHomeBACK()
{
    global $module_name, $CONT_CFG;
    $img2="<img src='modules/" . $module_name . "/style/images/toolbar/bullet_arrow_up.png' alt='"._GOHOME."' title='"._GOHOME."'/>";
	echo "<table width=100%><tr><td width=30%><p class='align-center'><a href=\"javascript:history.go(-1)\">["._BACK."]</a></p></td>";
	echo "<td>&nbsp;</td><td width=30%><p class='align-center'><a href='#home'>["._GOHOME."]</a></p></td></tr></table><br/>";
	cmx_copy(1);
}

function safeFilter ($cid,$fpos,$sortid,$filtername)
{
    global $module_name, $CONT_CFG;
	
			$content = "<?php\n";
			$content .= "/***************************************************************************\n";
			$content .= " DONT CHANGE THIS FILE \n";
			$content .= "***************************************************************************/\n\n";
			$content .= "if (!defined(\"mxMainFileLoaded\")) die (\"You can't access this file directly...\");\n\n";
			$content .= "\$cid='". $cid."';\n";
			$content .= "\$fpos='". $fpos."';\n";
			$content .= "\$sortid='". $sortid."';\n";
			$content .= "\n";
			$content .= "?>";
			$conffile = "modules/" . $module_name . "/inc/filter.".$filtername.".php";
			@chmod($conffile, 0755);
			$file = @fopen($conffile, "w");
            fwrite($file, $content);
            fclose($file);
}

function pmxHeaderAdd2($c="")
{
   if (!empty($c))  pmxHeader::add($c); 
   return;
}

function IsContest($pid)
{
    global $prefix;
    $result=sql_query("SELECT conid from ".$prefix."_pmxContest_contest where conid ='".$pid."' and published='1'");
	if (sql_num_rows($result)) 
	 {
	 return true;
	 } else {
	 echo mxErrorScreen("Sorry... This page doesn't exist.");
	 }
}

function IsCategory($pid)
{
    global $prefix;
    $result=sql_query("SELECT catid from ".$prefix."_pmxContest_category where catid ='".$pid."' and published='1'");
	if (sql_num_rows($result)==1) 
	 {
	 return true;
	 } else {
	 echo mxErrorScreen("Sorry... This page doesn't exist.");
	 }
}


function checkCategory($pid)
{
    global $prefix;
    $result=sql_query("SELECT catid from ".$prefix."_pmxContest_category where catid ='".$pid."'");
	if (sql_num_rows($result)==1) 
	 {
	 return true;
	 } else {
	 return false;
	 }
}
function PageNoExist(){
	           include_once("header.php");
			   OpenTable();
				echo "<br /><p class=warning>"._PAGENOEXIST."</p><br />";
				echo _GOBACK;  
			   CloseTable();
			   include_once ("footer.php");
}
function checkContest($pid)
{
    global $prefix;
    $result=sql_query("SELECT conid from ".$prefix."_pmxContest_contest where conid ='".$pid."'");
	if (sql_num_rows($result)) 
	 {
	 return true;
	 } else {
	 return false;
	 }
}
function readContest($con=0)
{
        global $prefix, $currentlang,$module_name, $CONT_CFG;
		    
		    $result = sql_query("SELECT * from ".$prefix."_pmxContest_contest where conid ='".$con."'") ;
			$mycat = sql_fetch_assoc($result);
			return $mycat;
}
function readContestStatus($con=0)
{
        global $prefix, $currentlang,$module_name, $CONT_CFG;
		    
		    $result = sql_query("SELECT status from ".$prefix."_pmxContest_contest where conid ='".$con."'") ;
			$mycat = sql_fetch_assoc($result);
		    $i= $mycat['status'];
			return $i;
}
function readContestName($con=0)
{
        global $prefix, $currentlang,$module_name, $CONT_CFG;
		    
		    $result = sql_query("SELECT cattitle from ".$prefix."_pmxContest_contest where conid ='".$con."'") ;
			$mycat = sql_fetch_assoc($result);
		    $i= $mycat['cattitle'];
			return $i;
}


function readCategory($con=1)
{
        global $prefix, $currentlang,$module_name, $CONT_CFG;
		    
		    $result = sql_query("SELECT * from ".$prefix."_pmxContest_category where catid ='".$con."'") ;
			$mycat = sql_fetch_assoc($result);
			return $mycat;
}

function readCategoryName($cat=1)
{
        global $prefix, $currentlang,$module_name, $CONT_CFG;
		  if ($cat>1) {
		    $result = sql_query("SELECT catid, cattitle from ".$prefix."_pmxContest_category where catid ='".$cat."'") ;
			$mycat = sql_fetch_assoc($result);
		    $i= $mycat['cattitle'];
			} else {
			$i=_NONE;
			}
			return $i;
}
function readCategoryBaseName()
{
        global $prefix, $currentlang,$module_name, $CONT_CFG;
		    $result = sql_query("SELECT catid, cattitle from ".$prefix."_pmxContest_category where catid ='1'") ;
			$mycat = sql_fetch_assoc($result);
		    $i= $mycat['cattitle'];
			return $i;
}
function onClick (){
    global $prefix, $currentlang,  $bgcolor1, $bgcolor2, $bgcolor3 ,$module_name, $CONT_CFG;
	 pmxHeaderAdd2('<script type="text/javascript" src="modules/'.$module_name.'/inc/click.js"></script>');
}

function popWindowJS (){
    global $prefix, $currentlang,  $bgcolor1, $bgcolor2, $bgcolor3 ,$module_name, $CONT_CFG;
	 pmxHeaderAdd2('<script type="text/javascript" src="modules/'.$module_name.'/inc/popWindow.js"></script>');
}
function popViewJS (){
    global $prefix, $currentlang,  $bgcolor1, $bgcolor2, $bgcolor3 ,$module_name, $CONT_CFG;
	 pmxHeaderAdd2('<script type="text/javascript" src="modules/'.$module_name.'/inc/viewImage.js"></script>');
}

function addOverlib (){
    global $prefix, $currentlang,  $bgcolor1, $bgcolor2, $bgcolor3 ,$module_name, $CONT_CFG;
	 pmxHeaderAdd2('<script type="text/javascript" src="modules/'.$module_name.'/inc/overlib.js"></script>');
}

function addCSS (){
    global $prefix, $currentlang,  $bgcolor1, $bgcolor2, $bgcolor3 ,$module_name, $CONT_CFG;
	 pmxHeaderAdd2('<style type="text/css" media="all">@import "modules/'.$module_name.'/style/style.css";</style>');
}

function switchPopup() {
    global $prefix, $currentlang,  $bgcolor1, $bgcolor2, $bgcolor3 ,$module_name, $CONT_CFG;
    
    if ($CONT_CFG['SET_POPUP']==4) CON_AddprettyPhoto();
    if ($CONT_CFG['SET_POPUP']==3) CON_pmxAddSlimbox();
    if ($CONT_CFG['SET_POPUP']==2) popViewJS();
    //if ($CONT_CFG['SET_POPUP']==2) popWindowJS();
}

function popupWindow($image, $title, $alt , $mode, $text)
{
    global $prefix, $currentlang,  $bgcolor1, $bgcolor2, $bgcolor3 ,$module_name, $CONT_CFG;
	$iLink="";
	switch ($CONT_CFG['SET_POPUP']) {
	     case 1:
		 $iLink= popupNewWindow($image, $title, $alt,  $mode,$text);
		 break;
	     case 2:
		 //$iLink=popupJSWindow($image, $title, $alt ,  $mode ,$text);
		 $iLink=popupJSView($image, $title, $alt ,  $mode ,$text);
		 break;
	     case 3:
		 $iLink=CON_CreateLinkForSlimbox ($image, $title, $alt ,  $mode,$text);
		 break;
	     case 4:
		 $iLink=CON_CreateLinkForPrettyPhoto ($image, $title, $alt,  $mode,$text);
		 break;
	}
	return $iLink;
}
function popupJSWindow($image, $title="", $alt = "",  $mode = "",$text="")
{
    global $prefix, $currentlang,  $bgcolor1, $bgcolor2, $bgcolor3 ,$module_name, $CONT_CFG;
   $aa= " <a href=\"\" onclick=\"popupWindow('".$image."', '".$text."', 800,600, 1)\" class=\"toolbar\">";
   $aa.=$alt."</a>";
   return $aa;
}
function popupJSView($image, $title="", $alt = "",  $mode = "",$text="")
{
    global $prefix, $currentlang,  $bgcolor1, $bgcolor2, $bgcolor3 ,$module_name, $CONT_CFG;
	list ($src_width, $src_height, $type, $w) = getimagesize($image);
   $aa= " <a href=\"Javascript:ViewImage('".$image."', $src_width,$src_height, '".$text."');\">";
   //<a href="Javascript:ViewImage('bild96.jpg','700','467','Planet Flower');">

   $aa.=$alt."</a>";
   return $aa;
}
function popupJSWindow2($image, $title="", $alt = "",  $mode = "",$text="")
{
    global $prefix, $currentlang,  $bgcolor1, $bgcolor2, $bgcolor3 ,$module_name, $CONT_CFG;
	//$image=$_SERVER['SERVER_NAME']."/".$image;
   $aa= " <a href=\"modules/" . $module_name . "/inc/showpicture.php?pic=$image\" target=_new>";
   $aa.=$alt."</a>";
   return $aa;
}

function popupNewWindow($image, $title="", $alt = "",  $mode = "",$text="")
{
    global $prefix, $currentlang,  $bgcolor1, $bgcolor2, $bgcolor3 ,$module_name, $CONT_CFG;
   $aa= " <a href=\"".$image."\" title=\"".$title."\" target=_blank >";
   $aa.=$alt."</a>";
   return $aa;
}


function CON_AddprettyPhoto()
{
   
    global $module_name, $CONT_CFG;
 
   pmxHeader::Add('<script src="modules/' . $module_name . '/inc/jquery_1_3_2.js" type="text/javascript" charset="utf-8"></script>');

   pmxHeader::Add('<link rel="stylesheet" href="modules/' . $module_name . '/inc/prettyPhoto/css/prettyPhoto.css" type="text/css" media="screen" charset="utf-8" />');
   pmxHeader::Add('<script src="modules/' . $module_name . '/inc/prettyPhoto/js/jquery.prettyPhoto.js" type="text/javascript" charset="utf-8"></script>');
   
   $prettyConfig="<script type=\"text/javascript\" charset=\"utf-8\">
                  $(document).ready(function(){
				  $(\"a[rel^='prettyPhoto']\").prettyPhoto({";

	$prettyConfig.="animationSpeed: '".$CONT_CFG['POPUP_SPEED']."',"; /* fast/slow/normal */
	$prettyConfig.="padding: ".$CONT_CFG['LIGHTBOX_BORDER'].", ";/* padding for each side of the picture */
	$prettyConfig.="opacity: ".$CONT_CFG['LIGHTBOX_TRANS'].", ";/* Value betwee 0 and 1 */
	$prettyConfig.="showTitle: ".$CONT_CFG['LIGHTBOX_TITLE'].", ";/* true/false */
	$prettyConfig.="allowresize: ".$CONT_CFG['LIGHTBOX_SIZE'].", ";/* true/false */
	$prettyConfig.="counter_separator_label: '/', ";/* The separator for the gallery counter 1 \"of\" 2 */
	$prettyConfig.="theme: '".$CONT_CFG['LIGHTBOX_THEME']."', ";/* light_rounded / dark_rounded / light_square / dark_square */
	$prettyConfig.="hideflash: false, ";/* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
	$prettyConfig.="modal: false, ";/* If set to true, only the close button will close the window */
	
	 $prettyConfig.="changepicturecallback: function(){}, ";/* Called everytime an item is shown/changed */
	 $prettyConfig.="callback: function(){} ";/* Called when prettyPhoto is closed */
	
	$prettyConfig.="});
	                });
			     </script>";
   
   pmxHeader::Add($prettyConfig);
}



/*
	Parameter:
		$image 	- Pfad zum Bild
		$title	- Optional: Titel des Bildes (wenn leer, wird der Bildname verwendet)
		$alt	- Optional: Beschreibung oder HTML-Code für Thumbnail (Wenn leer, wird der Bildname verwendet)
		$mode   - Optional: Galeriename ohne eckige Klammern 

	Rückgabewert:
		String - beinhaltet den HTML-Code für den Link 

*/

function CON_CreateLinkForPrettyPhoto ($image, $title="", $alt = "",  $mode = "",$text="")
{
    //$border = (int)$border;
//    @$size = GetImageSize($image);
    $para = "";
    if (empty($title)) {
        $pathinfo = pathinfo($image);
        $title = $pathinfo["filename"];
    }
        $para .= " title=\"" . $title . "\" alt=\"" . $title . "\"";

    if (!empty($text)) {
        
        $text1 = "name=\"".$text."\"";
		}else{
		$text1="";
    }
		
/*    if (empty($size[3])) {
        if (MX_IS_ADMIN) {
            return "<span class=\"tiny\">missing image:<br />" . $image . "</span>";
        }
        return $alt;
    }
*/	
	if (empty($alt)) {
        $pathinfo = pathinfo($image);
		$alt=$pathinfo["filename"];
	}
	if (empty($mode)) {
	    $more="";
		} else {
		$more="['".$mode."']";
	}
	$para='<a href="'.$image.'" rel="prettyPhoto'.$more.'" '.$para.'>'.$alt.'</a>';
	return $para;
}


function loadConfig () {
    global $prefix, $currentlang,$module_name, $bgcolor1, $bgcolor2, $bgcolor3, $CONT_CFG;


    include ("modules/" . $module_name . "/config.php");

    /* falls config.php nicht schreibgeschuetzt, dieses tun... */
    if (is_writable("modules/" . $module_name . "/config.php")) {
       mxChangeFilePerms("modules/" . $module_name . "/config.php", 'lock');
    }

}

function contest_ceck_category ($cid=0)
{
    global $prefix, $currentlang,  $bgcolor1, $bgcolor2, $bgcolor3 ,$module_name, $CONT_CFG;
    $cat_title="";
    if ($cid>0) {
            $res = sql_query("select title from " . $prefix . "_contest_categories where cid='" . $cid . "'");
            list($cat_title) = sql_fetch_row($res);
	   if ($cat_title=="") {		
        mxErrorScreen("Sorry... This page doesn't exist.");
	   } 
	}
	return $cat_title;
}

function seDay($begin,$end,$format,$sep){ 

	//$timeA = '09-03-2081'; 
	//$timeB = date("m-d-Y"); 
	//
	//$sonne = seDay($timeA,$timeB,"mdY","-"); 
	//
	//echo 'Die nächste totale Sonnenfinsternis in Deutschland ist in ' . $sonne . ' Tagen'; 
	//
	
	$pos1 = strpos($format, 'd'); 
	$pos2 = strpos($format, 'm'); 
	$pos3 = strpos($format, 'Y'); 
	
	$begin = explode($sep,$begin); 
	$end = explode($sep,$end); 
	
	$first = GregorianToJD($end[$pos2],$end[$pos1],$end[$pos3]); 
	$second = GregorianToJD($begin[$pos2],$begin[$pos1],$begin[$pos3]); 
	
	if($first > $second) 
	return $first - $second; 
	else 
	return $second - $first; 

} 

function untilDate ($enddate)
{
	$timeB = date("Y-m-d");
	if ($timeB>$enddate) {
	 $i=-1;
	} else {
 	 $i=seDay($timeB,$enddate,"Ymd","-");
	}
	return $i;
}

function langDate ($datum="2010-01-01")
{
   if(trim($datum)=="") $datum="2010-01-01";
   $lang=$GLOBALS['currentlang'];
   if ($lang="german_du") $lang="german";
   
		  $a= explode('-', $datum); 
		  if ($lang=="german") {
		    $dateformat="d.m.Y";
			} else {
		    $dateformat="M.d.Y";
		  }	
		  return date($dateformat,mktime(0,0,0,$a[1],$a[2],$a[0]));

}


function cmx_copy($backend=0)			// Keep copyrights !!
{
    global $prefix, $module_name, $CONT_CFG;
	$l=-2000;
	if ($CONT_CFG['SET_SHOW_COPYRIGHT']==1 or $backend!=0) $l=0;
   echo "<p align='center' class='tiny' style='text-indent:".$l."em;'><a href='http://www.tecmu.de' target=_blank><img src='modules/" . $module_name . "/style/images/site/contestMX_mb.jpg' title='Contest mX by tecmu.de' alt='Contest mX by tecmu.de'  /></a></p>";
}

function cmx_copyright ()
{
    global $prefix, $module_name, $CONT_CFG,$cmx_version,$cmx_revision;
    require("modules/" . $module_name . "/setup.pmx.php");
	echo "<p align='center' class='tiny'>".$credits;
	echo "Version ".$cmx_version." Build ".$cmx_revision."</p>";
	
}
	
function create_jpgthumb($original, $thumbnail, $max_width, $max_height, $quality) {
	global $CONT_CFG;
	
	if (!is_file($original)) return false;
	
	list ($src_width, $src_height, $type, $w) = getimagesize($original);
   
	if (!$srcImage = @imagecreatefromjpeg($original)) {
		return false;
	}
	# image resizes to natural height and width
	
	if ($CONT_CFG['THUMB_CONVERT']==0) {
	   // width
			$thumb_width = $max_width;
			$thumb_height = floor($src_height * ($max_width / $src_width));
	   } else {
	   // height
			$thumb_height = $max_height;
			$thumb_width = floor($src_width * ($max_height / $src_height));
	} 
	
	if ($CONT_CFG['THUMB_CONVERT']==2) {
		  if($thumb_width > $max_width) {
			$thumb_width = $max_width;
			$thumb_height = floor($src_height * ($max_width / $src_width));
		  }
	}
	
		if (!@$destImage = imagecreatetruecolor($thumb_width, $thumb_height)) {
			return false;
		}
	   
		if (!@imagecopyresampled($destImage, $srcImage, 0, 0, 0, 0, $thumb_width, $thumb_height, $src_width, $src_height)) {
			return false;
		}


	@imagedestroy($srcImage);

  
	if (!@imagejpeg($destImage, $thumbnail, $quality)) {
		return false;
	}                       
	@imagedestroy($destImage);      
	return true;
}

function string_to_filename($word) {
    $tmp = preg_replace('/^\W+|\W+$/', '', $word); // remove all non-alphanumeric chars at begin & end of string
    $tmp = preg_replace('/\s+/', '_', $tmp); // compress internal whitespace and replace with _
	$tmp = preg_replace('/[^a-z0-9\\040\\.\\-\\_]/i',"_",$tmp); // alow '-._'
    return strtolower(preg_replace('/\W-/', '', $tmp)); // remove all non-alphanumeric chars except _ and -
}	

function title_replace($ctitle="")
{
	  $ctitle=trim($ctitle);
	  $ctitle=preg_replace('/[^a-z0-9\\040\\.\\-\\_\\\\]/i',"-",$ctitle);
	  $ctitle= preg_replace('/\s+/', '-', $ctitle);
      return $ctitle;
}

function addCaptcha () 
{
    global $prefix, $module_name, $CONT_CFG;
	require("includes/captcha/captcha_java.php");

		echo "<br><center><img id=\"captchaimage\" src=\"includes/captcha/captchaimg.php?" . md5(crypt(uniqid(''))) . "\" alt=\"\"><br>";
		echo  _CAPTCHAINSERT . '<br><input type="text" name="captcha" value="" size="20" maxlength="20"><br><br><input type="button" value="' . _CAPTCHARELOAD . '" onclick="do_reload(); return false;"></center>';
}

function IsCaptchaok()
{
    global $prefix, $module_name, $CONT_CFG;
	require("includes/captcha/__captcha/SlickCaptcha.php");
	require("includes/captcha/__captcha/PhraseFactory.php");
	if ((!isset($_POST['captcha'])) || (empty($_POST['captcha']))) {
		$_POST['captcha'] = "abc!!def";
		return false;
	} else {
		$givenCaptcha = $_POST['captcha'];
		$storedCaptcha = PhraseFactory::get('', $passphraselenght, $givenCaptcha, $storagetype);
		
		if ($givenCaptcha !== $storedCaptcha) {
		  return false;
		} else {
		  return true;
		}    
	} 
}

function calculate_rank ($cid=0)
{
    global $prefix, $module_name, $CONT_CFG;
	
    $result=sql_query("SELECT conid,config from ".$prefix."_pmxContest_contest where conid ='".$cid."' ");
	if (!sql_num_rows($result))   echo mxErrorScreen("Sorry... This page doesn't exist.");
    
	$mycon=sql_fetch_assoc($result);
	
	$config=unserialize($mycon['config']);
    
            $res = sql_query("select * from " . $prefix . "_pmxContest_picture where cid='" . $cid . "'");		// hole Bild
			
			while ($pid = sql_fetch_assoc($res))
			{
			    $res1 = sql_query("select * from " . $prefix . "_pmxContest_voting where cid='" . $cid . "' and pic_id='" . $pid['pid'] . "' and active='1'");	
				// hole Votings
				// list($rank)=sql_fetch_row($res1);
			       $points=0;
				   $i1=0;
				   $i2=0;
				   $i3=0;
				   $iso=0;
				
				while ($rank = sql_fetch_assoc($res1))
				{
				   $i=0;
				   switch ($rank['rank']) {
				     case 1:
					 $i=intval($config['CONFIG_VOTING_P1']);
					 $i1++;
					 break;
				     case 2:
					 $i2++;
					 $i=intval($config['CONFIG_VOTING_P2']);
					 break;
				     case 3:
					 $i3++;
					 $i=intval($config['CONFIG_VOTING_P3']);
					 break;
				     case 999:
					 $iso++;
					 $i=intval($config['CONFIG_VOTING_PSO']);
					 break;
				   }
				   
				  //$points=$points+$i;
				}
				$points=$i1*intval($config['CONFIG_VOTING_P1'])+$i2*intval($config['CONFIG_VOTING_P2'])
				       +$i3*intval($config['CONFIG_VOTING_P3'])+$iso*intval($config['CONFIG_VOTING_PSO']);
					   
			    sql_query(" Update " . $prefix . "_pmxContest_picture set 
				     points='".$points."',
				     points1='".$i1."',
				     points2='".$i2."',
				     points3='".$i3."',					 
				     pointssp='".$iso."'
					 where pid='" . $pid['pid'] . "'");

			}
            
			$res3 = sql_query("select pid from " . $prefix . "_pmxContest_picture where cid='" . $cid . "'and active='1' order by points desc, points1 desc, points2 desc, points3 desc, datetime asc");		// hole Bild
			//$mypic=sql_fetch_assoc($res3);
			$i=1;
			$rank1=0;
			$rank2=0;
			$rank3=0;
			
			while ($mypic=sql_fetch_assoc($res3))
			{
			    sql_query(" Update " . $prefix . "_pmxContest_picture set rank='".$i."' where pid='" . $mypic['pid'] . "' ");
				if ($i==1) $rank1=$mypic['pid'];
				if ($i==2) $rank2=$mypic['pid'];
				if ($i==3) $rank3=$mypic['pid'];
			   $i++;
			  
			}
			
			sql_query("update " . $prefix . "_pmxContest_contest set 
						place1='".$rank1."',
						place2='".$rank2."',
						place3='".$rank3."'
			            where conid='" . $cid . "'");

}

function make_awards ($pid)
{
    global $prefix, $module_name,$CONT_CFG;

    $result=sql_query("SELECT * from ".$prefix."_pmxContest_contest where conid ='".$pid."' ");
	if (!sql_num_rows($result))   echo mxErrorScreen("Sorry... This page doesn't exist.");
    
	$mycon=sql_fetch_assoc($result);
	
	$config=unserialize($mycon['config']);
	
	       $awardpath=$CONT_CFG['PIC_FOLDER'].$mycon['alias']."/";
		   $text=$config['CONFIG_AWARDS_TITLE'];
		   $sx1=intval($config['CONFIG_AWARDS_FONTX']);
		   $sy1=intval($config['CONFIG_AWARDS_FONTY']);
		   $sw=60;
		   $sh=13;
		   
		   $px1=intval($config['CONFIG_AWARDS_PIC_X']);
		   $py1=intval($config['CONFIG_AWARDS_PIC_Y']);
		   $pw=intval($config['CONFIG_AWARDS_PIC_WIDTH']);
		   $ph=intval($config['CONFIG_AWARDS_PIC_HEIGHT']);
	   
	   $result1 = sql_query("select * from " . $prefix . "_pmxContest_picture where cid='" . intval($pid) . "' and active='1'  order by rank asc limit 3");
	   
       while($res1=sql_fetch_assoc($result1)) {
	       $award="";
		   $awfile="";
           switch (intval($res1['rank'])) {
		      case 1:
			    $award=$CONT_CFG['AWARDS_FOLDER'].$config['CONFIG_AWARDS_P1'];
				break;
		      case 2:
			    $award=$CONT_CFG['AWARDS_FOLDER'].$config['CONFIG_AWARDS_P2'];
				break;
		      case 3:
			    $award=$CONT_CFG['AWARDS_FOLDER'].$config['CONFIG_AWARDS_P3'];
				break;
		   
		   }
			 
		   $awfile=$awardpath.$pid."-".$res1['rank'].".jpg";
		   if (is_file($award)) {	
		     if ($config['CONFIG_AWARDS_AUTO']==1) {	   
			   $image1=imagecreatefromjpeg($res1['pic_url']);
			   $img_size=getimagesize($res1['pic_url']);
			   
			   $imgh=$ph/$pw*$img_size[0];
			   $py2=($img_size[1]-$imgh)/2;
			   
			   $img = imagecreatefromjpeg($award); //Hintergrundbild
			   imagecopyresampled($img, $image1, $px1,$py1,0,$py2, $pw,$ph, $img_size[0], $imgh ); 
			   
			   $ttf = "modules/".$module_name."/style/fonts/".$config['CONFIG_AWARDS_FONT'];
			   if (!is_file($ttf)) $ttf="modules/".$module_name."/style/fonts/ARIAL.ttf";
			   $ttfsize = ($config['CONFIG_AWARDS_FONTSIZE']==0)?7:$config['CONFIG_AWARDS_FONTSIZE']; //Schriftgrösse
			   $angle = 0;
			   $color = ImageColorAllocate($img, 255, 255, 255); //Farbe
			   imagettftext($img, $ttfsize, $angle, $sx1, $sy1, $color, $ttf, $text);
			   imagejpeg($img,$awfile,$CONT_CFG['THUMB_QUALITY']);
		     } else {
			   @copy($award,$awfile);
			 } 
		  } else {
		   $awfile="";  
		  }
			 switch (intval($res1['rank'])) {
				  case 1:
					sql_query("update " . $prefix . "_pmxContest_contest set place1='".$res1['pid']."',
			                award_p1='".$awfile."' where conid='" . $pid . "'");
					break;
				  case 2:
					sql_query("update " . $prefix . "_pmxContest_contest set place2='".$res1['pid']."',
			                award_p2='".$awfile."' where conid='" . $pid . "'");
					break;
				  case 3:
					sql_query("update " . $prefix . "_pmxContest_contest set place3='".$res1['pid']."',
			                award_p3='".$awfile."' where conid='" . $pid . "'");
					break;
			 }
		    

       }
			$result2 = sql_query("select * from ".$prefix."_pmxContest_picture where cid='".intval($pid)."' and active='1' order by pointssp desc, points desc, points1 desc, points2 desc, points3 desc, datetime asc limit 1 ");	   
			$res2=sql_fetch_assoc($result2) ;
			
			$award=$CONT_CFG['AWARDS_FOLDER'].$config['CONFIG_AWARDS_PSO'];
			$awfile=$awardpath.$pid."-sp.jpg";
       if ($config['CONFIG_VOTING_SO']==1) {
			if (is_file($award)) {
		     if ($config['CONFIG_AWARDS_AUTO']==1 ) {	   

					   $image1=imagecreatefromjpeg($res2['pic_url']);
					   $img_size=getimagesize($res2['pic_url']);
					   
					   $imgh=$ph/$pw*$img_size[0];
					   $py2=($img_size[1]-$imgh)/2;
					   
					   $img = imagecreatefromjpeg($award); //Hintergrundbild
					   imagecopyresampled($img, $image1, $px1,$py1,0,$py2, $pw,$ph, $img_size[0], $imgh ); 
					   
					   $color = ImageColorAllocate($img, 255, 255, 255); //Farbe
					   imagettftext($img, $ttfsize, $angle, $sx1, $sy1, $color, $ttf, $text);
					   
					   imagejpeg($img,$awfile,$CONT_CFG['THUMB_QUALITY']);
					   
					
			} else {
   			   copy($award,$awfile);
			}
			sql_query("update " . $prefix . "_pmxContest_contest set award_so='".$awfile."', placeso='".$res2['pid']."' where conid='" . $pid . "'");
		   }  
		} else {
			sql_query("update " . $prefix . "_pmxContest_contest set award_so='', placeso='0' where conid='" . $pid . "'");
		   @unlink($awfile);
		}
      
     return;
}
function delete_awards ($con)
{
    global $prefix, $module_name,$CONT_CFG;
    $result=sql_query("SELECT * from ".$prefix."_pmxContest_contest where conid ='".$con."' ");
	$mypage=sql_fetch_assoc($result);
	
	    @unlink( $mypage['award_p1']);
	    @unlink( $mypage['award_p2']);
	    @unlink( $mypage['award_p3']);
	    @unlink( $mypage['award_so']);
		
	
					sql_query("update " . $prefix . "_pmxContest_contest set 
					    award_p1='',
					    award_p2='',
					    award_p3='',
					    award_so=''
						where conid='" . $con . "'");
	return;

}


?>