Location: PHPKode > projects > ARBS > arbs-1.5.1.78/edit_entry_handler.php
<?php
/*
 * ARBS - Advanced Resource Booking System
 * Copyright (C) 2005-2007 ITMC der TU Dortmund
 * Based on MRBS by Daniel Gardner <http://mrbs.sourceforge.net/>
 * 
 * This program 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 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */


include_once("glob_inc.inc.php");

//do we change a entry?
if(isset($_GET['id'])){
	$id=(int)$_GET['id'];
}
$room_id=(int)$_GET['room_id'];
$type=substr(strip_tags($_GET['type']),0,8);

#only set session if all necessary fields are defined
#full input validation is done later
#dont change anything on editing entrys
if(!isset($id)&&!$_SESSION['db_entry_all_fields_set']){
        session_register("db_entry_all_fields_set");

	$storeSession=true;
	foreach($db_entry_fields as $key=>$val){
		#set storeSession=false if $val not optional,not set but has to be stored in session
		if($db_entry_fields_optional[$key])
			continue;
		if(isset($_GET[$val])&&$_GET[$val]!=""&&($_GET[$val]!="not_selected"))
			continue;
		if(!$db_entry_fields_session[$key])
			continue;
		$storeSession=false;
		break;
	}
	$_SESSION['db_entry_all_fields_set']=false;
	if($storeSession&&!$_SESSION['db_entry_all_fields_set']){
		#register userfields
		foreach($db_entry_fields as $key=>$val){
			if($db_entry_fields_session[$key]){
				session_register($val);
				$_SESSION[$val]=$_GET[$val];
			}
		}
		$_SESSION['db_entry_all_fields_set']=true;
	}
}
session_register("session_last_room_id");
$_SESSION['session_last_room_id']=$room_id;

#-----------------------------

if(!isset($_GET['area']))
	$area=get_default_area();
else
	$area=(int)$_GET['area'];
# If we don't know the right date then use today:
if (!isset($_GET['day']) or !isset($_GET['month']) or !isset($_GET['year'])){
	$day   = date("d",time());
	$month = date("m",time());
	$year  = date("Y",time());
}
else {
# Make the date valid if day is more then number of days in month:
	$day=(int)$_GET['day'];
	$month=(int)$_GET['month'];
	$year=(int)$_GET['year'];
	while (!checkdate($month, $day, $year))
		$day--;
}


//only auth changes if user changes his own entrys
if(isset($id)){
	$allow=false;
	foreach($_SESSION['session_booking_ids'] as $val){
		if($val==$id){
			$allow=true;
			break;
		}
	}
	if(!$allow&&!getAuthorised(getUserName(), getUserPassword(), 1)){
	
		showAccessDenied($day, $month, $year, $area);
		exit;
	}	

	if(!$allow&&!getWritable(sql_query1("SELECT create_by FROM mrbs_entry WHERE id=$id LIMIT 0,1"), getUserName())){
	
		showAccessDenied($day, $month, $year, $area);
		exit;
	}
}
// - Pflichtfelder pruefen!
$isOK=true;
foreach($db_entry_fields as $key=>$val){
	#set isOK=false if $val not optional and not set
	if($db_entry_fields_optional[$key])
		continue;
	if($_SESSION[$val]!=""&&$_SESSION[$val]!="not_selected")
		continue;
	if($_GET[$val]!=""&&$_GET[$val]!="not_selected")
		continue;
	$isOK=false;
	break;
}
// ------

$hour=(int)$_GET['hour'];
$minute=(int)$_GET['minute'];
$month=(int)$_GET['month'];
$day=(int)$_GET['day'];
$year=(int)$_GET['year'];
$endhour=(int)$_GET['endhour'];
$endminute=(int)$_GET['endminute'];
$end_month=(int)$_GET['end_month'];
$end_day=(int)$_GET['end_day'];
$end_year=(int)$_GET['end_year'];

$startTime = mktime($hour,$minute,0,$month,$day,$year);
$endTime = mktime($endhour,$endminute,0,$end_month,$end_day,$end_year);


//Erkennung ob limitiert & room-name
$sql = "SELECT limit_hour, limit_day, limit_week FROM mrbs_room WHERE id='$room_id LIMIT 0,1'";
$res = sql_query($sql);
if (! $res)
	fatal_error(1, sql_error().$sql);
if (sql_count($res) != 1)
	fatal_error(1, sprintf(_("Room ID %s not found"), $room_id));
