From d6319bfec1f8eed0e3be2ee4e663c18992f5f399 Mon Sep 17 00:00:00 2001 From: peter Date: Sat, 23 Feb 2008 12:28:44 +0000 Subject: [PATCH] Refactoring (Part I) git-svn-id: https://silmor.de/svn/softmagic/smoke/trunk@88 6e3c4bff-ac9f-4ac1-96c5-d2ea494d3e33 --- www/inc/cart.php | 239 ---------------------------- www/inc/cart_listing.php | 90 ----------- www/inc/classes/cart.php | 239 ++++++++++++++++++++++++++++ www/inc/classes/config_manager.php | 80 ++++++++++ www/inc/classes/customer.php | 93 +++++++++++ www/inc/classes/error.php | 74 +++++++++ www/inc/classes/event.php | 289 ++++++++++++++++++++++++++++++++++ www/inc/classes/language_manager.php | 133 ++++++++++++++++ www/inc/classes/order.php | 127 +++++++++++++++ www/inc/classes/parser.php | 197 +++++++++++++++++++++++ www/inc/classes/random.php | 53 ++++++ www/inc/classes/room.php | 84 ++++++++++ www/inc/classes/ticket.php | 26 +++ www/inc/config_manager.php | 80 ---------- www/inc/customer.php | 93 ----------- www/inc/db.php | 276 -------------------------------- www/inc/db/db.php | 276 ++++++++++++++++++++++++++++++++ www/inc/db/db_mysql.php | 171 ++++++++++++++++++++ www/inc/db/db_scheme.php | 237 ++++++++++++++++++++++++++++ www/inc/db_mysql.php | 171 -------------------- www/inc/db_scheme.php | 237 ---------------------------- www/inc/error.php | 74 --------- www/inc/event.php | 289 ---------------------------------- www/inc/event_listing.php | 73 --------- www/inc/language_manager.php | 133 ---------------- www/inc/loader.php | 6 +- www/inc/loader_nonadmin.php | 22 ++-- www/inc/order.php | 127 --------------- www/inc/order_listing.php | 42 ----- www/inc/parser.php | 197 ----------------------- www/inc/random.php | 53 ------ www/inc/rendering/cart_listing.php | 90 +++++++++++ www/inc/rendering/event_listing.php | 73 +++++++++ www/inc/rendering/order_listing.php | 42 +++++ www/inc/rendering/submit.php | 189 ++++++++++++++++++++++ www/inc/room.php | 84 ---------- www/inc/submit.php | 189 ---------------------- www/inc/ticket.php | 26 --- www/index.php | 8 +- 39 files changed, 2491 insertions(+), 2491 deletions(-) delete mode 100644 www/inc/cart.php delete mode 100644 www/inc/cart_listing.php create mode 100644 www/inc/classes/cart.php create mode 100644 www/inc/classes/config_manager.php create mode 100644 www/inc/classes/customer.php create mode 100644 www/inc/classes/error.php create mode 100644 www/inc/classes/event.php create mode 100644 www/inc/classes/language_manager.php create mode 100644 www/inc/classes/order.php create mode 100644 www/inc/classes/parser.php create mode 100644 www/inc/classes/random.php create mode 100644 www/inc/classes/room.php create mode 100644 www/inc/classes/ticket.php delete mode 100644 www/inc/config_manager.php delete mode 100644 www/inc/customer.php delete mode 100644 www/inc/db.php create mode 100644 www/inc/db/db.php create mode 100644 www/inc/db/db_mysql.php create mode 100644 www/inc/db/db_scheme.php delete mode 100644 www/inc/db_mysql.php delete mode 100644 www/inc/db_scheme.php delete mode 100644 www/inc/error.php delete mode 100644 www/inc/event.php delete mode 100644 www/inc/event_listing.php delete mode 100644 www/inc/language_manager.php delete mode 100644 www/inc/order.php delete mode 100644 www/inc/order_listing.php delete mode 100644 www/inc/parser.php delete mode 100644 www/inc/random.php create mode 100644 www/inc/rendering/cart_listing.php create mode 100644 www/inc/rendering/event_listing.php create mode 100644 www/inc/rendering/order_listing.php create mode 100644 www/inc/rendering/submit.php delete mode 100644 www/inc/room.php delete mode 100644 www/inc/submit.php delete mode 100644 www/inc/ticket.php diff --git a/www/inc/cart.php b/www/inc/cart.php deleted file mode 100644 index 131cfbe..0000000 --- a/www/inc/cart.php +++ /dev/null @@ -1,239 +0,0 @@ -, (C) 2007 -// -// Copyright: See README/COPYING files that come with this distribution -// -// - -/**this class represents a bunch of tickets in the shopping cart, it is created by Cart*/ -class CartTicket -{ - private $cartid; - private $eventid; - private $amount; - - /**used by Cart to create the tickets, never use this directly*/ - public function __construct($cid,$eid,$amt) - { - $this->cartid=$cid; - $this->eventid=$eid; - $this->amount=$amt; - } - - /**use this to increase or decrease the amount of tickets; if the amount is decreased to zero, the row in the DB is deleted and the ticket can only be re-added with Cart::addTicket */ - public function changeAmount($amt) - { - global $db; - if($amt<=0){ - $db->deleteRows("cart_ticket","cartid=".$db->escapeString($this->cartid)." and eventid=".$this->eventid); - $this->amount=0; - }else{ - $db->update("cart_ticket",array("amount"=>($amt+0)),"cartid=".$db->escapeInt($this->cartid)." AND eventid=".$db->escapeInt($this->eventid)); - $this->amount=$amt; - } - } - - /**use this to get the actual event*/ - public function eventObject() - { - return new Event($this->eventid); - } - - /**return the eventID*/ - public function getEventId() - { - return $this->eventid; - } - - /**return the current amount*/ - public function getAmount() - { - return $this->amount; - } -}; - -/**this error is returned if there are no items in a cart and the user wants to order it*/ -define("CE_NOITEMS",1); -/**this error is returned if the user tries to buy a ticket for a cancelled event*/ -define("CE_EVENTCANCELLED",10); -/**this error is returned if the event does not have that many tickets left*/ -define("CE_EVENTNOTICKETS",11); -/**this error is returned if the user wants to buy tickets for an unknown event (internal error?)*/ -define("CE_EVENTUNKNOWN",12); -/**this error is returned if the event is already over or tickets cannot be purchased anymore*/ -define("CE_EVENTOVER",13); - -/**instantiated by Cart::orderCheck to report errors*/ -class CartError -{ - private $etype; - private $eventid; - - /**instantiates an error object of the given type and optionally for the given event*/ - public function __construct($errtype,$eid=false) - { - $this->etype=$errtype; - $this->eventid=$eid; - } - - /**returns the error type (see CE_* constants)*/ - public function errorType() - { - return $this->etype; - } - - /**returns the event id associated with this error (false if none)*/ - public function eventId() - { - return $this->eventid; - } - - /**returns the Event object associated with this error (false if none)*/ - public function eventObject() - { - if($this->eventid===false)return false; - return new Event($this->eventid); - } -}; - -/**this class represents a shopping cart*/ -class Cart -{ - private $cartid=false; - - /**reloads a cart from the database, if $id is false a new one is created, use isValid() to check whether the cart really exists in the DB (it may have expired)*/ - public function __construct($id=false) - { - global $db; - global $CartTimeout; - if($id===false){ - $db->beginTransaction(); - while(1){ - //generate ID - $id=getRandom(128); - //check it does not exist - $res=$db->select("cart","cartid","cartid=".$db->escapeString($id)); - if(count($res)==0){ - $this->cartid=$id; - break; - } - } - //create entry - $db->insert("cart",array("cartid"=>$id,"timeout"=>(time()+$CartTimeout))); - $db->commitTransaction(); - }else{ - //check that cart exists - $res=$db->select("cart","cartid","cartid=".$db->escapeString($id)); - if(count($res)>0)$this->cartid=$id; - } - } - - /**returns true if this is a valid shopping cart, if it returns false, try to create a new one*/ - public function isValid() - { - return $this->cartid!==false; - } - - /**returns the ID of this cart, returns false if the cart is not valid*/ - public function getCartId() - { - return $this->cartid; - } - - /**use this to get all existing tickets in this cart, then manipulate the tickets directly*/ - public function getTickets() - { - global $db; - if($this->cartid===false)return array(); - $res=$db->select("cart_ticket","*","cartid=".$db->escapeString($this->cartid)); - $ret=array(); - reset($res); - if(count($res)>0) - foreach($res as $k => $tc) - $ret[]=new CartTicket($tc["cartid"],$tc["eventid"],$tc["amount"]); - return $ret; - } - - /**use this to get tickets by eventid; returns false if it does not exist*/ - public function getTicketsByEvent($eventid) - { - global $db; - $where="cartid=".$db->escapeString($this->cartid)." AND eventid=".$db->escapeInt($eventid); - $res=$db->select("cart_ticket","*",$where); - if(count($res) > 0) - return new CartTicket($res[0]["cartid"],$res[0]["eventid"],$res[0]["amount"]); - else - return false; - } - - /**use this to add tickets, returns new CartTicket object or false if the event does not exist or is cancelled*/ - public function addTickets($eventid,$amount) - { - global $db; - //sanity check - if($amount<=0)return false; - $this->renewCart(); - //check that ticket can be sold - $event=new Event($eventid); - if($event->isCancelled())return false; - //begin transaction, get current data - $db->beginTransaction(); - $where="cartid=".$db->escapeString($this->cartid)." AND eventid=".$db->escapeInt($eventid); - $res=$db->select("cart_ticket","*",$where); - if(count($res)>0){ - $amount+=$res[0]["amount"]; - $ret=$db->update("cart_ticket",array("amount"=>$amount),$where); - }else{ - //insert into cart - $ret=$db->insert("cart_ticket",array("cartid"=>$this->cartid,"eventid"=>$eventid,"amount"=>$amount)); - } - if($ret===false){ - $db->rollbackTransaction(); - return false; - } - $db->commitTransaction(); - return new CartTicket($this->cartid,$eventid,$amount); - } - - /**checks that the whole content of the cart can be ordered; returns an empty array on success or an array of CartError objects on failure*/ - public function orderCheck() - { - global $db; - //TODO: extend to differentiate online, shop and direct sale - $ret=array(); - //go through events - global $db; - $res=$db->select("cart_ticket","*","where cartid=".$db->escapeString($this->cartid)); - if(count($res)>0) - foreach($res as $k=>$tc){ - $evt=new Event($tc["eventid"]); - //TODO: add more checks (event over, cancelled, etc.pp.) - if($evt->availableTicketAmount()<$tc["amount"]) - $ret[]=new CartError(CE_EVENTNOTICKETS,$tc["eventid"]); - } - //vouchers are ok by default, just check amount - $itmcnt=count($res); - $res=$db->select("cart_voucher","cvid","where cartid=".$db->escapeString($this->cartid)); - $itmcnt+=count($res); - //check that we have something to order - if($itmcnt<=0) - $ret[]=new CartError(CE_NOITEMS); - //return... - return $ret; - } - - /**makes sure the cart continues to exist*/ - public function renewCart() - { - global $db; - $db->update("cart",array("timeout"=>(time()+$CartTimeout)),"cartid=".$db->escapeInt($this->cartid)); - } -}; - -?> \ No newline at end of file diff --git a/www/inc/cart_listing.php b/www/inc/cart_listing.php deleted file mode 100644 index 149df88..0000000 --- a/www/inc/cart_listing.php +++ /dev/null @@ -1,90 +0,0 @@ - -// +---------------------------------------------------------------------- -// | -// | Copyright: See COPYING file that comes with this distribution -// +---------------------------------------------------------------------- -// - -/** creates the cart overview */ -function createCartOverview() -{ - global $parser; - - $error = ErrorManager::singleton(); - $lang = LanguageManager::singleton(); - - $cart = new Cart($_COOKIE[COOKIE_NAME]); - - $p = new Parser("cart.html"); - - $tablerows = ""; - $totalsum = 0; - $hiddenfields = ""; - - // get tickets from cart - foreach ($cart->getTickets() as $ticket) - { - $cartRowTmpl = $p->getVar("ROW"); - $event = $ticket->eventObject(); - - // set event details - $p->setVars($event->getParserData()); - - // if no error exists set values of database, else values of submit - if (!$error->exists()) { - $p->setVar("AMOUNT", $ticket->getAmount()); - } else { - $ticketAmounts = $_POST["ms_amount"]; - $eventIDs = $_POST["ms_event"]; - $amountValue = $ticketAmounts[array_search($event->getEventId(),$eventIDs)]; - $p->setVar("AMOUNT", $amountValue); - } - - // set submit functionality - $p->setVar("linkDELETEROW", "index.php?mode=cart&action=deleteEvent&event=".$event->getEventId()); - $p->setVar("fieldAMOUNT", "ms_amount[]"); - - // fill hidden fields - $hiddenfields .= "getEventId()."\" />\n"; - - $rowsum = $ticket->getAmount()*$event->getDefaultPrice(); - $p->setVar("ROWSUM", $lang->getPrice($rowsum)); - - $totalsum += $rowsum; - - $tablerows .= $p->parse($cartRowTmpl); - } - - // if no tickets in cart set EMPTYROWS and disable order button - if (count($cart->getTickets()) == 0) { - $tablerows = $p->getVar("EMPTYROWS"); - $p->setVar("attribDISABLED", "disabled=\"disabled\""); - } else { - $p->setVar("attribDISABLED", ""); - } - - $p->setVar("TABLEROWS", $tablerows); - $p->setVar("TOTALSUM", $lang->getPrice($totalsum)); - - // set buttons - $p->setVar("buttonSAVE", "ms_save"); - $p->setVar("buttonORDER", "ms_goToOrder"); - // set hidden fields - $p->setVar("IS_HIDDEN", "true"); - $p->setVar("HIDDENAREA", $hiddenfields); - - // set error message - if ($error->exists()) { - $p->setVar("IS_ERROR", "true"); - $p->setVar("ERRORAREA", $error->getAllFormatted()); - } - - // create page - $parser->setVAR("PAGE", $p->parseFile("cart.html")); -} - -?> \ No newline at end of file diff --git a/www/inc/classes/cart.php b/www/inc/classes/cart.php new file mode 100644 index 0000000..131cfbe --- /dev/null +++ b/www/inc/classes/cart.php @@ -0,0 +1,239 @@ +, (C) 2007 +// +// Copyright: See README/COPYING files that come with this distribution +// +// + +/**this class represents a bunch of tickets in the shopping cart, it is created by Cart*/ +class CartTicket +{ + private $cartid; + private $eventid; + private $amount; + + /**used by Cart to create the tickets, never use this directly*/ + public function __construct($cid,$eid,$amt) + { + $this->cartid=$cid; + $this->eventid=$eid; + $this->amount=$amt; + } + + /**use this to increase or decrease the amount of tickets; if the amount is decreased to zero, the row in the DB is deleted and the ticket can only be re-added with Cart::addTicket */ + public function changeAmount($amt) + { + global $db; + if($amt<=0){ + $db->deleteRows("cart_ticket","cartid=".$db->escapeString($this->cartid)." and eventid=".$this->eventid); + $this->amount=0; + }else{ + $db->update("cart_ticket",array("amount"=>($amt+0)),"cartid=".$db->escapeInt($this->cartid)." AND eventid=".$db->escapeInt($this->eventid)); + $this->amount=$amt; + } + } + + /**use this to get the actual event*/ + public function eventObject() + { + return new Event($this->eventid); + } + + /**return the eventID*/ + public function getEventId() + { + return $this->eventid; + } + + /**return the current amount*/ + public function getAmount() + { + return $this->amount; + } +}; + +/**this error is returned if there are no items in a cart and the user wants to order it*/ +define("CE_NOITEMS",1); +/**this error is returned if the user tries to buy a ticket for a cancelled event*/ +define("CE_EVENTCANCELLED",10); +/**this error is returned if the event does not have that many tickets left*/ +define("CE_EVENTNOTICKETS",11); +/**this error is returned if the user wants to buy tickets for an unknown event (internal error?)*/ +define("CE_EVENTUNKNOWN",12); +/**this error is returned if the event is already over or tickets cannot be purchased anymore*/ +define("CE_EVENTOVER",13); + +/**instantiated by Cart::orderCheck to report errors*/ +class CartError +{ + private $etype; + private $eventid; + + /**instantiates an error object of the given type and optionally for the given event*/ + public function __construct($errtype,$eid=false) + { + $this->etype=$errtype; + $this->eventid=$eid; + } + + /**returns the error type (see CE_* constants)*/ + public function errorType() + { + return $this->etype; + } + + /**returns the event id associated with this error (false if none)*/ + public function eventId() + { + return $this->eventid; + } + + /**returns the Event object associated with this error (false if none)*/ + public function eventObject() + { + if($this->eventid===false)return false; + return new Event($this->eventid); + } +}; + +/**this class represents a shopping cart*/ +class Cart +{ + private $cartid=false; + + /**reloads a cart from the database, if $id is false a new one is created, use isValid() to check whether the cart really exists in the DB (it may have expired)*/ + public function __construct($id=false) + { + global $db; + global $CartTimeout; + if($id===false){ + $db->beginTransaction(); + while(1){ + //generate ID + $id=getRandom(128); + //check it does not exist + $res=$db->select("cart","cartid","cartid=".$db->escapeString($id)); + if(count($res)==0){ + $this->cartid=$id; + break; + } + } + //create entry + $db->insert("cart",array("cartid"=>$id,"timeout"=>(time()+$CartTimeout))); + $db->commitTransaction(); + }else{ + //check that cart exists + $res=$db->select("cart","cartid","cartid=".$db->escapeString($id)); + if(count($res)>0)$this->cartid=$id; + } + } + + /**returns true if this is a valid shopping cart, if it returns false, try to create a new one*/ + public function isValid() + { + return $this->cartid!==false; + } + + /**returns the ID of this cart, returns false if the cart is not valid*/ + public function getCartId() + { + return $this->cartid; + } + + /**use this to get all existing tickets in this cart, then manipulate the tickets directly*/ + public function getTickets() + { + global $db; + if($this->cartid===false)return array(); + $res=$db->select("cart_ticket","*","cartid=".$db->escapeString($this->cartid)); + $ret=array(); + reset($res); + if(count($res)>0) + foreach($res as $k => $tc) + $ret[]=new CartTicket($tc["cartid"],$tc["eventid"],$tc["amount"]); + return $ret; + } + + /**use this to get tickets by eventid; returns false if it does not exist*/ + public function getTicketsByEvent($eventid) + { + global $db; + $where="cartid=".$db->escapeString($this->cartid)." AND eventid=".$db->escapeInt($eventid); + $res=$db->select("cart_ticket","*",$where); + if(count($res) > 0) + return new CartTicket($res[0]["cartid"],$res[0]["eventid"],$res[0]["amount"]); + else + return false; + } + + /**use this to add tickets, returns new CartTicket object or false if the event does not exist or is cancelled*/ + public function addTickets($eventid,$amount) + { + global $db; + //sanity check + if($amount<=0)return false; + $this->renewCart(); + //check that ticket can be sold + $event=new Event($eventid); + if($event->isCancelled())return false; + //begin transaction, get current data + $db->beginTransaction(); + $where="cartid=".$db->escapeString($this->cartid)." AND eventid=".$db->escapeInt($eventid); + $res=$db->select("cart_ticket","*",$where); + if(count($res)>0){ + $amount+=$res[0]["amount"]; + $ret=$db->update("cart_ticket",array("amount"=>$amount),$where); + }else{ + //insert into cart + $ret=$db->insert("cart_ticket",array("cartid"=>$this->cartid,"eventid"=>$eventid,"amount"=>$amount)); + } + if($ret===false){ + $db->rollbackTransaction(); + return false; + } + $db->commitTransaction(); + return new CartTicket($this->cartid,$eventid,$amount); + } + + /**checks that the whole content of the cart can be ordered; returns an empty array on success or an array of CartError objects on failure*/ + public function orderCheck() + { + global $db; + //TODO: extend to differentiate online, shop and direct sale + $ret=array(); + //go through events + global $db; + $res=$db->select("cart_ticket","*","where cartid=".$db->escapeString($this->cartid)); + if(count($res)>0) + foreach($res as $k=>$tc){ + $evt=new Event($tc["eventid"]); + //TODO: add more checks (event over, cancelled, etc.pp.) + if($evt->availableTicketAmount()<$tc["amount"]) + $ret[]=new CartError(CE_EVENTNOTICKETS,$tc["eventid"]); + } + //vouchers are ok by default, just check amount + $itmcnt=count($res); + $res=$db->select("cart_voucher","cvid","where cartid=".$db->escapeString($this->cartid)); + $itmcnt+=count($res); + //check that we have something to order + if($itmcnt<=0) + $ret[]=new CartError(CE_NOITEMS); + //return... + return $ret; + } + + /**makes sure the cart continues to exist*/ + public function renewCart() + { + global $db; + $db->update("cart",array("timeout"=>(time()+$CartTimeout)),"cartid=".$db->escapeInt($this->cartid)); + } +}; + +?> \ No newline at end of file diff --git a/www/inc/classes/config_manager.php b/www/inc/classes/config_manager.php new file mode 100644 index 0000000..8cec61d --- /dev/null +++ b/www/inc/classes/config_manager.php @@ -0,0 +1,80 @@ + +// +---------------------------------------------------------------------- +// | +// | Copyright: See COPYING file that comes with this distribution +// +---------------------------------------------------------------------- +// + +class ConfigManager +{ + private $configFile; + private $config; + private static $instance; + + private function __construct($file) + { + global $template; + + $this->configFile = $template.$file; + $this->config = array(); + $this->readConfig(); + } + + /** returns the instance of the Config Manager */ + public static function singleton($file) + { + if(!self::$instance) { + self::$instance = new ConfigManager($file); + } + + return self::$instance; + } + + /** reads the configuration values from the file */ + private function readConfig() + { + // check if file really exists + if (file_exists($this->configFile)) { + $lines = file($this->configFile); + $key = ""; + foreach ($lines as $line_num => $line) { + if ( ereg("^msgid.*\"(.*)\"", $line, $reg) ) { + $key = $reg[1]; + } + if ( ereg("^msgstr.*\"(.*)\"", $line, $reg) ) { + $value = $reg[1]; + $this->config[$key] = $value; + } + } + } + } + + /** returns the value of the given configuration item */ + public function get($key) + { + if ($this->hasKey($key)) { + return $this->config[$key]; + } else { + return ""; + } + } + + /** checks if key exists */ + public function hasKey($key) + { + return array_key_exists($key, $this->config); + } + + /** can be used to set an alternate path to a config file */ + public function setConfigFile($file) + { + $this->configFile = $file; + $this->readConfig(); + } +} + +?> diff --git a/www/inc/classes/customer.php b/www/inc/classes/customer.php new file mode 100644 index 0000000..b503dc3 --- /dev/null +++ b/www/inc/classes/customer.php @@ -0,0 +1,93 @@ +id=false; + if($id!==false){ + $this->getByID($id); + } + } + + /**tries to get the customer by its ID, returns false if it fails*/ + public function getByID($id) + { + global $db; + $res=$db->select("customer","customerid","where customerid=".$db->escapeInt($id)); + if(count($res)>0){ + $this->id=$id+0; + return true; + }else + return false; + } + + /**tries to get the customer by its email address, returns false if it fails*/ + public function getByMail($mail) + { + global $db; + $res=$db->select("customer","customerid","where email=".$db->escapeString($mail)); + if(count($res)>0){ + $this->id=$res[0]["customerid"]; + return true; + }else + return false; + } + + /**checks whether the customer exists in the database; getByID or getByMail must have been called first*/ + public function exists() + { + return $this->id !== false; + } + + /**creates the customer in the database; getByID or getByMail must not have been called yet; + returns the new ID on success or false on failure*/ + public function create($name) + { + if($this->id!==false)return; + global $db; + $this->id=$db->insert("customer",array("name"=>$name)); + return $this->id; + } + + /**sets the email of this customer*/ + public function setMail($mail) + { + if($this->id===false)return; + global $db; + $db->update("customer",array("email"=>$mail),"customerid=".$db->escapeInt($this->id)); + } + + /**sets the password of this customer*/ + public function setPassword($pwd) + { + if($this->id===false)return; + global $db; + $pass=calcPasswd($pwd,getSalt()); + $db->update("customer",array("passwd"=>$pass),"customerid=".$db->escapeInt($this->id)); + } + + /**checks whether $password matches the stored password for this customer; returns true on success*/ + public function authenticate($passwd) + { + if($this->id===false)return false; + //get record + global $db; + $res=$db->select("customer","passwd","customerid=".$db->escapeInt($this->id)); + //found anything? + if(count($res)<0)return false; + //is it a password + if(!is_string($res[0]["passwd"]) || strlen($res[0]["passwd"])<10)return false; + //check + $pwd=explode(":",$res[0]["passwd"]); + $pwd2=calcPasswd($passwd,$pwd[0]); + return $pwd2 == $res[0]["passwd"]; + } +}; + +?> \ No newline at end of file diff --git a/www/inc/classes/error.php b/www/inc/classes/error.php new file mode 100644 index 0000000..5cc9ebc --- /dev/null +++ b/www/inc/classes/error.php @@ -0,0 +1,74 @@ + +// +---------------------------------------------------------------------- +// | +// | Copyright: See COPYING file that comes with this distribution +// +---------------------------------------------------------------------- +// + +class ErrorManager +{ + private $errorMessages; + private static $instance; + + private function __construct() + { + $this->errorMessages = array(); + } + + /** returns the instance of the Error Manager */ + public static function singleton() + { + if(!self::$instance) { + self::$instance = new ErrorManager(); + } + + return self::$instance; + } + + /** add new error message */ + public function add($message) + { + $this->errorMessages[] = $message; + } + + /** get all error messages in an array */ + public function getAll() + { + return $this->$errorMessages; + } + + /** get all error messages formatted */ + public function getAllFormatted() + { + $p = new Parser("definition.html"); + $messages = ""; + + foreach ($this->errorMessages as $message) + { + $errorTmpl = $p->getVar("ERROR"); + $p->setVar("MESSAGE", $message); + $messages .= $p->parse($errorTmpl); + } + + $errorArea = $p->getVar("ERRORAREA"); + $p->setVar("ERRORMESSAGES", $messages); + + return $p->parse($errorArea); + } + + /** returns true if errors exist */ + public function exists() + { + if (count($this->errorMessages) > 0) { + return true; + } + else { + return false; + } + } +} +?> \ No newline at end of file diff --git a/www/inc/classes/event.php b/www/inc/classes/event.php new file mode 100644 index 0000000..a694347 --- /dev/null +++ b/www/inc/classes/event.php @@ -0,0 +1,289 @@ +, (C) 2007 +// +// Copyright: See README/COPYING files that come with this distribution +// +// + + +/**Get an overview of all events: +returns an array of array("eventid"=>int, "title"=>string,"starttime"=>int)*/ +function getAllEvents() +{ + global $db; + return $db->select("event","eventid,title,starttime",""); +} + +/**Machine-wrapper for getAllEvents() */ +function getAllEventsXml() +{ + $all=getAllEvents(); + if($all===false){ + header("X-MagicSmoke-Status: Error"); + echo "Database Error."; + return; + } + header("X-MagicSmoke-Status: Ok"); + $xml=new DOMDocument; + $root=$xml->createElement("EventList"); + if(count($all)>0) + foreach($all as $k => $ev){ + $nod=$xml->createElement("Event",$ev["title"]); + $nod->setAttribute("id",$ev["eventid"]); + $nod->setAttribute("start",$ev["starttime"]); + $root->appendChild($nod); + } + $xml->appendChild($root); + echo $xml->saveXml(); +} + +/**Wrapper around event table*/ +class Event +{ + private $evid; + private $title; + private $artist; + private $description; + private $starttime; + private $endtime; + private $roomid; + private $capacity; + private $defaultprice; + private $cancelreason; + + /**creates an event object, the id must be a valid eventid gotten from getAllEvents or -1 if you + want to create a new event*/ + public function __construct($id) + { + global $db; + //check that event exists + $id=$id+0; + if($id<0)$id=-1; + else{ + $res=$db->select("event","*","eventid=$id"); + if(count($res)!=1)$id=-1; + else{ + $this->title=$res[0]["title"]; + $this->artist=$res[0]["artist"]; + $this->description=$res[0]["description"]; + $this->starttime=$res[0]["starttime"]; + $this->endtime=$res[0]["endtime"]; + $this->roomid=$res[0]["roomid"]; + $this->capacity=$res[0]["capacity"]; + $this->defaultprice=$res[0]["defaultprice"]; + $this->cancelreason=$res[0]["cancelreason"]; + } + } + //remember it + $this->evid=$id; + } + + /**returns whether this event already exists in the database*/ + public function exists() + { + return $this->evid >= 0; + } + + /**returns the ID of the event*/ + public function getEventId(){return $this->evid;} + /**returns the start time of the event*/ + public function getStartTime(){return $this->starttime;} + /**returns the end time of the event*/ + public function getEndTime(){return $this->endtime;} + /**returns the ticket capacity of the event*/ + public function getCapacity(){return $this->capacity;} + /**returns the default price in cent of the event*/ + public function getDefaultPrice(){return $this->defaultprice;} + /**returns whether the event is cancelled*/ + public function isCancelled() + { + if($this->cancelreason===false)return false; + else return $this->cancelreason!=""; + } + /**returns the title of the event*/ + public function getTitle(){return $this->title;} + /**returns the artist of the event*/ + public function getArtist(){return $this->artist;} + /**returns the room/place of the event*/ + public function getRoomId(){return $this->roomid;} + /**returns the description of the event*/ + public function getDescription(){return $this->description;} + /**returns the reason why the event is cancelled if isCancelled() returns true*/ + public function getCancelReason(){return $this->cancelreason;} + + /**returns the data in an array suitable for the web-page-renderer*/ + public function getParserData() + { + $lang = LanguageManager::singleton(); + + return array("DATE"=>$lang->getDate($this->getStartTime()), "TIME"=>$lang->getTime($this->getStartTime()), "PLACE"=>$this->getRoomId(), "EVENTNAME"=>$this->getTitle(), "ARTIST"=>$this->getArtist(),"PRICE"=>$lang->getPrice($this->getDefaultPrice()), "ID"=>$this->getEventId(), "DESCRIPTION"=>$this->getDescription(), "LINK"=>""); + } + + /**returns how many tickets can still be sold*/ + public function availableTicketAmount() + { + global $db; + //is it valid? + if($this->evid<0)return 0; + //is it cancelled? + if($this->isCancelled())return 0; + //is it already over? + if(time()>$this->endtime)return 0; + //get existing tickets + $res=$db->select("ticket","status","eventid=".$db->escapeInt($this->evid)); + $amt=0; + reset($res); + if(count($res)>0) + foreach($res as $tk){ + if(!($tk["status"]&TICKET_CANCELLED))$amt++; + } + return $this->capacity - $amt; + } +}; + +/**machine-function: get the requested events as XML data*/ +function getEventsXml($evts) +{ + header("X-MagicSmoke-Status: Ok"); + $xml=new DOMDocument; + $root=$xml->createElement("EventData"); + if(count($evts)>0) + foreach($evts as $k => $eid){ + $ev=new Event($eid); + if(!$ev->exists())continue; + $nod=$xml->createElement("Event"); + $nod->setAttribute("id",$eid); + $nod->setAttribute("start",$ev->getStartTime()); + $nod->setAttribute("end",$ev->getEndTime()); + $nod->setAttribute("capacity",$ev->getCapacity()); + $nod->setAttribute("defaultprice",$ev->getDefaultPrice()); + $nod->setAttribute("cancelled",$ev->isCancelled()?"true":"false"); + $nod->appendChild($xml->createElement("Title",$ev->getTitle())); + $nod->appendChild($xml->createElement("Artist",$ev->getArtist())); + $nod->appendChild($xml->createElement("Room",$ev->getRoomId())); + $nod->appendChild($xml->createElement("Description",$ev->getDescription())); + if($ev->isCancelled()) + $nod->appendChild($xml->createElement("CancelReason",$ev->getCancelReason())); + $root->appendChild($nod); + } + $xml->appendChild($root); + print($xml->saveXml()); +} + +/**Machine-Interface: set an event (it's not possible to set from Web-Browser)*/ +function setEventXml($xmldata) +{ + global $db; + //stage 1: parse XML + $xml=new DOMDocument; + if($xml->loadXML($xmldata)===false){ + header("X-MagicSmoke-Status: SyntaxError"); + echo "Unable to parse XML."; + return; + } + //stage 2: extract data from XML + $doc=$xml->documentElement; + $eventid=trim($doc->getAttribute("id")); + $start=trim($doc->getAttribute("start"))+0; + $end=trim($doc->getAttribute("end"))+0; + $capacity=trim($doc->getAttribute("capacity"))+0; + $defaultprice=trim($doc->getAttribute("defaultprice"))+0; + $cancelled=trim($doc->getAttribute("cancelled")); + $title=$artist=$description=$room=$cancelreason=""; + foreach($doc->getElementsByTagName("Title") as $el) + foreach($el->childNodes as $cn) + if($cn->nodeType==XML_TEXT_NODE) + $title=trim($cn->wholeText); + foreach($doc->getElementsByTagName("Artist") as $el) + foreach($el->childNodes as $cn) + if($cn->nodeType==XML_TEXT_NODE) + $artist=trim($cn->wholeText); + foreach($doc->getElementsByTagName("Description") as $el) + foreach($el->childNodes as $cn) + if($cn->nodeType==XML_TEXT_NODE) + $description=trim($cn->wholeText); + foreach($doc->getElementsByTagName("Room") as $el) + foreach($el->childNodes as $cn) + if($cn->nodeType==XML_TEXT_NODE) + $room=trim($cn->wholeText); + foreach($doc->getElementsByTagName("CancelReason") as $el) + foreach($el->childNodes as $cn) + if($cn->nodeType==XML_TEXT_NODE) + $cancelreason=trim($cn->wholeText); + //stage 3: validate input + if(ereg("^([0-9]+)|(new)$",$eventid)===false){ + header("X-MagicSmoke-Status: Error"); + echo "Invalid Event ID, must be positive integer or 'new'."; + return; + } + if($cancelled!="true" && $cancelled!="false"){ + header("X-MagicSmoke-Status: Error"); + echo "Event neither cancelled, nor non-cancelled."; + return; + } + if($title==""){ + header("X-MagicSmoke-Status: Error"); + echo "Empty Title."; + return; + } + if($artist==""){ + header("X-MagicSmoke-Status: Error"); + echo "No Artist."; + return; + } + $db->beginTransaction(); + $res=$db->select("room","roomid","roomid=".$db->escapeString($room)); + if(count($res)<1){ + //end DB transaction + $db->rollbackTransaction(); + //error + header("X-MagicSmoke-Status: Error"); + echo "Invalid Room."; + return; + } + + //stage 4: call DB + $data["title"]=$title; + $data["artist"]=$artist; + $data["description"]=$description; + $data["starttime"]=$start; + $data["endtime"]=$end; + $data["roomid"]=$room; + $data["capacity"]=$capacity; + $data["defaultprice"]=$defaultprice; + if($cancelled=="true") + $data["cancelreason"]=$cancelreason." "; + else + $data["cancelreason"]=false; + if($eventid=="new"){ + //create event + $eventid=$db->insert("event",$data); + if($eventid===false){ + header("X-MagicSmoke-Status: Error"); + echo "Error accessing database."; + return; + } + }else{ + //check ID + $eventid=$eventid+0; + $res=$db->select("event","eventid","eventid=".$eventid); + if(count($res)==0){ + header("X-MagicSmoke-Status: Error"); + echo "Invalid Event: eventid does not exist in database."; + $db->rollbackTransaction(); + return; + } + $db->update("event",$data,"eventid=".$eventid); + } + $db->commitTransaction(); + header("X-MagicSmoke-Status: Ok"); + echo $eventid; +} + +?> \ No newline at end of file diff --git a/www/inc/classes/language_manager.php b/www/inc/classes/language_manager.php new file mode 100644 index 0000000..d83a6b1 --- /dev/null +++ b/www/inc/classes/language_manager.php @@ -0,0 +1,133 @@ + +// +---------------------------------------------------------------------- +// | +// | Copyright: See COPYING file that comes with this distribution +// +---------------------------------------------------------------------- +// + +/** function to replace gettext */ +function i18n($key) +{ + $lang = LanguageManager::singleton(); + + $translation = $lang->getValue($key); + + if ($translation != "") { + return $translation; + } else { + return $key; + } +} + +/** replaces each {number} in a string with its equivalent in the array +{1} => array[0] */ +function string_format($string, $array) +{ + $num = count($array); + + for ($i=0; $i < $num; $i++) { + $string = str_replace("{".($i+1)."}", $array[$i], $string); + } + + return $string; +} + +class LanguageManager +{ + private static $COOKIE_NAME = "ms_lang"; + private static $instance; + private $lang; + private $config; + private $templateFolder; + + /** private constructor */ + private function __construct() + { + global $template; + + $this->templateFolder = $template; + //default fallback for empty setting + if($this->templateFolder == "") + $this->templateFolder = "./template/"; + //make sure it ends with / + if(substr($this->templateFolder,-1,1) != "/") + $this->templateFolder .= "/"; + + // check if cookie is set + if (isset($_COOKIE[self::$COOKIE_NAME])) { + $this->lang = $_COOKIE[self::$COOKIE_NAME]; + } else { + $this->lang = substr($_SERVER["HTTP_ACCEPT_LANGUAGE"],0,2); + } + + //sanity check for $lang -> must only contain letters; fallback is de + if(ereg("^[a-zA-Z]+$",$this->lang)===false) + $this->lang="de"; + + $this->setLanguageConfig(); + } + + /** returns the instance of the Language Manager */ + public static function singleton() + { + if(!self::$instance) { + self::$instance = new LanguageManager(); + } + + return self::$instance; + } + + /** set language */ + public function setLanguage($language) + { + $this->lang = $language; + setcookie(self::$COOKIE_NAME, $language, 0); + + $this->setLanguageConfig(); + } + + private function setLanguageConfig() { + global $template; + + $dir = $this->templateFolder.$this->lang."/"; + + if (is_dir($dir)) { + // if language folder exists + $template = $dir; + } else { + // set default value + $template = $this->templateFolder."de/"; + } + $this->config = ConfigManager::singleton("lang.po"); + } + + /** returns date in current language, default: ISO-date */ + public function getDate($date) + { + return date(i18n("Y-m-d"), $date); + } + + /** returns time in current language */ + public function getTime($time) + { + return date(i18n("h:i a"), $time); + } + + /** returns price in current language */ + public function getPrice($price) + { + return number_format($price/100, 2, i18n("."), i18n(",")); + } + + /** returns value for specified key in current language */ + public function getValue($key) + { + return $this->config->get($key); + } +} + +?> diff --git a/www/inc/classes/order.php b/www/inc/classes/order.php new file mode 100644 index 0000000..adffdcb --- /dev/null +++ b/www/inc/classes/order.php @@ -0,0 +1,127 @@ +, (C) 2007 +// +// Copyright: See README/COPYING files that come with this distribution +// +// + +/**an order has been placed, this flag is set when the order is filled and finalized*/ +define("ORDER_PLACED",1); +/**the order has been sent out (it must be placed first; direct sales are automatically sent)*/ +define("ORDER_SENT",2); +/**the order has been cancelled by the user (this is only possible as long as no money has been paid and nothing has been sent yet)*/ +define("ORDER_CANCELLED",4); +/**the order is closed (optional: this flag means no further payment/cancellation/etc. is possible)*/ +define("ORDER_CLOSED",8); + + +/**this class represents an order in the database*/ +class Order +{ + private $orderid; + private $status; + + /**instantiates an existing order with the given orderid or creates a new one if orderid===false*/ + public function __construct($orderid=false) + { + global $db; + if($orderid===false){ + //create a new one + $odr=array( + //set to default + "soldby"=>"_online", + "status" => 0, + "ordertime" => time() + ); + $this->orderid=$db->insert("order",$odr); + }else{ + //get it from DB + $res=$db->select("order","*","orderid=".$db->escapeInt($orderid)); + if(count($res)==0){ + $this->orderid=false; + return; + } + $this->orderid=$res[0]["orderid"]; + $this->status=$res[0]["status"]; + } + } + + /**returns whether the order can still be changed*/ + public function canChange() + { + return $this->isValid() && $this->status == 0; + } + + /**returns whether the order is a valid DB object*/ + public function isValid() + { + return $this->orderid!==false; + } + + /**removes all items from the given Cart and enters them into itself; returns false if some items cannot be ordered or the order is already closed*/ + public function emptyCart($cart) + { + //check carts contents + if(count($cart->orderCheck())>0)return false; + //check myself + if(!$this->canChange())return false; + //get tickets + $db->beginTransaction(); + $tick=$cart->getTickets(); + if(count($tick)>0) + foreach($tick as $k=>$tc){ + $this->addTickets($tc->getEventId(),$tc->getAmount()); + $tc->changeAmount(0); + } + //TODO: get vouchers + //done + $db->commitTransaction(); + return true; + } + + /**adds some tickets to the order, returns ticketid or false if change is not possible*/ + public function addTickets($eventid,$amount) + { + if(!$this->canChange() || $amount <= 0)return false; + global $db; + //get event + $event=new Event($eventid); + //create ticket + $tc=array("eventid" => $eventid, + "price" => $event->getDefaultPrice(), + "status" => 0, + "oderid" => $this->orderid + ); + $ret=array(); + for($i=0;$i<$amount;$i++)$ret[]=$db->insert("ticket",$tc); + return $ret; + } + + /**places/finalizes the order; returns false on failure, true on success or if the order already was finalized()*/ + public function placeOrder() + { + if(!$this->canChange())return; + global $db; + $db->beginTransaction(); + //get orderstatus and correct it + $res=$db->select("order","status","orderid=".$db->escapeInt($this->orderid)); + if(count($res)==0){ + $this->orderid=false; + $db->rollbackTransaction(); + return false; + } + $db->update("order",array("status"=>ORDER_PLACED),"orderid=".$db->escapeInt($this->orderid)); + $this->status=ORDER_PLACED; + //end + $db->commitTransaction(); + return true; + } +}; + +?> \ No newline at end of file diff --git a/www/inc/classes/parser.php b/www/inc/classes/parser.php new file mode 100644 index 0000000..6f38701 --- /dev/null +++ b/www/inc/classes/parser.php @@ -0,0 +1,197 @@ +cont=$c; + reset($this->cont); + } + /**return next line from array until end is reached*/ + public function getLine() + { + $r=current($this->cont); + next($this->cont); + return $r; + } +} + +/**Parser class: see syntax docu for details*/ +class Parser +{ + private $vars=array(); + + /**create parser object, initialize its internal state with optional file*/ + public function __construct($fname="") + { + global $_SERVER; + $this->vars["SCRIPT"]=$_SERVER[SCRIPT_NAME]; + $this->vars["FULLURL"]=$_SERVER[REQUEST_URI]; + if($fname!="") + $this->parseFile($fname); + } + /**parse a file, return parser-result*/ + public function parseFile($fname) + { + global $template; + $cont=file_get_contents($template.$fname); + return $this->parse($cont); + } + /**parse a string, return parser-result*/ + public function parse($str) + { + $cont=explode("\n",str_replace("\r","",$str)); + $help=new PHelper($cont); + return $this->parseNormal($help); + } + /**set an internal variable*/ + public function setVar($vname,$vval) + { + $this->vars[$vname]=$vval; + } + /**set several internal variables array(variablename=>value)*/ + public function setVars(array $vs) + { + reset($vs); + foreach($vs as $k => $v) + $this->vars[$k]=$v; + } + /**unset a variable*/ + public function unsetVar($vname) + { + if(isset($this->vars[$vname])) + unset($this->vars[$vname]); + } + /**get value of a variable (returns false if variable does not exist)*/ + public function getVar($vname) + { + if(isset($this->vars[$vname])) + return $this->vars[$vname]; + else + return false; + } + /**returns true if variable exists*/ + public function haveVar($vname) + { + return isset($this->vars[$vname]); + } + + /**internal: used by parse to load data*/ + protected function parseNormal($help) + { + $out=""; + while(1){ + //get next line + $line=$help->getLine(); + //exit if file end has been reached + if($line===false)return $out; + //check whether this is a special statement + if(strncmp("#if:",$line,4)==0)$out.=$this->parseIf($help,$line);else + if(strncmp("#set:",$line,5)==0)$out.=$this->parseSet($help,$line); + else $out.=$this->parseLine($line); + } + } + /**internal: replace variables on a line*/ + protected function parseLine($line) + { + $ak=array(); + $av=array(); + foreach($this->vars as $k => $v){ + $ak[]="@".$k."@"; + $av[]=$v; + } + return str_replace($ak,$av,$line)."\n"; + } + /**internal: handle an \#if statement*/ + protected function parseIf($help,$line) + { + //parse if-line + $reg=array(); + if(ereg("^#if:([a-zA-Z0-9_]+)[ \t]*([=<>!]+)(.*)$",trim($line),$reg)===false) + return "(erroneous #if line found)\n"; + //check variable exists + $doout=isset($this->vars[$reg[1]]); + //do comparison + if($doout){ + $v=trim($this->vars[$reg[1]]); + $c=trim($reg[3]); + switch($reg[2]){ + case "==":case "=":$doout= $v == $c;break; + case "<":$doout = $v < $c;break; + case "<=":$doout = $v <= $c;break; + case ">":$doout = $v > $c;break; + case ">=":$doout = $v >= $c;break; + case "!=":case "<>":$doout = $v != $c;break; + default: $doout=false; + } + } + //parse till #endif + if($doout){ + $out=""; + //handle content normally until endif is found, then return + while(1){ + $line=$help->getLine(); + if($line===false)return $out; + if(strncmp("#if:",$line,4)==0)$out.=$this->parseIf($help,$line);else + if(strncmp("#set:",$line,5)==0)$out.=$this->parseSet($help,$line);else + if(strncmp("#endif",$line,6)==0)return $out; + else $out.=$this->parseLine($line); + } + }else{ + $ifc=1; + //ignore everything until corresponding endif is found + //#if needs to be handled specially, since parseIf is not + // called recursively here + while(1){ + $line=$help->getLine(); + //last line already? + if($line===false)return ""; + //handle if and endif + if(strncmp("#if:",$line,4)==0)$ifc+=1;else + if(strncmp("#endif",$line,6)==0)$ifc-=1; + //found corresponding endif? + if($ifc<=0)return ""; + //ignore remainder + } + } + } + /**internal: handle \#set statement*/ + protected function parseSet($help,$line) + { + //parse set-line + $reg=array(); + if(ereg("^#set:([a-zA-Z0-9_]+)((:)|(=(.*)))$",trim($line),$reg)===false) + return "(erroneous #set line found)\n"; + //check type + $vname=$reg[1]; + $var=""; + if($reg[3]==":"){ + //syntax: #set:var:\nvalue...\n#endset + //parse till #endset + $setcnt=1; + while(1){ + $line=$help->getLine(); + //handle set/unset statements pseudo-recursively + if(strncmp("#set:",$line,5)==0)$setcnt+=1;else + if(strncmp("#endset",$line,7)==0)$setcnt-=1; + //corresponding endset found? + if($setcnt<=0)break; + //add content to variable + $var.=$line."\n"; + } + }else{ + //syntax: #set:var=value + //get value directly + $var=$reg[5]; + } + //set variable + $this->setVar(trim($vname),trim($var)); + //go back (set creates no visible output) + return ""; + } +}; + + +?> \ No newline at end of file diff --git a/www/inc/classes/random.php b/www/inc/classes/random.php new file mode 100644 index 0000000..9b19645 --- /dev/null +++ b/www/inc/classes/random.php @@ -0,0 +1,53 @@ +, (C) 2007 +// +// Copyright: See README/COPYING files that come with this distribution +// +// + +//TODO: try to use /dev/random + +//get current random seed +$RANDSEED=$db->getConfig("randseed"); + +/**add some seed into the random function*/ +function randseed($rand) +{ + global $RANDSEED; + $RANDSEED.=$rand; +} + +/**return $bits bits of random data*/ +function getRandom($bits) +{ + //number of digits... + $bits/=4; + //init + global $RANDSEED,$db; + $ret="";$ctr=0; + //get string + while(strlen($ret)<$bits){ + $ctr++; + $ret.=sha1($RANDSEED.microtime().$ctr); + } + //rewrite seed to DB + $RANDSEED=sha1($RANDSEED.microtime().$ret); + $db->setConfig("randseed",$RANDSEED); + //return + return substr($ret,0,$bits); +} + +/**return a salt value for Customer::setPassword */ +function getSalt() +{ + return getRandom(16*4); +} + +?> \ No newline at end of file diff --git a/www/inc/classes/room.php b/www/inc/classes/room.php new file mode 100644 index 0000000..40daa21 --- /dev/null +++ b/www/inc/classes/room.php @@ -0,0 +1,84 @@ +, (C) 2007 +// +// Copyright: See README/COPYING files that come with this distribution +// +// + +//TODO: implement: +class Room +{ + public function __construct($roomid){} + public function exists(){return false;} + +}; + +function getRoomsXml($xmldata) +{ + global $db; + //TODO: check xml data + //return rooms + $res=$db->select("room","roomid,capacity,description",""); + $xml=new DOMDocument; + $root=$xml->createElement("RoomData"); + if(count($res)>0) + foreach($res as $k => $rm){ + $room=$xml->createElement("Room"); + $room->setAttribute("capacity",$rm["capacity"]); + $id=$xml->createElement("ID",$rm["roomid"]); + $room->appendChild($id); + $des=$xml->createElement("Description",$rm["description"]); + $room->appendChild($des); + $root->appendChild($room); + } + $xml->appendChild($root); + header("X-MagicSmoke-Status: Ok"); + print($xml->saveXML()); +} + +function setRoomsXml($xmldata) +{ + //TODO:do more extensive syntax checking and better error reporting + //get XML + $xml=new DOMDocument; + if($xml->loadXML($xmldata)===false){ + header("X-MagicSmoke-Status: SyntaxError"); + echo "Unable to parse XML."; + return; + } + //stage 2: extract data from XML + $doc=$xml->documentElement; + global $db; + foreach($doc->getElementsByTagName("Room") as $room){ + //get data + $cap=$room->getAttribute("capacity")+0; + $id=false; + $descr=false; + foreach($room->getElementsByTagName("ID") as $el) + foreach($el->childNodes as $cn) + if($cn->nodeType==XML_TEXT_NODE) + $id=trim($cn->wholeText); + foreach($room->getElementsByTagName("Description") as $el) + foreach($el->childNodes as $cn) + if($cn->nodeType==XML_TEXT_NODE) + $descr=trim($cn->wholeText); + if($id===false)continue; + $db->beginTransaction(); + $res=$db->select("room","roomid","roomid=".$db->escapeString($id)); + if(count($res)>0){ + $db->update("room",array("capacity"=>$cap,"description"=>$descr),"roomid=".$db->escapeString($id)); + }else{ + $db->insert("room",array("roomid"=>$id,"capacity"=>$cap,"description"=>$descr)); + } + $db->commitTransaction(); + } + header("X-MagicSmoke-Status: Ok"); +} + +?> \ No newline at end of file diff --git a/www/inc/classes/ticket.php b/www/inc/classes/ticket.php new file mode 100644 index 0000000..ff3a28c --- /dev/null +++ b/www/inc/classes/ticket.php @@ -0,0 +1,26 @@ +, (C) 2007 +// +// Copyright: See README/COPYING files that come with this distribution +// +// + + +/**ticket has been reserved by a seller*/ +define("TICKET_RESERVED",1); +/**ticket is part of an order or has been sold independently*/ +define("TICKET_SOLD",2); +/**ticket has been used*/ +define("TICKET_USED",4); +/**the ticket has been paid*/ +define("TICKET_PAID",8); +/**ticket has been cancelled by some entity*/ +define("TICKET_CANCELLED",16); + +?> \ No newline at end of file diff --git a/www/inc/config_manager.php b/www/inc/config_manager.php deleted file mode 100644 index 8cec61d..0000000 --- a/www/inc/config_manager.php +++ /dev/null @@ -1,80 +0,0 @@ - -// +---------------------------------------------------------------------- -// | -// | Copyright: See COPYING file that comes with this distribution -// +---------------------------------------------------------------------- -// - -class ConfigManager -{ - private $configFile; - private $config; - private static $instance; - - private function __construct($file) - { - global $template; - - $this->configFile = $template.$file; - $this->config = array(); - $this->readConfig(); - } - - /** returns the instance of the Config Manager */ - public static function singleton($file) - { - if(!self::$instance) { - self::$instance = new ConfigManager($file); - } - - return self::$instance; - } - - /** reads the configuration values from the file */ - private function readConfig() - { - // check if file really exists - if (file_exists($this->configFile)) { - $lines = file($this->configFile); - $key = ""; - foreach ($lines as $line_num => $line) { - if ( ereg("^msgid.*\"(.*)\"", $line, $reg) ) { - $key = $reg[1]; - } - if ( ereg("^msgstr.*\"(.*)\"", $line, $reg) ) { - $value = $reg[1]; - $this->config[$key] = $value; - } - } - } - } - - /** returns the value of the given configuration item */ - public function get($key) - { - if ($this->hasKey($key)) { - return $this->config[$key]; - } else { - return ""; - } - } - - /** checks if key exists */ - public function hasKey($key) - { - return array_key_exists($key, $this->config); - } - - /** can be used to set an alternate path to a config file */ - public function setConfigFile($file) - { - $this->configFile = $file; - $this->readConfig(); - } -} - -?> diff --git a/www/inc/customer.php b/www/inc/customer.php deleted file mode 100644 index b503dc3..0000000 --- a/www/inc/customer.php +++ /dev/null @@ -1,93 +0,0 @@ -id=false; - if($id!==false){ - $this->getByID($id); - } - } - - /**tries to get the customer by its ID, returns false if it fails*/ - public function getByID($id) - { - global $db; - $res=$db->select("customer","customerid","where customerid=".$db->escapeInt($id)); - if(count($res)>0){ - $this->id=$id+0; - return true; - }else - return false; - } - - /**tries to get the customer by its email address, returns false if it fails*/ - public function getByMail($mail) - { - global $db; - $res=$db->select("customer","customerid","where email=".$db->escapeString($mail)); - if(count($res)>0){ - $this->id=$res[0]["customerid"]; - return true; - }else - return false; - } - - /**checks whether the customer exists in the database; getByID or getByMail must have been called first*/ - public function exists() - { - return $this->id !== false; - } - - /**creates the customer in the database; getByID or getByMail must not have been called yet; - returns the new ID on success or false on failure*/ - public function create($name) - { - if($this->id!==false)return; - global $db; - $this->id=$db->insert("customer",array("name"=>$name)); - return $this->id; - } - - /**sets the email of this customer*/ - public function setMail($mail) - { - if($this->id===false)return; - global $db; - $db->update("customer",array("email"=>$mail),"customerid=".$db->escapeInt($this->id)); - } - - /**sets the password of this customer*/ - public function setPassword($pwd) - { - if($this->id===false)return; - global $db; - $pass=calcPasswd($pwd,getSalt()); - $db->update("customer",array("passwd"=>$pass),"customerid=".$db->escapeInt($this->id)); - } - - /**checks whether $password matches the stored password for this customer; returns true on success*/ - public function authenticate($passwd) - { - if($this->id===false)return false; - //get record - global $db; - $res=$db->select("customer","passwd","customerid=".$db->escapeInt($this->id)); - //found anything? - if(count($res)<0)return false; - //is it a password - if(!is_string($res[0]["passwd"]) || strlen($res[0]["passwd"])<10)return false; - //check - $pwd=explode(":",$res[0]["passwd"]); - $pwd2=calcPasswd($passwd,$pwd[0]); - return $pwd2 == $res[0]["passwd"]; - } -}; - -?> \ No newline at end of file diff --git a/www/inc/db.php b/www/inc/db.php deleted file mode 100644 index 4a94b34..0000000 --- a/www/inc/db.php +++ /dev/null @@ -1,276 +0,0 @@ -adminuser=$u; - $this->adminpass=$p; - } - - /**check admin credentials*/ - public function checkAdmin() - { - global $_SERVER; - if(!$this->canAdministrate())return false; - if(!isset($_SERVER["PHP_AUTH_USER"]) || !isset($_SERVER["PHP_AUTH_PW"])){ - return false; - } - return $_SERVER["PHP_AUTH_USER"]==$this->adminuser && $_SERVER["PHP_AUTH_PW"]==$this->adminpass; - } - - /**returns whether a passcode is known and admin.php may be used*/ - public function canAdministrate() - { - return $this->adminpass!==false && $this->adminuser!==false; - } - - /**returns the version of the DB layout that is required by this version of Magic Smoke*/ - public function needVersion(){return "00.01";} - - /**returns whether the table exists; must be implemented by driver*/ - public abstract function haveTable($tablename); - - /**begins a transaction; must be implemented by driver*/ - public abstract function beginTransaction(); - - /**ends a transaction successfully; must be implemented by driver; returns true on success*/ - public abstract function commitTransaction(); - - /**ends a transaction with a rollback; must be implemented by driver; returns true on success*/ - public abstract function rollbackTransaction(); - - /**gets some data from the database; $table is the name of the table, $cols is the list of columns to return or "*" for all, $where is the where clause of the SQL-statement; returns array of rows, which are in *_fetch_array format; returns false on error*/ - public abstract function select($table,$cols,$where); - - /**insert values into a table; returns false on failure, the new primary key if a sequence was set, true otherwise*/ - public abstract function insert($table,array $values); - - /**update database values; returns how many rows have been changed or false for failure*/ - public abstract function update($table,array $values,$where); - - /**delete database values*/ - public abstract function deleteRows($table,$where); - - /**creates a table; the argument is an array of the form "col-name" => array("col-type", "flags"...); use sqlCreateTable() etc. to create the actual statement*/ - protected abstract function createTable($tablename,$table); - - /**transform an internally used table name to the actual table name in the DB; the default implementation returns exactly what it gets*/ - protected function tableName($tname){return $tname;} - - /**returns the correct type name for the required abstract data type; - types that must be understood are: int32 (INTEGER), int64 (LONG INTEGER), seq32 (auto-incrementing int), seq64, string:$length (text up to 255 chars, length is optional, default is 255; VARCHAR($length)), text (unlimited text)*/ - protected function dataType($type) - { - if($type=="int32")return "INTEGER"; - if($type=="int64")return "LONG INTEGER"; - $tpa=explode(":",$type); - if($tpa[0]=="string"){ - if(isset($tpa[1])) - return "VARCHAR(".$tpa[1].")"; - else - return "VARCHAR(255)"; - } - return false; - } - - /**returns the correct name/coding of a flag: - primarykey, notnull, unique (implies notnull), foreignkey:$table:$col, defaultint:$val, defaultstr:$val, index*/ - protected function columnFlag($flag) - { - if($flag=="primarykey")return "PRIMARY KEY"; - if($flag=="notnull")return "NOT NULL"; - if($flag=="unique")return "NOT NULL UNIQUE"; - if($flag=="index")return "INDEX"; - $tpa=explode(":",$flag); - if($tpa[0]=="foreignkey"){ - if(count($tpa)<3) - return false; - return "REFERENCES ".$this->tableName($tpa[1])."($tpa[2])"; - } - if($tpa[0]=="defaultint"){ - if(count($tpa)<2) - return "DEFAULT NULL"; - return "DEFAULT $tpa[1]"; - } - if($tpa[0]=="defaultstr"){ - if(count($tpa)<2) - return "DEFAULT NULL"; - return "DEFAULT ".$this->escapeString($tpa[1]); - } - } - - /**creates a SQL92 statement for creating a table*/ - protected function sqlCreateTable($tablename,$table) - { - $ret="CREATE TABLE ".$this->tableName($tablename)." ("; - $cm=""; - reset($table); - while(list($col,$def)=each($table)){ - $ret.=$cm;$cm=","; - //check whether this is a special column - if(substr($col,0,1)==":"){ - if($col==":primarykey")$ret.=$this->sqlCreateTablePrimaryKey($def); - else die("Unknown special column ".$col." while creating table ".$tablename); - }else{ - //column name - $ret.=$col." "; - //get type - $ret.=$this->dataType($def[0])." "; - //get flags - for($i=0;$icolumnFlag($def[$i])." "; - } - } - $ret.=")"; - return $ret; - } - - /**creates primary key statement for sqlCreateTable*/ - protected function sqlCreateTablePrimaryKey(array $cols) - { - $ret="PRIMARY KEY("; - for($i=0;$i0)$ret.=","; - $ret.=$cols[$i]; - } - $ret.=")"; - return $ret; - } - - /**creates a SQL92 statement for inserts*/ - protected function sqlInsert($table,array $values) - { - global $dbScheme; - $ret="INSERT INTO ".$this->tableName($table)." ("; - reset($values); - $cm=""; - $val=") VALUES ("; - while(list($k,$v)=each($values)){ - $ret.=$cm;$val.=$cm;$cm=","; - //append column name - $ret.=$k; - //append value - if($dbScheme->isIntColumn($table,$k)) - $val.=$this->escapeInt($v); - else - if($dbScheme->isStringColumn($table,$k)) - $val.=$this->escapeString($v); - else - //don't know how to escape it... - $val.="NULL"; - } - $ret.=$val.")"; - return $ret; - } - - /**creates a SQL92 statement for deletes*/ - protected function sqlDelete($table,$where) - { - return "DELETE FROM ".$this->tableName($table)." WHERE ".$where; - } - - /**creates a SQL92 statement for updates*/ - protected function sqlUpdate($table,array $values,$where) - { - global $dbScheme; - $ret="UPDATE ".$this->tableName($table)." SET "; - reset($values); - $cm=""; - while(list($k,$v)=each($values)){ - $ret.=$cm;$cm=","; - //append column name - $ret.=$k."="; - //append value - if($dbScheme->isIntColumn($table,$k)) - $ret.=$this->escapeInt($v); - else - if($dbScheme->isStringColumn($table,$k)) - $ret.=$this->escapeString($v); - else - //don't know how to escape it... - $ret.="NULL"; - } - $ret.=" WHERE ".$where; - return $ret; - } - - /**escapes integers; the default implementation just makes sure it is an int*/ - public function escapeInt($i) - { - if($i === false)return "NULL"; - return $i + 0; - } - - /**escapes strings; the default uses addslashes and encloses the value in ''*/ - public function escapeString($s) - { - if($s === false) return "NULL"; - return "'".addslashes($s)."'"; - } - - /**returns a configuration setting*/ - public function getConfig($key) - { - $mar=$this->select("config","cval","ckey=".$this->escapeString($key)); - if(count($mar)>0)return $mar[0][0]; - return false; - } - - /**sets a config setting*/ - public function setConfig($key,$val) - { - $this->beginTransaction(); - $mar=$this->select("config","cval","ckey=".$this->escapeString($key)); - if(count($mar)>0)$this->update("config",array("cval"=>$val),"ckey=".$this->escapeString($key)); - else $this->insert("config",array("ckey"=>$key,"cval"=>$val)); - $this->commitTransaction(); - } - - /**tries to find out whether the connected DB version is usable*/ - public function canUseDb() - { - if(!$this->haveTable("config")) - return false; - return $this->getConfig("MagicSmokeVersion")==$this->needVersion(); - } - - /**creates the database, used by admin.php only!!*/ - public function createDb() - { - global $dbScheme; - $this->beginTransaction(); - //iterate DB schema and create tables - $tabs=$dbScheme->tableNames(); - for($i=0;$icreateTable($tabs[$i],$dbScheme->tableDefinition($tabs[$i]))){ - print("DB Error while creating ".$tabs[$i].": ".$this->lastError()."

\n"); - print("Last statement was: ".$this->sqlCreateTable($tabs[$i],$dbScheme->tableDefinition($tabs[$i]))."

\n"); - $this->rollbackTransaction(); - die("Unable to create database."); - } - } - //insert some defaults - $this->insert("config",array("ckey"=>"MagicSmokeVersion","cval"=>$this->needVersion())); - $this->insert("host",array("hostname"=>"_any")); - $this->insert("host",array("hostname"=>"_anon")); - $this->insert("host",array("hostname"=>"_online")); - //close transaction - $this->commitTransaction(); - } - - /**returns the error string of the last operation*/ - public abstract function lastError(); -}; - -?> \ No newline at end of file diff --git a/www/inc/db/db.php b/www/inc/db/db.php new file mode 100644 index 0000000..4a94b34 --- /dev/null +++ b/www/inc/db/db.php @@ -0,0 +1,276 @@ +adminuser=$u; + $this->adminpass=$p; + } + + /**check admin credentials*/ + public function checkAdmin() + { + global $_SERVER; + if(!$this->canAdministrate())return false; + if(!isset($_SERVER["PHP_AUTH_USER"]) || !isset($_SERVER["PHP_AUTH_PW"])){ + return false; + } + return $_SERVER["PHP_AUTH_USER"]==$this->adminuser && $_SERVER["PHP_AUTH_PW"]==$this->adminpass; + } + + /**returns whether a passcode is known and admin.php may be used*/ + public function canAdministrate() + { + return $this->adminpass!==false && $this->adminuser!==false; + } + + /**returns the version of the DB layout that is required by this version of Magic Smoke*/ + public function needVersion(){return "00.01";} + + /**returns whether the table exists; must be implemented by driver*/ + public abstract function haveTable($tablename); + + /**begins a transaction; must be implemented by driver*/ + public abstract function beginTransaction(); + + /**ends a transaction successfully; must be implemented by driver; returns true on success*/ + public abstract function commitTransaction(); + + /**ends a transaction with a rollback; must be implemented by driver; returns true on success*/ + public abstract function rollbackTransaction(); + + /**gets some data from the database; $table is the name of the table, $cols is the list of columns to return or "*" for all, $where is the where clause of the SQL-statement; returns array of rows, which are in *_fetch_array format; returns false on error*/ + public abstract function select($table,$cols,$where); + + /**insert values into a table; returns false on failure, the new primary key if a sequence was set, true otherwise*/ + public abstract function insert($table,array $values); + + /**update database values; returns how many rows have been changed or false for failure*/ + public abstract function update($table,array $values,$where); + + /**delete database values*/ + public abstract function deleteRows($table,$where); + + /**creates a table; the argument is an array of the form "col-name" => array("col-type", "flags"...); use sqlCreateTable() etc. to create the actual statement*/ + protected abstract function createTable($tablename,$table); + + /**transform an internally used table name to the actual table name in the DB; the default implementation returns exactly what it gets*/ + protected function tableName($tname){return $tname;} + + /**returns the correct type name for the required abstract data type; + types that must be understood are: int32 (INTEGER), int64 (LONG INTEGER), seq32 (auto-incrementing int), seq64, string:$length (text up to 255 chars, length is optional, default is 255; VARCHAR($length)), text (unlimited text)*/ + protected function dataType($type) + { + if($type=="int32")return "INTEGER"; + if($type=="int64")return "LONG INTEGER"; + $tpa=explode(":",$type); + if($tpa[0]=="string"){ + if(isset($tpa[1])) + return "VARCHAR(".$tpa[1].")"; + else + return "VARCHAR(255)"; + } + return false; + } + + /**returns the correct name/coding of a flag: + primarykey, notnull, unique (implies notnull), foreignkey:$table:$col, defaultint:$val, defaultstr:$val, index*/ + protected function columnFlag($flag) + { + if($flag=="primarykey")return "PRIMARY KEY"; + if($flag=="notnull")return "NOT NULL"; + if($flag=="unique")return "NOT NULL UNIQUE"; + if($flag=="index")return "INDEX"; + $tpa=explode(":",$flag); + if($tpa[0]=="foreignkey"){ + if(count($tpa)<3) + return false; + return "REFERENCES ".$this->tableName($tpa[1])."($tpa[2])"; + } + if($tpa[0]=="defaultint"){ + if(count($tpa)<2) + return "DEFAULT NULL"; + return "DEFAULT $tpa[1]"; + } + if($tpa[0]=="defaultstr"){ + if(count($tpa)<2) + return "DEFAULT NULL"; + return "DEFAULT ".$this->escapeString($tpa[1]); + } + } + + /**creates a SQL92 statement for creating a table*/ + protected function sqlCreateTable($tablename,$table) + { + $ret="CREATE TABLE ".$this->tableName($tablename)." ("; + $cm=""; + reset($table); + while(list($col,$def)=each($table)){ + $ret.=$cm;$cm=","; + //check whether this is a special column + if(substr($col,0,1)==":"){ + if($col==":primarykey")$ret.=$this->sqlCreateTablePrimaryKey($def); + else die("Unknown special column ".$col." while creating table ".$tablename); + }else{ + //column name + $ret.=$col." "; + //get type + $ret.=$this->dataType($def[0])." "; + //get flags + for($i=0;$icolumnFlag($def[$i])." "; + } + } + $ret.=")"; + return $ret; + } + + /**creates primary key statement for sqlCreateTable*/ + protected function sqlCreateTablePrimaryKey(array $cols) + { + $ret="PRIMARY KEY("; + for($i=0;$i0)$ret.=","; + $ret.=$cols[$i]; + } + $ret.=")"; + return $ret; + } + + /**creates a SQL92 statement for inserts*/ + protected function sqlInsert($table,array $values) + { + global $dbScheme; + $ret="INSERT INTO ".$this->tableName($table)." ("; + reset($values); + $cm=""; + $val=") VALUES ("; + while(list($k,$v)=each($values)){ + $ret.=$cm;$val.=$cm;$cm=","; + //append column name + $ret.=$k; + //append value + if($dbScheme->isIntColumn($table,$k)) + $val.=$this->escapeInt($v); + else + if($dbScheme->isStringColumn($table,$k)) + $val.=$this->escapeString($v); + else + //don't know how to escape it... + $val.="NULL"; + } + $ret.=$val.")"; + return $ret; + } + + /**creates a SQL92 statement for deletes*/ + protected function sqlDelete($table,$where) + { + return "DELETE FROM ".$this->tableName($table)." WHERE ".$where; + } + + /**creates a SQL92 statement for updates*/ + protected function sqlUpdate($table,array $values,$where) + { + global $dbScheme; + $ret="UPDATE ".$this->tableName($table)." SET "; + reset($values); + $cm=""; + while(list($k,$v)=each($values)){ + $ret.=$cm;$cm=","; + //append column name + $ret.=$k."="; + //append value + if($dbScheme->isIntColumn($table,$k)) + $ret.=$this->escapeInt($v); + else + if($dbScheme->isStringColumn($table,$k)) + $ret.=$this->escapeString($v); + else + //don't know how to escape it... + $ret.="NULL"; + } + $ret.=" WHERE ".$where; + return $ret; + } + + /**escapes integers; the default implementation just makes sure it is an int*/ + public function escapeInt($i) + { + if($i === false)return "NULL"; + return $i + 0; + } + + /**escapes strings; the default uses addslashes and encloses the value in ''*/ + public function escapeString($s) + { + if($s === false) return "NULL"; + return "'".addslashes($s)."'"; + } + + /**returns a configuration setting*/ + public function getConfig($key) + { + $mar=$this->select("config","cval","ckey=".$this->escapeString($key)); + if(count($mar)>0)return $mar[0][0]; + return false; + } + + /**sets a config setting*/ + public function setConfig($key,$val) + { + $this->beginTransaction(); + $mar=$this->select("config","cval","ckey=".$this->escapeString($key)); + if(count($mar)>0)$this->update("config",array("cval"=>$val),"ckey=".$this->escapeString($key)); + else $this->insert("config",array("ckey"=>$key,"cval"=>$val)); + $this->commitTransaction(); + } + + /**tries to find out whether the connected DB version is usable*/ + public function canUseDb() + { + if(!$this->haveTable("config")) + return false; + return $this->getConfig("MagicSmokeVersion")==$this->needVersion(); + } + + /**creates the database, used by admin.php only!!*/ + public function createDb() + { + global $dbScheme; + $this->beginTransaction(); + //iterate DB schema and create tables + $tabs=$dbScheme->tableNames(); + for($i=0;$icreateTable($tabs[$i],$dbScheme->tableDefinition($tabs[$i]))){ + print("DB Error while creating ".$tabs[$i].": ".$this->lastError()."

\n"); + print("Last statement was: ".$this->sqlCreateTable($tabs[$i],$dbScheme->tableDefinition($tabs[$i]))."

\n"); + $this->rollbackTransaction(); + die("Unable to create database."); + } + } + //insert some defaults + $this->insert("config",array("ckey"=>"MagicSmokeVersion","cval"=>$this->needVersion())); + $this->insert("host",array("hostname"=>"_any")); + $this->insert("host",array("hostname"=>"_anon")); + $this->insert("host",array("hostname"=>"_online")); + //close transaction + $this->commitTransaction(); + } + + /**returns the error string of the last operation*/ + public abstract function lastError(); +}; + +?> \ No newline at end of file diff --git a/www/inc/db/db_mysql.php b/www/inc/db/db_mysql.php new file mode 100644 index 0000000..6365ca9 --- /dev/null +++ b/www/inc/db/db_mysql.php @@ -0,0 +1,171 @@ +user=$user; + $this->server=$server; + $this->pass=$pass; + } + + /**set a table-name prefix for the database*/ + public function setPrefix($pre) + { + $this->prefix=$pre; + } + + /**set the name of the database to be used*/ + public function setDbName($dbn) + { + $this->dbname=$dbn; + } + + /**set the name of the storage engine to be used on DB creation*/ + public function setStorageEngine($e) + { + $this->engine=$e; + } + + public function tryConnect() + { + //connect + $this->dbhdl=mysqli_connect($this->server,$this->user,$this->pass,$this->dbname); + if($this->dbhdl===false) + die("Unable to connect to database system. Giving up."); + //select Unicode; TODO: fix it to be configurable + if(mysqli_query($this->dbhdl,"SET NAMES 'utf8'")===false) + die("cannot set character set to utf-8"); + } + + public function haveTable($tnm) + { + $res=mysqli_query($this->dbhdl,"select * from ".$this->tableName($tnm)." where 1=2"); + if($res===false)return false; + mysqli_free_result($res); + return true; + } + public function beginTransaction() + { + return mysqli_query($this->dbhdl,"BEGIN"); + } + + public function commitTransaction() + { + return mysqli_query($this->dbhdl,"COMMIT"); + } + + public function rollbackTransaction() + { + return mysqli_query($this->dbhdl,"ROLLBACK"); + } + + public function select($table,$cols,$where) + { + $query="SELECT $cols FROM ".$this->tableName($table); + if($where!="")$query.=" WHERE ".$where; + $res=mysqli_query($this->dbhdl,$query); + if($res===false)return false; + $nr=mysqli_num_rows($res); + $ret=array(); + for($i=0;$i<$nr;$i++){ + $ret[]=mysqli_fetch_array($res,MYSQLI_BOTH); + } + mysqli_free_result($res); + return $ret; + } + + protected function createTable($tn,$t) + { + return mysqli_query($this->dbhdl,$this->sqlCreateTable($tn,$t)." engine=".$this->engine); + } + + protected function tableName($tn) + { + return $this->prefix.$tn; + } + + protected function dataType($type) + { + if($type=="int32")return "INT"; + if($type=="int64")return "BIGINT"; + if($type=="seq32")return "INT AUTO_INCREMENT"; + if($type=="seq64")return "BIGINT AUTO_INCREMENT"; + if($type=="text")return "TEXT"; + $tpa=explode(":",$type); + if($tpa[0]=="string"){ + if(isset($tpa[1])) + return "VARCHAR(".$tpa[1].")"; + else + return "VARCHAR(255)"; + } + //fallback to SQL standard + return parent::dataType($type); + } + + protected function columnFlag($flag) + { + //FIXME: currently MySQL does not mark columns for indexing, since the syntax is somewhat different --> this needs to be fixed! + if($flag=="index")return ""; + //fallback to SQL standard + return parent::columnFlag($flag); + } + + public function insert($table,array $values) + { + $res=mysqli_query($this->dbhdl,$this->sqlInsert($table,$values)); + if($res===false)return false; + global $dbScheme; + $seq=$dbScheme->hasSequence($table); + if($seq!==false){ + if(isset($values[$seq]))return $values[$seq]; + $res=mysqli_query($this->dbhdl,"select LAST_INSERT_ID()"); + if(mysqli_num_rows($res)>0){ + $row=mysqli_fetch_array($res); + $ret=$row[0]; + }else{ + $ret=true; + } + mysqli_free_result($res); + return $ret; + }else{ + return true; + } + } + + public function update($table,array $values,$where) + { + $res=mysqli_query($this->dbhdl,$this->sqlUpdate($table,$values,$where)); + if($res!==false)return mysqli_affected_rows($this->dbhdl); + else return false; + } + + public function deleteRows($table,$where) + { + mysqli_query($this->dbhdl,$this->sqlDelete($table,$where)); + } + + public function lastError() + { + return mysqli_error($this->dbhdl); + } + + /**escapes strings; it uses mysqli_escape_string and encloses the value in ''*/ + public function escapeString($s) + { + if($s === false) return "NULL"; + return "'".mysqli_real_escape_string($this->dbhdl,$s)."'"; + } +}; \ No newline at end of file diff --git a/www/inc/db/db_scheme.php b/www/inc/db/db_scheme.php new file mode 100644 index 0000000..51d4aa8 --- /dev/null +++ b/www/inc/db/db_scheme.php @@ -0,0 +1,237 @@ +scheme["config"]=array( + "ckey"=>array("string:32","primarykey"), + "cval"=>array("string") + ); + //clients + $this->scheme["host"]=array( + "hostname"=>array("string:64","primarykey"), + //if hostkey is NULL it is a special host (_any, _anon, _online) + "hostkey"=>array("string") + ); + //client users (ticket sellers, admins, etc.; for customers and web logins see below) + $this->scheme["users"]=array( + "uname" => array("string:64","primarykey"), + "passwd" => array("string","notnull"), + //more detailed data that can be displayed to customers + "description" => array("text") + ); + $this->scheme["userrole"]=array( + "uname" =>array("string:64","notnull","foreignkey:users:uname","index"), + "role" =>array("string:32","notnull") + ); + $this->scheme["userhosts"]=array( + "uname" => array("string:64","notnull","foreignkey:users:uname","index"), + "host" => array("string:64","notnull","foreignkey:host:hostname") + ); + //sessions + $this->scheme["session"]=array( + "sessionid" => array("string:64","primarykey"), + //if empty: not authenticated + "user"=>array("string:64"), + //emptied after authentication: + "hchallenge"=>array("string:64"), + "uchallenge"=>array("string:64"), + //unix timestamp at which to delete this session + // this needs to change to 64-bit int in 2038 + "timeout"=>array("int32","notnull") + ); + + //rooms + $this->scheme["room"]=array( + "roomid" => array("string:64","primarykey"), + "capacity" => array("int32","notnull"), + "description" => array("text") + ); + //event + $this->scheme["event"]=array( + "eventid" => array("seq32","primarykey"), + //display data + "title" => array("string","notnull"), + "artist" => array("string","notnull"), + "description" => array("text"), + //timing and location + "starttime" => array("int32","notnull"), + "endtime" => array("int32","notnull"), + "roomid" => array("string:64","foreignkey:room:roomid"), + //initially a copy from room, can be adjusted + "capacity" => array("int32","notnull"), + //default pricing in cents + "defaultprice" => array("int32","notnull"), + //if not null/empty: event has been cancelled + "cancelreason" => array("string") + ); + //customer + $this->scheme["customer"]=array( + "customerid" => array("seq32","primarykey"), + //contact data + "name" => array("string",notnull), + "address" => array("string"), + "contact" => array("string"),//phone or something + "comments" => array("text"), + //online login data + "email" => array("string"), + "passwd" => array("string:64"),//salted SHA-1 hash of passwd + ); + //orders by customers + $this->scheme["order"]=array( + "orderid" => array("seq32","primarykey"), + //customer + "customerid" => array("int32","foreignkey:customer:customerid"), + //seller (_online for web forms) + "soldby" => array("string:64","foreignkey:users:uname"), + //if not null/empty: this address for delivery, customer address for invoice + "deliveryaddress" => array("string"), + //if not null/empty: lodge/deposit the tickets at a seller with _deposit flag + "depositat" => array("string:64","foreignkey:users:uname"), + //status, see ORDER_* constants + "status" => array("int32","notnull"), + "ordertime" => array("int32","notnull"), + "senttime" => array("int32"), + //comments made on web form (eg. "urgently needed for dads birthday") + "comments" => array("text"), + //how much has been paid already (including used vouchers) + //this is for comparison with the price fields in ticket and voucher tables + "amountpaid" => array("int32") + ); + //tickets + $this->scheme["ticket"]=array( + "ticketid" => array("seq64","primarykey"), + "eventid" => array("int32","foreignkey:event:eventid"), + //initially a copy from event, can be adjusted by seller + "price" => array("int32","notnull"), + //status of ticket (see TICKET_* constants) + "status" => array("int32","notnull"), + //if status is reserved, this contains the reserving seller + "reservedby" => array("string:64","foreignkey:users:uname"), + "reservetimeout" => array("int32"), + //sold to someone (may be NULL for direct sales or reserves) + "oderid" => array("int32","foreignkey:orders:orderid") + ); + //vouchers and re-imbursments + $this->scheme["voucher"]=array( + //a 16char code (code39: case-insensitive letters+digits) for the voucher) + "voucherid" => array("string:16","primarykey"), + //if ordered: order-info + "price" => array("int32","notnull"), + "oderid" => array("int32","foreignkey:orders:orderid"), + //unix-timestamp of original sales date/time + "salestime" => array("int32","notnull"), + //remaining value in cents + "value" => array("int32","notnull") + ); + + //shopping cart + $this->scheme["cart"]=array( + //the cookie for this cart + "cartid" => array("string:32","primarykey"), + //when the cart expires + "timeout" => array("int32","notnull") + ); + //buying tickets + $this->scheme["cart_ticket"]=array( + "cartid" => array("string:32","notnull","foreignkey:cart:cartid"), + //tickets in the cart + "eventid" => array("int32","notnull","foreignkey:event:eventid"), + "amount" => array("int32","notnull"), + //primary key definition + ":primarykey" => array("cartid","eventid") + ); + //buying vouchers + $this->scheme["cart_voucher"]=array( + "cvid" => array("seq64","primarykey"), + "cartid" => array("string:32","notnull","foreignkey:cart:cartid"), + //voucher value + "value" => array("int32","notnull") + ); + + } + + /**return the tables to be created in order*/ + public function tableNames() + { + return array_keys($this->scheme); + } + + /**return the full definition of a table, or false if it does not exist*/ + public function tableDefinition($tab) + { + if(!isset($this->scheme[$tab])) + return false; + return $this->scheme[$tab]; + } + + /**return the names of all columns of a table, or false if the table does not exist*/ + public function tableColumns($tab) + { + if(!isset($this->scheme[$tab])) + return false; + return array_keys($this->scheme[$tab]); + } + + /**return the type of a column, or false if it does not exist*/ + public function columnType($tab,$col) + { + if(!isset($this->scheme[$tab][$col])) + return false; + return $this->scheme[$tab][$col][0]; + } + + /**return the flags of a column, empty array if no flags are set, or false if the column does not exist*/ + public function columnFlags($tab,$col) + { + if(!isset($this->scheme[$tab][$col])) + return false; + $tmp=$this->scheme[$tab][$col]; + unset($tmp[0]); + return array_values($tmp); + } + + /**returns true if the given column is of an integer type*/ + public function isIntColumn($tab,$col) + { + if(!isset($this->scheme[$tab][$col])) + return false; + $tpa=explode(":",$this->scheme[$tab][$col][0]); + switch($tpa[0]){ + case "int32":case "seq32":case "int64":case "seq64": + return true; + default: + return false; + } + } + + /**returns the sequence column name if the table has a sequence, false otherwise*/ + public function hasSequence($tab) + { + if(!isset($this->scheme[$tab])) + return false; + foreach($this->scheme[$tab] as $cl => $def){ + if($def[0] == "seq32" || $def[0] == "seq64") + return $cl; + } + return false; + } + + /**returns true if the given column is of a string type*/ + public function isStringColumn($tab,$col) + { + if(!isset($this->scheme[$tab][$col])) + return false; + $tpa=explode(":",$this->scheme[$tab][$col][0]); + switch($tpa[0]){ + case "string":case "text": + return true; + default: + return false; + } + } +}; +$dbScheme=new DbScheme; +?> \ No newline at end of file diff --git a/www/inc/db_mysql.php b/www/inc/db_mysql.php deleted file mode 100644 index 6365ca9..0000000 --- a/www/inc/db_mysql.php +++ /dev/null @@ -1,171 +0,0 @@ -user=$user; - $this->server=$server; - $this->pass=$pass; - } - - /**set a table-name prefix for the database*/ - public function setPrefix($pre) - { - $this->prefix=$pre; - } - - /**set the name of the database to be used*/ - public function setDbName($dbn) - { - $this->dbname=$dbn; - } - - /**set the name of the storage engine to be used on DB creation*/ - public function setStorageEngine($e) - { - $this->engine=$e; - } - - public function tryConnect() - { - //connect - $this->dbhdl=mysqli_connect($this->server,$this->user,$this->pass,$this->dbname); - if($this->dbhdl===false) - die("Unable to connect to database system. Giving up."); - //select Unicode; TODO: fix it to be configurable - if(mysqli_query($this->dbhdl,"SET NAMES 'utf8'")===false) - die("cannot set character set to utf-8"); - } - - public function haveTable($tnm) - { - $res=mysqli_query($this->dbhdl,"select * from ".$this->tableName($tnm)." where 1=2"); - if($res===false)return false; - mysqli_free_result($res); - return true; - } - public function beginTransaction() - { - return mysqli_query($this->dbhdl,"BEGIN"); - } - - public function commitTransaction() - { - return mysqli_query($this->dbhdl,"COMMIT"); - } - - public function rollbackTransaction() - { - return mysqli_query($this->dbhdl,"ROLLBACK"); - } - - public function select($table,$cols,$where) - { - $query="SELECT $cols FROM ".$this->tableName($table); - if($where!="")$query.=" WHERE ".$where; - $res=mysqli_query($this->dbhdl,$query); - if($res===false)return false; - $nr=mysqli_num_rows($res); - $ret=array(); - for($i=0;$i<$nr;$i++){ - $ret[]=mysqli_fetch_array($res,MYSQLI_BOTH); - } - mysqli_free_result($res); - return $ret; - } - - protected function createTable($tn,$t) - { - return mysqli_query($this->dbhdl,$this->sqlCreateTable($tn,$t)." engine=".$this->engine); - } - - protected function tableName($tn) - { - return $this->prefix.$tn; - } - - protected function dataType($type) - { - if($type=="int32")return "INT"; - if($type=="int64")return "BIGINT"; - if($type=="seq32")return "INT AUTO_INCREMENT"; - if($type=="seq64")return "BIGINT AUTO_INCREMENT"; - if($type=="text")return "TEXT"; - $tpa=explode(":",$type); - if($tpa[0]=="string"){ - if(isset($tpa[1])) - return "VARCHAR(".$tpa[1].")"; - else - return "VARCHAR(255)"; - } - //fallback to SQL standard - return parent::dataType($type); - } - - protected function columnFlag($flag) - { - //FIXME: currently MySQL does not mark columns for indexing, since the syntax is somewhat different --> this needs to be fixed! - if($flag=="index")return ""; - //fallback to SQL standard - return parent::columnFlag($flag); - } - - public function insert($table,array $values) - { - $res=mysqli_query($this->dbhdl,$this->sqlInsert($table,$values)); - if($res===false)return false; - global $dbScheme; - $seq=$dbScheme->hasSequence($table); - if($seq!==false){ - if(isset($values[$seq]))return $values[$seq]; - $res=mysqli_query($this->dbhdl,"select LAST_INSERT_ID()"); - if(mysqli_num_rows($res)>0){ - $row=mysqli_fetch_array($res); - $ret=$row[0]; - }else{ - $ret=true; - } - mysqli_free_result($res); - return $ret; - }else{ - return true; - } - } - - public function update($table,array $values,$where) - { - $res=mysqli_query($this->dbhdl,$this->sqlUpdate($table,$values,$where)); - if($res!==false)return mysqli_affected_rows($this->dbhdl); - else return false; - } - - public function deleteRows($table,$where) - { - mysqli_query($this->dbhdl,$this->sqlDelete($table,$where)); - } - - public function lastError() - { - return mysqli_error($this->dbhdl); - } - - /**escapes strings; it uses mysqli_escape_string and encloses the value in ''*/ - public function escapeString($s) - { - if($s === false) return "NULL"; - return "'".mysqli_real_escape_string($this->dbhdl,$s)."'"; - } -}; \ No newline at end of file diff --git a/www/inc/db_scheme.php b/www/inc/db_scheme.php deleted file mode 100644 index 51d4aa8..0000000 --- a/www/inc/db_scheme.php +++ /dev/null @@ -1,237 +0,0 @@ -scheme["config"]=array( - "ckey"=>array("string:32","primarykey"), - "cval"=>array("string") - ); - //clients - $this->scheme["host"]=array( - "hostname"=>array("string:64","primarykey"), - //if hostkey is NULL it is a special host (_any, _anon, _online) - "hostkey"=>array("string") - ); - //client users (ticket sellers, admins, etc.; for customers and web logins see below) - $this->scheme["users"]=array( - "uname" => array("string:64","primarykey"), - "passwd" => array("string","notnull"), - //more detailed data that can be displayed to customers - "description" => array("text") - ); - $this->scheme["userrole"]=array( - "uname" =>array("string:64","notnull","foreignkey:users:uname","index"), - "role" =>array("string:32","notnull") - ); - $this->scheme["userhosts"]=array( - "uname" => array("string:64","notnull","foreignkey:users:uname","index"), - "host" => array("string:64","notnull","foreignkey:host:hostname") - ); - //sessions - $this->scheme["session"]=array( - "sessionid" => array("string:64","primarykey"), - //if empty: not authenticated - "user"=>array("string:64"), - //emptied after authentication: - "hchallenge"=>array("string:64"), - "uchallenge"=>array("string:64"), - //unix timestamp at which to delete this session - // this needs to change to 64-bit int in 2038 - "timeout"=>array("int32","notnull") - ); - - //rooms - $this->scheme["room"]=array( - "roomid" => array("string:64","primarykey"), - "capacity" => array("int32","notnull"), - "description" => array("text") - ); - //event - $this->scheme["event"]=array( - "eventid" => array("seq32","primarykey"), - //display data - "title" => array("string","notnull"), - "artist" => array("string","notnull"), - "description" => array("text"), - //timing and location - "starttime" => array("int32","notnull"), - "endtime" => array("int32","notnull"), - "roomid" => array("string:64","foreignkey:room:roomid"), - //initially a copy from room, can be adjusted - "capacity" => array("int32","notnull"), - //default pricing in cents - "defaultprice" => array("int32","notnull"), - //if not null/empty: event has been cancelled - "cancelreason" => array("string") - ); - //customer - $this->scheme["customer"]=array( - "customerid" => array("seq32","primarykey"), - //contact data - "name" => array("string",notnull), - "address" => array("string"), - "contact" => array("string"),//phone or something - "comments" => array("text"), - //online login data - "email" => array("string"), - "passwd" => array("string:64"),//salted SHA-1 hash of passwd - ); - //orders by customers - $this->scheme["order"]=array( - "orderid" => array("seq32","primarykey"), - //customer - "customerid" => array("int32","foreignkey:customer:customerid"), - //seller (_online for web forms) - "soldby" => array("string:64","foreignkey:users:uname"), - //if not null/empty: this address for delivery, customer address for invoice - "deliveryaddress" => array("string"), - //if not null/empty: lodge/deposit the tickets at a seller with _deposit flag - "depositat" => array("string:64","foreignkey:users:uname"), - //status, see ORDER_* constants - "status" => array("int32","notnull"), - "ordertime" => array("int32","notnull"), - "senttime" => array("int32"), - //comments made on web form (eg. "urgently needed for dads birthday") - "comments" => array("text"), - //how much has been paid already (including used vouchers) - //this is for comparison with the price fields in ticket and voucher tables - "amountpaid" => array("int32") - ); - //tickets - $this->scheme["ticket"]=array( - "ticketid" => array("seq64","primarykey"), - "eventid" => array("int32","foreignkey:event:eventid"), - //initially a copy from event, can be adjusted by seller - "price" => array("int32","notnull"), - //status of ticket (see TICKET_* constants) - "status" => array("int32","notnull"), - //if status is reserved, this contains the reserving seller - "reservedby" => array("string:64","foreignkey:users:uname"), - "reservetimeout" => array("int32"), - //sold to someone (may be NULL for direct sales or reserves) - "oderid" => array("int32","foreignkey:orders:orderid") - ); - //vouchers and re-imbursments - $this->scheme["voucher"]=array( - //a 16char code (code39: case-insensitive letters+digits) for the voucher) - "voucherid" => array("string:16","primarykey"), - //if ordered: order-info - "price" => array("int32","notnull"), - "oderid" => array("int32","foreignkey:orders:orderid"), - //unix-timestamp of original sales date/time - "salestime" => array("int32","notnull"), - //remaining value in cents - "value" => array("int32","notnull") - ); - - //shopping cart - $this->scheme["cart"]=array( - //the cookie for this cart - "cartid" => array("string:32","primarykey"), - //when the cart expires - "timeout" => array("int32","notnull") - ); - //buying tickets - $this->scheme["cart_ticket"]=array( - "cartid" => array("string:32","notnull","foreignkey:cart:cartid"), - //tickets in the cart - "eventid" => array("int32","notnull","foreignkey:event:eventid"), - "amount" => array("int32","notnull"), - //primary key definition - ":primarykey" => array("cartid","eventid") - ); - //buying vouchers - $this->scheme["cart_voucher"]=array( - "cvid" => array("seq64","primarykey"), - "cartid" => array("string:32","notnull","foreignkey:cart:cartid"), - //voucher value - "value" => array("int32","notnull") - ); - - } - - /**return the tables to be created in order*/ - public function tableNames() - { - return array_keys($this->scheme); - } - - /**return the full definition of a table, or false if it does not exist*/ - public function tableDefinition($tab) - { - if(!isset($this->scheme[$tab])) - return false; - return $this->scheme[$tab]; - } - - /**return the names of all columns of a table, or false if the table does not exist*/ - public function tableColumns($tab) - { - if(!isset($this->scheme[$tab])) - return false; - return array_keys($this->scheme[$tab]); - } - - /**return the type of a column, or false if it does not exist*/ - public function columnType($tab,$col) - { - if(!isset($this->scheme[$tab][$col])) - return false; - return $this->scheme[$tab][$col][0]; - } - - /**return the flags of a column, empty array if no flags are set, or false if the column does not exist*/ - public function columnFlags($tab,$col) - { - if(!isset($this->scheme[$tab][$col])) - return false; - $tmp=$this->scheme[$tab][$col]; - unset($tmp[0]); - return array_values($tmp); - } - - /**returns true if the given column is of an integer type*/ - public function isIntColumn($tab,$col) - { - if(!isset($this->scheme[$tab][$col])) - return false; - $tpa=explode(":",$this->scheme[$tab][$col][0]); - switch($tpa[0]){ - case "int32":case "seq32":case "int64":case "seq64": - return true; - default: - return false; - } - } - - /**returns the sequence column name if the table has a sequence, false otherwise*/ - public function hasSequence($tab) - { - if(!isset($this->scheme[$tab])) - return false; - foreach($this->scheme[$tab] as $cl => $def){ - if($def[0] == "seq32" || $def[0] == "seq64") - return $cl; - } - return false; - } - - /**returns true if the given column is of a string type*/ - public function isStringColumn($tab,$col) - { - if(!isset($this->scheme[$tab][$col])) - return false; - $tpa=explode(":",$this->scheme[$tab][$col][0]); - switch($tpa[0]){ - case "string":case "text": - return true; - default: - return false; - } - } -}; -$dbScheme=new DbScheme; -?> \ No newline at end of file diff --git a/www/inc/error.php b/www/inc/error.php deleted file mode 100644 index 5cc9ebc..0000000 --- a/www/inc/error.php +++ /dev/null @@ -1,74 +0,0 @@ - -// +---------------------------------------------------------------------- -// | -// | Copyright: See COPYING file that comes with this distribution -// +---------------------------------------------------------------------- -// - -class ErrorManager -{ - private $errorMessages; - private static $instance; - - private function __construct() - { - $this->errorMessages = array(); - } - - /** returns the instance of the Error Manager */ - public static function singleton() - { - if(!self::$instance) { - self::$instance = new ErrorManager(); - } - - return self::$instance; - } - - /** add new error message */ - public function add($message) - { - $this->errorMessages[] = $message; - } - - /** get all error messages in an array */ - public function getAll() - { - return $this->$errorMessages; - } - - /** get all error messages formatted */ - public function getAllFormatted() - { - $p = new Parser("definition.html"); - $messages = ""; - - foreach ($this->errorMessages as $message) - { - $errorTmpl = $p->getVar("ERROR"); - $p->setVar("MESSAGE", $message); - $messages .= $p->parse($errorTmpl); - } - - $errorArea = $p->getVar("ERRORAREA"); - $p->setVar("ERRORMESSAGES", $messages); - - return $p->parse($errorArea); - } - - /** returns true if errors exist */ - public function exists() - { - if (count($this->errorMessages) > 0) { - return true; - } - else { - return false; - } - } -} -?> \ No newline at end of file diff --git a/www/inc/event.php b/www/inc/event.php deleted file mode 100644 index a694347..0000000 --- a/www/inc/event.php +++ /dev/null @@ -1,289 +0,0 @@ -, (C) 2007 -// -// Copyright: See README/COPYING files that come with this distribution -// -// - - -/**Get an overview of all events: -returns an array of array("eventid"=>int, "title"=>string,"starttime"=>int)*/ -function getAllEvents() -{ - global $db; - return $db->select("event","eventid,title,starttime",""); -} - -/**Machine-wrapper for getAllEvents() */ -function getAllEventsXml() -{ - $all=getAllEvents(); - if($all===false){ - header("X-MagicSmoke-Status: Error"); - echo "Database Error."; - return; - } - header("X-MagicSmoke-Status: Ok"); - $xml=new DOMDocument; - $root=$xml->createElement("EventList"); - if(count($all)>0) - foreach($all as $k => $ev){ - $nod=$xml->createElement("Event",$ev["title"]); - $nod->setAttribute("id",$ev["eventid"]); - $nod->setAttribute("start",$ev["starttime"]); - $root->appendChild($nod); - } - $xml->appendChild($root); - echo $xml->saveXml(); -} - -/**Wrapper around event table*/ -class Event -{ - private $evid; - private $title; - private $artist; - private $description; - private $starttime; - private $endtime; - private $roomid; - private $capacity; - private $defaultprice; - private $cancelreason; - - /**creates an event object, the id must be a valid eventid gotten from getAllEvents or -1 if you - want to create a new event*/ - public function __construct($id) - { - global $db; - //check that event exists - $id=$id+0; - if($id<0)$id=-1; - else{ - $res=$db->select("event","*","eventid=$id"); - if(count($res)!=1)$id=-1; - else{ - $this->title=$res[0]["title"]; - $this->artist=$res[0]["artist"]; - $this->description=$res[0]["description"]; - $this->starttime=$res[0]["starttime"]; - $this->endtime=$res[0]["endtime"]; - $this->roomid=$res[0]["roomid"]; - $this->capacity=$res[0]["capacity"]; - $this->defaultprice=$res[0]["defaultprice"]; - $this->cancelreason=$res[0]["cancelreason"]; - } - } - //remember it - $this->evid=$id; - } - - /**returns whether this event already exists in the database*/ - public function exists() - { - return $this->evid >= 0; - } - - /**returns the ID of the event*/ - public function getEventId(){return $this->evid;} - /**returns the start time of the event*/ - public function getStartTime(){return $this->starttime;} - /**returns the end time of the event*/ - public function getEndTime(){return $this->endtime;} - /**returns the ticket capacity of the event*/ - public function getCapacity(){return $this->capacity;} - /**returns the default price in cent of the event*/ - public function getDefaultPrice(){return $this->defaultprice;} - /**returns whether the event is cancelled*/ - public function isCancelled() - { - if($this->cancelreason===false)return false; - else return $this->cancelreason!=""; - } - /**returns the title of the event*/ - public function getTitle(){return $this->title;} - /**returns the artist of the event*/ - public function getArtist(){return $this->artist;} - /**returns the room/place of the event*/ - public function getRoomId(){return $this->roomid;} - /**returns the description of the event*/ - public function getDescription(){return $this->description;} - /**returns the reason why the event is cancelled if isCancelled() returns true*/ - public function getCancelReason(){return $this->cancelreason;} - - /**returns the data in an array suitable for the web-page-renderer*/ - public function getParserData() - { - $lang = LanguageManager::singleton(); - - return array("DATE"=>$lang->getDate($this->getStartTime()), "TIME"=>$lang->getTime($this->getStartTime()), "PLACE"=>$this->getRoomId(), "EVENTNAME"=>$this->getTitle(), "ARTIST"=>$this->getArtist(),"PRICE"=>$lang->getPrice($this->getDefaultPrice()), "ID"=>$this->getEventId(), "DESCRIPTION"=>$this->getDescription(), "LINK"=>""); - } - - /**returns how many tickets can still be sold*/ - public function availableTicketAmount() - { - global $db; - //is it valid? - if($this->evid<0)return 0; - //is it cancelled? - if($this->isCancelled())return 0; - //is it already over? - if(time()>$this->endtime)return 0; - //get existing tickets - $res=$db->select("ticket","status","eventid=".$db->escapeInt($this->evid)); - $amt=0; - reset($res); - if(count($res)>0) - foreach($res as $tk){ - if(!($tk["status"]&TICKET_CANCELLED))$amt++; - } - return $this->capacity - $amt; - } -}; - -/**machine-function: get the requested events as XML data*/ -function getEventsXml($evts) -{ - header("X-MagicSmoke-Status: Ok"); - $xml=new DOMDocument; - $root=$xml->createElement("EventData"); - if(count($evts)>0) - foreach($evts as $k => $eid){ - $ev=new Event($eid); - if(!$ev->exists())continue; - $nod=$xml->createElement("Event"); - $nod->setAttribute("id",$eid); - $nod->setAttribute("start",$ev->getStartTime()); - $nod->setAttribute("end",$ev->getEndTime()); - $nod->setAttribute("capacity",$ev->getCapacity()); - $nod->setAttribute("defaultprice",$ev->getDefaultPrice()); - $nod->setAttribute("cancelled",$ev->isCancelled()?"true":"false"); - $nod->appendChild($xml->createElement("Title",$ev->getTitle())); - $nod->appendChild($xml->createElement("Artist",$ev->getArtist())); - $nod->appendChild($xml->createElement("Room",$ev->getRoomId())); - $nod->appendChild($xml->createElement("Description",$ev->getDescription())); - if($ev->isCancelled()) - $nod->appendChild($xml->createElement("CancelReason",$ev->getCancelReason())); - $root->appendChild($nod); - } - $xml->appendChild($root); - print($xml->saveXml()); -} - -/**Machine-Interface: set an event (it's not possible to set from Web-Browser)*/ -function setEventXml($xmldata) -{ - global $db; - //stage 1: parse XML - $xml=new DOMDocument; - if($xml->loadXML($xmldata)===false){ - header("X-MagicSmoke-Status: SyntaxError"); - echo "Unable to parse XML."; - return; - } - //stage 2: extract data from XML - $doc=$xml->documentElement; - $eventid=trim($doc->getAttribute("id")); - $start=trim($doc->getAttribute("start"))+0; - $end=trim($doc->getAttribute("end"))+0; - $capacity=trim($doc->getAttribute("capacity"))+0; - $defaultprice=trim($doc->getAttribute("defaultprice"))+0; - $cancelled=trim($doc->getAttribute("cancelled")); - $title=$artist=$description=$room=$cancelreason=""; - foreach($doc->getElementsByTagName("Title") as $el) - foreach($el->childNodes as $cn) - if($cn->nodeType==XML_TEXT_NODE) - $title=trim($cn->wholeText); - foreach($doc->getElementsByTagName("Artist") as $el) - foreach($el->childNodes as $cn) - if($cn->nodeType==XML_TEXT_NODE) - $artist=trim($cn->wholeText); - foreach($doc->getElementsByTagName("Description") as $el) - foreach($el->childNodes as $cn) - if($cn->nodeType==XML_TEXT_NODE) - $description=trim($cn->wholeText); - foreach($doc->getElementsByTagName("Room") as $el) - foreach($el->childNodes as $cn) - if($cn->nodeType==XML_TEXT_NODE) - $room=trim($cn->wholeText); - foreach($doc->getElementsByTagName("CancelReason") as $el) - foreach($el->childNodes as $cn) - if($cn->nodeType==XML_TEXT_NODE) - $cancelreason=trim($cn->wholeText); - //stage 3: validate input - if(ereg("^([0-9]+)|(new)$",$eventid)===false){ - header("X-MagicSmoke-Status: Error"); - echo "Invalid Event ID, must be positive integer or 'new'."; - return; - } - if($cancelled!="true" && $cancelled!="false"){ - header("X-MagicSmoke-Status: Error"); - echo "Event neither cancelled, nor non-cancelled."; - return; - } - if($title==""){ - header("X-MagicSmoke-Status: Error"); - echo "Empty Title."; - return; - } - if($artist==""){ - header("X-MagicSmoke-Status: Error"); - echo "No Artist."; - return; - } - $db->beginTransaction(); - $res=$db->select("room","roomid","roomid=".$db->escapeString($room)); - if(count($res)<1){ - //end DB transaction - $db->rollbackTransaction(); - //error - header("X-MagicSmoke-Status: Error"); - echo "Invalid Room."; - return; - } - - //stage 4: call DB - $data["title"]=$title; - $data["artist"]=$artist; - $data["description"]=$description; - $data["starttime"]=$start; - $data["endtime"]=$end; - $data["roomid"]=$room; - $data["capacity"]=$capacity; - $data["defaultprice"]=$defaultprice; - if($cancelled=="true") - $data["cancelreason"]=$cancelreason." "; - else - $data["cancelreason"]=false; - if($eventid=="new"){ - //create event - $eventid=$db->insert("event",$data); - if($eventid===false){ - header("X-MagicSmoke-Status: Error"); - echo "Error accessing database."; - return; - } - }else{ - //check ID - $eventid=$eventid+0; - $res=$db->select("event","eventid","eventid=".$eventid); - if(count($res)==0){ - header("X-MagicSmoke-Status: Error"); - echo "Invalid Event: eventid does not exist in database."; - $db->rollbackTransaction(); - return; - } - $db->update("event",$data,"eventid=".$eventid); - } - $db->commitTransaction(); - header("X-MagicSmoke-Status: Ok"); - echo $eventid; -} - -?> \ No newline at end of file diff --git a/www/inc/event_listing.php b/www/inc/event_listing.php deleted file mode 100644 index 9840db0..0000000 --- a/www/inc/event_listing.php +++ /dev/null @@ -1,73 +0,0 @@ - -// +---------------------------------------------------------------------- -// | -// | Copyright: See COPYING file that comes with this distribution -// +---------------------------------------------------------------------- -// - -function createEventList() -{ - global $parser; - - //pass 1: get layout of single event - $p=new Parser("index.html"); - $list=""; - $eventTmpl=$p->getVar("EVENT"); - $events = getAllEvents(); - foreach ($events as $event) - { - $eventID = $event["eventid"]; - $event = new Event($eventID); - $p->setVars($event->getParserData()); - $list .= $p->parse($eventTmpl); - } - - //pass 2: create page - $p->setVar("LIST",$list); - $parser->setVar("PAGE",$p->parseFile("index.html")); -} - -function createEventDetails() -{ - global $parser; - - $error = ErrorManager::singleton(); - - if (isset($_GET["event"])) { - $eventID = $_GET["event"]; - } - - $p = new Parser("eventdetails.html"); - $eventTmpl = $p->getVar("EVENT"); - - // check if event exists - $event = new Event($eventID); - if (!$event->exists()) - { - header("Location:index.php"); - return; - } - - // set event details - $p->setVars($event->getParserData()); - $details = $p->parse($eventTmpl); - $p->setVar("EVENTDETAILS",$details); - $p->setVar("fieldAMOUNT", "ms_amount"); - $p->setVar("buttonSAVE", "ms_save"); - - // set error message - if ($error->exists()) { - $p->setVar("ERROR", "true"); - $p->setVar("ERRORAREA", $error->getAllFormatted()); - } - - // create page - $parser->setVAR("PAGE", $p->parseFile("eventdetails.html")); -} - - -?> diff --git a/www/inc/language_manager.php b/www/inc/language_manager.php deleted file mode 100644 index d83a6b1..0000000 --- a/www/inc/language_manager.php +++ /dev/null @@ -1,133 +0,0 @@ - -// +---------------------------------------------------------------------- -// | -// | Copyright: See COPYING file that comes with this distribution -// +---------------------------------------------------------------------- -// - -/** function to replace gettext */ -function i18n($key) -{ - $lang = LanguageManager::singleton(); - - $translation = $lang->getValue($key); - - if ($translation != "") { - return $translation; - } else { - return $key; - } -} - -/** replaces each {number} in a string with its equivalent in the array -{1} => array[0] */ -function string_format($string, $array) -{ - $num = count($array); - - for ($i=0; $i < $num; $i++) { - $string = str_replace("{".($i+1)."}", $array[$i], $string); - } - - return $string; -} - -class LanguageManager -{ - private static $COOKIE_NAME = "ms_lang"; - private static $instance; - private $lang; - private $config; - private $templateFolder; - - /** private constructor */ - private function __construct() - { - global $template; - - $this->templateFolder = $template; - //default fallback for empty setting - if($this->templateFolder == "") - $this->templateFolder = "./template/"; - //make sure it ends with / - if(substr($this->templateFolder,-1,1) != "/") - $this->templateFolder .= "/"; - - // check if cookie is set - if (isset($_COOKIE[self::$COOKIE_NAME])) { - $this->lang = $_COOKIE[self::$COOKIE_NAME]; - } else { - $this->lang = substr($_SERVER["HTTP_ACCEPT_LANGUAGE"],0,2); - } - - //sanity check for $lang -> must only contain letters; fallback is de - if(ereg("^[a-zA-Z]+$",$this->lang)===false) - $this->lang="de"; - - $this->setLanguageConfig(); - } - - /** returns the instance of the Language Manager */ - public static function singleton() - { - if(!self::$instance) { - self::$instance = new LanguageManager(); - } - - return self::$instance; - } - - /** set language */ - public function setLanguage($language) - { - $this->lang = $language; - setcookie(self::$COOKIE_NAME, $language, 0); - - $this->setLanguageConfig(); - } - - private function setLanguageConfig() { - global $template; - - $dir = $this->templateFolder.$this->lang."/"; - - if (is_dir($dir)) { - // if language folder exists - $template = $dir; - } else { - // set default value - $template = $this->templateFolder."de/"; - } - $this->config = ConfigManager::singleton("lang.po"); - } - - /** returns date in current language, default: ISO-date */ - public function getDate($date) - { - return date(i18n("Y-m-d"), $date); - } - - /** returns time in current language */ - public function getTime($time) - { - return date(i18n("h:i a"), $time); - } - - /** returns price in current language */ - public function getPrice($price) - { - return number_format($price/100, 2, i18n("."), i18n(",")); - } - - /** returns value for specified key in current language */ - public function getValue($key) - { - return $this->config->get($key); - } -} - -?> diff --git a/www/inc/loader.php b/www/inc/loader.php index de7fce0..263cbf4 100644 --- a/www/inc/loader.php +++ b/www/inc/loader.php @@ -2,10 +2,10 @@ //internal info: server version $MAGICSMOKEVERSION="0.1 alpha"; //load DB drivers -include('./inc/db.php'); -include('./inc/db_mysql.php'); +include('./inc/db/db.php'); +include('./inc/db/db_mysql.php'); include('./config.php'); -include('./inc/db_scheme.php'); +include('./inc/db/db_scheme.php'); //try to connect $db->tryConnect(); //move on in loader_nonadmin.php (or admin.php) diff --git a/www/inc/loader_nonadmin.php b/www/inc/loader_nonadmin.php index fe7b5a0..664579b 100644 --- a/www/inc/loader_nonadmin.php +++ b/www/inc/loader_nonadmin.php @@ -3,17 +3,17 @@ if(!$db->canUseDb()) die("Database is not correctly configured. Giving up."); //load class-files -include('./inc/event.php'); -include('./inc/room.php'); -include("./inc/random.php"); -include("./inc/order.php"); -include("./inc/ticket.php"); -include("./inc/cart.php"); -include('./inc/error.php'); -include('./inc/language_manager.php'); -include('./inc/parser.php'); -include('./inc/config_manager.php'); -include('./inc/customer.php'); +include('./inc/classes/event.php'); +include('./inc/classes/room.php'); +include("./inc/classes/random.php"); +include("./inc/classes/order.php"); +include("./inc/classes/ticket.php"); +include("./inc/classes/cart.php"); +include('./inc/classes/error.php'); +include('./inc/classes/language_manager.php'); +include('./inc/classes/parser.php'); +include('./inc/classes/config_manager.php'); +include('./inc/classes/customer.php'); //load hash lib include("./inc/cauth_".$HashLib.".php"); diff --git a/www/inc/order.php b/www/inc/order.php deleted file mode 100644 index adffdcb..0000000 --- a/www/inc/order.php +++ /dev/null @@ -1,127 +0,0 @@ -, (C) 2007 -// -// Copyright: See README/COPYING files that come with this distribution -// -// - -/**an order has been placed, this flag is set when the order is filled and finalized*/ -define("ORDER_PLACED",1); -/**the order has been sent out (it must be placed first; direct sales are automatically sent)*/ -define("ORDER_SENT",2); -/**the order has been cancelled by the user (this is only possible as long as no money has been paid and nothing has been sent yet)*/ -define("ORDER_CANCELLED",4); -/**the order is closed (optional: this flag means no further payment/cancellation/etc. is possible)*/ -define("ORDER_CLOSED",8); - - -/**this class represents an order in the database*/ -class Order -{ - private $orderid; - private $status; - - /**instantiates an existing order with the given orderid or creates a new one if orderid===false*/ - public function __construct($orderid=false) - { - global $db; - if($orderid===false){ - //create a new one - $odr=array( - //set to default - "soldby"=>"_online", - "status" => 0, - "ordertime" => time() - ); - $this->orderid=$db->insert("order",$odr); - }else{ - //get it from DB - $res=$db->select("order","*","orderid=".$db->escapeInt($orderid)); - if(count($res)==0){ - $this->orderid=false; - return; - } - $this->orderid=$res[0]["orderid"]; - $this->status=$res[0]["status"]; - } - } - - /**returns whether the order can still be changed*/ - public function canChange() - { - return $this->isValid() && $this->status == 0; - } - - /**returns whether the order is a valid DB object*/ - public function isValid() - { - return $this->orderid!==false; - } - - /**removes all items from the given Cart and enters them into itself; returns false if some items cannot be ordered or the order is already closed*/ - public function emptyCart($cart) - { - //check carts contents - if(count($cart->orderCheck())>0)return false; - //check myself - if(!$this->canChange())return false; - //get tickets - $db->beginTransaction(); - $tick=$cart->getTickets(); - if(count($tick)>0) - foreach($tick as $k=>$tc){ - $this->addTickets($tc->getEventId(),$tc->getAmount()); - $tc->changeAmount(0); - } - //TODO: get vouchers - //done - $db->commitTransaction(); - return true; - } - - /**adds some tickets to the order, returns ticketid or false if change is not possible*/ - public function addTickets($eventid,$amount) - { - if(!$this->canChange() || $amount <= 0)return false; - global $db; - //get event - $event=new Event($eventid); - //create ticket - $tc=array("eventid" => $eventid, - "price" => $event->getDefaultPrice(), - "status" => 0, - "oderid" => $this->orderid - ); - $ret=array(); - for($i=0;$i<$amount;$i++)$ret[]=$db->insert("ticket",$tc); - return $ret; - } - - /**places/finalizes the order; returns false on failure, true on success or if the order already was finalized()*/ - public function placeOrder() - { - if(!$this->canChange())return; - global $db; - $db->beginTransaction(); - //get orderstatus and correct it - $res=$db->select("order","status","orderid=".$db->escapeInt($this->orderid)); - if(count($res)==0){ - $this->orderid=false; - $db->rollbackTransaction(); - return false; - } - $db->update("order",array("status"=>ORDER_PLACED),"orderid=".$db->escapeInt($this->orderid)); - $this->status=ORDER_PLACED; - //end - $db->commitTransaction(); - return true; - } -}; - -?> \ No newline at end of file diff --git a/www/inc/order_listing.php b/www/inc/order_listing.php deleted file mode 100644 index 16854dd..0000000 --- a/www/inc/order_listing.php +++ /dev/null @@ -1,42 +0,0 @@ - -// +---------------------------------------------------------------------- -// | -// | Copyright: See COPYING file that comes with this distribution -// +---------------------------------------------------------------------- -// - -/** creates the login to an order */ -function createOrderLogin() -{ - global $parser; - - $error = ErrorManager::singleton(); - - $localParser = new Parser("orderlogin.html"); - - $localParser->setVar("fieldEMAIL", "ms_email"); - $localParser->setVar("radioIS_CUSTOMER", "ms_isCustomer"); - $localParser->setVar("fieldPASSWORD", "ms_password"); - $localParser->setVar("buttonCONTINUE", "ms_loginContinue"); - - if (!empty($_POST["ms_email"])) { - $localParser->setVar("valueEMAIL", $_POST["ms_email"]); - } else { - $localParser->setVar("valueEMAIL", ""); - } - - // set error message - if ($error->exists()) { - $localParser->setVar("IS_ERROR", "true"); - $localParser->setVar("ERRORAREA", $error->getAllFormatted()); - } - - // create page - $parser->setVAR("PAGE", $localParser->parseFile("orderlogin.html")); -} - -?> \ No newline at end of file diff --git a/www/inc/parser.php b/www/inc/parser.php deleted file mode 100644 index 6f38701..0000000 --- a/www/inc/parser.php +++ /dev/null @@ -1,197 +0,0 @@ -cont=$c; - reset($this->cont); - } - /**return next line from array until end is reached*/ - public function getLine() - { - $r=current($this->cont); - next($this->cont); - return $r; - } -} - -/**Parser class: see syntax docu for details*/ -class Parser -{ - private $vars=array(); - - /**create parser object, initialize its internal state with optional file*/ - public function __construct($fname="") - { - global $_SERVER; - $this->vars["SCRIPT"]=$_SERVER[SCRIPT_NAME]; - $this->vars["FULLURL"]=$_SERVER[REQUEST_URI]; - if($fname!="") - $this->parseFile($fname); - } - /**parse a file, return parser-result*/ - public function parseFile($fname) - { - global $template; - $cont=file_get_contents($template.$fname); - return $this->parse($cont); - } - /**parse a string, return parser-result*/ - public function parse($str) - { - $cont=explode("\n",str_replace("\r","",$str)); - $help=new PHelper($cont); - return $this->parseNormal($help); - } - /**set an internal variable*/ - public function setVar($vname,$vval) - { - $this->vars[$vname]=$vval; - } - /**set several internal variables array(variablename=>value)*/ - public function setVars(array $vs) - { - reset($vs); - foreach($vs as $k => $v) - $this->vars[$k]=$v; - } - /**unset a variable*/ - public function unsetVar($vname) - { - if(isset($this->vars[$vname])) - unset($this->vars[$vname]); - } - /**get value of a variable (returns false if variable does not exist)*/ - public function getVar($vname) - { - if(isset($this->vars[$vname])) - return $this->vars[$vname]; - else - return false; - } - /**returns true if variable exists*/ - public function haveVar($vname) - { - return isset($this->vars[$vname]); - } - - /**internal: used by parse to load data*/ - protected function parseNormal($help) - { - $out=""; - while(1){ - //get next line - $line=$help->getLine(); - //exit if file end has been reached - if($line===false)return $out; - //check whether this is a special statement - if(strncmp("#if:",$line,4)==0)$out.=$this->parseIf($help,$line);else - if(strncmp("#set:",$line,5)==0)$out.=$this->parseSet($help,$line); - else $out.=$this->parseLine($line); - } - } - /**internal: replace variables on a line*/ - protected function parseLine($line) - { - $ak=array(); - $av=array(); - foreach($this->vars as $k => $v){ - $ak[]="@".$k."@"; - $av[]=$v; - } - return str_replace($ak,$av,$line)."\n"; - } - /**internal: handle an \#if statement*/ - protected function parseIf($help,$line) - { - //parse if-line - $reg=array(); - if(ereg("^#if:([a-zA-Z0-9_]+)[ \t]*([=<>!]+)(.*)$",trim($line),$reg)===false) - return "(erroneous #if line found)\n"; - //check variable exists - $doout=isset($this->vars[$reg[1]]); - //do comparison - if($doout){ - $v=trim($this->vars[$reg[1]]); - $c=trim($reg[3]); - switch($reg[2]){ - case "==":case "=":$doout= $v == $c;break; - case "<":$doout = $v < $c;break; - case "<=":$doout = $v <= $c;break; - case ">":$doout = $v > $c;break; - case ">=":$doout = $v >= $c;break; - case "!=":case "<>":$doout = $v != $c;break; - default: $doout=false; - } - } - //parse till #endif - if($doout){ - $out=""; - //handle content normally until endif is found, then return - while(1){ - $line=$help->getLine(); - if($line===false)return $out; - if(strncmp("#if:",$line,4)==0)$out.=$this->parseIf($help,$line);else - if(strncmp("#set:",$line,5)==0)$out.=$this->parseSet($help,$line);else - if(strncmp("#endif",$line,6)==0)return $out; - else $out.=$this->parseLine($line); - } - }else{ - $ifc=1; - //ignore everything until corresponding endif is found - //#if needs to be handled specially, since parseIf is not - // called recursively here - while(1){ - $line=$help->getLine(); - //last line already? - if($line===false)return ""; - //handle if and endif - if(strncmp("#if:",$line,4)==0)$ifc+=1;else - if(strncmp("#endif",$line,6)==0)$ifc-=1; - //found corresponding endif? - if($ifc<=0)return ""; - //ignore remainder - } - } - } - /**internal: handle \#set statement*/ - protected function parseSet($help,$line) - { - //parse set-line - $reg=array(); - if(ereg("^#set:([a-zA-Z0-9_]+)((:)|(=(.*)))$",trim($line),$reg)===false) - return "(erroneous #set line found)\n"; - //check type - $vname=$reg[1]; - $var=""; - if($reg[3]==":"){ - //syntax: #set:var:\nvalue...\n#endset - //parse till #endset - $setcnt=1; - while(1){ - $line=$help->getLine(); - //handle set/unset statements pseudo-recursively - if(strncmp("#set:",$line,5)==0)$setcnt+=1;else - if(strncmp("#endset",$line,7)==0)$setcnt-=1; - //corresponding endset found? - if($setcnt<=0)break; - //add content to variable - $var.=$line."\n"; - } - }else{ - //syntax: #set:var=value - //get value directly - $var=$reg[5]; - } - //set variable - $this->setVar(trim($vname),trim($var)); - //go back (set creates no visible output) - return ""; - } -}; - - -?> \ No newline at end of file diff --git a/www/inc/random.php b/www/inc/random.php deleted file mode 100644 index 9b19645..0000000 --- a/www/inc/random.php +++ /dev/null @@ -1,53 +0,0 @@ -, (C) 2007 -// -// Copyright: See README/COPYING files that come with this distribution -// -// - -//TODO: try to use /dev/random - -//get current random seed -$RANDSEED=$db->getConfig("randseed"); - -/**add some seed into the random function*/ -function randseed($rand) -{ - global $RANDSEED; - $RANDSEED.=$rand; -} - -/**return $bits bits of random data*/ -function getRandom($bits) -{ - //number of digits... - $bits/=4; - //init - global $RANDSEED,$db; - $ret="";$ctr=0; - //get string - while(strlen($ret)<$bits){ - $ctr++; - $ret.=sha1($RANDSEED.microtime().$ctr); - } - //rewrite seed to DB - $RANDSEED=sha1($RANDSEED.microtime().$ret); - $db->setConfig("randseed",$RANDSEED); - //return - return substr($ret,0,$bits); -} - -/**return a salt value for Customer::setPassword */ -function getSalt() -{ - return getRandom(16*4); -} - -?> \ No newline at end of file diff --git a/www/inc/rendering/cart_listing.php b/www/inc/rendering/cart_listing.php new file mode 100644 index 0000000..149df88 --- /dev/null +++ b/www/inc/rendering/cart_listing.php @@ -0,0 +1,90 @@ + +// +---------------------------------------------------------------------- +// | +// | Copyright: See COPYING file that comes with this distribution +// +---------------------------------------------------------------------- +// + +/** creates the cart overview */ +function createCartOverview() +{ + global $parser; + + $error = ErrorManager::singleton(); + $lang = LanguageManager::singleton(); + + $cart = new Cart($_COOKIE[COOKIE_NAME]); + + $p = new Parser("cart.html"); + + $tablerows = ""; + $totalsum = 0; + $hiddenfields = ""; + + // get tickets from cart + foreach ($cart->getTickets() as $ticket) + { + $cartRowTmpl = $p->getVar("ROW"); + $event = $ticket->eventObject(); + + // set event details + $p->setVars($event->getParserData()); + + // if no error exists set values of database, else values of submit + if (!$error->exists()) { + $p->setVar("AMOUNT", $ticket->getAmount()); + } else { + $ticketAmounts = $_POST["ms_amount"]; + $eventIDs = $_POST["ms_event"]; + $amountValue = $ticketAmounts[array_search($event->getEventId(),$eventIDs)]; + $p->setVar("AMOUNT", $amountValue); + } + + // set submit functionality + $p->setVar("linkDELETEROW", "index.php?mode=cart&action=deleteEvent&event=".$event->getEventId()); + $p->setVar("fieldAMOUNT", "ms_amount[]"); + + // fill hidden fields + $hiddenfields .= "getEventId()."\" />\n"; + + $rowsum = $ticket->getAmount()*$event->getDefaultPrice(); + $p->setVar("ROWSUM", $lang->getPrice($rowsum)); + + $totalsum += $rowsum; + + $tablerows .= $p->parse($cartRowTmpl); + } + + // if no tickets in cart set EMPTYROWS and disable order button + if (count($cart->getTickets()) == 0) { + $tablerows = $p->getVar("EMPTYROWS"); + $p->setVar("attribDISABLED", "disabled=\"disabled\""); + } else { + $p->setVar("attribDISABLED", ""); + } + + $p->setVar("TABLEROWS", $tablerows); + $p->setVar("TOTALSUM", $lang->getPrice($totalsum)); + + // set buttons + $p->setVar("buttonSAVE", "ms_save"); + $p->setVar("buttonORDER", "ms_goToOrder"); + // set hidden fields + $p->setVar("IS_HIDDEN", "true"); + $p->setVar("HIDDENAREA", $hiddenfields); + + // set error message + if ($error->exists()) { + $p->setVar("IS_ERROR", "true"); + $p->setVar("ERRORAREA", $error->getAllFormatted()); + } + + // create page + $parser->setVAR("PAGE", $p->parseFile("cart.html")); +} + +?> \ No newline at end of file diff --git a/www/inc/rendering/event_listing.php b/www/inc/rendering/event_listing.php new file mode 100644 index 0000000..9840db0 --- /dev/null +++ b/www/inc/rendering/event_listing.php @@ -0,0 +1,73 @@ + +// +---------------------------------------------------------------------- +// | +// | Copyright: See COPYING file that comes with this distribution +// +---------------------------------------------------------------------- +// + +function createEventList() +{ + global $parser; + + //pass 1: get layout of single event + $p=new Parser("index.html"); + $list=""; + $eventTmpl=$p->getVar("EVENT"); + $events = getAllEvents(); + foreach ($events as $event) + { + $eventID = $event["eventid"]; + $event = new Event($eventID); + $p->setVars($event->getParserData()); + $list .= $p->parse($eventTmpl); + } + + //pass 2: create page + $p->setVar("LIST",$list); + $parser->setVar("PAGE",$p->parseFile("index.html")); +} + +function createEventDetails() +{ + global $parser; + + $error = ErrorManager::singleton(); + + if (isset($_GET["event"])) { + $eventID = $_GET["event"]; + } + + $p = new Parser("eventdetails.html"); + $eventTmpl = $p->getVar("EVENT"); + + // check if event exists + $event = new Event($eventID); + if (!$event->exists()) + { + header("Location:index.php"); + return; + } + + // set event details + $p->setVars($event->getParserData()); + $details = $p->parse($eventTmpl); + $p->setVar("EVENTDETAILS",$details); + $p->setVar("fieldAMOUNT", "ms_amount"); + $p->setVar("buttonSAVE", "ms_save"); + + // set error message + if ($error->exists()) { + $p->setVar("ERROR", "true"); + $p->setVar("ERRORAREA", $error->getAllFormatted()); + } + + // create page + $parser->setVAR("PAGE", $p->parseFile("eventdetails.html")); +} + + +?> diff --git a/www/inc/rendering/order_listing.php b/www/inc/rendering/order_listing.php new file mode 100644 index 0000000..16854dd --- /dev/null +++ b/www/inc/rendering/order_listing.php @@ -0,0 +1,42 @@ + +// +---------------------------------------------------------------------- +// | +// | Copyright: See COPYING file that comes with this distribution +// +---------------------------------------------------------------------- +// + +/** creates the login to an order */ +function createOrderLogin() +{ + global $parser; + + $error = ErrorManager::singleton(); + + $localParser = new Parser("orderlogin.html"); + + $localParser->setVar("fieldEMAIL", "ms_email"); + $localParser->setVar("radioIS_CUSTOMER", "ms_isCustomer"); + $localParser->setVar("fieldPASSWORD", "ms_password"); + $localParser->setVar("buttonCONTINUE", "ms_loginContinue"); + + if (!empty($_POST["ms_email"])) { + $localParser->setVar("valueEMAIL", $_POST["ms_email"]); + } else { + $localParser->setVar("valueEMAIL", ""); + } + + // set error message + if ($error->exists()) { + $localParser->setVar("IS_ERROR", "true"); + $localParser->setVar("ERRORAREA", $error->getAllFormatted()); + } + + // create page + $parser->setVAR("PAGE", $localParser->parseFile("orderlogin.html")); +} + +?> \ No newline at end of file diff --git a/www/inc/rendering/submit.php b/www/inc/rendering/submit.php new file mode 100644 index 0000000..3471d9c --- /dev/null +++ b/www/inc/rendering/submit.php @@ -0,0 +1,189 @@ + +// +---------------------------------------------------------------------- +// | +// | Copyright: See COPYING file that comes with this distribution +// +---------------------------------------------------------------------- +// + +// forward to order login when order button in cart is pressed +if (isset($_POST["ms_goToOrder"])) { + Header("Location: index.php?mode=orderLogin"); + exit(); +} + +/** adds an event to the cart */ +function addEventToCart() +{ + $error = ErrorManager::singleton(); + + if (isset($_POST["ms_save"])) { + $event = new Event(($_GET["event"]+0)); + $availableTickets = $event->availableTicketAmount(); + if (empty($_POST["ms_amount"])) { + $error->add(i18n("Please insert the number of tickets!")); + return; + } elseif (!is_numeric($_POST["ms_amount"])) { + $error->add(i18n("Please insert a number!")); + return; + } elseif (!$event->exists()) { + $error->add(i18n("The event does not exist!")); + return; + } else if ($availableTickets == 0) { + $error->add(i18n("No more tickets for this event available!")); + return; + } else { + $cart = new Cart(addslashes($_COOKIE[COOKIE_NAME])); + if (!$cart->isValid()) { + $cart = new Cart(); + setcookie(COOKIE_NAME, $cart->getCartId(), 0); + } + + // check if event is already booked + $cartTicket = $cart->getTicketsByEvent($event->getEventId()); + + // if event is not booked + if ($cartTicket == false) { + // check if enough tickets available + if ($availableTickets < ($_POST["ms_amount"]+0)) { + $error->add(string_format(i18n("Only {1} tickets left!"), array("$availableTickets"))); + return; + } + + // add tickets to cart + $cart->addTickets(($event->getEventId()+0), ($_POST["ms_amount"]+0)); + } else { + // check if enough tickets available + if ($availableTickets < ($_POST["ms_amount"] + $cartTicket->getAmount())) { + $ticketsLeft = $availableTickets - $cartTicket->getAmount(); + if ($ticketsLeft > 0) + $error->add(string_format(i18n("Only {1} more tickets left!"),array("$ticketsLeft"))); + else + $error->add(i18n("No more tickets for this event available!")); + return; + } + + // set tickets to cartTicket + $cartTicket->changeAmount($cartTicket->getAmount() + $_POST["ms_amount"]); + } + + Header("Location: index.php?mode=cart"); + exit(); + } + } +} + +/** deletes an event from the cart */ +function deleteEventFromCart() +{ + if ($_GET["action"]=="deleteEvent") { + $cart = new Cart(addslashes($_COOKIE[COOKIE_NAME])); + // check if cart valid + if ($cart->isValid()) { + // get cart ticket + $cartTicket = $cart->getTicketsByEvent($_GET["event"]+0); + if ($cartTicket != false) { + $cartTicket->changeAmount(0); + } + } + } +} + +/** modifies the amount of tickets in the cart */ +function changeTicketAmountInCart() +{ + $error = ErrorManager::singleton(); + + if (isset($_POST["ms_save"])) { + + $cart = new Cart(addslashes($_COOKIE[COOKIE_NAME])); + // check if cart valid + if ($cart->isValid()) { + + // get event IDs and amounts + $eventIDs = $_POST["ms_event"]; + $ticketAmounts = $_POST["ms_amount"]; + + $num = count($eventIDs); + + // check for errors in input + for ($i=0; $i < $num; $i++) { + $line = $i + 1; + if (empty($ticketAmounts[$i]) || !is_numeric($ticketAmounts[$i])) { + $error->add(string_format(i18n("Please enter an amount in line {1}!"), array("$line"))); + } + } + + if ($error->exists()) + return; + + // iterate over events + for ($i=0; $i < $num; $i++) { + // get eventID and belonging amount + $eventID = $eventIDs[$i]+0; + $amount = $ticketAmounts[$i]+0; + + $cartTicket = $cart->getTicketsByEvent($eventID); + + // check if amount changed + if ($cartTicket->getAmount() != $amount) { + // check if enough tickets available + $event = $cartTicket->eventObject(); + if ($event->availableTicketAmount() >= $amount) { + $cartTicket->changeAmount($amount); + } else { + $title = $event->getTitle(); + $availableTickets = $event->availableTicketAmount(); + $error->add(string_format(i18n("Event {1} has only {2} tickets left."), array("\"$title\"", "$availableTickets"))); + } + } + } + } + } +} + +/** checks order login for valid values */ +function checkOrderLogin() +{ + $error = ErrorManager::singleton(); + + if (isset($_POST["ms_loginContinue"])) { + // if user isn't registered + if ($_POST["ms_isCustomer"] == "false") { + if (!isEmail($_POST["ms_email"])) { + $error->add(i18n("Please enter a correct email address!")); + return; + } + + // if user is registered + } elseif ($_POST["ms_isCustomer"] == "true") { + if (!isEmail($_POST["ms_email"])) { + $error->add(i18n("Please enter a correct email address!")); + } + if (empty($_POST["ms_password"])) { + $error->add(i18n("Please enter a password!")); + } + if ($error->exists()) + return; + // TODO: check if login valid + + // if radio button is not checked + } else { + $error->add(i18n("Please specify if you're a registered user!")); + return; + } + + Header("Location: index.php?mode=userdata"); + exit(); + } +} + +/** checks if given value is a valid email address */ +function isEmail($value) { + return ereg("^[a-zA-Z0-9\._-]+@[a-zA-Z0-9\._-]+$", $value); +} + +?> \ No newline at end of file diff --git a/www/inc/room.php b/www/inc/room.php deleted file mode 100644 index 40daa21..0000000 --- a/www/inc/room.php +++ /dev/null @@ -1,84 +0,0 @@ -, (C) 2007 -// -// Copyright: See README/COPYING files that come with this distribution -// -// - -//TODO: implement: -class Room -{ - public function __construct($roomid){} - public function exists(){return false;} - -}; - -function getRoomsXml($xmldata) -{ - global $db; - //TODO: check xml data - //return rooms - $res=$db->select("room","roomid,capacity,description",""); - $xml=new DOMDocument; - $root=$xml->createElement("RoomData"); - if(count($res)>0) - foreach($res as $k => $rm){ - $room=$xml->createElement("Room"); - $room->setAttribute("capacity",$rm["capacity"]); - $id=$xml->createElement("ID",$rm["roomid"]); - $room->appendChild($id); - $des=$xml->createElement("Description",$rm["description"]); - $room->appendChild($des); - $root->appendChild($room); - } - $xml->appendChild($root); - header("X-MagicSmoke-Status: Ok"); - print($xml->saveXML()); -} - -function setRoomsXml($xmldata) -{ - //TODO:do more extensive syntax checking and better error reporting - //get XML - $xml=new DOMDocument; - if($xml->loadXML($xmldata)===false){ - header("X-MagicSmoke-Status: SyntaxError"); - echo "Unable to parse XML."; - return; - } - //stage 2: extract data from XML - $doc=$xml->documentElement; - global $db; - foreach($doc->getElementsByTagName("Room") as $room){ - //get data - $cap=$room->getAttribute("capacity")+0; - $id=false; - $descr=false; - foreach($room->getElementsByTagName("ID") as $el) - foreach($el->childNodes as $cn) - if($cn->nodeType==XML_TEXT_NODE) - $id=trim($cn->wholeText); - foreach($room->getElementsByTagName("Description") as $el) - foreach($el->childNodes as $cn) - if($cn->nodeType==XML_TEXT_NODE) - $descr=trim($cn->wholeText); - if($id===false)continue; - $db->beginTransaction(); - $res=$db->select("room","roomid","roomid=".$db->escapeString($id)); - if(count($res)>0){ - $db->update("room",array("capacity"=>$cap,"description"=>$descr),"roomid=".$db->escapeString($id)); - }else{ - $db->insert("room",array("roomid"=>$id,"capacity"=>$cap,"description"=>$descr)); - } - $db->commitTransaction(); - } - header("X-MagicSmoke-Status: Ok"); -} - -?> \ No newline at end of file diff --git a/www/inc/submit.php b/www/inc/submit.php deleted file mode 100644 index 3471d9c..0000000 --- a/www/inc/submit.php +++ /dev/null @@ -1,189 +0,0 @@ - -// +---------------------------------------------------------------------- -// | -// | Copyright: See COPYING file that comes with this distribution -// +---------------------------------------------------------------------- -// - -// forward to order login when order button in cart is pressed -if (isset($_POST["ms_goToOrder"])) { - Header("Location: index.php?mode=orderLogin"); - exit(); -} - -/** adds an event to the cart */ -function addEventToCart() -{ - $error = ErrorManager::singleton(); - - if (isset($_POST["ms_save"])) { - $event = new Event(($_GET["event"]+0)); - $availableTickets = $event->availableTicketAmount(); - if (empty($_POST["ms_amount"])) { - $error->add(i18n("Please insert the number of tickets!")); - return; - } elseif (!is_numeric($_POST["ms_amount"])) { - $error->add(i18n("Please insert a number!")); - return; - } elseif (!$event->exists()) { - $error->add(i18n("The event does not exist!")); - return; - } else if ($availableTickets == 0) { - $error->add(i18n("No more tickets for this event available!")); - return; - } else { - $cart = new Cart(addslashes($_COOKIE[COOKIE_NAME])); - if (!$cart->isValid()) { - $cart = new Cart(); - setcookie(COOKIE_NAME, $cart->getCartId(), 0); - } - - // check if event is already booked - $cartTicket = $cart->getTicketsByEvent($event->getEventId()); - - // if event is not booked - if ($cartTicket == false) { - // check if enough tickets available - if ($availableTickets < ($_POST["ms_amount"]+0)) { - $error->add(string_format(i18n("Only {1} tickets left!"), array("$availableTickets"))); - return; - } - - // add tickets to cart - $cart->addTickets(($event->getEventId()+0), ($_POST["ms_amount"]+0)); - } else { - // check if enough tickets available - if ($availableTickets < ($_POST["ms_amount"] + $cartTicket->getAmount())) { - $ticketsLeft = $availableTickets - $cartTicket->getAmount(); - if ($ticketsLeft > 0) - $error->add(string_format(i18n("Only {1} more tickets left!"),array("$ticketsLeft"))); - else - $error->add(i18n("No more tickets for this event available!")); - return; - } - - // set tickets to cartTicket - $cartTicket->changeAmount($cartTicket->getAmount() + $_POST["ms_amount"]); - } - - Header("Location: index.php?mode=cart"); - exit(); - } - } -} - -/** deletes an event from the cart */ -function deleteEventFromCart() -{ - if ($_GET["action"]=="deleteEvent") { - $cart = new Cart(addslashes($_COOKIE[COOKIE_NAME])); - // check if cart valid - if ($cart->isValid()) { - // get cart ticket - $cartTicket = $cart->getTicketsByEvent($_GET["event"]+0); - if ($cartTicket != false) { - $cartTicket->changeAmount(0); - } - } - } -} - -/** modifies the amount of tickets in the cart */ -function changeTicketAmountInCart() -{ - $error = ErrorManager::singleton(); - - if (isset($_POST["ms_save"])) { - - $cart = new Cart(addslashes($_COOKIE[COOKIE_NAME])); - // check if cart valid - if ($cart->isValid()) { - - // get event IDs and amounts - $eventIDs = $_POST["ms_event"]; - $ticketAmounts = $_POST["ms_amount"]; - - $num = count($eventIDs); - - // check for errors in input - for ($i=0; $i < $num; $i++) { - $line = $i + 1; - if (empty($ticketAmounts[$i]) || !is_numeric($ticketAmounts[$i])) { - $error->add(string_format(i18n("Please enter an amount in line {1}!"), array("$line"))); - } - } - - if ($error->exists()) - return; - - // iterate over events - for ($i=0; $i < $num; $i++) { - // get eventID and belonging amount - $eventID = $eventIDs[$i]+0; - $amount = $ticketAmounts[$i]+0; - - $cartTicket = $cart->getTicketsByEvent($eventID); - - // check if amount changed - if ($cartTicket->getAmount() != $amount) { - // check if enough tickets available - $event = $cartTicket->eventObject(); - if ($event->availableTicketAmount() >= $amount) { - $cartTicket->changeAmount($amount); - } else { - $title = $event->getTitle(); - $availableTickets = $event->availableTicketAmount(); - $error->add(string_format(i18n("Event {1} has only {2} tickets left."), array("\"$title\"", "$availableTickets"))); - } - } - } - } - } -} - -/** checks order login for valid values */ -function checkOrderLogin() -{ - $error = ErrorManager::singleton(); - - if (isset($_POST["ms_loginContinue"])) { - // if user isn't registered - if ($_POST["ms_isCustomer"] == "false") { - if (!isEmail($_POST["ms_email"])) { - $error->add(i18n("Please enter a correct email address!")); - return; - } - - // if user is registered - } elseif ($_POST["ms_isCustomer"] == "true") { - if (!isEmail($_POST["ms_email"])) { - $error->add(i18n("Please enter a correct email address!")); - } - if (empty($_POST["ms_password"])) { - $error->add(i18n("Please enter a password!")); - } - if ($error->exists()) - return; - // TODO: check if login valid - - // if radio button is not checked - } else { - $error->add(i18n("Please specify if you're a registered user!")); - return; - } - - Header("Location: index.php?mode=userdata"); - exit(); - } -} - -/** checks if given value is a valid email address */ -function isEmail($value) { - return ereg("^[a-zA-Z0-9\._-]+@[a-zA-Z0-9\._-]+$", $value); -} - -?> \ No newline at end of file diff --git a/www/inc/ticket.php b/www/inc/ticket.php deleted file mode 100644 index ff3a28c..0000000 --- a/www/inc/ticket.php +++ /dev/null @@ -1,26 +0,0 @@ -, (C) 2007 -// -// Copyright: See README/COPYING files that come with this distribution -// -// - - -/**ticket has been reserved by a seller*/ -define("TICKET_RESERVED",1); -/**ticket is part of an order or has been sold independently*/ -define("TICKET_SOLD",2); -/**ticket has been used*/ -define("TICKET_USED",4); -/**the ticket has been paid*/ -define("TICKET_PAID",8); -/**ticket has been cancelled by some entity*/ -define("TICKET_CANCELLED",16); - -?> \ No newline at end of file diff --git a/www/index.php b/www/index.php index e51c800..439258b 100644 --- a/www/index.php +++ b/www/index.php @@ -5,12 +5,12 @@ include('inc/loader_nonadmin.php'); include('inc/global_variables.php'); //include process script -include('inc/submit.php'); +include('inc/rendering/submit.php'); //include display scripts -include('inc/event_listing.php'); -include('inc/cart_listing.php'); -include('inc/order_listing.php'); +include('inc/rendering/event_listing.php'); +include('inc/rendering/cart_listing.php'); +include('inc/rendering/order_listing.php'); //set common basics $mode="index"; -- 1.7.2.5