<?php
///////////////////////////////////////////////////////////////////////////////////////
// PHPizabi 0.848b C1 [ALICIA]                               http://www.phpizabi.net //
///////////////////////////////////////////////////////////////////////////////////////
// Please read the license.txt file before using / modifying this software           //
// Original author:         Claude Desjardins, R - feedback@realitymedias.com        //
// Last modification date:  August 13th 2006                                         //
// Version:                 PHPizabi 0.848b C1                                       //
//                                                                                   //
// (C) 2005, 2006 Real!ty Medias / PHPizabi - All rights reserved                    //
///////////////////////////////////////////////////////////////////////////////////////

	/* Check Structure Availability */
	if (!defined("CORE_STRAP")) die("Out of structure call");
	/* Administrative restriction */
	(!me('is_administrator')&&!me('is_superadministrator')?die("Access restricted"):NULL);

	$tpl = new template;
	$tpl -> Load("mngevents");
	$tpl -> GetObjects();

	$eventid = isset($_GET["e"]) ? $_GET["e"] : (isset($_POST["e"]) ? $_POST["e"] : false);

	if($eventid) {

	$event = myF(myQ("select * from `[x]events` where `id` = '{$eventid}'"));

	} else $event = false;

	
	// HANDLE THE ACTION REQUEST /////////////////////////////////////////////////////////
	if (isset($_GET["action"], $_GET["ck"]) && $_GET["action"] != NULL && is_array($_GET["ck"])) {
			
				$query = NULL;
				for ($i=0; $i < count($_GET["ck"]); $i++) {
					$query .= "OR `id`='{$_GET["ck"][$i]}'";
				}
				$query .= ")";
				
				myQ("DELETE FROM `[x]events` {$query}");
				
				$tpl -> Zone("dbUpdate", "enabled");
				$tpl -> AssignArray(array("dbUpdateCount" => mysql_affected_rows()));
	}

