#include <infodrom.style>
#include "lt.style"
#include "functions.inc"
#include "jobs.inc"

<postgresconnect>
<randpass>
<split_timeframe>

<ltpage title="Project Management">

<?

function email_ok($email)
{
  if (preg_match('/^[a-z0-9+.=-]+@[a-z0-9.-]+$/', $email)) {
    return true;
  } else {
    return false;
  }
}

<when <not <string-eq "$(NILI)" "" />>>
function insert_nili()
{
	# Now add the new ones

	reset ($GLOBALS['days']);
	while (list($day,$value) = each($GLOBALS['days']))
	{
		$meals = array();

		reset ($value);
		while (list($meal,$variable) = each($value))
		{
			if ($GLOBALS[$variable] == 1) { $meals[$meal] = 1; }
		}
<when <string-eq "$(DINNER)" "" />>
		$meals["dinner"] = 0;
</when>
		if (($meals["breakfast"] != 0) || ($meals["dinner"] != 0) || ($meals["sleeping"] != 0)) {
		    $query = sprintf("INSERT INTO nili (person, date, breakfast, dinner, sleeping) " .
				 " VALUES (%d, '%s', %d, %d, %d)", addslashes($GLOBALS['id']),
				 addslashes($day), $meals["breakfast"],
				 $meals["dinner"], $meals["sleeping"]);
		    pg_exec($GLOBALS['dbh'], $query) or die ("Cannot insert into nili");
		}

	}
}
</when>