$row = sql_row($res, 0);
sql_free($res);
$limit_hour = $row[0];
$limit_day = $row[1];
$limit_week = $row[2];
$room_limited = ($limit_hour!=0) || ($limit_week!=0); //|| ($limit_day!=0)   uncomment this to restore limit_day capability

if(isset($_GET['rep_type']))
	$rep_type=(int)$_GET['rep_type'];
if(isset($_GET['rep_opt']))
        $rep_opt=(int)$_GET['rep_opt'];

if(isset($_GET['rep_end_month']))
	$rep_end_month=(int)$_GET['rep_end_month'];
if(isset($_GET['rep_end_day']))
	$rep_end_day=(int)$_GET['rep_end_day'];
if(isset($_GET['rep_end_year']))
	$rep_end_year=(int)$_GET['rep_end_year'];	
	

if ($rep_type == 1 and $endTime > $startTime + 86400)
	$more_hours = 1 ;

//rep-type 3 bedeuet, Semesterauswahl!
//translate values to week-repeat

if ($rep_type==3){
    $period=(int)$_GET['period'];	
    $sql = "select startdate,enddate from mrbs_periods where id='$period'";
    $res = sql_query($sql);
    if (! $res)
        fatal_error(1, sql_error());
	if (sql_count($res) != 1)
		fatal_error(1, "Period ID $period not found.");
	$row = sql_row($res, 0);
    sql_free($res);

    //setzen auf 2, 2 ist w�chentlich
    $rep_type=2;

    $td = time();
    if ($td > $row[0]){
		//Startdatum setzen
        $sd = time();
	}
    else{
		$sd = $row[0];
    }
    //wochentag bestimmen
    $wt = date("w",$sd);
    $diff=0;
    $weekday = date("w",mktime($hour,$minute,0,$month,$day,$year));
    if ($weekday > $wt){
		//OK
        $diff = $weekday-$wt;
    }
    else{
		if($wt > $weekday){
			$diff = 7 - $wt + $weekday;
        }
    }
    $sd = $sd + $diff*60*60*24;
    $month = date("m",$sd);
    $day = date("d",$sd);
    $year = date("Y",$sd);
    $rep_end_day=date("d",$row[1]);
    $rep_end_month=date("m",$row[1]);
    $rep_end_year=date("Y",$row[1]);
}
else{
	$rep_end_day=(int)$_GET['rep_end_day'];
    $rep_end_month=(int)$_GET['rep_end_month'];
    $rep_end_year=(int)$_GET['rep_end_year'];
}
$isOK = $isOK && ($hour<=$lastBookingHour&&(!$room_limited&& ($endTime > $startTime)&& ($more_hours != 1) ) || $room_limited);

$isOK = $isOK && ($rep_type==0||$rep_end_year>$end_year || ($rep_end_year==$end_year && $rep_end_month>$end_month)||($rep_end_year==$end_year && $rep_end_month==$end_month && $rep_end_day>$end_day));

if(!$allowStartBookingAtWeekend){//config value
	$weekendcheck=date("D",mktime(0,0,0,$month,$day,$year));
        if($weekendcheck=="Sat"||$weekendcheck=="Sun"){
        	$errorText=_("You can't start a booking at a weekend.");
		$isOK=false;
        }
}

if ($isOK){
	if ($room_limited){
		$correct=false;
		if ($_GET['limit_type']=="hour"){
			$duration=(int)$_GET['li_hour'];
			$dur_units = "hours";
		}
		elseif ($_GET['limit_type']=="day"){
			$duration=(int)$_GET['$li_day'];
			$dur_units = "days";
		}
		elseif($_GET['limit_type']=="week"){			
			if($rep_li_type=="hour"){
				$duration=(int)$_GET['$rep_li_hour'];
				$dur_units = "hours";
				$correct=true;
			}
			elseif($rep_li_type=="day"){
				$duration=(int)$_GET['$rep_li_day'];
				$dur_units = "days";
				$correct=true;
			}
			if ($correct){
				$rep_type=2;
				$sd = mktime(0,0,0,$month,$day,$year);
				$sd += $li_week*7*24*60*60;
				$rep_end_day=date("d",$sd);
				$rep_end_month=date("m",$sd);
				$rep_end_year=date("Y",$sd);
			}
		}
		// Units start in seconds
		$units = 1.0;

		switch($dur_units){
			case "years":
				$units *= 52;
			case "weeks":
				$units *= 7;
			case "days":
				$units *= 24;
			case "hours":
				$units *= 60;
			case "minutes":
				$units *= 60;
			case "seconds":
				break;
		}
		$timeAddition = ($units * $duration);
	}
	else{
		$timeAddition = $endTime - $startTime;
	}


	// Units are now in "$dur_units" numbers of seconds

	if(isset($all_day) && ($all_day == "yes")){
		$starttime = mktime(0, 0, 0, $month, $day  , $year);
		$endtime   = mktime(0, 0, 0, $month, $day+1, $year);
	}
	else{
		$starttime = mktime($hour, $minute, 0, $month, $day, $year);
		$endtime   = mktime($hour, $minute, 0, $month, $day, $year) + $timeAddition;

# Round up the duration to the next whole resolution unit.
# If they asked for 0 minutes, push that up to 1 resolution unit.
		$diff = $endtime - $starttime;
		if (($tmp = $diff % $resolution) != 0 || $diff == 0)
			$endtime += $resolution - $tmp;
	}

	if(isset($rep_type) && isset($rep_end_month) && isset($rep_end_day) && isset($rep_end_year)){
	// Get the repeat entry settings
		$rep_enddate = mktime($hour, $minute, 0, $rep_end_month, $rep_end_day, $rep_end_year);
	}
	else
		$rep_type = 0;
	if(!isset($rep_day))
		$rep_day = "";

# For weekly repeat(2), build string of weekdays to repeat on:
	$rep_opt = "";
	if (($rep_type == 2) || ($rep_type == 6))
		for ($i = 0; $i < 7; $i++)
			$rep_opt .= empty($rep_day[$i]) ? "0" : "1";

# Expand a series into a list of start times:
	if ($rep_type != 0)
		$reps = mrbsGetRepeatEntryList($starttime, isset($rep_enddate) ? $rep_enddate : 0,$rep_type, $rep_opt, $max_rep_entrys, $rep_num_weeks);
# When checking for overlaps, for Edit (not New), ignore this entry and series:
	$repeat_id = 0;
	if (isset($id)){
		$ignore_id = $id;
		$repeat_id = sql_query1("SELECT repeat_id FROM mrbs_entry WHERE id=$id LIMIT 0,1");
		if ($repeat_id < 0)
			$repeat_id = 0;
	}
	else{
		$ignore_id = 0;
	}

# Acquire mutex to lock out others trying to book the same slot(s).
	if (!sql_mutex_lock('mrbs_entry'))
		fatal_error(1, _("Coudln't gain exclusive database access"));

#check, if the rooms day limit is exceeded
	$limit_day=sql_query1("SELECT limit_day FROM mrbs_room WHERE id=$room_id");
# Check for any schedule conflicts
	$err = "";
	$conflictcount=0;
# user didnt requested to book all free slots.
# thus we have to check for conflicts and show them
	if(!isset($_GET['forcebooking'])){
		if ($rep_type != 0 && !empty($reps)){
			if(count($reps) < $max_rep_entrys){
				$diff = $endtime - $starttime;
				for($i = 0; $i < count($reps); $i++){
					#$tmp = mrbsCheckFree($room_id, $reps[$i], $reps[$i] + $diff, $ignore_id, $repeat_id);
	                                $tmp= checkAllTimeslots($room_id, $reps[$i], $reps[$i]+$diff, $ignore_id, $repeat_id);
					if(!empty($tmp)){
						$err = $err . $tmp;
						$conflictcount++;
					}
				}
			}
			else{
				$err        = $lang["too_may_entrys"] . "<P>";
				$hide_title = 1;
			}
		}
		else
			$err = checkAllTimeslots($room_id, $starttime, $endtime, $ignore_id, 0);
	}

	if(empty($err)){
        # Delete the original entry from db,save original timestamp
		if(isset($id)){
			if($_GET['edit_type']=="series")
				$res=sql_query("SELECT created FROM mrbs_entry WHERE repeat_id=$id LIMIT 0,1");
			else
				$res=sql_query("SELECT created FROM mrbs_entry WHERE id=$id LIMIT 0,1");
			$zeile=mysql_fetch_row($res);
			$insert_timestamp=$zeile[0];
			mrbsDelEntry(getUserName(), $id, ($_GET['edit_type'] == "series"), 1);
		}
		else{
			$res=sql_query("SELECT NOW()");
			$zeile=mysql_fetch_row($res);
			$insert_timestamp=$zeile[0];
		}
		$newID=0;
		$type=(authGetUserLevel(getUserName(), $auth["admin"]) >= 2)?$type:$default_typel;
		//construct userfields array
                $userfields=array();
		foreach($db_entry_fields as $key=>$val){
			#optional fiels are not saved in session and non-optional fiels may ONLY be stored in session
			#so decide with data must be used
			$userfields[$key]=trim(isset($_SESSION[$val])?$_SESSION[$val]:$_GET[$val]);
		}
		if($_GET['edit_type'] == "series"){
			$new_repeat_id=mrbsCreateRepeatingEntrys($starttime,$endtime,$rep_type, $rep_enddate,$rep_opt,$room_id,getUserName(),$type,$rep_num_weeks,$userfields,isset($id)?1:0);
			sql_query("UPDATE mrbs_entry SET created='".$insert_timestamp."' WHERE repeat_id=".$new_repeat_id);
		}
		else{
			# Mark changed entry in a series with entry_type 2:
			if ($repeat_id > 0)
				$entry_type = 2;
			else
				$entry_type = 0;

			# Create the entry: after mrbsCreateSingleEntry, newID has been set to the id of the created entry
			mrbsCreateSingleEntry($starttime,$endtime,$entry_type,$repeat_id,$room_id,getUserName(), $type,$userfields,isset($id)?1:0);
			sql_query("UPDATE mrbs_entry SET created='".$insert_timestamp."' WHERE id=".$newID);
			$new_repeat_id=0;
		}
		sql_mutex_unlock('mrbs_entry');


		$area = mrbsGetRoomArea($room_id);

		#forwarding

			if($newID!=""){
					#update shoping cart id or add new id
				#session_key_to_update is set in edit_entry.php
				if($id>0){
					$_SESSION['session_booking_ids'][$_SESSION['session_key_to_update']]=$newID;
					$_SESSION['session_booking_rid'][$_SESSION['session_key_to_update']]=$new_repeat_id;
				}
				else{
					$_SESSION['session_booking_ids'][]=$newID;
					$_SESSION['session_booking_rid'][]=$new_repeat_id;
				}
				#forward to cart-page 
				Header("Location: korb_kompl.php?year=$year&month=$month&day=$day&room_id=$room_id");
				exit;
			}
          	//if we get to this point,something went wrong and we dont know what. most likely, no entry was created
          	exit;
		
	}
	# The room was not free.
	sql_mutex_unlock('mrbs_entry');
	if(strlen($err)){
		print_header($day, $month, $year, $area);
	
echo "<H1><FONT COLOR=\"#FF0000\">" . $lang["sched_conflict"] . "</H1></FONT>";	
	#	echo "<H1>" . _("Konflikt in der Planung") . "</H1>";
		if(!isset($hide_title)){
			echo "<h3>", _("The new entry is conflicting with the following entries:"), "</h3>";
			echo "<ul>";
		}
		echo $err;
		$frees=count($reps)-$conflictcount;
		if($frees>0){
			echo "<form method=GET action=edit_entry_handler.php>";
		        formHiddenFields("");
		        echo "<input type=hidden name=forcebooking value=1><input type=submit value=\"",_("Book the free slots"),"\"> &nbsp;&nbsp;<b>";
			echo "(", sprintf(_("%d of %d slots are free"), $frees, count($reps)),")</b></form>";
		}
		if(!isset($hide_title))
			echo "</ul>";
	}
	echo "<a href=\"week.php?room=",$_SESSION['session_last_room_id'],"&year=",$_GET['year'],"&month=",$_GET['month'],"\">", _("Back to calendar view"), "</a><p>";
	include("trailer.inc.php");
}
else{
	//sonst nochmal formular anzeigen!
	if($errorText!="")
		$insertError=$errorText;
	elseif(!($rep_type==0||$rep_end_year>$end_year || ($rep_end_year==$end_year && $rep_end_month>$end_month)||($rep_end_year==$end_year && $rep_end_month==$end_month && $rep_end_day>$end_day)))
		$insertError=_("The end time has to be after the start time; the end of a repeating entry has to be after the end time.");
       	elseif ($more_hours == 1)
       		$insertError = _("You can't have daily repeating entries which are longer than 24 hours.");
	elseif ($endTime > $startTime){
		$insertError = _("You didn't fill all neccessary fields. Neccessary fields are marked with a *.");
		$forceshow=true;
	}
	else{
		$insertError = _("The end time has to be after the start time; the end of a repeating entry has to be after the end time.");
	}
	include "edit_entry.php";
}
?>
Return current item: ARBS