elseif($event){

if(isset($_POST["e"])){		

		
		/*
			Make sure a title was posted
		*/
		if (isset($_POST["title"]) && $_POST["title"] != "" && isset($_POST["body"]) && $_POST["body"] != "") {
				
			/*
				Generate the UDATE value for the posted date and time
				and make sure the event is not set to be in the past
			*/
			$eventUDate = date("U", mktime($_POST["date_h"], $_POST["date_i"], 0, $_POST["date_m"], $_POST["date_d"], $_POST["date_y"]));
			if ($eventUDate > date("U")) {
				
				/*
					Find out the display type
				*/
				if (isset($_POST["display"])) {
					
					if ($_POST["display"] == "public") $displayType = "public";
					elseif ($_POST["display"] == "shared") $displayType = "shared";
					else $displayType = "private";
				} else $displayType = "private";
				
				/*
					Handle sent image
				*/
				$mainpicture = "";
				if (
					is_uploaded_file($_FILES["file"]["tmp_name"]) 
					and preg_match('/\\.jpg$|\\.jpeg$|\\.gif$|\\.png$/i', basename($_FILES["file"]["name"]))
				) {
			
					$eventPicture = strtolower(rand(1,999)."_".basename($_FILES["file"]["name"]));
					move_uploaded_file($_FILES["file"]["tmp_name"], "system/cache/temp/{$eventPicture}");
					rename("system/cache/temp/{$eventPicture}", "system/cache/pictures/{$eventPicture}");
					if(is_file("system/cache/temp/{$event["mainpicture"]}")) @unlink("system/cache/pictures/{$event["mainpicture"]}");
					$mainpicture = ",`mainpicture` = '$eventPicture'";
				} else $eventPicture = NULL;

				if(isset($_POST["del"]))@unlink("system/cache/pictures/{$event["mainpicture"]}");
				
				/*
					Ok that's ready to save... Let's go
				*/
				myQ("update `[x]events` set `active` = '{$_POST["active"]}',`title`='{$_POST["title"]}',`location`='{$_POST["location"]}',`body`='{$_POST["body"]}',`date`='{$eventUDate}',`set_date`='".date("U")."',`display`='{$displayType}' $mainpicture where `id` = '{$event["id"]}'");
				/*
					tell the user about it!
				*/
				$tpl->Zone("editEventHeader", "success");
			}
				
			/*
				Event date was set to be in the past... uh?!
			*/
			else $tpl->Zone("editEventHeader", "retroDate");
			
		}
			
		/*
			Event had no body or no title
		*/
		else $tpl->Zone("editEventHeader", "emptyField");
		
$tpl->AssignArray(array("event.id"=>$event["id"]));

$tpl->Zone("editEventHeader","success");

//_fnc("reload",1,"?L=events.mngevents");


}else {

switch($event["display"]){

case "public":
$display_c = "";
$display_p = "checked";
$display_v = "";
break;

case "private":
$display_c = "";
$display_p = "";
$display_v = "checked";

break;

default:
$display_c = "checked";
$display_p = "";
$display_v = "";

}

	$n=0;

	for ($i=date("Y"); $i<(date("Y")+2); $i++) {

		$yearsReplaceArray[$n]["year.value"] = $i;

		$n++;

	}

	$months = array("1"=>"[January {55}]",
	                "2"=>"[February {60}]",
	                "3"=>"[March {65}]",
	                "4"=>"[April {70}]",
	                "5"=>"[May {75}]",
	                "6"=>"[June {80}]",
	                "7"=>"[July {85}]",
	                "8"=>"[August {90}]",
	                "9"=>"[September {95}]",
	                "10"=>"[October {100}]",
	                "11"=>"[November {105}]",
	                "12"=>"[December {110}]"
					);

	$hours = array("0"=>"12 am",
					"1"=>"1 am",
					"2"=>"2 am",
					"3"=>"3 am",
					"4"=>"4 am",
					"5"=>"5 am",
					"6"=>"6 am",
					"7"=>"7 am",
					"8"=>"8 am",
					"9"=>"9 am",
					"10"=>"10 am",
					"11"=>"11 am",
					"12"=>"12 pm",
					"13"=>"1 pm",
					"14"=>"2 pm",
					"15"=>"3 pm",
					"16"=>"4 pm",
					"17"=>"5 pm",
					"18"=>"6 pm",
					"19"=>"7 pm",
					"20"=>"8 pm",
					"21"=>"9 pm",
					"22"=>"10 pm",
					"23"=>"11 pm"
				);

	$mins = array(
					"0"=>":00",
					"15"=>":15",
					"30"=>":30",
					"45"=>":45"
				);
	
	$year_html = "";

	$month_html = "";

	$day_html = "";

	$hour_html = "";

	$min_html = "";

	for ($i=date("Y"); $i<(date("Y")+2); $i++) {

		if(date("Y",$event["date"]) == $i){
	
		$year_html .= "<option value=\"$i\" selected>$i</option>\r\n"; 

		} else $year_html .= "<option value=\"$i\">$i</option>\r\n"; 

	}


	foreach($months as $key => $val){

	if(date("n",$event["date"]) == $key){

		$month_html .= "<option value=\"$key\" selected>$val</option>\r\n"; 

		} else $month_html .= "<option value=\"$key\">$val</option>\r\n"; 

	}

	foreach($hours as $key => $val){

	if(date("h",$event["date"]) == $key){

		$hour_html .= "<option value=\"$key\" selected>$val</option>\r\n"; 

		} else $hour_html .= "<option value=\"$key\">$val</option>\r\n"; 

	}

	foreach($mins as $key => $val){

	if(date("i",$event["date"]) == $key){

		$min_html .= "<option value=\"$key\" selected>$val</option>\r\n"; 

		} else $min_html .= "<option value=\"$key\">$val</option>\r\n"; 

	}

	$month_lastday = date('t',mktime(0,0,0,date("d",$event["date"]),date("d",$event["date"]),date("Y",$event["date"])));

	for ($i=1; $i<$month_lastday; $i++) {

		if(date("d",$event["date"]) == $i){
	
		$day_html .= "<option value=\"$i\" selected>$i</option>\r\n"; 

		} else $day_html .= "<option value=\"$i\">$i</option>\r\n"; 

	}

$active_n = $event["active"] == 0 ? "selected" : "";

$active_y = $event["active"] == 1 ? "selected" : "";

$tpl->AssignArray(array(
			"event.id" => $event["id"],
			"event.title" => $event["title"],
			"event.location" => $event["location"],
			"event.body" => $event["body"],
			"event.mainpicture" => (!empty($event["mainpicture"]) ? $event["mainpicture"] : "nopicture.gif"),
			"event.date" => date($CONF["LOCALE_LONG_DATE_TIME"], $event["date"]),
			"event.p"=>$display_p,
			"event.c"=>$display_c,
			"event.v"=>$display_v
		));

$tpl->Zone("editEventHeader","edit");

	$tpl->AssignArray(array("active_n"=>$active_n,"active_y"=>$active_y,"date.year"=>$year_html,"date.month"=>$month_html,"date.day"=>$day_html,"date.hour"=>$hour_html,"date.min"=>$min_html));
}

} else {

	// QUERY STRING PREPARATION ///////////////////////////////////////////////////////
	if (isset($_GET["query"]) && !is_numeric($_GET["query"])) {
		
		/*
			If there was only one word, we will prefix it with
			a strict search char and append a wildcard char at
			the end of the word, this help the search engine
			find some results with short queries.
		*/
		if (strlen(trim($_GET["query"])) > 0 && !strstr(trim($_GET["query"]), " ") && !strstr($_GET["query"], "*")) {
			$query = "+".$_GET["query"]."*";
		}
				
		/*
			If there was more than a word and the boolean is
			null or is "OR", we will use the query as-is.
		*/
		else $query = $_GET["query"];

	}

	/*
		A numeric search has been passed. We will get the 
		user by ID
	*/
	if (isset($_GET["query"]) && is_numeric($_GET["query"])) $qID = "AND `id` = '{$_GET["query"]}' ";
	else $qID = NULL;

	// ORDER GET REQUEST ///////////////////////////////////////////////////////////////
	$qOrder = "ORDER BY `".(isset($_GET["order"])?$_GET["order"]:"id")."` ".(isset($_GET["direction"])?$_GET["direction"]:"ASC");


	// POPULATE FORM FIELDS ////////////////////////////////////////////////////////////
	/*
		Results per page
	*/
	$tpl -> AssignArray(array(
		"rpp.ck.10" => ( (isset($_GET["rpp"]) && $_GET["rpp"] == 10) || !isset($_GET["rpp"]) ? "selected" : NULL),
		"rpp.ck.20" => (isset($_GET["rpp"]) && $_GET["rpp"] == 20 ? "selected" : NULL),
		"rpp.ck.50" => (isset($_GET["rpp"]) && $_GET["rpp"] == 50 ? "selected" : NULL)
	));
	

	/*
		Order field
	*/
	$tpl -> AssignArray(array(
		"order.ck.id" => ( (isset($_GET["order"]) && $_GET["order"] == "id") || !isset($_GET["order"]) ? "selected" : NULL),
		"order.ck.date" => (isset($_GET["order"]) && $_GET["order"] == "date" ? "selected" : NULL),
		"order.ck.title" => (isset($_GET["order"]) && $_GET["order"] == "title" ? "selected" : NULL),
		
		"direction.ck.asc" => ((isset($_GET["direction"]) && $_GET["direction"] == "ASC") || !isset($_GET["direction"])?"selected":NULL),
		"direction.ck.desc" => (isset($_GET["direction"]) && $_GET["direction"] == "DESC" ? "selected" : NULL)
		
	));
	
	/*
		Query
	*/
	$tpl -> AssignArray(array("query" => (isset($_GET["query"])?$_GET["query"]:NULL)));
	
	// PAGINATION PREPARATION /////////////////////////////////////////////////////
	if (!isset($_GET["page"]) || !is_numeric($_GET["page"]) || $_GET["page"] == 0) $page = 1;
	else $page = $_GET["page"];
	
	/*
		Find out how many results per page we will display
	*/
	$resultsPerPage = (isset($_GET["rpp"])?$_GET["rpp"]:20);	

	// RUN QUERY //////////////////////////////////////////////////////////////////////
	$select = myQ("
		SELECT SQL_CALC_FOUND_ROWS  * 
		FROM `[x]events` 
		WHERE `id`!='0'
		".(isset($query)&&$query!=""?"AND MATCH (`title`) AGAINST ('{$query}' IN BOOLEAN MODE)":NULL)."
		{$qID}
		{$qOrder}
		LIMIT ".(($page * $resultsPerPage) - $resultsPerPage).",{$resultsPerPage}
	");
	
	/*
		Find out how many rows we would have got
		without the limit statement
	*/
	$countRowsSelect = myQ("SELECT FOUND_ROWS()");
	$countRowsResult = mysql_fetch_row($countRowsSelect);
	$totalRows = $countRowsResult[0];

	// PAGINATION ////////////////////////////////////////////////////////////////
	$totalPages = ceil($totalRows / $resultsPerPage);
		
	if ($totalPages > 1) {
			
		$tpl -> Zone("paginationBlock", "enabled");
			
		/*
			If the total number of pages to be shown exceed
			the total number of pages we are allowed to show,
			we will show the total allowed pages instead.
		*/
		$showPages = ($totalPages>$CONF["SEARCH_PAGINATION_PADDING"]?$CONF["SEARCH_PAGINATION_PADDING"]:$totalPages);
			
		/*
			Find out the first page to start up with; if
			the total number of pages to show divided by
			two (total middle) is greater than the actual 
			page number, we will start with the actual page
			minus the result of the total pages to show 
			divided by two; else, we start with page one.
		*/
		if ($totalPages > $showPages && $page > ceil($showPages/2)) {
				
			/*
				Set the first page
			*/
			$startUpPage = $page - floor($showPages/2);
	
			/*
				Make sure we show the maximum number of pages
				when we're at the end of the results. If 
				the value of startuppage (first page
				to be shown) minus the total number of
				shown pages is greater than the total number
				of pages to be displayed, it means the
				first page should be the result of the
				total pages minus the total of shown
				pages
			*/
			if (($startUpPage+$showPages) > $totalPages) $startUpPage = $totalPages - $showPages;
		}
			
		else $startUpPage = 1;
	
		/*
			Find out the last page number we will show
		*/		
		$lastPage = ($startUpPage+$showPages<$totalPages?$startUpPage+$showPages:$totalPages);
	
		/*
			Build up the actual page link, we will force the
			L value and remove the page value.
		*/
		$getDataString = "?L=".$_GET["L"];
	
		foreach ($_GET as $var => $val) {
			if (!is_array($val)) {
				if ($var != "page" && $var != "L" && $val != "ck") $getDataString .= "&{$var}={$val}";
			} else foreach ($val as $arVar => $arVal) {
				$getDataString .= "&{$var}[]={$arVal}";
			}
		}
	
		/*
			If the page is greater than page 2
			(not page one, not page two which are
			already linked if $page <= 2), we show
			a "back" link
		*/
		if ($page > 1) {
			$tpl -> Zone("pagination.back", "linked");
			$tpl -> AssignArray(array("pagination.back.link" => $getDataString."&page=".($page-1)));
		} else $tpl -> Zone("pagination.back", "disabled");
	
		/*
			If the first page isnt page number one, 
			we will show a link to it
		*/
		if ($startUpPage > 1) {
			$tpl -> Zone("pagination.first", "linked");
			$tpl -> AssignArray(array("pagination.first.link" => $getDataString."&page=1"));
		} else $tpl -> Zone("pagination.first", "disabled");
	
	
		/*
			Generate the pages
		*/
		$paginationMergeContent = NULL;
		for ($i=$startUpPage; $i<=$lastPage; $i++) {
				
			if ($i == $page) {
				$replaceArray = array(
					"{pagination.page.pageNumber}" => $i
				);
					
				$paginationMergeContent .= strtr($GLOBALS["OBJ"]["pagination.unlinked.page"], $replaceArray);
			} else {
				$replaceArray = array(
					"{pagination.page.pageNumber}" => $i,
					"{pagination.page.link}" => $getDataString."&page={$i}"
				);
					
				$paginationMergeContent .= strtr($GLOBALS["OBJ"]["pagination.linked.page"], $replaceArray);
			}
		}
			
		if (!is_null($paginationMergeContent)) $tpl -> AssignArray(array("pagination.pages" => $paginationMergeContent));
			
			
		/*
			If the last possible page isnt shown, we will
			show a link to it here
		*/
		if ($lastPage < $totalPages) {
			
			$tpl -> Zone("pagination.last", "linked");
			$tpl -> AssignArray(array(
				"pagination.last.link" => $getDataString."&page={$totalPages}",
				"pagination.last.pageNumber" => $totalPages
			));
		} else $tpl -> Zone("pagination.last", "disabled");
			
		/*
			
		*/
		if ($page < $totalPages) {
			$tpl -> Zone("pagination.next", "linked");
			$tpl -> AssignArray(array(
				"pagination.next.link" => $getDataString."&page=".($page+1),
			));
		} else $tpl -> Zone("pagination.next", "disabled");
	
	}
		
	else $tpl -> Zone("paginationBlock", "disabled");
		
	$tpl -> AssignArray(array(
		"page.thisPage" => $page,
		"page.total" => $totalPages,
	));

	// COUNT ALL USERS ///////////////////////////////////////////////////////////
	$selectCount = myQ("SELECT SQL_CALC_FOUND_ROWS * FROM `[x]events`");
	$countRowsSelectCount = myQ("SELECT FOUND_ROWS()");
	$countRowsResultCount = mysql_fetch_row($countRowsSelectCount);
	$totalRowsCount = $countRowsResultCount[0];
	
	$tpl -> AssignArray(array(
		"dbCount.total" => $totalRowsCount,
		"dbCount.sample" => $totalRows,
		"page.pagenumber" => $page,
		"page.totalpages" => $totalPages
	));
		

	if(myNum($select) > 0){
	// ASSIGN LOOP ////////////////////////////////////////////////////////////////
	while ($eventRow = myF($select)) {
		
		$eventsReplacementArray[] = array(
			"event.id" => $eventRow["id"],
			"event.title" => $eventRow["title"],
			"event.location" => $eventRow["location"],
			"event.mainpicture" => (!empty($eventRow["mainpicture"]) ? $eventRow["mainpicture"] : "nopicture.gif"),
			"event.date" => date($CONF["LOCALE_LONG_DATE_TIME"], $eventRow["date"])
		);
	}
	
	if (isset($eventsReplacementArray)) {
		
		$tpl->Zone("editEventHeader","enabled");

		$tpl -> Loop("eventsList", $eventsReplacementArray);
	}
}

}
	$tpl -> CleanZones();

	$tpl -> Flush();
	
?>