# First we check the type
if ($type == "person")
{
	# OK, update person data
	
	# First we check if the person is allowed to edit this person

	if (!allowed_to_edit($id))
	{
		die ("Sorry, you are not allowed to edit this person");
	}
	
	if (is_admin() && (strlen($email) > 0) && ! email_ok($email)) {
		die ("Mail address is incorrect.");
	}

	# Then we need to get the name

	# OK, now lets start a transaction
	$query = 'BEGIN TRANSACTION';
	pg_exec($dbh, $query) or die ("Sorry, could not start transaction");
	
	# Should this person be deleted

	$query = sprintf ("SELECT project FROM person WHERE id = %d", $id);
	$sth = pg_exec ($dbh, $query) or die("Cannot discover the primary project");
	if (pg_NumRows ($sth) > 0) {
	  $row = pg_fetch_array ($sth, 0);
	  $primproject = $row['project'];
	}

	if ($delete == 1)
	{
	    $query = sprintf ("SELECT project FROM junction WHERE person = %d AND project <> '%s'",
	                      $id,
			      addslashes($LINUXTAG_AUTH['project']));
	    $sth = pg_exec($dbh, $query) or die ("Cannot investigate junction.");

	    if (pg_NumRows ($sth) == 0) {

		$query = sprintf("DELETE from junction where person = %d", $id);
		pg_exec($dbh, $query) or die ("Cannot delete junction");
		
		# Delete this person
		$query = sprintf("DELETE from person where id = %d", $id);
		pg_exec($dbh, $query) or die ("Cannot delete user");
		
<when <not <string-eq "$(NILI)" "" />>>
		# Delete data from nili
		$query = sprintf("DELETE from nili where person = %d", $id);
		pg_exec($dbh, $query) or die ("Cannot delete nilis");
</when>		
		if ( is_supporter() ) {
		  $query = sprintf("DELETE from availability where person = %d", $id);
		  pg_exec($dbh, $query) or die ("Cannot delete user from availability");

		  $query = sprintf("DELETE from assignment where person = %d", $id);
		  pg_exec($dbh, $query) or die ("Cannot delete user from assignments");
		}
            } else {	# pg_NumRows() > 1 ==> user is member of >1 projects
		$query = sprintf("DELETE from junction where person = %d AND project = '%s'",
		                 $id,
		                 addslashes($LINUXTAG_AUTH['project']));
		pg_exec($dbh, $query) or die ("Cannot delete junction.");

		$row = pg_fetch_array($sth, 0);
		$newproject = $row['project'];

	        if ($primproject == $LINUXTAG_AUTH['project']) {
		  $query = sprintf ("UPDATE person SET project = '%s',admin=0 WHERE id = %d",
				   addslashes ($row['project']),
				   $id);
                  pg_exec($dbh, $query) or die ("Cannot adjust person.");
		}
	      if ( (is_admin() && is_supporter()) ||
		 (!is_admin() && (is_supporter() || is_also_supporter()) && ($LINUXTAG_AUTH['project'] == 'Supporter')) ) {
		$query = sprintf("DELETE from availability where person = %d", $id);
		pg_exec($dbh, $query) or die ("Cannot delete user from availability");
		
		$query = sprintf("DELETE from assignment where person = %d", $id);
		pg_exec($dbh, $query) or die ("Cannot delete user from assignments");
	      }
	    }
	} else {

<when <string-eq "$(INSURANCE)" "" />>
	        $insurance = 0;
</when>

<when <string-eq "$(SOCIALEVENT)" "" />>
	        $socialevent = 0;
</when>
		# Now, update the user-data

		# First all fields a normal user can change

		$query = sprintf ("UPDATE person SET nightplace='%s',infomail=%d,insurance=%d,socialevent=%d," .
				  "mobile = '%s', " .
				  "phone = '%s', " .
				  "comment = '%s' ",
				  addslashes($nightplace),
				  $infomail, $insurance, $socialevent,
				  addslashes($mobile),
				  addslashes($phone),
				  addslashes($comment));

		# Generate a new password for the user 
		$newpass = '';
		if ($password == 1 && $list == 0 && $login == 1 && strlen ($email) > 0) {
			$newpass = randpass();
			$query = $query . sprintf(", password = '%s' ", addslashes(md5($newpass)));
		}

		$oldmail = $email;
		if (empty($email)) {
		  $email = 'NULL';
		} else {
		  $email = "'".addslashes ($email)."'";
		}

		# Now the admin-fields
		if (is_admin() && ($LINUXTAG_AUTH['project'] == $primproject)) {
			$query = $query . sprintf (", email = %s, list = %d, admin= %d, login = %d ", 
					  $email, $list, $admin, $login);
		}

		# Now the where-part
		$query = $query . sprintf(" WHERE id = %d", $id);

		# Now we hope that this works
		pg_exec($dbh, $query) or die ("Sorry, could not execute query");

<when <not <string-eq "$(NILI)" "" />>>
		# update nili

		# First delete all entries from nili

		$query = sprintf("DELETE from nili where person = %d", $id);
		pg_exec($dbh, $query) or die ("Cannot delete from nili");

		insert_nili();
</when>

		# Send the new password for the user 
		if (strlen ($newpass) > 0) {
			mail_password($oldmail, $newpass);
		}

# When should availability be updated:
#  a) user is a supporter and edits his own data
#  c) admin edits supporter data
#  d) admin edits is own data

#  a) ($oldmail == $LINUXTAG_AUTH['email']) && !is_admin() && (is_supporter() || is_also_supporter())
#  c) ($oldmail != $LINUXTAG_AUTH['email']) && is_admin() && is_supporter()
#  d) ($oldmail == $LINUXTAG_AUTH['email']) && is_admin() && is_supporter()

	   if ( (($oldmail == $LINUXTAG_AUTH['email']) && !is_admin() && (is_supporter() || is_also_supporter())) ||
		(is_admin() && is_supporter()) ) {

		# Now process the availability table
		$thisday = '';
		$counter = 0;
		for ($nr=0; $nr < $maxcounter; $nr++) {
		  $append = sprintf ("_%d", $counter);

		  if (strlen ($GLOBALS["date".$append]) > 0) {
		    $thisday = $GLOBALS["date".$append];

		  if ($GLOBALS["oid".$append] > 0) {
		    if (strlen ($GLOBALS["shift".$append]) > 0) {
		      $fromto = split_timeframe ($GLOBALS["shift".$append]);
		      $query = sprintf ("UPDATE availability SET starttime='%s',endtime='%s',comment='%s' "
				       ."WHERE oid = %d",
				       addslashes ($thisday." ".$fromto[0]),
				       addslashes ($thisday." ".$fromto[1]),
				       addslashes ($GLOBALS["comment".$append]),
				       $GLOBALS["oid".$append]);
		      pg_exec($dbh, $query) or die ("Cannot update availability");
		    } else {
		      $query = sprintf ("DELETE FROM availability WHERE oid = %d", $GLOBALS["oid".$append]);
		      pg_exec($dbh, $query) or die ("Cannot delete from availability");
		    }
		  } else {
		    if (strlen ($GLOBALS["shift".$append]) > 0) {
		      $fromto = split_timeframe ($GLOBALS["shift".$append]);
		      $query = sprintf ("INSERT INTO availability (person,starttime,endtime,comment) "
				       ."VALUES (%d,'%s','%s','%s')",
					$id,
					addslashes ($thisday." ".$fromto[0]),
					addslashes ($thisday." ".$fromto[1]),
					addslashes ($GLOBALS["comment".$append]));
		      pg_exec($dbh, $query) or die ("Cannot insert into availability");
		    }
		  }
		  }

		  $counter++;
		}
	    }
	}

	# Finish transaction
	pg_exec($dbh, "COMMIT") or die ("Could not finish my transaction");
	
} elseif ($type == "person_new") {
	# First make a permission check

	# Every admin is allowed to add more persons

	if (!is_admin())
	{
		die("Sorry, you cannot add a person");
	}

	# Every person needs to have a name

	if (empty ($name))
	{
		die("Sorry, you did not enter a name");
	}

	if ((strlen($email) > 0) && ! email_ok($email)) {
		die ("Mail address is incorrect.");
	}

<when <string-eq "$(INSURANCE)" "" />>
	        $insurance = 0;
</when>

<when <string-eq "$(SOCIALEVENT)" "" />>
	        $socialevent = 0;
</when>

	# Start a transaction
	$query = 'BEGIN TRANSACTION';
	pg_exec($dbh, $query) or die ("Sorry, could not start transaction");

	# Now, prepare the query
	
	if ($list == 1) {
		$login = 0;
		$socialevent = 0;
		$admin = 0;
	}

	$name = trim($name);
	$email = trim($email);
	
	# Generate a new password for the user 
	$newpass = '';
	if ($password == 1 && $list == 0 && $login == 1 && strlen ($email) > 0) {
		$newpass = randpass();
	}
	$oldmail = $email;
	if (empty($email)) {
	  $email = 'NULL';
	  $infomail = 0;
	  $admin = 0;
	  $login = 0;
	  $list = 0;
	} else {
	  $email = "'".addslashes ($email)."'";
	}

	$query = sprintf ("SELECT id FROM person WHERE name = '%s' AND email = '%s'",
			  addslashes ($name),
			  addslashes ($oldmail));
	$sth = pg_exec ($dbh, $query) or die("Datenbank-Abfrage!");
	if (pg_NumRows ($sth) == 0) {
	  $query = sprintf("INSERT INTO person (nightplace, infomail, insurance, comment, " .
		           "email, mobile, phone, socialevent, list, " .
			 " admin, login, password, project, name ) " .
			 "VALUES ('%s', %d, %d, '%s', %s, '%s', '%s', %d, %d, " .
			 "%d, %d, '%s', '%s', '%s')",
			 addslashes($nightplace), $infomail, $insurance, addslashes($comment),
			 $email,
			 addslashes($mobile),
			 addslashes($phone),
			 $socialevent, $list, $admin, $login, addslashes(md5($newpass)), 
			 addslashes($LINUXTAG_AUTH['project']), addslashes($name));
	  $sth = pg_exec($dbh, $query) or die ("Sorry, cannot insert: " . $query);

	  $query = sprintf ("SELECT id FROM person WHERE oid = %d", pg_getlastoid ($sth));
	  $sth = pg_exec ($dbh, $query) or die("Datenbank-Abfrage!");
          if (pg_NumRows ($sth) > 0) {
	    $row = pg_fetch_array($sth, 0);
            $id = $row['id'];
	  } else {
	    die ("Cannot retrieve id through oid.");
	  }

	  $query = sprintf ("INSERT INTO junction (person,project) VALUES (%d, '%s')",
			   $id,
			   addslashes ($LINUXTAG_AUTH['project']));
	  pg_exec ($dbh, $query) or die("Datenbank-Abfrage!");
	} else {
	  $row = pg_fetch_array($sth, 0);
          $id = $row['id'];

	  # Check if the person is already a member of this project
	  $query = sprintf ("SELECT person FROM junction WHERE person = %d AND project = '%s'",
			    $id,
			    addslashes ($LINUXTAG_AUTH['project']));
	  $sth = pg_exec ($dbh, $query) or die("Datenbank-Abfrage!");
	  if (pg_NumRows ($sth) == 0) {
	    $query = sprintf ("INSERT INTO junction (person,project) VALUES (%d, '%s')",
			     $id,
			     addslashes ($LINUXTAG_AUTH['project']));
	    pg_exec ($dbh, $query) or die("Datenbank-Abfrage!");
	  }
	  $newpass = '';
	}

<when <not <string-eq "$(NILI)" "" />>>
	# update nili

	insert_nili();
</when>
	
	# Send the new password for the user 
	if (strlen ($newpass) > 0) {
		mail_password($oldmail, $newpass);
	}

# When should availability be updated:
#  b) admin creates new supporter (i.e. is_admin() && is_supporter())

       if ( is_admin() && is_supporter() ) {

	    # Now process the availability table
	    $thisday = '';
	    $counter = 0;
	    for ($nr=0; $nr < $maxcounter; $nr++) {
	      $append = sprintf ("_%d", $counter);

	      if (strlen ($GLOBALS["date".$append]) > 0) {
		$thisday = $GLOBALS["date".$append];
	      }

	      if ($GLOBALS["oid".$append] > 0) {
		if (strlen ($GLOBALS["shift".$append]) > 0) {
		  $fromto = split_timeframe ($GLOBALS["shift".$append]);
		  $query = sprintf ("UPDATE availability SET starttime='%s',endtime='%s',comment='%s' "
				   ."WHERE oid = %d",
				   addslashes ($thisday." ".$fromto[0]),
				   addslashes ($thisday." ".$fromto[1]),
				   addslashes ($GLOBALS["comment".$append]),
				   $GLOBALS["oid".$append]);
		  pg_exec($dbh, $query) or die ("Cannot update availability");
		} else {
		  $query = sprintf ("DELETE FROM availability WHERE oid = %d", $GLOBALS["oid".$append]);
		  pg_exec($dbh, $query) or die ("Cannot delete from availability");
		}
	      } else {
		if (strlen ($GLOBALS["shift".$append]) > 0) {
		  $fromto = split_timeframe ($GLOBALS["shift".$append]);
		  $query = sprintf ("INSERT INTO availability (person,starttime,endtime,comment) "
				   ."VALUES (%d,'%s','%s','%s')",
				    $id,
				    addslashes ($thisday." ".$fromto[0]),
				    addslashes ($thisday." ".$fromto[1]),
				    addslashes ($GLOBALS["comment".$append]));
		  pg_exec($dbh, $query) or die ("Cannot insert into availability");
		}
	      }

	      $counter++;
	    }
	}

	# Finish transaction
	pg_exec($dbh, "COMMIT") or die ("Could not finish my transaction");

} elseif ($type == "comment") {
    if (!strlen ($oid)) {
        unset ($oid);
    }
    
    if (!isset ($oid)) {

	$thisproject = $LINUXTAG_AUTH['project'];
	if (isset ($project) && is_member ($project)) {
	  $thisproject = $project;
	}

	$query = sprintf ("INSERT INTO comments (project,date,who,email,body) "
                         ."VALUES ('%s','%s','%s','%s','%s')",
                         $thisproject, date ("Y-m-j H:i"),
			 $LINUXTAG_AUTH['name'], $LINUXTAG_AUTH['email'], addslashes ($body));
	pg_exec($dbh, $query) or die ("Couldn't insert comment.");
    } elseif (is_admin()) {
      $query = sprintf ("SELECT project FROM comments WHERE oid = %d", $oid);
      $sth = pg_exec ($dbh, $query) or die("Datenbank-Abfrage!");

      $permit = false;
      if (pg_NumRows ($sth) > 0) {
        $row = pg_fetch_array ($sth, 0);
	if ($row['project'] == $LINUXTAG_AUTH['project']) {
	  $permit = true;
	}
      }

      if ($permit) {
        $query = sprintf ("UPDATE comments SET who='%s',email='%s',body='%s' WHERE oid = %d",
			 addslashes ($who),
			 addslashes ($email),
			 addslashes ($body),
			 $oid);
	pg_exec($dbh, $query) or die ("Couldn't update comment.");
      } else {
        echo ("<p><strong>You are not permitted to edit this comment.</strong>");
      }
    } else {
      echo ("<p><strong>You are not permitted to edit a comment.</strong>");
    }
} elseif ($type == "project") {
    # OK, first check if the user is an admin
    if (!(is_admin())) { die ("Sorry, you are not allowed to edit this informations"); }

    # Start transaction
    pg_exec($dbh, "BEGIN TRANSACTION") or die ("Sorry, could not start transaction");

    # Now, prepare the query
    $query = sprintf("UPDATE project set url = '%s', computer = '%d', comment = '%s' where " .
    		     " name = '%s'", addslashes($url), $computer, addslashes($comment),
		     addslashes($LINUXTAG_AUTH['project']));
    
    # Execute this query
    pg_exec($dbh, $query) or die ("Could not execute query");

    $query = sprintf ("SELECT project FROM appendix WHERE project = '%s'", $LINUXTAG_AUTH['project']);
    $sth = pg_exec ($dbh, $query) or die("Datenbank-Abfrage!");

    if (pg_NumRows ($sth) > 0) {
      $appendix = true;
    } else {
      $appendix = false;
    }

    if ($appendix) {
      $query = sprintf ("UPDATE appendix SET boothtitle='%s',description='%s',description_en='%s' "
		       ."WHERE project = '%s'",
		       addslashes ($boothtitle),
		       addslashes (substr($description, 0, 1000)),
		       addslashes (substr($description_en, 0, 1000)),
		       addslashes ($LINUXTAG_AUTH['project']));
      pg_exec ($dbh, $query) or die("Datenbank-Abfrage!");
    } else {
      if (strlen ($boothtitle) || strlen ($description) || strlen ($description)) {
        $query = sprintf ("INSERT INTO appendix (project,boothtitle,description,description_en) "
			 ."VALUES ('%s','%s','%s','%s')",
			 addslashes ($LINUXTAG_AUTH['project']),
			 addslashes ($boothtitle),
			 addslashes (substr($description, 0, 1000)),
			 addslashes (substr($description_en, 0, 1000)));
        pg_exec ($dbh, $query) or die("Datenbank-Abfrage!");
      }
    }

    # Finish transaction
    pg_exec($dbh, "COMMIT") or die ("Could not finish my transaction");

} elseif ($type == "passwd") {
  if (!strcmp ($passwd,$copy)) {
    $query = sprintf ("UPDATE person SET password = '%s' WHERE email = '%s'",
		    addslashes (md5 ($passwd)), addslashes($LINUXTAG_AUTH['email']));
    pg_exec($dbh, $query) or die ("Could not update password");
  } else {
    echo "<p><b>You mistyped your password.</b></p>";
  }
} elseif ($type == "url") {
  if (!is_admin()) {
    echo  ("<p><b>You are not allowed to edit or update an URL.</b></p>");
  } else {
    $error = false;
    if (isset ($oid)) {
      $query = sprintf("SELECT project FROM urls WHERE oid = %d", $oid);
      $sth = pg_exec($dbh, $query) or die ("Sorry, cannot execute query");

      if (pg_NumRows($sth) > 0) {
        $row = pg_fetch_array($sth, 0);

	if ($row['project'] != $LINUXTAG_AUTH['project']) {
  	  echo  ("<p><b>You are not allowed to edit this URL.</b></p>");
	  $error = true;
	}
      } else {
        unset ($oid);
      }
    }

    if (isset ($oid)) {
      if (!$error) {
        if ($delete) {
	  $query = sprintf ("DELETE FROM urls WHERE oid = %d", $oid);
        } else {
	  $query = sprintf ("UPDATE urls set url='%s',description='%s',visible=%d "
			 ."WHERE oid = %d",
			 addslashes ($url),
			 addslashes ($description),
			 $visible, $oid);
	}
	pg_exec($dbh, $query) or die ("Sorry, cannot execute query");
      }
    } else {
      $query = sprintf ("INSERT INTO urls (project,url,description,visible) "
		       ."VALUES ('%s','%s','%s',%d)",
		       addslashes ($LINUXTAG_AUTH['project']),
		       addslashes ($url),
		       addslashes ($description),
		       $visible);
      pg_exec($dbh, $query) or die ("Sorry, cannot execute query");
    }
  }
} elseif ($type == "job") {
  if (!(is_supporter() && is_admin())) {
    die("You have no permissions to add or edit jobs.");
  }

  # Begin transaction
  pg_exec($dbh, "BEGIN TRANSACTION") or die ("Could not start transaction.");

  if ($id > 0 && $delete == 1) {
    $query = sprintf ("SELECT id FROM fragment WHERE job = %d", $id);
    $sth = pg_exec ($dbh, $query) or die ("Cannot execute query");
    for ($x = 0; $x < pg_NumRows($sth); $x++) {
      $row = pg_fetch_array($sth, $x);
      $query = sprintf("DELETE FROM assignment WHERE fragment = %d", $row['id']);
      pg_exec($dbh, $query) or die ("Cannot execute query");
    }
    $query = sprintf ("DELETE FROM job WHERE id = %d", $id);
    pg_exec($dbh, $query) or die ("Can't delete job.");
    $query = sprintf ("DELETE FROM fragment WHERE job = %d", $id);
    pg_exec($dbh, $query) or die ("Can't delete job fragments.");
  } else {
    if (!strlen ($section)) {
      $section = $usersection;
    }
    if (!strlen ($section)) { die ("Error: Section required."); }
    if (!strlen ($location)) { die ("Error: Location required."); }
    if (!strlen ($title)) { die ("Error: Title required."); }
    if ($id == 0) {
      $query = sprintf("INSERT INTO job (title, location, description, priority, comment, section) " .
		       " VALUES ('%s', '%s', '%s', %d, '%s', '%s')",
		       addslashes($title),
		       addslashes($location),
		       addslashes($description),
		       $priority,
		       addslashes($comment),
		       addslashes($section));
    } else {
      $query = sprintf("UPDATE job SET title = '%s', location = '%s', description = '%s', " .
		       " priority = %d, comment = '%s', section = '%s' WHERE id = %d",
		       addslashes($title),
		       addslashes($location),
		       addslashes($description),
		       $priority,
		       addslashes($comment),
		       addslashes($section),
		       $id);
    }
    $sth = pg_exec($dbh, $query) or die ("Cannot add or edit this job.");

    if ($id == 0) {
      $query = sprintf ("SELECT id FROM job WHERE oid = %d", pg_getlastoid ($sth));
      $sth = pg_exec($dbh, $query) or die ("Database Query.");
      if (pg_NumRows ($sth) > 0) {
	$row = pg_fetch_array ($sth, 0);
	$id = $row['id'];
      } else {
	die ("Can't find the job.");
      }
    }

    for ($nr=0; $nr < <nrfragments>; $nr++) {
      $append = sprintf ("_%d", $nr);

      # Calculate min. and max. people required
      #
      $foo = explode ("-", $GLOBALS["minmax".$append]);
      $min = $foo[0];
      $max = $foo[1];
      if ($max < $min) { $max = $min; }

      if ($min > 0) {
	$fromto = split_timeframe ($GLOBALS["timeframe".$append]);

	$query = sprintf ("INSERT INTO fragment (job, min, max, starttime, endtime, comment) "
		       ."VALUES (%d, %d, %d, '%s', '%s', '%s')",
		       $id, $min, $max,
		       addslashes ($GLOBALS["date".$append] . " " . $fromto[0]),
		       addslashes ($GLOBALS["date".$append] . " " . $fromto[1]),
		       addslashes ($GLOBALS["comment".$append]));
	pg_exec($dbh, $query) or die ("Database Query.");
      }
    }

    # Let's see if old fragments need to be altered
    if (isset ($oids)) {
      $bar = explode (" ", $oids);
      reset ($bar);
      while (list(,$oid) = each ($bar)) {
	if ($oid == 0) { continue; }

	$append = sprintf ("_%d", $oid);

	# Calculate min. and max. people required
	#
	if (strlen ($GLOBALS["minmax".$append]) > 0 && strlen ($GLOBALS["timeframe".$append]) > 0) {
	  $foo = explode ("-", $GLOBALS["minmax".$append]);
	  $min = $foo[0];
	  $max = $foo[1];
	  if ($max < $min) { $max = $min; }
	} else {
	  $min = 0;
	}

	if ($min > 0) {
	  $fromto = split_timeframe ($GLOBALS["timeframe".$append]);

	  $query = sprintf ("UPDATE fragment SET min=%d,max=%d,starttime='%s',endtime='%s',comment='%s' "
			 ."WHERE oid = %d",
			 $min, $max,
			 addslashes ($GLOBALS["date".$append] . " " . $fromto[0]),
			 addslashes ($GLOBALS["date".$append] . " " . $fromto[1]),
			 addslashes ($GLOBALS["comment".$append]),
			 $oid);
	  pg_exec($dbh, $query) or die ("Database Query.");
	} else {
	  $query = sprintf ("SELECT id FROM fragment WHERE oid = %d", $oid);
	  $sth = pg_exec($dbh, $query) or die ("Cannot execute query");
	  if (pg_NumRows($sth) > 0)
	  {
	    $row = pg_fetch_array($sth, 0);
	  } else {
	    die ("Could not find fragment");
	  }
	  $query = sprintf ("DELETE FROM assignment WHERE fragment = %d", $row['id']);
	  pg_exec($dbh, $query) or die ("Cannot execute query");
	  $query = sprintf ("DELETE FROM fragment WHERE oid = %d", $oid);
	  pg_exec($dbh, $query) or die ("Database Query.");
	}
      }
    }
  }

  # Finish transaction
  pg_exec($dbh, "COMMIT") or die ("Could not finish transaction.");

  # Only to ensure no query is executed later
  $query = '';


} elseif ($type == "assign") {
  $error = false;
  $query = '';

  if (!is_supporter() && !is_also_supporter()) {
    echo ("<p><b>You're not permitted to alter supporter information.</b></p>");
    $error = true;
  }

  if (!$error
    && !(is_admin() && is_supporter())
    && !((is_also_supporter()) && $person == $LINUXTAG_AUTH['id'])) {
    echo ("<p><b>You're not permitted to alter other supporter's information.</b></p>");
    $error = true;
  }

  if (!$error) {
    $query = sprintf ("SELECT starttime,endtime FROM fragment WHERE id = %d", $fragment);
    $sth = pg_exec($dbh, $query) or die ("Cannot execute query");

    if (pg_NumRows ($sth) > 0) {
      $row = pg_fetch_array($sth, 0);
      $query = sprintf ("INSERT INTO assignment (fragment,person,starttime,endtime) "
		       ." VALUES (%d,%d,'%s','%s')",
		       $fragment,
		       $person,
		       $row['starttime'], $row['endtime']);
      pg_exec($dbh, $query) or die ("Sorry, cannot execute query");
    } else {
      echo ("<p><b>No such fragment found.</b></p>");
      $error = true;
    }
  }
} elseif ($type == "loose") {
  $error = false;
  $query = '';

  if (!is_supporter() && !is_also_supporter()) {
    echo ("<p><b>You're not permitted to alter supporter information.</b></p>");
    $error = true;
  }

  if (!$error) {
    $query = sprintf ("SELECT person FROM assignment WHERE oid = %d", $assignment);
    $sth = pg_exec($dbh, $query) or die ("Cannot execute query");

    if (pg_NumRows ($sth) > 0) {
      $row = pg_fetch_array($sth, 0);

      if (!(is_admin() && is_supporter())
	&& !((is_supporter() || is_also_supporter()) && $row['person'] == $LINUXTAG_AUTH['id'])) {
	echo ("<p><b>You're not permitted to alter other supporter's information.</b></p>");
	$error = true;
      }
    } else {
      echo ("<p><b>No such assignment found.</b></p>");
      $error = true;
    }
  }
  if (!$error) {
    $query = sprintf ("DELETE FROM assignment WHERE oid = %d", $assignment);
    pg_exec($dbh, $query) or die ("Sorry, cannot execute query");
  }
} elseif ($type == "workshop") {
  $error = false;

  if (allowed_to_edit_workshop ($oid)) {
    $query = sprintf ("SELECT project,person FROM workshop WHERE oid = %d", $oid);
  } else {
    $error = true;
  }

  if (!$error) {
    $sth = pg_exec ($dbh, $query) or die("Datenbank-Abfrage!");

    if (pg_NumRows ($sth) > 0) {
      $row = pg_fetch_array ($sth, 0);

      if ($row['project'] != $LINUXTAG_AUTH['project']
       && $row['person'] != $LINUXTAG_AUTH['id']) {
	echo ("<p><b>You don't own this workshop.</b></p>");
	$error = true;
      }
    } else {
      echo ("<p><b>Workshop not found.</b></p>");
      $error = true;
    }
  }
  if (!$error) {
    if (strlen($title) > <len_title>) {
      $title = substr($title, 0, <len_title>);
      echo "<p>Title shortened.</p>";
    }
    $query = sprintf ("UPDATE workshop SET title='%s',abstract='%s',language='%s',comment='%s',visible=%d",
		     addslashes ($title),
		     addslashes ($abstract),
		     addslashes ($language),
		     addslashes ($comment),
		     $visible);
    if (is_admin()) {
      $query .= sprintf (",person=%d", $speaker);
    }
    $query .= sprintf (" WHERE oid = %d", $oid);
    pg_exec ($dbh, $query) or die("Datenbank-Abfrage!");
  }
} elseif ($type == "flyers") {
  if ($flyers > 0 || $posters > 0) {
    if (strlen($address0) > 0) {
<protect>
      $body = sprintf ("%s <%s>\n  %s\n", $LINUXTAG_AUTH['name'], $LINUXTAG_AUTH['email'], $address0);
      if (strlen($address1) > 0) { $body .= sprintf ("  %s\n", $address1); }
      if (strlen($address2) > 0) { $body .= sprintf ("  %s\n", $address2); }
      if (strlen($address3) > 0) { $body .= sprintf ("  %s\n", $address3); }
      $body .= sprintf ("    %d Plakate, %d Flyer\n\n", $posters, $flyers);
</protect>
      mail("<flyers_mail>", "Request for Flyers and Posters", $body, "From: joey@infodrom.org (LinuxTag Projects Management)");
    } else {
      echo ("<p><b>You need to tell us where to send the flyers or posters.</b></p>");
    }
  } else {
    echo ("<p><b>You need to specify the number of flyers or posters you want to receive.</b></p>");
  }
} else {
  printf ("<p><b>Unknown type <code>%s</code></b></p>", $type);
}
		     
?>

<p>Transaction done.  Thanks for your contribution.
See you at LinuxTag.</p>

</ltpage>

# Local variables:
# mode: indented-text
# mode: auto-fill
# end:
