function view_dates()
 {
     global $CFG, $USER;
     $rday = optional_param('rday', NULL, PARAM_INT);
     $rslot = optional_param('rslot', NULL, PARAM_INT);
     $delete = optional_param('delete', NULL, PARAM_INT);
     $resid = optional_param('resid', NULL, PARAM_INT);
     $uid = optional_param('uid', NULL, PARAM_INT);
     require_once "../../config.php";
     $cmid = $this->cm->id;
     if (!($course = get_record('course', 'id', $this->cm->course))) {
         error('Course is misconfigured');
     }
     $itemid = $this->bookings->itemid;
     $username = $USER->username;
     $UID = $USER->id;
     $firstname = $USER->firstname;
     $lastname = $USER->lastname;
     if ($firstname == '' or $lastname == '') {
         return "";
     }
     $html .= '<form name=myform id=myform method=post action="view.php?id=' . $cmid . '">';
     $proplist = bookings_item_properties($itemid);
     $days = explode(',', 'A,B,C,D,E,F');
     $daylimits = array();
     if (isset($proplist['days']) and $proplist['days'] != '') {
         $days = explode(',', $proplist['days']);
         $dag = 0;
         foreach ($days as $day) {
             list($dy, $lim) = explode(':', $day);
             // pick out optional size limit
             $days[$dag] = $dy;
             $daylimits[$dag] = (int) $lim;
             $dag++;
         }
     }
     $widthprcent = (int) (95 / count($days));
     // default width
     $slots = explode(',', '1,2,3,4,5,6');
     $slotlimits = array();
     if (isset($proplist['slots']) and $proplist['slots'] != '') {
         $slots = explode(',', $proplist['slots']);
         $slt = 0;
         foreach ($slots as $slot) {
             list($sl, $lim) = explode(':', $slot);
             // pick out optional size limit
             $slots[$slt] = $sl;
             $slotlimits[$slt] = (int) $lim;
             $slt++;
         }
     }
     $multiple = 0;
     if (isset($proplist['multiple'])) {
         $multiple = (int) $proplist['multiple'];
     }
     $exclusive = 'non';
     // many entries pr user
     if (isset($proplist['exclusive'])) {
         $exclusive = $proplist['exclusive'];
     }
     $can_edit = 1;
     // any user can make a booking
     if (isset($proplist['edit_group'])) {
         $can_edit = isadmin() ? 1 : 0;
         if ($proplist['edit_group'] == 'teachers' and isteacherinanycourse($USER->id)) {
             $can_edit = 1;
         } else {
             if ($proplist['edit_group'] == 'students') {
                 $can_edit = 1;
             } else {
                 $can_edit = isteacherinanycourse($USER->id) ? 1 : 0;
                 // default is teachers can make a booking
             }
         }
     }
     $privilege = isteacherinanycourse($USER->id) ? isadmin() ? 2 : 1 : 0;
     /// here we fetch out all reservations
     $sql = 'SELECT * FROM ' . $CFG->prefix . 'bookings_calendar 
             WHERE eventtype="reservation" 
             AND bookingid=' . $this->bookings->id;
     $reservation = array();
     $daycount = array();
     // count of reservations pr day (colcount)
     $slotcount = array();
     // count of reservations pr slot (rowcount)
     $total = 0;
     if ($res = get_records_sql($sql)) {
         foreach ($res as $re) {
             $reservation[$re->day][$re->slot][] = $re;
             $reservation[$re->day][$re->slot]->res = $re;
             $daycount[$re->day] += 1;
             $slotcount[$re->slot] += 1;
             $total++;
         }
     }
     /// this is where we make the reservation or delete reservations
     if ((isset($resid) and isset($uid) or isset($rday) and isset($rslot)) and $can_edit) {
         if (!isteacherinanycourse($USER->id) and !isadmin() and isset($reservation[$rday][$rslot])) {
             if ($uid != $UID) {
                 // return;  // assume an attempt to phreak the system with params
             }
         }
         /// exclusive decides if and how multiple bookings made by one user is handled
         /// default is that a user can book once in any available slot
         switch ($exclusive) {
             case 'row':
                 /// only one booking pr row
                 $sql = 'DELETE FROM ' . $CFG->prefix . 'bookings_calendar WHERE eventtype="reservation" AND userid=' . $UID . ' AND slot=' . $rslot;
                 break;
             case 'rowcol':
                 /// only one booking in this row+col
                 $sql = 'DELETE FROM ' . $CFG->prefix . 'bookings_calendar WHERE eventtype="reservation" AND userid=' . $UID . ' AND (day=' . $rday . ' OR slot=' . $rslot . ')';
                 break;
             case 'col':
                 /// only one booking pr col
                 $sql = 'DELETE FROM ' . $CFG->prefix . 'bookings_calendar WHERE eventtype="reservation" AND userid=' . $UID . ' AND day=' . $rday;
                 break;
             case 'all':
                 /// only one booking
                 $sql = 'DELETE FROM ' . $CFG->prefix . 'bookings_calendar WHERE eventtype="reservation" AND userid=' . $UID;
                 break;
             default:
                 $sql = 'DELETE FROM ' . $CFG->prefix . 'bookings_calendar WHERE eventtype="reservation" AND slot=' . $rslot . ' AND day=' . $rday . ' AND userid=' . $UID;
         }
         execute_sql($sql, 0);
         /// this removes multiple bookings by one person for a given slot (or all bookings if exclusive)
         if (isset($resid)) {
             $sql = 'DELETE FROM ' . $CFG->prefix . 'bookings_calendar WHERE id=' . $resid;
             execute_sql($sql, 0);
         }
         if (!isset($delete)) {
             $sql = 'INSERT INTO ' . $CFG->prefix . 'bookings_calendar (bookingid,name,value,userid,eventtype,slot,day) 
                 VALUES (' . $this->bookings->id . ',"' . $username . '","' . $username . '",' . $UID . ',"reservation",' . $rslot . ',' . $rday . ')';
             execute_sql($sql, 0);
         }
         // have to refetch data
         $sql = 'SELECT * FROM ' . $CFG->prefix . 'bookings_calendar 
             WHERE eventtype="reservation" 
             AND bookingid=' . $this->bookings->id;
         $reservation = array();
         $daycount = array();
         // count of reservations pr day (colcount)
         $slotcount = array();
         // count of reservations pr slot (rowcount)
         $total = 0;
         // total number of reservations
         if ($res = get_records_sql($sql)) {
             foreach ($res as $re) {
                 $reservation[$re->day][$re->slot][] = $re;
                 $daycount[$re->day] += 1;
                 $slotcount[$re->slot] += 1;
                 $total++;
             }
         }
     }
     $html .= '<div id="all">';
     // now we draw up the table
     $table = array();
     $lastrow = '';
     if ($can_edit) {
         $baselink = '<a href="view.php?id=' . $cmid;
     } else {
         $baselink = '';
     }
     $table[] = '<table border=1 width=100%>';
     $table[] = '<tr><th width=5%>&nbsp;</th>';
     $dag = 0;
     foreach ($days as $day) {
         if ($day == '') {
             continue;
         }
         $table[] = '<th>' . $day . '</th>';
         $lastrow .= "<td>" . $daycount[$dag] . "&nbsp;</td>\n";
         $dag++;
     }
     $table[] = '</tr>';
     $time = 0;
     foreach ($slots as $slottime) {
         $t = $time + 1;
         $table[] = "<tr><th class=\"number\"><span class=\"time\">{$slottime}</span></th>";
         $dag = 0;
         $scanedit = ($slotlimits[$time] == 0 or $slotlimits[$time] > $slotcount[$time]) ? $can_edit : 0;
         foreach ($days as $day) {
             $canedit = $scanedit;
             $class = 'normal';
             if ($day != '') {
                 $canedit = ($daylimits[$dag] == 0 or $daylimits[$dag] > $daycount[$dag]) ? $canedit : 0;
                 if ($tp[$dag][$time] == '') {
                     $class = 'free';
                     $tp[$dag][$time] = $canedit ? $baselink . '&rday=' . $dag . '&rslot=' . $time . '">' . get_string('free', 'bookings') . '</a>' : get_string('free', 'bookings');
                 }
                 if (isset($reservation[$dag][$time])) {
                     $tp[$dag][$time] = '';
                     foreach ($reservation[$dag][$time] as $myres) {
                         $class = 'reserved';
                         $linktext = 'Reserved ' . $myres->value;
                         if ($myres->userid == $UID) {
                             $linktext = 'M';
                         } else {
                             if (sizeof($reservation[$dag][$time] > 1)) {
                                 $linktext = isteacherinanycourse($myres->userid) ? 'T' : 'S';
                             }
                         }
                         // admin can override any, teacher can override student
                         if ($myres->userid == $UID or isadmin() or isteacherinanycourse($USER->id) and !isteacherinanycourse($myres->userid)) {
                             $tp[$dag][$time] .= $can_edit ? $baselink . '&delete=1&resid=' . $myres->id . '&uid=' . $myres->userid . '"
                         title="' . $myres->value . '" >' . $linktext . '</a> ' : $linktext . $myres->value;
                         } else {
                             $tp[$dag][$time] .= '<span title="' . $myres->value . '">' . $linktext . ' </span>';
                         }
                     }
                     if (isset($multiple) and $multiple > sizeof($reservation[$dag][$time])) {
                         /// $tp[$dag][$time] .= ' ' .$reservation[$dag][$time]->count . ' ';
                         $tp[$dag][$time] .= $canedit ? $baselink . '&rday=' . $dag . '&rslot=' . $time . '">' . get_string('free', 'bookings') . '</a>' : get_string('free', 'bookings');
                     }
                 }
                 $table[] = "<td width=\"{$widthprcent}%\" class=\"{$class}\" >" . $tp[$dag][$time] . "&nbsp;</td>\n";
             }
             $dag++;
         }
         if ($privilege > 0) {
             $table[] = "<td>" . $slotcount[$time] . "&nbsp;</td>\n";
         }
         $table[] = "</tr>\n";
         $idx++;
         $time += 1;
     }
     if ($privilege > 0) {
         $table[] = "<tr><td></td>" . $lastrow . "<td>{$total}</td></tr>";
     }
     $table[] = "</table>\n";
     $html .= implode("", $table);
     $html .= '<input type="hidden" name="itemid" value="' . $itemid . '">';
     $html .= '<input type="hidden" name="jday" value="' . $jday . '">';
     $html .= '</div>';
     // end div=all
     print $html;
     if ($privilege > 0) {
         unset($table);
         $table->head = array('&nbsp;', get_string('name'));
         $table->align = array('center', 'left');
         $table->wrap = array('nowrap', 'nowrap');
         $table->width = '100%';
         $table->size = array(10, '*');
         $table->head[] = get_string('email');
         $table->align[] = 'center';
         $table->wrap[] = 'nowrap';
         $table->size[] = '*';
         $table->head[] = get_string('reservation', 'bookings');
         $table->align[] = 'center';
         $table->wrap[] = 'nowrap';
         $table->size[] = '*';
         $table->head[] = get_string('choice', 'bookings');
         $table->align[] = 'center';
         $table->wrap[] = 'nowrap';
         $table->size[] = '*';
         // $books = get_records('calendar', 'bookingid', $this->bookings->id);
         if ($books = get_records_sql("SELECT r.*, u.firstname, u.lastname, u.picture, u.email\n                                FROM {$CFG->prefix}bookings_calendar r,\n                                    {$CFG->prefix}user u\n                                WHERE r.bookingid = '{$this->bookings->id}' \n                                AND r.userid = u.id ORDER BY r.day,r.slot")) {
             foreach ($books as $request) {
                 $row = array();
                 $row[] = print_user_picture($request->userid, $course->id, $request->picture, 0, true);
                 $row[] = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $request->userid . '&course=' . $course->id . '">' . $request->lastname . ' ' . $request->firstname . '</a>';
                 $row[] = obfuscate_mailto($request->email);
                 $row[] = $days[$request->day];
                 $row[] = $slots[$request->slot];
                 $table->data[] = $row;
             }
             print "<p>";
             print_table($table);
         }
     }
     print "</form>";
     return;
 }
 function view_dates()
 {
     global $CFG, $USER;
     $showcombo = optional_param('showcombo', NULL, PARAM_INT);
     $komboroom = optional_param('komboroom', NULL, PARAM_ALPHAEXT);
     $prev = optional_param('prev', NULL, PARAM_ALPHAEXT);
     $next = optional_param('next', NULL, PARAM_ALPHAEXT);
     $jday = optional_param('jday', NULL, PARAM_INT);
     $rday = optional_param('rday', NULL, PARAM_INT);
     $rslot = optional_param('rslot', NULL, PARAM_INT);
     $delete = optional_param('delete', NULL, PARAM_INT);
     $resid = optional_param('resid', NULL, PARAM_INT);
     $uid = optional_param('uid', NULL, PARAM_INT);
     require_once "../../config.php";
     $cmid = $this->cm->id;
     /// require_once($CFG->dirroot.'/blocks/timetable/locallib.php');
     $itemid = $this->bookings->itemid;
     $username = $USER->username;
     $UID = $USER->id;
     $firstname = $USER->firstname;
     $lastname = $USER->lastname;
     ///$prover = mineprover();
     ///$fridager = Fridager();
     if ($firstname == '' or $lastname == '') {
         return "";
     }
     $html .= '<form name=myform id=myform method=post action="view.php?id=' . $cmid . '">';
     //// show combo is used if we don't already know which room/item is to be scheduled
     if (isset($showcombo)) {
         if (isset($komboroom)) {
             $itemid = $komboroom;
         }
         $sql = 'SELECT r.id, r.name
                 FROM ' . $CFG->prefix . 'bookings_item r,
                     ' . $CFG->prefix . 'bookings_item_property p
                 WHERE p.itemid = r.id
                     AND p.name="scheduled"
                     AND p.value="yes"
                 ORDER BY r.name';
         if ($roomlist = get_records_sql($sql)) {
             $kombo = "<select name=\"komboroom\" onchange=\"document.myform.reload.click()\">";
             $kombo .= "<option value=\" \"> -- Select -- </option>\n ";
             foreach ($roomlist as $room) {
                 $selected = "";
                 if ($room->id == $itemid) {
                     $selected = "selected";
                     $rname = $room->name;
                 }
                 $kombo .= '<option value="' . $room->id . '" ' . $selected . '>' . $room->name . '</option>' . "\n ";
             }
             $kombo .= '</select>' . "\n";
         }
         $html .= $kombo;
         $html .= '<input id="reload" type="submit" name="reload">';
         $html .= '<input type="hidden" name="showcombo" value="yes">';
     }
     ///////////////////////////
     // fetch out any timetable-data for this item
     $sql = 'SELECT r.id,r.name,r.type FROM ' . $CFG->prefix . 'bookings_item r WHERE r.id=' . $itemid;
     $r = get_record_sql($sql);
     $sql = "SELECT concat(c.id,t.day,t.slot),c.id,c.shortname, r.type, r.name, t.day, t.slot  \n                    FROM {$CFG->prefix}bookings_calendar t,\n                        {$CFG->prefix}bookings_item r left join\n                        {$CFG->prefix}course c  on c.id = t.courseid\n                WHERE r.id={$itemid}\n                    AND t.eventtype = 'timetable'\n                    AND r.id = t.itemid\n                ORDER BY day,slot";
     $tp = array();
     if ($tplan = get_records_sql($sql)) {
         foreach ($tplan as $tpelm) {
             $shortshortname = $tpelm->shortname;
             $tp[$tpelm->day][$tpelm->slot] = "<a href=\"/moodle/course/view.php?id={$tpelm->id}\">{$shortshortname}</a>";
         }
     }
     // build array of props for this item (room)
     $proplist = bookings_item_properties($itemid);
     $days = explode(',', 'Mon,Tue,Wed,Thu,Fri,,');
     if (isset($proplist['days'])) {
         $days = explode(',', $proplist['days']);
     }
     $widthprcent = (int) (95 / count($days));
     // default width
     $slots = array(8, 9, 10, 11, 12, 13, 14, 15, 16);
     if (isset($proplist['slots'])) {
         $slots = explode(',', $proplist['slots']);
     }
     $lookahead = 700;
     // limit on number of weeks you can move from present week (100 weeks +/-)
     if (isset($proplist['lookahead'])) {
         $lookahead = 7 * (int) $proplist['lookahead'];
     }
     // decide if user can edit timetable
     $can_edit = isteacherinanycourse($USER->id) ? 1 : 0;
     // default is that teachers can edit
     $link2room = '';
     if (isset($proplist['edit_group'])) {
         $can_edit = 0;
         // default is no edit (that is: edit_group != teacher|student )
         if ($proplist['edit_group'] == 'teachers' and isteacherinanycourse($USER->id)) {
             $can_edit = 1;
             $link2room = ' <a href="itemeditor.php?id=' . $cmid . '&newid=' . $itemid . '">' . get_string('edit') . ' ' . $r->type . '</a>';
         } else {
             if ($proplist['edit_group'] == 'students') {
                 $can_edit = 1;
             }
         }
     }
     // intended to give edit-rights to named students
     if (isset($proplist['edit_list'])) {
         if (strstr($proplist['edit_list'], $username)) {
             $can_edit = 1;
         }
     }
     // a multiple resource has a property that is counted down on each reservation
     // so long as number of resevations is less than this values, then user can make a
     // reservation
     if (isset($proplist['multiple'])) {
         $multiple = (int) $proplist['multiple'];
     }
     // calculate week and day
     list($ty, $tm, $td) = explode("/", strftime("%Y/%m/%d", time()));
     $tjday = gregoriantojd($tm, $td, $ty);
     $tweek = bookings_week($tjday);
     if (!isset($jday)) {
         $jday = $tjday;
     }
     // a list of days that isn't a week (7 days) or doesn't start on the first day of the week
     // should have this property, otherwise the schedule wont tile over the year
     list($ys, $ms, $ds) = explode(',', $proplist['startsched']);
     $start = gregoriantojd($ms, $ds, $ys) or 0;
     $jday = $start + sizeof($days) * (int) (($jday - $start) / sizeof($days));
     // $jday = 7 * (int)($jday/7);
     if (isset($prev) and $jday > $tjday - $lookahead) {
         $jday -= sizeof($days);
     }
     if (isset($next) and $jday < $tjday + $lookahead - 7) {
         $jday += sizeof($days);
     }
     list($ey, $em, $ed) = explode("/", strftime("%Y/%m/%d", $this->bookings->enddate));
     $ejday = gregoriantojd($em, $ed, $ey);
     if ($jday > $ejday) {
         $can_edit = 0;
     }
     if ($jday + sizeof($days) < $tjday) {
         $can_edit = 0;
     }
     if (isadmin()) {
         /// no matter what, admin can edit - even past dates
         $can_edit = 1;
         $link2room = ' <a href="itemeditor.php?id=' . $cmid . '&newid=' . $itemid . '">' . get_string('edit') . ' ' . $r->type . '</a>';
     }
     /// here we fetch out all reservations
     // list($m,$d,$y) = explode('/',jdtogregorian($jday));
     // $start = gmmktime(0, 0, 0, $m, $d, $y);
     // $stop = $start + 604800;   // weekofseconds
     $sql = 'SELECT * FROM ' . $CFG->prefix . 'bookings_calendar 
             WHERE eventtype="reservation" 
             AND itemid=' . $r->id . '
             AND julday >= ' . $jday . '
             AND julday <= ' . ($jday + sizeof($days) - 1);
     $reservation = array();
     if ($res = get_records_sql($sql)) {
         foreach ($res as $re) {
             $reservation[$re->day][$re->slot][] = $re;
             if ($res->userid == $UID) {
                 $reservation[$re->day][$re->slot]->res = $re;
             }
         }
     }
     /// this is where we make the reservation or delete reservations
     if ((isset($resid) and isset($uid) or isset($rday) and isset($rslot)) and $can_edit) {
         if (!isteacherinanycourse($USER->id) and !isadmin() and isset($reservation[$rday][$rslot])) {
             if ($uid != $UID) {
                 // return;  // assume an attempt to phreak the system with params
             }
         }
         $sql = 'DELETE FROM ' . $CFG->prefix . 'bookings_calendar WHERE eventtype="reservation" AND slot=' . $rslot . ' AND day=' . $rday . ' AND julday=' . ($jday + $rday) . '
                     AND userid=' . $UID . ' AND itemid=' . $r->id;
         execute_sql($sql, 0);
         /// this removes multiple bookings by one person for a given slot
         if (isset($resid)) {
             $sql = 'DELETE FROM ' . $CFG->prefix . 'bookings_calendar WHERE id=' . $resid;
             execute_sql($sql, 0);
         }
         if (!isset($delete)) {
             $sql = 'INSERT INTO ' . $CFG->prefix . 'bookings_calendar (name,value,userid,eventtype,itemid,slot,day,julday) 
                 VALUES ("' . $r->name . '","' . $username . '",' . $UID . ',"reservation",' . $r->id . ',' . $rslot . ',' . $rday . ',' . ($jday + $rday) . ')';
             execute_sql($sql, 0);
         }
         // have to refetch data
         $sql = 'SELECT * FROM ' . $CFG->prefix . 'bookings_calendar 
             WHERE eventtype="reservation" 
             AND itemid=' . $r->id . '
             AND julday >= ' . $jday . '
             AND julday <= ' . ($jday + sizeof($days) - 1);
         $reservation = array();
         if ($res = get_records_sql($sql)) {
             foreach ($res as $re) {
                 $reservation[$re->day][$re->slot][] = $re;
             }
         }
     }
     // navigation (next/prev) week
     $week = bookings_week($jday);
     list($m, $d, $y) = explode("/", jdtogregorian($jday));
     list($m1, $d1, $y1) = explode("/", jdtogregorian($jday + sizeof($days) - 1));
     if (bookings_week($jday + sizeof($days) - 1) != $week) {
         $week .= '-' . bookings_week($jday + sizeof($days) - 1);
     }
     $html .= '<div id="all"><h2>' . $r->name . ' (' . $r->type . ')</h2>';
     $html .= '<div class="mod-bookings navigate" ><input type="submit"  name="prev" value="&lt;&lt;">';
     $html .= get_string('week') . " {$week} &nbsp; <span id=\"date\">{$d}.{$m} - {$d1}.{$m1} {$y}</span>";
     $html .= '<input type="submit" name="next" value="&gt;&gt;"></div>';
     $html .= $link2room;
     // now we draw up the table
     $table = array();
     if ($can_edit) {
         $baselink = '<a href="view.php?id=' . $cmid . '&jday=' . $jday . '&itemid=' . $itemid;
     } else {
         $baselink = '';
     }
     $table[] = '<table border=1 width=100%>';
     $table[] = '<tr><th width=5%>&nbsp;</th>';
     foreach ($days as $day) {
         if ($day == '') {
             continue;
         }
         $table[] = '<th>' . $day . '</th>';
     }
     $table[] = '</tr>';
     $time = 0;
     foreach ($slots as $slottime) {
         $t = $time + 1;
         $table[] = "<tr><th><span class=\"number\">{$slottime}</span></th>";
         $dag = 0;
         foreach ($days as $day) {
             $class = 'normal';
             if ($day != '') {
                 if ($tp[$dag][$time] == '') {
                     $class = 'free';
                     $tp[$dag][$time] = $can_edit ? $baselink . '&rday=' . $dag . '&rslot=' . $time . '">' . get_string('free', 'bookings') . '</a>' : get_string('free', 'bookings');
                 }
                 if (isset($reservation[$dag][$time])) {
                     $tp[$dag][$time] = '';
                     foreach ($reservation[$dag][$time] as $myres) {
                         $class = 'reserved';
                         $linktext = 'Reserved ' . $myres->value;
                         if ($myres->userid == $UID) {
                             $linktext = 'M';
                         } else {
                             if (sizeof($reservation[$dag][$time] > 1)) {
                                 $linktext = isteacherinanycourse($myres->userid) ? 'T' : 'S';
                             }
                         }
                         // admin can override any, teacher can override student
                         if ($myres->userid == $UID or isadmin() or isteacherinanycourse($USER->id) and !isteacherinanycourse($myres->userid)) {
                             $tp[$dag][$time] .= $can_edit ? $baselink . '&delete=1&resid=' . $myres->id . '&uid=' . $myres->userid . '"
                         title="' . $myres->value . '" >' . $linktext . '</a> ' : $linktext . $myres->value;
                         } else {
                             $tp[$dag][$time] .= '<span title="' . $myres->value . '">' . $linktext . ' </span>';
                         }
                     }
                     if (isset($multiple) and $multiple > sizeof($reservation[$dag][$time])) {
                         $tp[$dag][$time] .= ' ' . $reservation[$dag][$time]->count . ' ';
                         $tp[$dag][$time] .= $can_edit ? $baselink . '&rday=' . $dag . '&rslot=' . $time . '">' . get_string('free', 'bookings') . '</a>' : get_string('free', 'bookings');
                     }
                 }
                 $table[] = "<td width=\"{$widthprcent}%\" class=\"{$class}\" >" . $tp[$dag][$time] . "&nbsp;</td>\n";
             }
             $dag++;
         }
         $table[] = "</tr>\n";
         $idx++;
         $time += 1;
     }
     $table[] = "</table>\n";
     $html .= implode("", $table);
     $html .= '<input type="hidden" name="itemid" value="' . $itemid . '">';
     $html .= '<input type="hidden" name="jday" value="' . $jday . '">';
     $html .= '</div>';
     // end div=all
     print $html;
     print "</form>";
     return;
 }
 function view_dates()
 {
     global $CFG, $USER;
     $showcombo = optional_param('showcombo', NULL, PARAM_INT);
     $komboroom = optional_param('komboroom', NULL, PARAM_ALPHAEXT);
     $jday = optional_param('jday', NULL, PARAM_INT);
     $subitemid = optional_param('subitemid', NULL, PARAM_INT);
     $tidx = optional_param('tidx', NULL, PARAM_INT);
     $delete = optional_param('delete', NULL, PARAM_INT);
     $edit = optional_param('edit', NULL, PARAM_INT);
     $save = optional_param('save', NULL, PARAM_INT);
     $restore = optional_param('restore', NULL, PARAM_INT);
     $resid = optional_param('resid', NULL, PARAM_INT);
     $uid = optional_param('uid', NULL, PARAM_INT);
     $value = optional_param('value');
     $cmid = $this->cm->id;
     $itemid = $this->bookings->itemid;
     $username = $USER->username;
     // $bookings = get_record('bookings', 'id', $this->bookings->id);
     /// get start and end julian day number
     list($ey, $em, $ed) = explode("/", strftime("%Y/%m/%d", $this->bookings->enddate));
     $ejday = 7 * (int) (gregoriantojd($em, $ed, $ey) / 7);
     list($ey, $em, $ed) = explode("/", strftime("%Y/%m/%d", $this->bookings->startdate));
     $sjday = 7 * (int) (gregoriantojd($em, $ed, $ey) / 7);
     $UID = $USER->id;
     $firstname = $USER->firstname;
     $lastname = $USER->lastname;
     if ($firstname == '' or $lastname == '') {
         return "";
     }
     print '<form name=myform id=myform method=post action="view.php?id=' . $cmid . '">';
     // fetch out data for this item
     $sql = 'SELECT id,name,type,parent
             FROM ' . $CFG->prefix . 'bookings_item i
             WHERE i.parent = ' . $itemid . '
             ORDER BY i.name';
     $idx = 0;
     $main_reservation = array();
     $iteminfo = array();
     $itemid_list = array();
     if (!($childlist = get_records_sql($sql))) {
         $sql = 'SELECT r.id,r.name,r.type,r.parent FROM ' . $CFG->prefix . 'bookings_item r WHERE r.id=' . $itemid;
         $childlist = get_records_sql($sql);
     }
     foreach ($childlist as $child) {
         // build array of props for this item (room)
         $itemid_list[] = $child->id;
         $proplist = bookings_item_properties($child->id);
         if (isset($proplist['image'])) {
             $childlist[$child->id]->image = '<br>' . '<img src="' . $proplist['image'] . '">';
         }
         /// here we fetch out all reservations
         $reservation = array();
         $sql = 'SELECT * FROM ' . $CFG->prefix . 'bookings_calendar 
                 WHERE eventtype="reservation" 
                 AND itemid=' . $child->id . '
                 AND julday >= ' . $sjday . '
                 AND julday <= ' . $ejday;
         if ($res = get_records_sql($sql)) {
             foreach ($res as $re) {
                 $reservation[7 * (int) ($re->julday / 7)] = $re;
             }
         }
         $childlist[$child->id]->proplist = $proplist;
         $main_reservation[$idx] = $reservation;
         $iteminfo[$idx] = $child;
         /// $childlist[$child->id]->reservation = $reservation;
         $idx++;
     }
     /// if there are children, then we must fetch out properties for parent
     /// these props decide if teachers or students can make bookings
     if ($idx > 1) {
         $proplist = bookings_item_properties($itemid);
     }
     // decide if user can edit timetable
     // 0 = view only, 1 = add items, delete/edit own, 2 add/delete/edit any
     $can_edit = isteacherinanycourse($USER->id) ? 1 : 0;
     // default is that teachers can edit
     $link2room = '';
     if (isset($proplist['edit_group'])) {
         $can_edit = 0;
         // default is no edit (that is: edit_group != teacher|student )
         if ($proplist['edit_group'] == 'teachers' and isteacherinanycourse($USER->id)) {
             $can_edit = 1;
             $link2room = ' <a href="itemeditor.php?id=' . $cmid . '&newid=' . $itemid . '">Edit Item</a>';
         } else {
             if ($proplist['edit_group'] == 'students') {
                 $can_edit = 1;
             }
         }
     }
     // intended to give edit-rights to named users
     // these users have admin rights, can delete/edit any booking
     if (isset($proplist['edit_list'])) {
         if (strstr($proplist['edit_list'], $username)) {
             $can_edit = 2;
         }
     }
     if (isadmin()) {
         /// no matter what, admin can edit - even past dates
         $can_edit = 2;
         $link2room = ' <a href="itemeditor.php?id=' . $cmid . '&newid=' . $itemid . '">Edit Item</a>';
     }
     /// this is where we make the reservation or delete reservations
     if (isset($subitemid) and $can_edit) {
         $orig_res = $main_reservation[$tidx][$jday];
         // print_r($orig_res);
         // print "UID = $UID<p>";
         $value = isset($value) ? $value : $username;
         if (isset($edit) and ($can_edit == 2 or $UID == $orig_res->userid)) {
             print "<table><tr><td>";
             print '<script type="text/javascript" src="http://localhost/moodle/lib/editor/htmlarea.php?id=3"></script>
             <script type="text/javascript" src="http://localhost/moodle/lib/editor/lang/en.php"></script>';
             helpbutton("writing", get_string("helpwriting"), "moodle", true, true);
             echo "<br />";
             helpbutton("questions", get_string("helpquestions"), "moodle", true, true);
             echo "<br />";
             if ($usehtmleditor) {
                 helpbutton("richtext", get_string("helprichtext"), "moodle", true, true);
             } else {
                 emoticonhelpbutton("form", "description");
             }
             echo "</td><td>";
             print_textarea($usehtmleditor, 20, 60, 680, 400, "value", $orig_res->value);
             if ($usehtmleditor) {
                 echo '<input type="hidden" name="format" value="' . FORMAT_HTML . '" />';
             } else {
                 echo '<div align="right">';
                 helpbutton("textformat", get_string("formattexttype"));
                 print_string("formattexttype");
                 echo ':&nbsp;';
                 if (!$form->format) {
                     $form->format = $defaultformat;
                 }
                 choose_from_menu(format_text_menu(), "format", $form->format, "");
                 echo '</div>';
             }
             print "<script language=\"javascript\" type=\"text/javascript\" defer=\"defer\">\n                var config = new HTMLArea.Config();\n                config.pageStyle = \"body { background-color: #ffffff; font-family: Trebuchet MS,Verdana,Arial,Helvetica,sans-serif; }\";\n                config.killWordOnPaste = true;\n                config.fontname = {\n                \"Trebuchet\":    'Trebuchet MS,Verdana,Arial,Helvetica,sans-serif',\n                \"Arial\":    'arial,helvetica,sans-serif',\n                \"Courier New\":  'courier new,courier,monospace',\n                \"Georgia\":  'georgia,times new roman,times,serif',\n                \"Tahoma\":   'tahoma,arial,helvetica,sans-serif',\n                \"Times New Roman\":  'times new roman,times,serif',\n                \"Verdana\":  'verdana,arial,helvetica,sans-serif',\n                \"Impact\":   'impact',\n                \"Wingdings\":    'wingdings'};\n                HTMLArea.replaceAll(config);\n                </script>";
             print '<input type="submit" name="save" value="save" />';
             print "</td></tr></table>";
             print '<input type="hidden" name="subitemid" value="' . $subitemid . '" />';
             print '<input type="hidden" name="tidx" value="' . $tidx . '" />';
             print '<input type="hidden" name="jday" value="' . $jday . '" />';
             print '<input type="hidden" name="resid" value="' . $resid . '" />';
             print "</form>";
             return;
         }
         if (isset($resid) and ($orig_res->userid == $UID or $can_edit == 2)) {
             $sql = 'DELETE FROM ' . $CFG->prefix . 'bookings_calendar 
                     WHERE id=' . $resid;
             execute_sql($sql, 0);
             unset($main_reservation[$tidx][$jday]);
         }
         unset($res);
         if (isset($restore)) {
             $res->start = 0;
             $value = $orig_res->value;
         }
         if (isset($delete) and ($orig_res->userid == $UID or $can_edit == 2)) {
             if ($orig_res->start != -1) {
                 $res->start = -1;
                 $value = $orig_res->value;
                 unset($delete);
             }
         }
         if (!isset($delete)) {
             $res->name = $username;
             $res->value = $value;
             $res->bookingid = $this->bookings->id;
             $res->userid = $UID;
             $res->eventtype = 'reservation';
             $res->itemid = $iteminfo[$tidx]->id;
             $res->julday = $jday;
             if ($returnid = insert_record("bookings_calendar", $res)) {
                 $res->id = $returnid;
                 $main_reservation[$tidx][$jday] = $res;
             }
         }
     }
     $html = $link2room;
     // now we draw up the table
     // print_r($childlist);
     $html .= '<table border=2><tr><th>' . get_string('week') . '</th>';
     foreach ($childlist as $child) {
         $html .= '<th>' . $child->name . ' ' . $child->image . '</th>';
     }
     $html .= '</tr>';
     $count = count($childlist);
     /// $widthprcent = (int)(95 / $count ) ;    // default width
     $julday = $sjday;
     $date = jdtogregorian($julday);
     list($m1, $d1, $y) = explode('/', $date);
     $time = mktime(12, 0, 0, $m1, $d1, $y);
     while ($julday < $ejday) {
         $baselink = '<a href="view.php?id=' . $cmid . '&jday=' . $julday;
         $date = jdtogregorian($julday);
         list($m, $d, $y) = explode('/', $date);
         $date = jdtogregorian($julday + 6);
         list($m1, $d1, $y) = explode('/', $date);
         $monthname = userdate($time, '%b');
         $date = sprintf("%02d.%02d-%02d.%02d", $d, $m, $d1, $m1);
         $html .= "<tr><th><a name=\"jd{$julday}\">" . bookings_week($julday) . "</a><div class='mod-bookings tiny'>{$monthname} {$date}<div></th>";
         for ($idx = 0; $idx < $count; $idx++) {
             if (isset($main_reservation[$idx][$julday])) {
                 $res = $main_reservation[$idx][$julday];
                 $class = 'reserved';
                 if ($can_edit and ($res->userid == $UID or $can_edit == 2)) {
                     // $linktext = $main_reservation[$idx][$julday]->value;
                     $resid = $res->id;
                     $link = $res->value . '<br>';
                     if ($res->start == -1) {
                         $class = 'deleted';
                         $link .= $baselink . '&tidx=' . $idx . '&subitemid=' . $iteminfo[$idx]->id . '&restore=1&resid=' . $resid . '#jd' . $julday . '" title="Restore" ><img src="' . $CFG->pixpath . '/i/restore.gif" ' . ' height="14" width="14" border="0" alt="Restore" /></a> ';
                     } else {
                         $link .= $baselink . '&tidx=' . $idx . '&subitemid=' . $iteminfo[$idx]->id . '&edit=1&resid=' . $resid . '#jd' . $julday . '" title="Edit" ><img src="' . $CFG->pixpath . '/t/edit.gif" ' . ' height="12" width="12" border="0" alt="Edit" /></a> ';
                     }
                     $link .= $baselink . '&tidx=' . $idx . '&subitemid=' . $iteminfo[$idx]->id . '&delete=1&resid=' . $resid . '#jd' . $julday . '" title="Delete" ><img src="' . $CFG->pixpath . '/t/delete.gif" ' . ' height="12" width="12" border="0" alt="Delete" /></a>';
                 } else {
                     $link = get_string('reserved', 'bookings');
                     if ($can_edit) {
                         $link = $res->value;
                     }
                 }
             } else {
                 $linktext = 'free';
                 $class = 'free';
                 $link = $can_edit ? $baselink . '&tidx=' . $idx . '&subitemid=' . $iteminfo[$idx]->id . '#jd' . $julday . '">' . get_string('free', 'bookings') . '</a>' : get_string('free', 'bookings');
             }
             $html .= "<td class='{$class}'>{$link}</td>\n";
         }
         $julday += 7;
         $time += WEEKSECS;
         $html .= "</tr>";
     }
     $html .= "</table>";
     $html .= '<input type="hidden" name="itemid" value="' . $itemid . '">';
     print $html;
     if ($can_edit > 0) {
         unset($table);
         $table->head = array('&nbsp;', get_string('bookedby', 'bookings'));
         $table->align = array('center', 'left');
         $table->wrap = array('nowrap', 'nowrap');
         $table->width = '100%';
         $table->size = array(10, '*');
         $table->head[] = get_string('week');
         $table->align[] = 'center';
         $table->wrap[] = 'nowrap';
         $table->size[] = '*';
         $table->head[] = get_string('date');
         $table->align[] = 'center';
         $table->wrap[] = 'nowrap';
         $table->size[] = '*';
         $table->head[] = get_string('reservation', 'bookings');
         $table->align[] = 'center';
         $table->wrap[] = 'nowrap';
         $table->size[] = '*';
         $table->head[] = get_string('item', 'bookings');
         $table->align[] = 'center';
         $table->wrap[] = 'nowrap';
         $table->size[] = '*';
         // $books = get_records('calendar', 'bookingid', $this->bookings->id);
         $itemid_list = implode(',', $itemid_list);
         /// WHERE r.bookingid = '{$this->bookings->id}'
         if ($books = get_records_sql("SELECT r.*, u.firstname, u.lastname, u.picture, u.email\n                                FROM {$CFG->prefix}bookings_calendar r,\n                                    {$CFG->prefix}user u\n                                WHERE r.itemid in ( {$itemid_list} )\n                                AND r.julday >= {$sjday}\n                                AND r.julday <= {$ejday}\n                                AND r.userid = u.id ORDER BY r.itemid,r.julday")) {
             foreach ($books as $request) {
                 $row = array();
                 $row[] = print_user_picture($request->userid, $course->id, $request->picture, 0, true);
                 $row[] = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $request->userid . '&course=' . $course->id . '">' . $request->lastname . ' ' . $request->firstname . '</a>';
                 $date = jdtogregorian($request->julday);
                 list($m1, $d1, $y) = explode('/', $date);
                 $time = mktime(12, 0, 0, $m1, $d1, $y);
                 $monthname = userdate($time, '%b');
                 $date = jdtogregorian($request->julday + 6);
                 list($m1, $d1, $y) = explode('/', $date);
                 $date = sprintf("%02d.%02d-%02d.%02d", $d, $m, $d1, $m1);
                 $row[] = get_string('week') . bookings_week($request->julday);
                 $row[] = " {$monthname} " . $date;
                 $row[] = $request->value;
                 $row[] = $childlist[$request->itemid]->name;
                 $table->data[] = $row;
             }
             print "<p>";
             print_table($table);
         }
     }
     print "</form>";
     return;
 }