Dokeos PHP Cross Reference Learning Management Systems

Source: /main/calendar/functions.php - 4263 lines - 176422 bytes - Summary - Text - Print

   1  <?php
   2  
   3  /* For licensing terms, see /dokeos_license.txt */
   4  
   5  
   6  /**
   7  ==============================================================================
   8  *    @package dokeos.calendar
   9  ==============================================================================
  10  */
  11  
  12  // google calendar import
  13  if (api_get_setting('calendar_google_import')=='true'){
  14      require_once  ('google.inc.php');    
  15  }
  16  
  17  /**
  18   * Display the links that appear in the action bar in the course calendar
  19   *
  20   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  21   * @version june 2010
  22   */
  23  function calendar_actions() {
  24      global $_course, $_user;
  25  
  26      // Additional libraries
  27      require_once(api_get_path(LIBRARY_PATH).'groupmanager.lib.php');
  28  
  29      $return = '';
  30  
  31      // if group members can add events we have to retrieve the groups of the user
  32      if (api_get_setting('user_manage_group_agenda')=='true'){
  33          $group_memberships        = GroupManager::get_group_ids($_course['dbName'],$_user['user_id']);
  34      }
  35  
  36      //if (api_get_setting('calendar_navigation') == 'actions' AND $_GET['action'] <> 'detail' AND $_GET['action'] <> 'edit' AND $_GET['action'] <> 'add'){
  37          if ((api_get_setting('calendar_navigation') == 'actions' && $_GET['op'] == 'new') || !isset($_GET['action'])){
  38          // javascript for the buttons in the actions bar
  39          $return .= '<script type="text/javascript">
  40                      $(document).ready(function() {
  41                          var d = $("#calendar").fullCalendar("getDate");
  42  
  43                          var view = $("#calendar").fullCalendar("getView");
  44                          $("#my-title").html(view.title);
  45  
  46                          // default view
  47                          $(".fc-button-'.api_get_setting('agenda_default_view').'").addClass("fc-state-active");
  48  
  49  
  50                          // previous
  51                          $("#my-prev-button").click(function() {
  52                              //move to previous month/week/day
  53                              $("#calendar").fullCalendar("prev");
  54                              view = $("#calendar").fullCalendar("getView");
  55                              // make the today button active
  56                              $("#my-today-button").removeClass("fc-state-disabled");
  57  
  58                              // update the title
  59                              $("#my-title").html(view.title);
  60                          });
  61  
  62                          // next
  63                          $("#my-next-button").click(function() {
  64                              //move to next month/week/day
  65                              $("#calendar").fullCalendar("next");
  66                              view = $("#calendar").fullCalendar("getView");
  67                              // make the today button active
  68                              $("#my-today-button").removeClass("fc-state-disabled");
  69  
  70                              // update the title
  71                              $("#my-title").html(view.title);
  72                          });
  73  
  74                          // today
  75                          $("#my-today-button").click(function() {
  76                              // move to today
  77                              $("#calendar").fullCalendar("today");
  78                              view = $("#calendar").fullCalendar("getView");
  79                              // make the today button inactive
  80                              $("#my-today-button").addClass("fc-state-disabled");
  81  
  82                              // update the title
  83                              $("#my-title").html(view.title);
  84                          });
  85  
  86                          // month view
  87                          $("#my-month-view").click(function() {
  88                              // change view to month view
  89                              $("#calendar").fullCalendar("changeView","month");
  90                              view = $("#calendar").fullCalendar("getView");
  91                              // make all the views inactive except the one clicked
  92                              $(".myview").removeClass("fc-state-active");
  93                              $("#my-month-view").addClass("fc-state-active");
  94  
  95                              // update the title
  96                              $("#my-title").html(view.title);
  97                          });
  98  
  99                          // week view
 100                          $("#my-week-view").click(function() {
 101                              // change view to month view
 102                              $("#calendar").fullCalendar("changeView","agendaWeek");
 103                              view = $("#calendar").fullCalendar("getView");
 104                              // make all the views inactive except the one clicked
 105                              $(".myview").removeClass("fc-state-active");
 106                              $("#my-week-view").addClass("fc-state-active");
 107  
 108                              // update the title
 109                              $("#my-title").html(view.title);
 110                          });
 111  
 112                          // day view
 113                          $("#my-day-view").click(function() {
 114                              // change view to month view
 115                              $("#calendar").fullCalendar("changeView","agendaDay");
 116                              view = $("#calendar").fullCalendar("getView");
 117                              // make all the views inactive except the one clicked
 118                              $(".myview").removeClass("fc-state-active");
 119                              $("#my-day-view").addClass("fc-state-active");
 120  
 121                              // update the title
 122                              $("#my-title").html(view.title);
 123                          });
 124                      });
 125                      </script>
 126                      ';
 127                // the     buttons in the actions bar
 128              $return .= '<table border="0" id="my-navigation">';
 129              $return .= '<tr>';
 130              $return .= '<td width="50%" id="my-fc-header-center">';
 131              $return .= '            <center><h2 id="my-title" class="fc-header-title"></h2></center>';
 132              $return .= '</td>';
 133              $return .= '<td width="25%">';
 134              $return .= '    <table border="0" id="my-fc-header-left" >';
 135              $return .= '        <tr>';
 136              $return .= '            <td><div id="my-prev-button" class="fc-button-prev fc-state-default fc-corner-left fc-no-right"><a><span>&nbsp;&#9668;&nbsp;</span></a></div></td>';
 137              $return .= '            <td><div id="my-next-button" class="fc-button-next fc-state-default fc-corner-right"><a><span>&nbsp;&#9658;&nbsp;</span></a></div></td>';
 138              $return .= '            <td><span class="fc-header-space"></span></td>';
 139              $return .= '            <td><div id="my-today-button" class="fc-button-today fc-state-default fc-corner-left fc-corner-right fc-state-disabled"><a><span>'.get_lang('Today').'</span></a></div></td>';
 140              $return .= '        </tr>';
 141              $return .= '    </table>';
 142              $return .= '</td>';
 143              $return .= '<td width="25%">';
 144              $return .= '    <table border="0" id="my-fc-header-right">';
 145              $return .= '        <tr>';
 146              $return .= '            <td><div id="my-month-view" class="myview fc-button-month fc-state-default fc-corner-left fc-no-right"><a><span>'.get_lang('MonthView').'</span></a></div></td>';
 147              $return .= '            <td><div id="my-week-view" class="myview fc-button-agendaWeek fc-state-default fc-no-right"><a><span>'.get_lang('WeekView').'</span></a></div></td>';
 148              $return .= '            <td><div id="my-day-view" class="myview fc-button-agendaDay fc-state-default fc-corner-right"><a><span>'.get_lang('DayView').'</span></a></div></td>';
 149              $return .= '        </tr>';
 150              $return .= '    </table>';
 151              $return .= '</td>';
 152              $return .= '</table>';
 153      }
 154          
 155  
 156      switch ($_GET ['action']) {
 157          case 'add' :
 158              // return to the calendar display
 159              if (!isset($_POST['submit_agenda_item'])) {
 160                  $return .= '<a href="agenda.php?'.api_get_cidreq().'">'.Display::return_icon('pixel.gif', get_lang('ReturnToCalendar'), array('class' => 'toolactionplaceholdericon toolactionback')).get_lang('ReturnToCalendar').'</a>';
 161              }
 162              $return .= '<a href="agenda.php?'.api_get_cidreq().'&action=add">'.Display::return_icon('pixel.gif', get_lang('AgendaAdd'), array('class' => 'toolactionplaceholdericon toolcalendaraddevent')).get_lang('AgendaAdd').'</a>';
 163              break;
 164          case 'edit' :
 165              // return to the calendar display
 166              if (!isset($_POST['submit_agenda_item'])) {
 167                  $return .= '<a href="agenda.php?'.api_get_cidreq().'">'.Display::return_icon('pixel.gif', get_lang('ReturnToCalendar'), array('class' => 'toolactionplaceholdericon toolactionback')).get_lang('ReturnToCalendar').'</a>';
 168              }
 169              // adding of event
 170              if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous() && api_is_allowed_to_session_edit(false,true) ) OR (api_get_setting('user_manage_group_agenda')=='true' AND !empty($group_memberships))){
 171                  $return .= '<a href="agenda.php?'.api_get_cidreq().'&action=add">'.Display::return_icon('pixel.gif', get_lang('AgendaAdd'), array('class' => 'toolactionplaceholdericon toolcalendaraddevent')).get_lang('AgendaAdd').'</a>';
 172              }
 173              break;
 174          case 'detail' :
 175              // return to the calendar display
 176              $return .= '<a href="agenda.php?'.api_get_cidreq().'">'.Display::return_icon('pixel.gif', get_lang('ReturnToCalendar'), array('class' => 'toolactionplaceholdericon toolactionback')).get_lang('ReturnToCalendar').'</a>';
 177                          break;
 178          case 'delete' :
 179              // return to the calendar display
 180              $return .= '<a href="agenda.php?'.api_get_cidreq().'">'.Display::return_icon('pixel.gif', get_lang('ReturnToCalendar'), array('class' => 'toolactionplaceholdericon toolactionback')).get_lang('ReturnToCalendar').'</a>';
 181          case '':
 182              // adding of event
 183              if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous() && api_is_allowed_to_session_edit(false,true) ) OR (api_get_setting('user_manage_group_agenda')=='true' AND !empty($group_memberships))){
 184                  $return .= '<a href="agenda.php?'.api_get_cidreq().'&action=add">'.Display::return_icon('pixel.gif', get_lang('AgendaAdd'), array('class' => 'toolactionplaceholdericon toolcalendaraddevent')).get_lang('AgendaAdd').'</a>';
 185              }
 186              break;
 187      }
 188      // export of all events
 189      if (api_get_setting('calendar_export_all')=='true'){
 190          $return .= '<a href="agenda.php?action=export">'.Display::return_icon('pixel.gif', get_lang('IcalExport'), array('class' => 'toolactionplaceholdericon toolcalendaricalexport')).get_lang('IcalExport').'</a>';
 191      }
 192      if (api_get_setting('calendar_google_import')=='true'){
 193          $return .= google_calendar_action_link();
 194      }
 195      return $return;
 196  }
 197  
 198  /**
 199   * Display the links that appear in the action bar in the "My calendar"
 200   *
 201   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
 202   * @version june 2010
 203   */
 204  function mycalendar_actions() {
 205      $return = '';
 206  
 207      if (api_get_setting('calendar_navigation') == 'actions'){
 208          // javascript for the buttons in the actions bar
 209          $return .= '<script type="text/javascript">
 210                      $(document).ready(function() {
 211                          var d = $("#calendar").fullCalendar("getDate");
 212  
 213                          var view = $("#calendar").fullCalendar("getView");
 214                          $("#my-title").html(view.title);
 215  
 216                          // default view
 217                          $(".fc-button-'.api_get_setting('agenda_default_view').'").addClass("fc-state-active");
 218  
 219  
 220                          // previous
 221                          $("#my-prev-button").click(function() {
 222                              //move to previous month/week/day
 223                              $("#calendar").fullCalendar("prev");
 224                              view = $("#calendar").fullCalendar("getView");
 225                              // make the today button active
 226                              $("#my-today-button").removeClass("fc-state-disabled");
 227  
 228                              // update the title
 229                              $("#my-title").html(view.title);
 230                          });
 231  
 232                          // next
 233                          $("#my-next-button").click(function() {
 234                              //move to next month/week/day
 235                              $("#calendar").fullCalendar("next");
 236                              view = $("#calendar").fullCalendar("getView");
 237                              // make the today button active
 238                              $("#my-today-button").removeClass("fc-state-disabled");
 239  
 240                              // update the title
 241                              $("#my-title").html(view.title);
 242                          });
 243  
 244                          // today
 245                          $("#my-today-button").click(function() {
 246                              // move to today
 247                              $("#calendar").fullCalendar("today");
 248                              view = $("#calendar").fullCalendar("getView");
 249                              // make the today button inactive
 250                              $("#my-today-button").addClass("fc-state-disabled");
 251  
 252                              // update the title
 253                              $("#my-title").html(view.title);
 254                          });
 255  
 256                          // month view
 257                          $("#my-month-view").click(function() {
 258                              // change view to month view
 259                              $("#calendar").fullCalendar("changeView","month");
 260                              view = $("#calendar").fullCalendar("getView");
 261                              // make all the views inactive except the one clicked
 262                              $(".myview").removeClass("fc-state-active");
 263                              $("#my-month-view").addClass("fc-state-active");
 264  
 265                              // update the title
 266                              $("#my-title").html(view.title);
 267                          });
 268  
 269                          // week view
 270                          $("#my-week-view").click(function() {
 271                              // change view to month view
 272                              $("#calendar").fullCalendar("changeView","agendaWeek");
 273                              view = $("#calendar").fullCalendar("getView");
 274                              // make all the views inactive except the one clicked
 275                              $(".myview").removeClass("fc-state-active");
 276                              $("#my-week-view").addClass("fc-state-active");
 277  
 278                              // update the title
 279                              $("#my-title").html(view.title);
 280                          });
 281  
 282                          // day view
 283                          $("#my-day-view").click(function() {
 284                              // change view to month view
 285                              $("#calendar").fullCalendar("changeView","agendaDay");
 286                              view = $("#calendar").fullCalendar("getView");
 287                              // make all the views inactive except the one clicked
 288                              $(".myview").removeClass("fc-state-active");
 289                              $("#my-day-view").addClass("fc-state-active");
 290  
 291                              // update the title
 292                              $("#my-title").html(view.title);
 293                          });
 294  
 295                      });
 296                      </script>
 297                      ';
 298  
 299  
 300          // the     buttons in the actions bar
 301                  if (!in_array($_GET['action'], array('myadd', 'myedit'))) {
 302                      $return .= '<table border="0" id="my-navigation">';
 303                      $return .= '<tr>';
 304                      $return .= '<td width="50%" id="my-fc-header-center">';
 305                      $return .= '            <center><h2 id="my-title" class="fc-header-title"></h2></center>';
 306                      $return .= '</td>';
 307                      $return .= '<td width="25%">';
 308                      $return .= '    <table border="0" id="my-fc-header-left" >';
 309                      $return .= '        <tr>';
 310                      $return .= '            <td><div id="my-prev-button" class="fc-button-prev fc-state-default fc-corner-left fc-no-right"><a><span>&nbsp;&#9668;&nbsp;</span></a></div></td>';
 311                      $return .= '            <td><div id="my-next-button" class="fc-button-next fc-state-default fc-corner-right"><a><span>&nbsp;&#9658;&nbsp;</span></a></div></td>';
 312                      $return .= '            <td><span class="fc-header-space"></span></td>';
 313                      $return .= '            <td><div id="my-today-button" class="fc-button-today fc-state-default fc-corner-left fc-corner-right fc-state-disabled"><a><span>'.get_lang('Today').'</span></a></div></td>';
 314                      $return .= '        </tr>';
 315                      $return .= '    </table>';
 316                      $return .= '</td>';
 317                      $return .= '<td width="25%">';
 318                      $return .= '    <table border="0" id="my-fc-header-right">';
 319                      $return .= '        <tr>';
 320                      $return .= '            <td><div id="my-month-view" class="myview fc-button-month fc-state-default fc-corner-left fc-no-right"><a><span>'.get_lang('MonthView').'</span></a></div></td>';
 321                      $return .= '            <td><div id="my-week-view" class="myview fc-button-agendaWeek fc-state-default fc-no-right"><a><span>'.get_lang('WeekView').'</span></a></div></td>';
 322                      $return .= '            <td><div id="my-day-view" class="myview fc-button-agendaDay fc-state-default fc-corner-right"><a><span>'.get_lang('DayView').'</span></a></div></td>';
 323                      $return .= '        </tr>';
 324                      $return .= '    </table>';
 325                      $return .= '</td>';
 326                      $return .= '</table>';
 327                  }
 328                  
 329      }
 330  
 331      switch ($_GET ['action']) {
 332          case 'myadd' :
 333              // return to the calendar display
 334              $return .= '<a href="myagenda.php">'.Display::return_icon('pixel.gif', get_lang('ReturnToCalendar'), array('class' => 'toolactionplaceholdericon toolactionback')).get_lang('ReturnToCalendar').'</a>';
 335              break;
 336          case 'myedit' :
 337              // return to the calendar display
 338              $return .= '<a href="myagenda.php">'.Display::return_icon('pixel.gif', get_lang('ReturnToCalendar'), array('class' => 'toolactionplaceholdericon toolactionback')).get_lang('ReturnToCalendar').'</a>';
 339              break;
 340          case '':
 341              // add an agenda
 342              if (api_get_setting('allow_personal_agenda') == 'true'){
 343                  $return .= '<a href="myagenda.php?action=myadd">'.Display::return_icon('pixel.gif', get_lang('AgendaAddPersonal'), array('class' => 'toolactionplaceholdericon toolcalendaraddevent')).get_lang('AgendaAddPersonal').'</a>';
 344              }
 345              break;
 346      }
 347  
 348      return $return;
 349  }
 350  
 351  /**
 352   * Display the links that appear in the action bar in the "My calendar"
 353   *
 354   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
 355   * @version june 2010
 356   */
 357  function platformcalendar_actions() {
 358      $return = '';
 359  
 360      // adding of agenda item
 361      $return .= '<a href="agenda.php?action=platformadd">'.Display::return_icon('pixel.gif', get_lang('AgendaAddPlatform'), array('class' => 'toolactionplaceholdericon toolcalendaraddevent')).get_lang('AgendaAddPlatform').'</a>';
 362      return $return;
 363  }
 364  
 365  /**
 366   * Action handling for adding, editing or exporting agenda items
 367   * Moving, deleting and changing the visibility is handled through ajax.php
 368   *
 369   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
 370   * @version june 2010
 371   */
 372  function handle_calendar_actions() {
 373      global $_course, $_user;
 374  
 375      // if group members can add events we have to retrieve the groups of the user
 376      if (api_get_setting('user_manage_group_agenda')=='true'){
 377          // Additional libraries
 378          require_once(api_get_path(LIBRARY_PATH).'groupmanager.lib.php');
 379          $group_memberships        = GroupManager::get_group_ids($_course['dbName'],$_user['user_id']);
 380      }
 381  
 382      switch ($_GET ['action']) {
 383          case 'add' :
 384              if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous() && api_is_allowed_to_session_edit(false,true) ) OR (api_get_setting('user_manage_group_agenda')=='true' AND !empty($group_memberships))){
 385                  show_agenda_form (array(),$_GET['date']);
 386              }
 387              break;
 388          case 'edit' :
 389              if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous() && api_is_allowed_to_session_edit(false,true) ) OR (api_get_setting('user_manage_group_agenda')=='true' AND !empty($group_memberships))){
 390                  $input_values = get_course_agenda_item ( $_GET ['id'] );
 391                  show_agenda_form ( $input_values );
 392              }
 393              break;
 394          case 'delete' :
 395              if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous() && api_is_allowed_to_session_edit(false,true) ) OR (api_get_setting('user_manage_group_agenda')=='true' AND !empty($group_memberships))){
 396                  delete_agenda_item($_GET['id']);
 397                  Display::display_confirmation_message(get_lang('AgendaDeleteSuccess'));
 398              }
 399              break;
 400          case 'show' :
 401              if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous() && api_is_allowed_to_session_edit(false,true) ) OR (api_get_setting('user_manage_group_agenda')=='true' AND !empty($group_memberships))){
 402                  // second parameter = current status
 403                  change_visibility_agenda_item((int)$_GET['id'],'invisible');
 404                  Display::display_confirmation_message(get_lang("VisibilityChanged"));
 405              }
 406              break;
 407          case 'hide' :
 408              if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous() && api_is_allowed_to_session_edit(false,true) ) OR (api_get_setting('user_manage_group_agenda')=='true' AND !empty($group_memberships))){
 409                  // second parameter = current status
 410                  change_visibility_agenda_item((int)$_GET['id'],'visible');
 411                  Display::display_confirmation_message(get_lang("VisibilityChanged"));
 412              }
 413              break;
 414          case 'detail' :
 415              display_detail($_GET['id'], $_GET['event_type']);
 416              break;
 417      }
 418  
 419      if (api_get_setting('calendar_google_import')=='true'){
 420          google_calendar_action_handling();
 421      }
 422  }
 423  
 424  function handle_header_calendar_actions(){
 425      switch ($_GET ['action']) {
 426          case 'export' :
 427              export_events('course',$_GET['id']);
 428              exit;
 429              break;
 430      }
 431  }
 432  
 433  /**
 434   * Action handling for adding, editing or exporting agenda items
 435   *
 436   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
 437   * @version june 2010
 438   */
 439  function handle_mycalendar_actions() {
 440      switch ($_GET ['action']) {
 441          case 'myadd' :
 442              if (api_get_setting('allow_personal_agenda') == 'true'){
 443                  show_myagenda_form (array(),$_GET['date']);
 444              }
 445              break;
 446          case 'myedit' :
 447              if (api_get_setting('allow_personal_agenda') == 'true'){
 448                  $input_values = get_myagenda_item ( $_GET ['id'] );
 449                  show_myagenda_form ( $input_values );
 450              }
 451              break;
 452      }
 453  }
 454  
 455  /**
 456   * Action handling for adding, editing or exporting agenda items
 457   *
 458   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
 459   * @version june 2010
 460   */
 461  function handle_platformcalendar_actions() {
 462      switch ($_GET ['action']) {
 463          case 'platformadd' :
 464              show_platformagenda_form (array(),$_GET['date']);
 465              break;
 466          case 'platformedit' :
 467              $input_values = get_platformagenda_item ( $_GET ['id'] );
 468              show_platformagenda_form ( $input_values );
 469              break;
 470      }
 471  }
 472  
 473  /**
 474   * Display the form to add an agenda
 475   *
 476   * @param array $input_values containing all the form information that has already been typed or that was already stored in the database (editing)
 477   *
 478   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
 479   * @version june 2010
 480   */
 481  function show_agenda_form($input_values,$date='') {
 482      global $_user, $_course;
 483  
 484      // initiate the object
 485      $form = new FormValidator ( 'new_agenda_item', 'post', $_SERVER ['REQUEST_URI'].'&op=new' );
 486  
 487      // the header for the form
 488      if ($_GET ['action'] == 'add') {
 489          $form->addElement ( 'header', '', get_lang ( 'AgendaAdd' ) );
 490      }
 491      if ($_GET ['action'] == 'edit') {
 492          $form->addElement ( 'header', '', get_lang ( 'AgendaEdit' ) );
 493      }
 494  
 495      // a hidden form with the id of the agenda item we are editing
 496      $form->addElement ( 'hidden', 'agenda_id', $input_values['agenda_id'], array('id' => 'agenda_id'));
 497  
 498      if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous() && api_is_allowed_to_session_edit(false,true) )){
 499          // The receivers: groups
 500          $course_groups = CourseManager::get_group_list_of_course(api_get_course_id(), intval($_SESSION['id_session']));
 501          foreach ( $course_groups as $key => $group ) {
 502              $receivers ['G' . $key] = '-G- ' . $group ['name'];
 503          }
 504          // The receivers: users
 505          $course_users = CourseManager::get_user_list_from_course_code(api_get_course_id(), intval($_SESSION['id_session']));
 506          foreach ( $course_users as $key => $user ) {
 507              $receivers ['U' . $key] = $user ['lastname'] . ' ' . $user ['firstname'];
 508          }
 509      } else {
 510          // if group members can add events we have to retrieve the groups of the user
 511          if (api_get_setting('user_manage_group_agenda')=='true' AND !api_is_allowed_to_edit(false,true)){
 512              // Additional libraries
 513              require_once(api_get_path(LIBRARY_PATH).'groupmanager.lib.php');
 514  
 515              // The receivers: groups (the user belongs to)
 516              $group_memberships        = GroupManager::get_selected_group_info_of_subscribed_groups($_course['dbName'],$_user['user_id'],array('g.id','name'));
 517              foreach ( $group_memberships as $key => $group ) {
 518                  $receivers ['G' . $group['id']] = '-G- ' . $group['name'];
 519              }
 520  
 521              // The receivers: other users of the groups (the user belongs to)
 522  
 523          }
 524      }
 525  
 526      $form->addElement ( 'receivers', 'send_to', get_lang ( 'VisibleFor' ), array ('receivers' => $receivers, 'receivers_selected' => '' ) );
 527  
 528      // Start Date
 529      $form->addElement ( 'datepicker', 'start_date', get_lang ( 'StartDate' ), array ('form_name' => 'new_agenda_item', 'id' => 'start_date', 'onchange' => 'update_enddate();' ) );
 530  
 531      // End date
 532      $form->addElement ( 'datepicker', 'end_date', get_lang ( 'EndDate' ), array ('form_name' => 'new_agenda_item', 'id' => 'end_date' ) );
 533  
 534      // The title
 535      $form->addElement ( 'text', 'title', get_lang ( 'Title' ), array ('maxlength' => '250', 'style' => 'width:600px', 'class' => 'focus' ) );
 536  
 537      // The message
 538      $form->addElement ( 'textarea', 'content', get_lang ( 'Text' ), 'rows="12" cols="83"');
 539  
 540      // the recurrence button
 541      //$form->addElement ( 'static', 'recurrence_image', null, '<span onclick="toggle_recurrency_form();" class="link_alike">' . Display::return_icon ( 'recurrence.png' ) . ' ' . get_lang ( 'Recurrence' ) . '</span>' );
 542  
 543      // the recurrency form elements
 544      $form->addElement ( 'html', '<div id="recurrency_form" style="display:none;">' );
 545      //$form->addElement('html','<div class="row"><div class="formw">');
 546      $form->addElement ( 'select', 'recurrency_frequency', get_lang ( 'Frequency' ), array ('once' => get_lang ( 'Once' ), 'daily' => get_lang ( 'Daily' ), 'weekly' => get_lang ( 'Weekly' ), 'monthly' => get_lang ( 'Monthly' ) ), array ('id' => 'recurrency_frequency' ) );
 547      //$form->addElement('html','</div></div>');
 548      $form->addElement ( 'html', '<div id="recurrency_form_detail" style="display:none;">' );
 549      $grp = array ();
 550      $grp [] = & $form->createElement ( 'static', null, null, get_lang ( 'Every' ) );
 551      $grp [] = & $form->createElement ( 'text', 'recurrency_repeat_every' );
 552      $grp [] = & $form->createElement ( 'static', null, null, '<span id="recurrency_repeat_every_timeperiod"></span>' );
 553      $form->addGroup ( $grp, 'recurrency_repeat', '', null, false );
 554      $grp = array ();
 555      $grp [] = & $form->createElement ( 'radio', 'recurrency_ends_on', '', get_lang ( 'After' ), 'recurrency_ends_after_times' );
 556      $grp [] = & $form->createElement ( 'text', 'recurrency_ends_after_times', '', array ('maxlength' => '2', 'size' => '2' ) );
 557      $grp [] = & $form->createElement ( 'static', null, null, get_lang ( 'Times' ) );
 558      $form->addGroup ( $grp, 'recurrency_ends', get_lang ( 'Ends' ), null, false );
 559      $grp = array ();
 560      $grp [] = & $form->createElement ( 'radio', 'recurrency_ends_on', '', get_lang ( 'On' ), 'recurrency_ends_on_date' );
 561      $grp [] = & $form->createElement ( 'datepicker', 'recurrency_ends_on_date', 'recurrency_ends_on_date', array ('form_name' => 'new_agenda_item', 'dateformat' => 'dFY', 'timeformat' => '' ) );
 562      $form->addGroup ( $grp, 'recurrency_ends2', '', null, false );
 563  
 564      $form->addElement ( 'html', '</div>' );
 565      $form->addElement ( 'html', '</div>' );
 566  
 567      // google calendar import
 568      if (api_get_setting('calendar_google_import')=='true'){
 569          google_calendar_form($form);
 570      }
 571  
 572      // export and delete
 573      if (!empty($input_values) AND api_get_setting('agenda_show_actions_on_edit')=='true')
 574      {
 575          $actions_on_edit .= '';
 576          $actions_on_edit .= '<a href="agenda.php?'.api_get_cidreq().'&action=export&amp;id='.$input_values['id'].'">'.Display :: return_icon('download_manager.gif', get_lang('IcalExport'),array('style'=>'vertical-align:middle')).' '.get_lang('IcalExport').'</a> ';
 577          $actions_on_edit .= '<a href="agenda.php?action=delete&amp;id='.$input_values['id'].'">'.Display :: return_icon('delete.png', get_lang('Delete'), array('onclick' => "javascript:if(!confirm('".addslashes(htmlentities(get_lang("ConfirmYourChoice")))."')) return false;",'style'=>'vertical-align:middle')).' '.get_lang('Delete').'</a>';
 578          //$form->addElement('static','test','',$actions_on_edit);
 579          $group='';
 580          $group[] =& HTML_QuickForm::createElement('static', 'test','test',$actions_on_edit,0);
 581  
 582          // The OK button
 583          $group[] =& HTML_QuickForm::createElement( 'style_submit_button', 'submit_agenda_item', get_lang ( 'SaveEvent' ) ,'class="save" style="margin-left:355px;"');
 584  
 585          $form->addGroup($group, 'formactions','', '&nbsp;');
 586      }
 587      else
 588      {
 589          // The OK button
 590          $form->addElement ( 'style_submit_button', 'submit_agenda_item', get_lang ( 'SaveEvent' ) ,'id="submit_agenda_item" class="save" style="margin-left:520px;"');
 591      }
 592  
 593  
 594                  //$return .= ';
 595  
 596      // The javascript for updating the end date
 597      $form->addElement ( 'html', "<script type=\"text/javascript\">
 598  			function toggle_recurrency_form(){
 599                  $('#recurrency_form').slideToggle();
 600              }
 601  
 602              $('#recurrency_frequency').change(function() {
 603                  // the value of the frequency
 604                  var tmp = $('#recurrency_frequency').val();
 605  
 606                  // if the frequency is not once we display the advanced form elements
 607                    if( tmp != 'once'){
 608                      $('#recurrency_form_detail').css('display','block');
 609  
 610                      // displaying the correct time period
 611                      if (tmp == 'daily'){
 612                          $('#recurrency_repeat_every_timeperiod').html('" . get_lang ( 'Days' ) . "');
 613                      }
 614                      if (tmp == 'weekly'){
 615                          $('#recurrency_repeat_every_timeperiod').html('" . get_lang ( 'Weeks' ) . "');
 616                      }
 617                      if (tmp == 'monthly'){
 618                          $('#recurrency_repeat_every_timeperiod').html('" . get_lang ( 'Months' ) . "');
 619                      }
 620                    } else {
 621                      $('#recurrency_form_detail').css('display','none');
 622                    }
 623              });
 624  
 625  			function update_enddate()
 626              {
 627                  var start_date_d = $('select[name=\'start_date\\[d\\]\']').val();
 628                  var start_date_F = $('select[name=\'start_date\\[F\\]\']').val();
 629                  var start_date_Y = $('select[name=\'start_date\\[Y\\]\']').val();
 630                  var start_date_H = $('select[name=\'start_date\\[H\\]\']').val();
 631                  var start_date_i = $('select[name=\'start_date\\[i\\]\']').val();
 632  
 633                  $('select[name=\'end_date\\[d\\]\']').val(start_date_d);
 634                  $('select[name=\'end_date\\[F\\]\']').val(start_date_F);
 635                  $('select[name=\'end_date\\[Y\\]\']').val(start_date_Y);
 636                  $('select[name=\'end_date\\[H\\]\']').val(parseInt(start_date_H) + 1);
 637                  $('select[name=\'end_date\\[i\\]\']').val(start_date_i);
 638              }
 639  
 640  
 641              </script>\n" );
 642  
 643      // The form values
 644      // Defaults
 645      // Time : should propose next hour and not NOW. For instance if I am 10h19, scroll should not propose to start 10h19 because few events start 10h19. Should propose 11h00. And end : should propose 12h00
 646      $current_hour = date ( 'H' );
 647      $current_hour = $current_hour + 1;
 648      if ($current_hour == 23) {
 649          $current_hour = 0;
 650      }
 651      $next_hour = $current_hour + 1;
 652      if ($next_hour == 23) {
 653          $next_hour = 0;
 654      }
 655  
 656      $defaults ['send_to'] ['receivers'] = 0;
 657      $defaults ['start_date'] = array ('d' => date ( 'd' ), 'F' => date ( 'm' ), 'Y' => date ( 'Y' ), 'H' => $current_hour, 'i' => 0 );
 658      $defaults ['end_date'] = array ('d' => date ( 'd' ), 'F' => date ( 'm' ), 'Y' => date ( 'Y' ), 'H' => ($next_hour), 'i' => 0 );
 659      $defaults ['recurrency_ends_on_date'] = array ('d' => date ( 'd' ), 'F' => date ( 'm' ), 'Y' => date ( 'Y' ), 'H' => $current_hour, 'i' => date ( 'i' ) );
 660      $defaults ['recurrency_repeat_every'] = 1;
 661  
 662      // When a item has to be added to a certain date
 663      if (!empty($date)) {
 664          $defaults ['start_date']['d'] = (int)substr($date,8,2);
 665          $defaults ['end_date']  ['d'] = (int)substr($date,8,2);
 666          $defaults ['start_date']['F'] = (int)substr($date,5,2);
 667          $defaults ['end_date']     ['F'] = (int)substr($date,5,2);
 668          $defaults ['start_date']['Y'] = (int)substr($date,0,4);
 669          $defaults ['end_date']  ['Y'] = (int)substr($date,0,4);
 670          if (substr($date,11,2) == '00' AND substr($date,14,2)=='00')
 671          {
 672              // add from month view => we use the current time
 673              $defaults ['start_date']['H'] = date ('H');
 674              $defaults ['end_date']  ['H'] = date('H',time()+(60*60));
 675              $defaults ['start_date']['i'] = date ('i');
 676              $defaults ['end_date']  ['i'] = date ('i');
 677          }
 678          else
 679          {
 680              $defaults ['start_date']['H'] = (int)substr($date,11,2);
 681              $defaults ['end_date']  ['H'] = (int)substr($date,11,2) + 1;
 682              $defaults ['start_date']['i'] = (int)substr($date,14,2);
 683              $defaults ['end_date']  ['i'] = (int)substr($date,14,2);
 684          }
 685      }
 686  
 687      // when we are editing we have to overwrite all this with the information form the event we are editing
 688      if (!empty($input_values))
 689      {
 690          $defaults = $input_values;
 691          if ($input_values['visibilty'] == 0){
 692              $defaults['send_to']['receivers'] = '-1';
 693          }
 694      }
 695  
 696      // The rules (required fields)
 697      $form->addRule ( 'title', get_lang ( 'ThisFieldIsRequired' ), 'required' );
 698      $form->addRule ( 'start_date', get_lang ( 'ThisFieldIsRequired' ), 'required' );
 699  
 700      // The validation or display
 701      if ($form->validate ()) {
 702          $values = $form->exportValues ();
 703          $values = $form->exportValues ();
 704                  $form_actions = $values['formactions'];
 705          if (isset ( $_POST ['submit_agenda_item'] ) || isset($form_actions['submit_agenda_item'])) {
 706              // store_agenda_item
 707              if (! $values ['agenda_id'] or ! is_numeric ( $values ['agenda_id'] )) {
 708                  $id = store_new_agenda_item ( $values );
 709                  //store_added_resources ( TOOL_CALENDAR_EVENT, $id );
 710              } else {
 711                  store_edit_agenda_item ( $values );
 712                  //update_added_resources ( TOOL_CALENDAR_EVENT, $values ['agenda_id'] );
 713              }
 714              Display::display_confirmation_message ( get_lang ( 'AgendaStored' ) );
 715              echo calendar_javascript();
 716          }
 717  
 718      } else {
 719          $form->setDefaults ($defaults);
 720          $form->display ();
 721  
 722          if ($defaults ['send_to'] ['receivers'] == 0 OR $defaults ['send_to'] ['receivers'] == '-1') {
 723              $js = "<script type=\"text/javascript\">/* <![CDATA[ */ receivers_hide('receivers_to'); /* ]]> */</script>\n";
 724          } else {
 725              $js = "<script type=\"text/javascript\">/* <![CDATA[ */ receivers_show('receivers_to'); /* ]]> */ </script>\n";
 726          }
 727          echo $js;
 728      }
 729  }
 730  
 731  /**
 732   * Enter description here...
 733   *
 734   * @param array $input_values containing all the form information that has already been typed (returning to
 735   * this page after coming from resourcelinker page or the recurrence page)
 736   * or that was already stored in the database (editing)
 737   *
 738   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
 739   * @version june 2010
 740   */
 741  function show_myagenda_form($input_values,$date='') {
 742      // initiate the object
 743      $form = new FormValidator ( 'new_myagenda_item', 'post', $_SERVER ['REQUEST_URI'] );
 744  
 745      // the header for the form
 746      if ($_GET ['action'] == 'myadd') {
 747          $form->addElement ( 'header', '', get_lang ( 'AgendaAdd' ) );
 748      }
 749      if ($_GET ['action'] == 'myedit') {
 750          $form->addElement ( 'header', '', get_lang ( 'AgendaEdit' ) );
 751      }
 752  
 753      // a hidden form with the id of the agenda item we are editing
 754      if ($input_values and is_numeric ( $input_values ['agenda_id'] )) {
 755          $form->addElement ( 'hidden', 'agenda_id', $input_values ['agenda_id'] );
 756      }
 757  
 758          // The receivers: users
 759          if ($_GET ['action'] == 'myadd') {
 760              $receivers = array();
 761              $user_table = Database::get_main_table(TABLE_MAIN_USER);
 762              $rs_users = Database::query("SELECT user_id, lastname, firstname FROM $user_table WHERE status <> ".ANONYMOUS." AND user_id <> ".api_get_user_id());
 763              if (Database::num_rows($rs_users) > 0) {
 764                  while ($row_users = Database::fetch_array($rs_users, 'ASSOC')) {
 765                      $receivers[$row_users['user_id']] = $row_users['lastname'] . ' ' . $row_users['firstname'];
 766                  }
 767              }
 768              $form->addElement ( 'receivers', 'send_to', get_lang ( 'VisibleFor' ), array ('receivers' => $receivers, 'receivers_selected' => '' ));
 769          }
 770      // Start Date
 771      $form->addElement ( 'datepicker', 'start_date', get_lang ( 'StartDate' ), array ('form_name' => 'new_agenda_item', 'id' => 'start_date', 'onchange' => 'update_enddate();' ) );
 772  
 773      // End date
 774      $form->addElement ( 'datepicker', 'end_date', get_lang ( 'EndDate' ), array ('form_name' => 'new_agenda_item', 'id' => 'end_date' ) );
 775  
 776      // The title
 777      $form->addElement ( 'text', 'title', get_lang ( 'Title' ), array ('maxlength' => '250', 'size' => '80', 'class' => 'focus' ) );
 778  
 779      // The message
 780      $form->addElement ( 'textarea', 'content', get_lang ( 'Text' ), 'rows="12" cols="90"');
 781  
 782      // the recurrence button
 783      //$form->addElement ( 'static', 'recurrence_image', null, '<span onclick="toggle_recurrency_form();" class="link_alike">' . Display::return_icon ( 'recurrence.png' ) . ' ' . get_lang ( 'Recurrence' ) . '</span>' );
 784  
 785      // the recurrency form elements
 786      $form->addElement ( 'html', '<div id="recurrency_form" style="display:none;">' );
 787      //$form->addElement('html','<div class="row"><div class="formw">');
 788      $form->addElement ( 'select', 'recurrency_frequency', get_lang ( 'Frequency' ), array ('once' => get_lang ( 'Once' ), 'daily' => get_lang ( 'Daily' ), 'weekly' => get_lang ( 'Weekly' ), 'monthly' => get_lang ( 'Monthly' ) ), array ('id' => 'recurrency_frequency' ) );
 789      //$form->addElement('html','</div></div>');
 790      $form->addElement ( 'html', '<div id="recurrency_form_detail" style="display:none;">' );
 791      $grp = array ();
 792      $grp [] = & $form->createElement ( 'static', null, null, get_lang ( 'Every' ) );
 793      $grp [] = & $form->createElement ( 'text', 'recurrency_repeat_every' );
 794      $grp [] = & $form->createElement ( 'static', null, null, '<span id="recurrency_repeat_every_timeperiod"></span>' );
 795      $form->addGroup ( $grp, 'recurrency_repeat', '', null, false );
 796      $grp = array ();
 797      $grp [] = & $form->createElement ( 'radio', 'recurrency_ends_on', '', get_lang ( 'After' ), 'recurrency_ends_after_times' );
 798      $grp [] = & $form->createElement ( 'text', 'recurrency_ends_after_times', '', array ('maxlength' => '2', 'size' => '2' ) );
 799      $grp [] = & $form->createElement ( 'static', null, null, get_lang ( 'Times' ) );
 800      $form->addGroup ( $grp, 'recurrency_ends', get_lang ( 'Ends' ), null, false );
 801      $grp = array ();
 802      $grp [] = & $form->createElement ( 'radio', 'recurrency_ends_on', '', get_lang ( 'On' ), 'recurrency_ends_on_date' );
 803      $grp [] = & $form->createElement ( 'datepicker', 'recurrency_ends_on_date', 'recurrency_ends_on_date', array ('form_name' => 'new_agenda_item', 'dateformat' => 'dFY', 'timeformat' => '' ) );
 804      $form->addGroup ( $grp, 'recurrency_ends2', '', null, false );
 805  
 806      $form->addElement ( 'html', '</div>' );
 807      $form->addElement ( 'html', '</div>' );
 808  
 809      // The OK button
 810      $form->addElement ( 'style_submit_button', 'submit_agenda_item', get_lang ( 'SaveEvent' ) ,'class="save" style="margin-left:520px;"');
 811  
 812      // The javascript for updating the end date
 813      $form->addElement ( 'html', "<script type=\"text/javascript\">
 814  			function toggle_recurrency_form(){
 815                  $('#recurrency_form').slideToggle();
 816              }
 817  
 818              $('#recurrency_frequency').change(function() {
 819                  // the value of the frequency
 820                  var tmp = $('#recurrency_frequency').val();
 821  
 822                  // if the frequency is not once we display the advanced form elements
 823                    if( tmp != 'once'){
 824                      $('#recurrency_form_detail').css('display','block');
 825  
 826                      // displaying the correct time period
 827                      if (tmp == 'daily'){
 828                          $('#recurrency_repeat_every_timeperiod').html('" . get_lang ( 'Days' ) . "');
 829                      }
 830                      if (tmp == 'weekly'){
 831                          $('#recurrency_repeat_every_timeperiod').html('" . get_lang ( 'Weeks' ) . "');
 832                      }
 833                      if (tmp == 'monthly'){
 834                          $('#recurrency_repeat_every_timeperiod').html('" . get_lang ( 'Months' ) . "');
 835                      }
 836                    } else {
 837                      $('#recurrency_form_detail').css('display','none');
 838                    }
 839              });
 840  
 841  			function update_enddate()
 842              {
 843                  var start_date_d = $('select[name=\'start_date\\[d\\]\']').val();
 844                  var start_date_F = $('select[name=\'start_date\\[F\\]\']').val();
 845                  var start_date_Y = $('select[name=\'start_date\\[Y\\]\']').val();
 846                  var start_date_H = $('select[name=\'start_date\\[H\\]\']').val();
 847                  var start_date_i = $('select[name=\'start_date\\[i\\]\']').val();
 848  
 849                  $('select[name=\'end_date\\[d\\]\']').val(start_date_d);
 850                  $('select[name=\'end_date\\[F\\]\']').val(start_date_F);
 851                  $('select[name=\'end_date\\[Y\\]\']').val(start_date_Y);
 852                  $('select[name=\'end_date\\[H\\]\']').val(parseInt(start_date_H) + 1);
 853                  $('select[name=\'end_date\\[i\\]\']').val(start_date_i);
 854              }
 855  
 856  
 857              </script>\n" );
 858  
 859      // The form values
 860      // Defaults
 861      $current_hour = date ( 'H' );
 862      $current_hour = $current_hour + 1;
 863      if ($current_hour == 23) {
 864          $current_hour = 0;
 865      }
 866      $next_hour = $current_hour + 1;
 867      if ($next_hour == 23) {
 868          $next_hour = 0;
 869      }
 870      $defaults ['send_to'] ['receivers'] = 0;
 871      $defaults ['start_date'] = array ('d' => date ( 'd' ), 'F' => date ( 'm' ), 'Y' => date ( 'Y' ), 'H' => $current_hour, 'i' => 0 );
 872      $defaults ['end_date'] = array ('d' => date ( 'd' ), 'F' => date ( 'm' ), 'Y' => date ( 'Y' ), 'H' => $next_hour, 'i' => 0 );
 873      $defaults ['recurrency_ends_on_date'] = array ('d' => date ( 'd' ), 'F' => date ( 'm' ), 'Y' => date ( 'Y' ), 'H' => $current_hour, 'i' => date ( 'i' ) );
 874  
 875      // When a item has to be added to a certain date
 876      if (!empty($date)) {
 877          $defaults ['start_date']['d'] = (int)substr($date,8,2);
 878          $defaults ['end_date']  ['d'] = (int)substr($date,8,2);
 879          $defaults ['start_date']['F'] = (int)substr($date,5,2);
 880          $defaults ['end_date']     ['F'] = (int)substr($date,5,2);
 881          $defaults ['start_date']['Y'] = (int)substr($date,0,4);
 882          $defaults ['end_date']  ['Y'] = (int)substr($date,0,4);
 883          $defaults ['start_date']['H'] = $_GET ['hour'];
 884          $defaults ['end_date']  ['H'] = $_GET ['hour'];
 885          $defaults ['start_date']['i'] = $_GET ['minute'];
 886          $defaults ['end_date']  ['i'] = $_GET ['minute'];
 887      }
 888  
 889      // when we are editing we have to overwrite all this with the information form the event we are editing
 890      if (!empty($input_values))
 891      {
 892          $defaults = $input_values;
 893      }
 894  
 895      // The rules (required fields)
 896      $form->addRule ( 'title', get_lang ( 'ThisFieldIsRequired' ), 'required' );
 897      $form->addRule ( 'start_date', get_lang ( 'ThisFieldIsRequired' ), 'required' );
 898  
 899      // The validation or display
 900      if ($form->validate ()) {
 901          $values = $form->exportValues ();
 902                  $check = Security::check_token('post');
 903                  if($check) {
 904                      if (isset ( $_POST ['submit_agenda_item'] )) {
 905                              // store_agenda_item
 906                              if (! $values ['agenda_id'] or ! is_numeric ( $values ['agenda_id'] )) {
 907                                  $saved = store_new_myagenda_item ( $values );
 908                              } else {
 909                                  $saved = store_edit_myagenda_item ( $values );
 910                              }
 911                              Display::display_confirmation_message ( get_lang ( 'AgendaStored' ) );
 912                              echo '<script>location.href="'.api_get_path(WEB_CODE_PATH).'calendar/myagenda.php";</script>';
 913                              //echo mycalendar_javascript();
 914                      }
 915                  } else {
 916                      //echo mycalendar_javascript();
 917                      echo '<script>location.href="'.api_get_path(WEB_CODE_PATH).'calendar/myagenda.php";</script>';
 918                  }
 919                  Security::clear_token();
 920      } else {
 921                  if (isset($_POST['submit'])) {
 922                          Security::clear_token();
 923                  }
 924                  $token = Security::get_token();
 925                  $form->addElement('hidden', 'sec_token');
 926                  $defaults['sec_token'] = $token;
 927              
 928          $form->setDefaults ($defaults);
 929          $form->display ();
 930      }
 931  }
 932  
 933  /**
 934   * Enter description here...
 935   *
 936   * @param array $input_values containing all the form information that has already been typed (returning to
 937   * this page after coming from resourcelinker page or the recurrence page)
 938   * or that was already stored in the database (editing)
 939   *
 940   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
 941   * @version june 2010
 942   */
 943  function show_platformagenda_form($input_values,$date='') {
 944      // initiate the object
 945      $form = new FormValidator ( 'new_myagenda_item', 'post', $_SERVER ['REQUEST_URI'] );
 946          $editor_config = array('ToolbarSet' => 'PortalNews', 'Width' => '97%', 'Height' => '300');
 947      // the header for the form
 948      if ($_GET ['action'] == 'add') {
 949          $form->addElement ( 'header', '', get_lang ( 'AgendaAdd' ) );
 950      }
 951      if ($_GET ['action'] == 'edit') {
 952          $form->addElement ( 'header', '', get_lang ( 'AgendaEdit' ) );
 953      }
 954  
 955      // a hidden form with the id of the agenda item we are editing
 956      if ($input_values and is_numeric ( $input_values ['agenda_id'] )) {
 957          $form->addElement ( 'hidden', 'agenda_id', $input_values ['agenda_id'] );
 958      }
 959  
 960      // Start Date
 961      $form->addElement ( 'datepicker', 'start_date', get_lang ( 'StartDate' ), array ('form_name' => 'new_agenda_item', 'id' => 'start_date', 'onchange' => 'update_enddate();' ) );
 962  
 963      // End date
 964      $form->addElement ( 'datepicker', 'end_date', get_lang ( 'EndDate' ), array ('form_name' => 'new_agenda_item', 'id' => 'end_date' ) );
 965  
 966      // The title
 967      $form->addElement ( 'text', 'title', get_lang ( 'Title' ), array ('maxlength' => '250', 'style' => 'width:450px', 'class' => 'focus' ) );
 968  
 969      // The message
 970      $form->addElement ( 'html_editor', 'content', get_lang ( 'Text' ),'style="vertical-align:middle"',$editor_config);
 971  
 972      // the recurrence button
 973      $form->addElement ( 'static', 'recurrence_image', null, '<span onclick="toggle_recurrency_form();" class="link_alike">' . Display::return_icon ( 'recurrence.png',get_lang ( 'Recurrence' )) . ' ' . get_lang ( 'Recurrence' ) . '</span>' );
 974  
 975      // the recurrency form elements
 976      $form->addElement ( 'html', '<div id="recurrency_form" style="display:none;">' );
 977      //$form->addElement('html','<div class="row"><div class="formw">');
 978      $form->addElement ( 'select', 'recurrency_frequency', get_lang ( 'Frequency' ), array ('once' => get_lang ( 'Once' ), 'daily' => get_lang ( 'Daily' ), 'weekly' => get_lang ( 'Weekly' ), 'monthly' => get_lang ( 'Monthly' ) ), array ('id' => 'recurrency_frequency' ) );
 979      //$form->addElement('html','</div></div>');
 980      $form->addElement ( 'html', '<div id="recurrency_form_detail" style="display:none;">' );
 981      $grp = array ();
 982      $grp [] = & $form->createElement ( 'static', null, null, get_lang ( 'Every' ) );
 983      $grp [] = & $form->createElement ( 'text', 'recurrency_repeat_every' );
 984      $grp [] = & $form->createElement ( 'static', null, null, '<span id="recurrency_repeat_every_timeperiod"></span>' );
 985      $form->addGroup ( $grp, 'recurrency_repeat', '', null, false );
 986      $grp = array ();
 987      $grp [] = & $form->createElement ( 'radio', 'recurrency_ends_on', '', get_lang ( 'After' ), 'recurrency_ends_after_times' );
 988      $grp [] = & $form->createElement ( 'text', 'recurrency_ends_after_times', '', array ('maxlength' => '2', 'size' => '2' ) );
 989      $grp [] = & $form->createElement ( 'static', null, null, get_lang ( 'Times' ) );
 990      $form->addGroup ( $grp, 'recurrency_ends', get_lang ( 'Ends' ), null, false );
 991      $grp = array ();
 992      $grp [] = & $form->createElement ( 'radio', 'recurrency_ends_on', '', get_lang ( 'On' ), 'recurrency_ends_on_date' );
 993      $grp [] = & $form->createElement ( 'datepicker', 'recurrency_ends_on_date', 'recurrency_ends_on_date', array ('form_name' => 'new_agenda_item', 'dateformat' => 'dFY', 'timeformat' => '' ) );
 994      $form->addGroup ( $grp, 'recurrency_ends2', '', null, false );
 995  
 996      $form->addElement ( 'html', '</div>' );
 997      $form->addElement ( 'html', '</div>' );
 998  
 999      // The OK button
1000      $form->addElement ( 'style_submit_button', 'submit_agenda_item', get_lang ( 'SaveEvent' ) ,'class="save" style="margin-left:520px;"');
1001  
1002      // The javascript for updating the end date
1003      $form->addElement ( 'html', "<script type=\"text/javascript\">
1004  			function toggle_recurrency_form(){
1005                  $('#recurrency_form').slideToggle();
1006              }
1007  
1008              $('#recurrency_frequency').change(function() {
1009                  // the value of the frequency
1010                  var tmp = $('#recurrency_frequency').val();
1011  
1012                  // if the frequency is not once we display the advanced form elements
1013                    if( tmp != 'once'){
1014                      $('#recurrency_form_detail').css('display','block');
1015  
1016                      // displaying the correct time period
1017                      if (tmp == 'daily'){
1018                          $('#recurrency_repeat_every_timeperiod').html('" . get_lang ( 'Days' ) . "');
1019                      }
1020                      if (tmp == 'weekly'){
1021                          $('#recurrency_repeat_every_timeperiod').html('" . get_lang ( 'Weeks' ) . "');
1022                      }
1023                      if (tmp == 'monthly'){
1024                          $('#recurrency_repeat_every_timeperiod').html('" . get_lang ( 'Months' ) . "');
1025                      }
1026                    } else {
1027                      $('#recurrency_form_detail').css('display','none');
1028                    }
1029              });
1030  
1031  			function update_enddate()
1032              {
1033                  var start_date_d = $('select[name=\'start_date\\[d\\]\']').val();
1034                  var start_date_F = $('select[name=\'start_date\\[F\\]\']').val();
1035                  var start_date_Y = $('select[name=\'start_date\\[Y\\]\']').val();
1036                  var start_date_H = $('select[name=\'start_date\\[H\\]\']').val();
1037                  var start_date_i = $('select[name=\'start_date\\[i\\]\']').val();
1038  
1039                  $('select[name=\'end_date\\[d\\]\']').val(start_date_d);
1040                  $('select[name=\'end_date\\[F\\]\']').val(start_date_F);
1041                  $('select[name=\'end_date\\[Y\\]\']').val(start_date_Y);
1042                  $('select[name=\'end_date\\[H\\]\']').val(start_date_H);
1043                  $('select[name=\'end_date\\[i\\]\']').val(start_date_i);
1044              }
1045  
1046  
1047              </script>\n" );
1048  
1049      // The form values
1050      // Defaults
1051      $current_hour = date ( 'H' );
1052      $current_hour = $current_hour + 1;
1053      if ($current_hour == 23) {
1054          $current_hour = 0;
1055      }
1056      $next_hour = $current_hour + 1;
1057      if ($next_hour == 23) {
1058          $next_hour = 0;
1059      }
1060      $defaults ['start_date'] = array ('d' => date ( 'd' ), 'F' => date ( 'm' ), 'Y' => date ( 'Y' ), 'H' => $current_hour, 'i' => date ( 'i' ) );
1061      $defaults ['end_date'] = array ('d' => date ( 'd' ), 'F' => date ( 'm' ), 'Y' => date ( 'Y' ), 'H' => $next_hour, 'i' => date ( 'i' ) );
1062      $defaults ['recurrency_ends_on_date'] = array ('d' => date ( 'd' ), 'F' => date ( 'm' ), 'Y' => date ( 'Y' ), 'H' => $current_hour, 'i' => date ( 'i' ) );
1063  
1064      // When a item has to be added to a certain date
1065      if (!empty($date)) {
1066          $defaults ['start_date']['d'] = (int)substr($date,8,2);
1067          $defaults ['end_date']  ['d'] = (int)substr($date,8,2);
1068          $defaults ['start_date']['F'] = (int)substr($date,5,2);
1069          $defaults ['end_date']     ['F'] = (int)substr($date,5,2);
1070          $defaults ['start_date']['Y'] = (int)substr($date,0,4);
1071          $defaults ['end_date']  ['Y'] = (int)substr($date,0,4);
1072          $defaults ['start_date']['H'] = Security::remove_XSS($_GET ['hour']);
1073          $defaults ['end_date']  ['H'] = Security::remove_XSS($_GET ['hour']) + 1;
1074          $defaults ['start_date']['i'] = Security::remove_XSS($_GET ['minute']);
1075          $defaults ['end_date']  ['i'] = Security::remove_XSS($_GET ['minute']);
1076      }
1077  
1078      // when we are editing we have to overwrite all this with the information form the event we are editing
1079      if (!empty($input_values))
1080      {
1081          $defaults = $input_values;
1082      }
1083  
1084      // The rules (required fields)
1085      $form->addRule ( 'title', get_lang ( 'ThisFieldIsRequired' ), 'required' );
1086      $form->addRule ( 'start_date', get_lang ( 'ThisFieldIsRequired' ), 'required' );
1087  
1088      // The validation or display
1089      if ($form->validate ()) {
1090          $values = $form->exportValues ();
1091  
1092          if (isset ( $_POST ['submit_agenda_item'] )) {
1093              // store_agenda_item
1094              if (! $values ['agenda_id'] or ! is_numeric ( $values ['agenda_id'] )) {
1095                  $id = store_new_platformagenda_item ( $values );
1096              } else {
1097                  store_edit_platformagenda_item ( $values );
1098              }
1099              Display::display_confirmation_message ( get_lang ( 'AgendaStored' ) );
1100          }
1101  
1102      } else {
1103          $form->setDefaults ( $defaults );
1104          $form->display ();
1105      }
1106  }
1107  
1108  /**
1109   * This function stores the Agenda Item in the table calendar_event and updates the item_property table also
1110   *
1111   * @return integer the id of the last added agenda item
1112   *
1113   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
1114   * @version june 2010
1115   */
1116  function store_new_agenda_item($values) {
1117      global $_course;
1118  
1119      // Database table definition
1120      $table_agenda = Database::get_course_table ( TABLE_AGENDA );
1121  
1122      // some filtering of the input data
1123      $title = strip_tags ( trim ( $values ['title'] ) ); // no html allowed in the title
1124      $content = trim ( $values ['content'] );
1125      $start_date = $values ['start_date'];
1126      $end_date = $values ['end_date'];
1127      //$start_date=(int)$_POST['fyear']."-".(int)$_POST['fmonth']."-".(int)$_POST['fday']." ".(int)$_POST['fhour'].":".(int)$_POST['fminute'].":00";
1128      //$end_date=(int)$_POST['end_fyear']."-".(int)$_POST['end_fmonth']."-".(int)$_POST['end_fday']." ".(int)$_POST['end_fhour'].":".(int)$_POST['end_fminute'].":00";
1129  
1130  
1131      // store in the table calendar_event
1132      $sql = "INSERT INTO " . $table_agenda . "
1133                              (title,content, start_date, end_date)
1134                              VALUES (
1135                                  '" . Database::escape_string ( $title ) . "',
1136                                  '" . Database::escape_string ( $content ) . "',
1137                                  '" . Database::escape_string ( $start_date ) . "',
1138                                  '" . Database::escape_string ( $end_date ) . "'
1139                                  )";
1140  
1141      $result = api_sql_query ( $sql, __FILE__, __LINE__ );
1142      $last_id = mysql_insert_id ();
1143  
1144      // store in item_property (visibility, insert_date, target users/groups, visibility timewindow, ...)
1145      store_item_property ( $values, $last_id, 'AgendaAdded' );
1146  
1147      // storing the resources
1148      //store_resources($_SESSION['source_type'],$last_id);
1149  
1150      // storing the recurrence
1151      do_recurrence ( $values );
1152  
1153      if (api_get_setting('calendar_google_import')=='true'){
1154          store_google($values, $last_id);
1155      }
1156  
1157      return $last_id;
1158  }
1159  
1160  /**
1161   * This function stores the Agenda Item in the table calendar_event and updates the item_property table also
1162   *
1163   * @return integer the id of the last added agenda item
1164   *
1165   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
1166   * @version june 2010
1167   */
1168  function store_new_myagenda_item($values) {
1169      global $_course, $_user;
1170  
1171      // Database table definition
1172      $table_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
1173  
1174      // some filtering of the input data
1175      $title = strip_tags ( trim ( $values ['title'] ) ); // no html allowed in the title
1176      $content = trim ( $values ['content'] );
1177      $start_date = $values ['start_date'];
1178      $end_date = $values ['end_date'];
1179  
1180          $affected_rows = 0;
1181          // first save the original event
1182          Database::query("INSERT INTO ".$table_agenda."(user, title, text, date, enddate)
1183                              VALUES (
1184                                          '" . intval($_user['user_id'])."',
1185                                  '" . Database::escape_string ( $title ) . "',
1186                                  '" . Database::escape_string ( $content ) . "',
1187                                  '" . Database::escape_string ( $start_date ) . "',
1188                                  '" . Database::escape_string ( $end_date ) . "'
1189                                          )");         
1190          $parent_event_id = Database::insert_id();
1191          $affected_rows += Database::affected_rows();
1192          // Now send the event to selected users
1193          if ($parent_event_id) {
1194              if (isset($values['send_to']['receivers'])) {
1195                  $receivers = intval($values['send_to']['receivers']);                
1196                  if ($receivers == 0) {                                        
1197                      $user_table = Database::get_main_table(TABLE_MAIN_USER);
1198                      $rs_users = Database::query("SELECT user_id FROM $user_table WHERE status <> ".ANONYMOUS." AND user_id <> ".api_get_user_id());
1199                      if (Database::num_rows($rs_users) > 0) {
1200                          while ($row_users = Database::fetch_array($rs_users, 'ASSOC')) {
1201                              Database::query("INSERT INTO ".$table_agenda."(user, title, text, date, enddate, parent_event_id)
1202                                              VALUES (
1203                                                          '" . intval($row_users['user_id'])."',
1204                                                          '" . Database::escape_string ($title) . "',
1205                                                          '" . Database::escape_string ($content) . "',
1206                                                          '" . Database::escape_string ($start_date) . "',
1207                                                          '" . Database::escape_string ($end_date) . "',
1208                                                          '".intval($parent_event_id)."'
1209                                                          )");
1210                              $affected_rows += Database::affected_rows();
1211  }
1212                      }
1213                  } else if ($receivers == 1) {
1214                       $users = $values['send_to']['to'];
1215                       if (!empty($users)) {
1216                          foreach ($users as $user_id) {
1217                              if (api_is_anonymous($user_id, true) || $user_id == $_user['user_id']) { continue; }                
1218                              Database::query("INSERT INTO ".$table_agenda."(user, title, text, date, enddate, parent_event_id)
1219                                                  VALUES (
1220                                                              '" . intval($user_id)."',
1221                                                              '" . Database::escape_string ($title) . "',
1222                                                              '" . Database::escape_string ($content) . "',
1223                                                              '" . Database::escape_string ($start_date) . "',
1224                                                              '" . Database::escape_string ($end_date) . "',
1225                                                              '".intval($parent_event_id)."'
1226                                                              )");
1227                              $affected_rows += Database::affected_rows();
1228                          }
1229                      }                                        
1230                  }                               
1231              }
1232          }           
1233      return $affected_rows;
1234  }
1235  
1236  /**
1237   * Enter description here...
1238   *
1239   * @param unknown_type $values
1240   * @todo consider moving this into the function for storing a new agenda item
1241   *
1242   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
1243   * @version june 2010
1244   */
1245  function store_edit_agenda_item($values) {
1246      // Database table definition
1247      $tbl_agenda = Database::get_course_table ( TABLE_AGENDA );
1248      $tbl_item_property = Database::get_course_table ( TABLE_ITEM_PROPERTY );
1249  
1250      // Step 1: we have to find the old item_property information of the item
1251      // This is needed because we do not want to lose when it was first inserted and by who
1252      $sql = "SELECT * FROM $tbl_item_property WHERE tool='" . Database::escape_string ( TOOL_CALENDAR_EVENT ) . "' AND ref='" . Database::escape_string ( $values ['agenda_id'] ) . "'";
1253      $result = api_sql_query ( $sql, __LINE__, __FILE__ );
1254      $old_itemproperty_info = mysql_fetch_assoc ( $result );
1255  
1256      // Step 2: updating the information in the calendar_event table
1257      $update_calendar_event_sql = "UPDATE $tbl_agenda SET
1258                                          title        = '" . Database::escape_string ( $values ['title'] ) . "',
1259                                          content        = '" . Database::escape_string ( $values ['content'] ) . "',
1260                                          start_date    = '" . Database::escape_string ( $values ['start_date'] ) . "',
1261                                          end_date    = '" . Database::escape_string ( $values ['end_date'] ) . "'
1262                                      WHERE id = '" . Database::escape_string ( $values ['agenda_id'] ) . "'";
1263      $result = api_sql_query ( $update_calendar_event_sql, __LINE__, __FILE__ );
1264  
1265      // Step 3: removing all the old entries for this agenda item from item_property
1266      $del_old_itemproperty_sql = "DELETE FROM $tbl_item_property WHERE tool='" . Database::escape_string ( TOOL_CALENDAR_EVENT ) . "' AND ref='" . Database::escape_string ( $values ['agenda_id'] ) . "'";
1267      $result = api_sql_query ( $del_old_itemproperty_sql, __LINE__, __FILE__ );
1268  
1269      // Step 4: updating the information in the item_property table
1270      store_item_property ( $values, $values ['agenda_id'], 'AgendaModified' );
1271  
1272      // storing the recurrence
1273      //do_recurrence ( $values );
1274  
1275      // Step 5: updating the information in the item_property table with the old item_property information
1276      // note: we can consider changing the function store_item_property so that it no longer uses api_item_property_update
1277      // but a (api_store_item_property) general function that receives all the field information (too, insert_user_id, insert_date, lastedit_date, ref, ...)
1278      // and stores it in the item_property table
1279      $sql = "UPDATE $tbl_item_property SET
1280                  insert_user_id    = '" . Database::escape_string ( $old_itemproperty_info ['insert_user_id'] ) . "',
1281                  insert_date        = '" . Database::escape_string ( $old_itemproperty_info ['insert_date'] ) . "'
1282              WHERE tool = '" . Database::escape_string ( TOOL_CALENDAR_EVENT ) . "' AND ref = '" . Database::escape_string ( $values ['agenda_id'] ) . "'";
1283      $result = api_sql_query ( $sql, __LINE__, __FILE__ );
1284  }
1285  
1286  /**
1287   * This function stores the Agenda Item in the table calendar_event and updates the item_property table also
1288   *
1289   * @return integer the id of the last added agenda item
1290   *
1291   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
1292   * @version june 2010
1293   */
1294  function store_edit_myagenda_item($values) {
1295      global $_course, $_user;
1296  
1297      // Database table definition
1298      $table_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
1299  
1300      // some filtering of the input data
1301      $title = strip_tags ( trim ( $values ['title'] ) ); // no html allowed in the title
1302      $content = trim ( $values ['content'] );
1303      $start_date = $values ['start_date'];
1304      $end_date = $values ['end_date'];
1305  
1306          $affected_rows = 0;
1307  
1308          // first edit the original event
1309      Database::query("UPDATE " . $table_agenda . " SET
1310                              title = '" . Database::escape_string ( $title ) . "',
1311                              `text` = '" . Database::escape_string ( $content ) . "',
1312                              `date` = '" . Database::escape_string ( $start_date ) . "',
1313                              enddate = '" . Database::escape_string ( $end_date ) . "'
1314                  WHERE id = " . intval( $values ['agenda_id'] )."
1315                          AND user = " . intval( $_user['user_id']));
1316          $affected_rows += Database::affected_rows();
1317  
1318          // now edit the copied messages
1319          Database::query("UPDATE " . $table_agenda . " SET
1320                              title = '" . Database::escape_string ( $title ) . "',
1321                              `text` = '" . Database::escape_string ( $content ) . "',
1322                              `date` = '" . Database::escape_string ( $start_date ) . "',
1323                              enddate = '" . Database::escape_string ( $end_date ) . "'
1324                          WHERE parent_event_id = " . intval( $values ['agenda_id'] ));
1325          $affected_rows += Database::affected_rows();
1326          
1327      // storing the recurrence
1328      do_recurrence ( $values , 'personal');
1329  
1330      return $affected_rows;
1331  }
1332  
1333  /**
1334   * This function stores the Agenda Item in the table calendar_event and updates the item_property table also
1335   *
1336   * @return integer the id of the last added agenda item
1337   *
1338   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
1339   * @version june 2010
1340   */
1341  function store_edit_platformagenda_item($values) {
1342      global $_course, $_user;
1343  
1344      // Database table definition
1345      $table_agenda = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
1346  
1347      // some filtering of the input data
1348      $title = strip_tags ( trim ( $values ['title'] ) ); // no html allowed in the title
1349      $content = trim ( $values ['content'] );
1350      $start_date = $values ['start_date'];
1351      $end_date = $values ['end_date'];
1352      //$start_date=(int)$_POST['fyear']."-".(int)$_POST['fmonth']."-".(int)$_POST['fday']." ".(int)$_POST['fhour'].":".(int)$_POST['fminute'].":00";
1353      //$end_date=(int)$_POST['end_fyear']."-".(int)$_POST['end_fmonth']."-".(int)$_POST['end_fday']." ".(int)$_POST['end_fhour'].":".(int)$_POST['end_fminute'].":00";
1354  
1355  
1356      // store in the table calendar_event
1357      $sql = "UPDATE " . $table_agenda . " SET
1358                              title = '" . Database::escape_string ( $title ) . "',
1359                              content = '" . Database::escape_string ( $content ) . "',
1360                              start_date = '" . Database::escape_string ( $start_date ) . "',
1361                              end_date = '" . Database::escape_string ( $end_date ) . "'
1362                  WHERE id = " . intval( $values ['agenda_id'] );
1363      $result = api_sql_query ( $sql, __FILE__, __LINE__ );
1364      $last_id = mysql_insert_id ();
1365  
1366      // storing the recurrence
1367      do_recurrence ( $values , 'platform');
1368  
1369      return $last_id;
1370  }
1371  
1372  function store_new_platformagenda_item ($values) {
1373      $tbl_platformagenda = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
1374  
1375      // store the platform event
1376      $sql = "INSERT INTO ".$tbl_platformagenda."
1377            (title,content, start_date, end_date)
1378            VALUES
1379            ('".Database::escape_string(strip_tags(trim($values['title'])))."','".Database::escape_string(trim($values['content']))."','".Database::escape_string($values['start_date'])."','".Database::escape_string($values['end_date'])."' )";
1380  
1381      $rs = Database::query($sql, __FILE__,__LINE__);
1382      $id = Database::get_last_insert_id();
1383  
1384      return $id;
1385  }
1386  
1387  /**
1388   * Enter description here...
1389   *
1390   * @param unknown_type $values
1391   * @param unknown_type $id
1392   * @param unknown_type $action_string
1393   *
1394   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
1395   * @version june 2010
1396   */
1397  function store_item_property($values, $id, $action_string) {
1398      global $_course;
1399      global $_user;
1400  
1401      if ($values ['send_to'] ['receivers'] == 0) {
1402          api_item_property_update ( $_course, TOOL_CALENDAR_EVENT, $id, $action_string, $_user ['user_id'], '', '', $start_visible, $end_visible );
1403      }
1404      if ($values ['send_to'] ['receivers'] == 1) {
1405          foreach ( $values ['send_to'] ['to'] as $key => $target ) {
1406              if (substr ( $target, 0, 1 ) == 'U') {
1407                  $user = substr ( $target, 1 );
1408                  api_item_property_update ( $_course, TOOL_CALENDAR_EVENT, $id, $action_string, $_user ['user_id'], '', $user, $start_visible, $end_visible );
1409                  //api_item_property_update($_course, $tool,                 $item_id,     $lastedit_type, $user_id,     $to_group_id = 0,     $to_user_id = NULL, $start_visible = 0, $end_visible = 0)
1410              }
1411              if (substr ( $target, 0, 1 ) == 'G') {
1412                  $group = substr ( $target, 1 );
1413                  api_item_property_update ( $_course, TOOL_CALENDAR_EVENT, $id, $action_string, $_user ['user_id'], $group, '', $start_visible, $end_visible );
1414              }
1415          }
1416      }
1417      if ($values ['send_to'] ['receivers'] == '-1') {
1418          // adding to everybody
1419          api_item_property_update ( $_course, TOOL_CALENDAR_EVENT, $id, $action_string, $_user ['user_id'], '', '', $start_visible, $end_visible );
1420          // making it invisible
1421          api_item_property_update($_course, TOOL_CALENDAR_EVENT, $id, 'invisible');
1422      }
1423  }
1424  
1425  /**
1426   * This function handles the actual recurrence.
1427   *
1428   * @param array $values the array containing all the information for the database (from the initial agenda item): title, content, start date, end date
1429   *
1430   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
1431   * @version may 2010
1432   */
1433  function do_recurrence($values, $type='course') {
1434      global $_course;
1435  
1436      // Table Definitions
1437      if ($type == 'course')
1438      {
1439          $tbl_agenda = Database::get_course_table ( TABLE_AGENDA );
1440      }
1441      elseif ($type == 'platform')
1442      {
1443          $tbl_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
1444      }
1445      elseif ($type == 'personal')
1446      {
1447          $tbl_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
1448      }
1449      $tbl_item_property = Database::get_course_table ( TABLE_ITEM_PROPERTY );
1450  
1451      if ($values['recurrency_frequency']<>'once') {
1452          if ($values ['recurrency_ends_on'] == 'recurrency_ends_after_times') {
1453              $counter = 1;
1454              while ( $counter < $values['recurrency_ends_after_times'] ) {
1455                  store_recurrence ( $values, $counter, $type);
1456                  $counter ++;
1457              }
1458          } elseif ($values ['recurrency_ends_on'] == 'recurrency_ends_on_date') {
1459              $counter = 1;
1460              $continue = true;
1461              while ( $continue == true ) {
1462                  // storing a recurrent agenda item
1463                  $last_id = store_recurrence ( $values, $counter, $type );
1464  
1465                  // checking if the recurrent agenda item is still OK
1466                  $sql = "SELECT * FROM $tbl_agenda WHERE id = '" . Database::escape_string ( $last_id ) . "'";
1467                  $result = api_sql_query ( $sql, __FILE__, __LINE__ );
1468                  $row = mysql_fetch_assoc ( $result );
1469  
1470                  if ($row ['start_date'] <= $values['recurrency_ends_on_date'].' 23:59:59') {
1471                      $continue = true;
1472                      $counter ++;
1473                  } else {
1474                      $sql = "DELETE FROM $tbl_agenda WHERE id = '" . Database::escape_string ( $last_id ) . "'";
1475                      $result = api_sql_query ( $sql, __FILE__, __LINE__ );
1476                      if ($type == 'course')
1477                      {
1478                          $sql = "DELETE FROM $tbl_item_property WHERE ref= '" . Database::escape_string ( $last_id ) . "' AND tool = '" . Database::escape_string ( TOOL_CALENDAR_EVENT ) . "'";
1479                          $result = api_sql_query ( $sql, __FILE__, __LINE__ );
1480                      }
1481                      $continue = false;
1482                  }
1483              }
1484              $counter ++;
1485          }
1486      }
1487  }
1488  
1489  
1490  /**
1491   * Enter description here...
1492   *
1493   * @param unknown_type $values
1494   * @param unknown_type $counter
1495   * @param string $type this determines if it is a course agenda item, a personal agenda item or a platform agenda item
1496   * @return unknown
1497   *
1498   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
1499   * @version may 2006
1500   */
1501  function store_recurrence($values, $counter, $type='course')
1502  {
1503      global $_user;
1504  
1505      // Table Definitions
1506      if ($type == 'course')
1507      {
1508          $tbl_agenda         = Database::get_course_table(TABLE_AGENDA);
1509      }
1510      elseif ($type == 'platform')
1511      {
1512          $tbl_agenda = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
1513      }
1514      elseif ($type == 'personal')
1515      {
1516          $tbl_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
1517      }
1518      $tbl_item_property    = Database::get_course_table(TABLE_ITEM_PROPERTY);
1519  
1520  
1521      if ($values['recurrency_frequency']=='daily')
1522      {
1523          $mysql_interval = 'INTERVAL '.$values['recurrency_repeat_every'] * $counter.' DAY';
1524      }
1525      if ($values['recurrency_frequency']=='weekly')
1526      {
1527          // MySQL >= 5.0.0
1528          //$mysql_interval = 'INTERVAL '.$values['recurrency_repeat_every'] * $counter.' DAY';
1529          // MySQL < 5.0.0
1530          $mysql_interval = 'INTERVAL '.$values['recurrency_repeat_every'] * $counter * 7 .' DAY';
1531      }
1532      if ($values['recurrency_frequency']=='monthly')
1533      {
1534          $mysql_interval = 'INTERVAL '.$values['recurrency_repeat_every'] * $counter.' MONTH';
1535      }
1536  
1537      // store in the table calendar_event
1538      $sql = "INSERT INTO ".$tbl_agenda."
1539              (title,content, start_date, end_date)
1540              VALUES
1541              ('".Database::escape_string(strip_tags(trim($values['title'])))."','".Database::escape_string(trim($values['content']))."', DATE_ADD('".$values['start_date']."', $mysql_interval), DATE_ADD('".$values['end_date']."', $mysql_interval) )";
1542      if ($type == 'personal')
1543      {
1544          $sql = "INSERT INTO ".$tbl_agenda."
1545                  (title,text, date, enddate, user)
1546                  VALUES
1547                  ('".Database::escape_string(strip_tags(trim($values['title'])))."','".Database::escape_string(trim($values['content']))."', DATE_ADD('".$values['start_date']."', $mysql_interval), DATE_ADD('".$values['end_date']."', $mysql_interval),".$_user['user_id'].")";
1548      }
1549      $result = api_sql_query($sql,__FILE__,__LINE__);
1550      $last_id=mysql_insert_id();
1551  
1552      // store in item_property (visibility, insert_date, target users/groups, visibility timewindow, ...)
1553      if ($type == 'course')
1554      {
1555          store_item_property($values, $last_id, 'AgendaAdded');
1556      }
1557  
1558      return $last_id;
1559  }
1560  
1561  /**
1562   * This function gets all the information about an agenda item
1563   *
1564   * @param unknown_type $agenda_id
1565   * @return unknown
1566   * @todo consider moving this to the itemmanager.lib.php and/or replace this by the function get_item_information
1567   *
1568   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
1569   * @version june 2006
1570   */
1571  function get_course_agenda_item($agenda_id) {
1572      // table definitions
1573      $tbl_agenda = Database::get_course_table ( TABLE_AGENDA );
1574      $tbl_item_property = Database::get_course_table ( TABLE_ITEM_PROPERTY );
1575  
1576      // The sql statement to get all the information of one particular event
1577      $sql = "SELECT
1578              agenda.*,
1579                  HOUR(agenda.start_date) as start_hour,
1580                  MINUTE(agenda.start_date) as start_minute,
1581                  DAYOFMONTH(agenda.start_date) AS start_day,
1582                  MONTH(agenda.start_date) AS start_month,
1583                  YEAR(agenda.start_date) AS start_year,
1584                  HOUR(agenda.end_date) as end_hour,
1585                  MINUTE(agenda.end_date) as end_minute,
1586                  DAYOFMONTH(agenda.end_date) AS end_day,
1587                  MONTH(agenda.end_date) AS end_month,
1588                  YEAR(agenda.end_date) AS end_year,
1589                  UNIX_TIMESTAMP(start_date) as start,
1590                  UNIX_TIMESTAMP(end_date) as end,
1591                  toolitemproperties.*
1592              FROM " . $tbl_agenda . " agenda, " . $tbl_item_property . " toolitemproperties
1593              WHERE `agenda`.`id` = `toolitemproperties`.`ref`
1594              AND `toolitemproperties`.`tool`='" . TOOL_CALENDAR_EVENT . "'
1595              AND `agenda`.`id`='" . Database::escape_string ( $agenda_id ) . "'";
1596      $result = Database::query ( $sql, __FILE__, __LINE__ );
1597      $return ['send_to'] ['receivers'] = 1;
1598      while ( $row = Database::fetch_array( $result, 'ASSOC' ) ) {
1599          $return ['id']                     = $row ['id'];
1600          if ($row ['to_group_id'] == '0' and $row ['to_user_id'] == null) {
1601              $return ['send_to'] ['receivers'] = 0;
1602          }
1603          if ($row ['to_group_id'] != null and $row ['to_group_id'] != '0') {
1604              $return ['send_to'] ['to'] [] = 'G' . $row ['to_group_id'];
1605          }
1606          if ($row ['to_user_id'] != null) {
1607              $return ['send_to'] ['to'] [] = 'U' . $row ['to_user_id'];
1608          }
1609          $return ['start_date'] ['d'] = $row ['start_day'];
1610          $return ['start_date'] ['F'] = $row ['start_month'];
1611          $return ['start_date'] ['Y'] = $row ['start_year'];
1612          $return ['start_date'] ['H'] = $row ['start_hour'];
1613          $return ['start_date'] ['i'] = $row ['start_minute'];
1614          $return ['end_date'] ['d'] = $row ['end_day'];
1615          $return ['end_date'] ['F'] = $row ['end_month'];
1616          $return ['end_date'] ['Y'] = $row ['end_year'];
1617          $return ['end_date'] ['H'] = $row ['end_hour'];
1618          $return ['end_date'] ['i'] = $row ['end_minute'];
1619          $return ['title']                 = $row ['title'];
1620          $return ['content']                 = $row ['content'];
1621          $return ['agenda_id']             = $row ['id'];
1622          $return ['start_full']             = $row['start'];
1623          $return ['start']                 = date('c',$row['start']);
1624          $return ['end_full']             = $row['end'];
1625          $return ['end']                 = date('c',$row['end']);
1626          $return ['type']                = 'course';
1627          $return ['visibility']            = $row['visibility'];
1628      }
1629      return $return;
1630  }
1631  
1632  /**
1633   *
1634   * Get the quiz events by the quiz ID
1635   * @param integer $quiz_id
1636   * @return array
1637   */
1638  function get_quiz_events_by_quiz_id ($quiz_id) {
1639      // table definitions
1640      $tbl_quiz = Database::get_course_table ( TABLE_QUIZ_TEST );
1641      // The sql statement to get all the information of one particular event
1642      $sql = "SELECT title,description,HOUR(start_time) as start_hour,
1643                  MINUTE(start_time) as start_minute,
1644                  DAYOFMONTH(start_time) AS start_day,
1645                  MONTH(start_time) AS start_month,
1646                  YEAR(start_time) AS start_year,
1647                  HOUR(end_time) as end_hour,
1648                  MINUTE(end_time) as end_minute,
1649                  DAYOFMONTH(end_time) AS end_day,
1650                  MONTH(end_time) AS end_month,
1651                  YEAR(end_time) AS end_year,UNIX_TIMESTAMP(start_time) as start,UNIX_TIMESTAMP(end_time) as end FROM $tbl_quiz WHERE session_id='".api_get_session_id()."' AND id='".Database::escape_string(Security::remove_XSS($quiz_id))."'";
1652      $result = Database::query ( $sql, __FILE__, __LINE__ );
1653  
1654      while ( $row = Database::fetch_array( $result, 'ASSOC' ) ) {
1655          $return ['start_date'] ['d'] = $row ['start_day'];
1656          $return ['start_date'] ['F'] = $row ['start_month'];
1657          $return ['start_date'] ['Y'] = $row ['start_year'];
1658          $return ['start_date'] ['H'] = $row ['start_hour'];
1659          $return ['start_date'] ['i'] = $row ['start_minute'];
1660          $return ['end_date'] ['d'] = $row ['end_day'];
1661          $return ['end_date'] ['F'] = $row ['end_month'];
1662          $return ['end_date'] ['Y'] = $row ['end_year'];
1663          $return ['end_date'] ['H'] = $row ['end_hour'];
1664          $return ['end_date'] ['i'] = $row ['end_minute'];
1665          $return ['title']                 = $row ['title'];
1666          $return ['content']                 = $row ['description'];
1667          $return ['agenda_id']             = $row ['id'];
1668          $return ['start_full']             = $row['start'];
1669          $return ['start']                 = date('c',strtotime($row['start']));
1670          $return ['end_full']             = $row['end'];
1671          $return ['end']                 = date('c',strtotime($row['end']));
1672          $return ['type']                = 'quiz';
1673          $return ['visibility']            = $row['visibility'];
1674      }
1675      return $return;
1676  }
1677  
1678  /**
1679   *
1680   * Get assignment events by assigment ID
1681   * @param integer $assignment_id
1682   * @return array
1683   */
1684  function get_assignment_events_by_assignment_id($assignment_id)
1685  {
1686      $events = array();
1687  
1688      // Database table definition
1689      $table_student_publication                 = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
1690      $table_student_publication_assignment    = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1691  
1692      $sql = "SELECT
1693                  student_publication.id     AS id,
1694                  student_publication.url AS title,student_publication.description,HOUR(student_publication.sent_date) as start_hour,
1695                  MINUTE(student_publication.sent_date) as start_minute,
1696                  DAYOFMONTH(student_publication.sent_date) AS start_day,
1697                  MONTH(student_publication.sent_date) AS start_month,
1698                  YEAR(student_publication.sent_date) AS start_year,
1699                  HOUR(student_publication_assignment.expires_on) as end_hour,
1700                  MINUTE(student_publication_assignment.expires_on) as end_minute,
1701                  DAYOFMONTH(student_publication_assignment.expires_on) AS end_day,
1702                  MONTH(student_publication_assignment.expires_on) AS end_month,
1703                  YEAR(student_publication_assignment.expires_on) AS end_year,
1704                  UNIX_TIMESTAMP(student_publication.sent_date) AS start,
1705                  UNIX_TIMESTAMP(student_publication_assignment.expires_on) AS end
1706              FROM $table_student_publication student_publication, $table_student_publication_assignment student_publication_assignment
1707              WHERE student_publication_assignment.add_to_calendar <> 0
1708              AND student_publication.id = student_publication_assignment.publication_id AND student_publication.id ='".Database::escape_string(Security::remove_XSS($assignment_id))."'";
1709  
1710      $result = Database::query ( $sql, __FILE__, __LINE__ );
1711  
1712      while ( $row = Database::fetch_array( $result, 'ASSOC' ) ) {
1713          $return ['start_date'] ['d'] = $row ['start_day'];
1714          $return ['start_date'] ['F'] = $row ['start_month'];
1715          $return ['start_date'] ['Y'] = $row ['start_year'];
1716          $return ['start_date'] ['H'] = $row ['start_hour'];
1717          $return ['start_date'] ['i'] = $row ['start_minute'];
1718          $return ['end_date'] ['d'] = $row ['end_day'];
1719          $return ['end_date'] ['F'] = $row ['end_month'];
1720          $return ['end_date'] ['Y'] = $row ['end_year'];
1721          $return ['end_date'] ['H'] = $row ['end_hour'];
1722          $return ['end_date'] ['i'] = $row ['end_minute'];
1723          $return ['title']                 = substr($row ['title'],1);
1724          $return ['content']                 = $row ['description'];
1725          $return ['agenda_id']             = $row ['id'];
1726          $return ['start_full']             = $row['start'];
1727          $return ['start']                 = date('c',strtotime($row['start']));
1728          $return ['end_full']             = $row['end'];
1729          $return ['end']                 = date('c',strtotime($row['end']));
1730          $return ['type']                = 'assignment';
1731          $return ['visibility']            = $row['visibility'];
1732      }
1733      return $return;
1734  }
1735  
1736  /**
1737   *
1738   * Get session events by session ID
1739   * @param integer $session_id
1740   * @return array
1741   */
1742  function get_session_events_by_session_id($session_id)
1743  {
1744      $events = array();
1745  
1746      // Database table definition
1747      $table_session                 = Database::get_main_table(TABLE_MAIN_SESSION);
1748  
1749      $sql = "SELECT session.id, session.name as title,HOUR(session.date_start) as start_hour,
1750                  MINUTE(session.date_start) as start_minute,
1751                  DAYOFMONTH(session.date_start) AS start_day,
1752                  MONTH(session.date_start) AS start_month,
1753                  YEAR(session.date_start) AS start_year,
1754                  HOUR(session.date_end) as end_hour,
1755                  MINUTE(session.date_end) as end_minute,
1756                  DAYOFMONTH(session.date_end) AS end_day,
1757                  MONTH(session.date_end) AS end_month,
1758                  YEAR(session.date_end) AS end_year,
1759                  UNIX_TIMESTAMP(session.date_start) as start, UNIX_TIMESTAMP(session.date_end) as end
1760          FROM $table_session session
1761          WHERE session.id = '".Database::escape_string($session_id)."'";
1762      $result = Database::query ( $sql, __FILE__, __LINE__ );
1763   
1764      while ( $row = Database::fetch_array( $result, 'ASSOC' ) ) {
1765          $return ['start_date'] ['d'] = $row ['start_day'];
1766          $return ['start_date'] ['F'] = $row ['start_month'];
1767          $return ['start_date'] ['Y'] = $row ['start_year'];
1768          $return ['start_date'] ['H'] = $row ['start_hour'];
1769          $return ['start_date'] ['i'] = $row ['start_minute'];
1770          $return ['end_date'] ['d'] = $row ['end_day'];
1771          $return ['end_date'] ['F'] = $row ['end_month'];
1772          $return ['end_date'] ['Y'] = $row ['end_year'];
1773          $return ['end_date'] ['H'] = $row ['end_hour'];
1774          $return ['end_date'] ['i'] = $row ['end_minute'];
1775          $return ['title']                 = $row ['title'];
1776          $return ['content']                 = $row ['description'];
1777          $return ['agenda_id']             = $row ['id'];
1778          $return ['start_full']             = $row['start'];
1779          $return ['start']                 = date('c',strtotime($row['start']));
1780          $return ['end_full']             = $row['end'];
1781          $return ['end']                 = date('c',strtotime($row['end']));
1782          $return ['type']                = 'session';
1783          $return ['visibility']            = $row['visibility'];
1784      }
1785      return $return;
1786  }
1787  
1788  /**
1789   * This function gets all the information about an agenda item
1790   *
1791   * @param unknown_type $agenda_id
1792   * @return unknown
1793   * @todo consider moving this to the itemmanager.lib.php and/or replace this by the function get_item_information
1794   *
1795   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
1796   * @version june 2006
1797   */
1798  function get_myagenda_item($agenda_id) {
1799      global $_user;
1800  
1801      // table definitions
1802      $tbl_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
1803  
1804      // The sql statement to get all the information of one particular
1805      $sql = "SELECT
1806              agenda.*,
1807                  HOUR(agenda.date) as start_hour,
1808                  MINUTE(agenda.date) as start_minute,
1809                  DAYOFMONTH(agenda.date) AS start_day,
1810                  MONTH(agenda.date) AS start_month,
1811                  YEAR(agenda.date) AS start_year,
1812                  HOUR(agenda.enddate) as end_hour,
1813                  MINUTE(agenda.enddate) as end_minute,
1814                  DAYOFMONTH(agenda.enddate) AS end_day,
1815                  MONTH(agenda.enddate) AS end_month,
1816                  YEAR(agenda.enddate) AS end_year
1817              FROM " . $tbl_agenda . " agenda
1818              WHERE `agenda`.`id`='" . Database::escape_string ( $agenda_id ) . "'
1819              AND user = ".intval($_user['user_id']);
1820      $result = api_sql_query ( $sql, __FILE__, __LINE__ );
1821      while ( $row = mysql_fetch_assoc ( $result ) ) {
1822          $return ['start_date'] ['d']     = $row ['start_day'];
1823          $return ['start_date'] ['F']     = $row ['start_month'];
1824          $return ['start_date'] ['Y']     = $row ['start_year'];
1825          $return ['start_date'] ['H']     = $row ['start_hour'];
1826          $return ['start_date'] ['i']     = $row ['start_minute'];
1827          $return ['end_date'] ['d']         = $row ['end_day'];
1828          $return ['end_date'] ['F']         = $row ['end_month'];
1829          $return ['end_date'] ['Y']         = $row ['end_year'];
1830          $return ['end_date'] ['H']         = $row ['end_hour'];
1831          $return ['end_date'] ['i']         = $row ['end_minute'];
1832          $return ['title']                 = $row ['title'];
1833          $return ['content']             = $row ['text'];
1834          $return ['agenda_id'] = $row ['id'];
1835      }
1836      return $return;
1837  }
1838  
1839  /**
1840   * This function gets all the information about an agenda item
1841   *
1842   * @param unknown_type $agenda_id
1843   * @return unknown
1844   * @todo consider moving this to the itemmanager.lib.php and/or replace this by the function get_item_information
1845   *
1846   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
1847   * @version june 2006
1848   */
1849  function get_platformagenda_item($agenda_id) {
1850      global $_user;
1851  
1852      // table definitions
1853      $tbl_agenda = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
1854  
1855      // The sql statement to get all the information of one particular
1856      $sql = "SELECT
1857              agenda.*,
1858                  HOUR(agenda.start_date) as start_hour,
1859                  MINUTE(agenda.start_date) as start_minute,
1860                  DAYOFMONTH(agenda.start_date) AS start_day,
1861                  MONTH(agenda.start_date) AS start_month,
1862                  YEAR(agenda.start_date) AS start_year,
1863                  HOUR(agenda.end_date) as end_hour,
1864                  MINUTE(agenda.end_date) as end_minute,
1865                  DAYOFMONTH(agenda.end_date) AS end_day,
1866                  MONTH(agenda.end_date) AS end_month,
1867                  YEAR(agenda.end_date) AS end_year
1868              FROM " . $tbl_agenda . " agenda
1869              WHERE `agenda`.`id`=" . intval( $agenda_id );
1870      $result = api_sql_query ( $sql, __FILE__, __LINE__ );
1871      while ( $row = mysql_fetch_assoc ( $result ) ) {
1872          $return ['start_date'] ['d']     = $row ['start_day'];
1873          $return ['start_date'] ['F']     = $row ['start_month'];
1874          $return ['start_date'] ['Y']     = $row ['start_year'];
1875          $return ['start_date'] ['H']     = $row ['start_hour'];
1876          $return ['start_date'] ['i']     = $row ['start_minute'];
1877          $return ['end_date'] ['d']         = $row ['end_day'];
1878          $return ['end_date'] ['F']         = $row ['end_month'];
1879          $return ['end_date'] ['Y']         = $row ['end_year'];
1880          $return ['end_date'] ['H']         = $row ['end_hour'];
1881          $return ['end_date'] ['i']         = $row ['end_minute'];
1882          $return ['title']                 = $row ['title'];
1883          $return ['content']             = $row ['content'];
1884          $return ['agenda_id']             = $row ['id'];
1885      }
1886      return $return;
1887  }
1888  
1889  /**
1890   * This is the function that deletes an agenda item.
1891   * The agenda item is no longer fycically deleted but the visibility in the item_property table is set to 2
1892   * which means that it is invisible for the student AND course admin. Only the platform administrator can see it.
1893   * This will in a later stage allow the platform administrator to recover resources that were mistakenly deleted
1894   * by the course administrator
1895   *
1896   * @param integer the id of the agenda item wa are deleting
1897   *
1898   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
1899   * @version june 2010
1900   */
1901  function delete_agenda_item($id)
1902  {
1903      global $_course, $_user;
1904      if (api_get_setting('calendar_google_import')=='true' AND strstr($id,'google_')){
1905          google_calendar_delete_event($id);
1906          return true;
1907      }
1908      if (api_is_allowed_to_edit(false,true)  OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()))
1909      {
1910          if (isset($_GET['id']) && $_GET['id'] && isset($_GET['action']) && $_GET['action']=="delete")
1911          {
1912              $id=(int)$id;
1913              api_item_property_update($_course,TOOL_CALENDAR_EVENT,$id,'delete',api_get_user_id());
1914          }
1915      }
1916  }
1917  
1918  /**
1919   * Delete a personal event. Contrary to the course events, the personal events are actually deleted from the database.
1920   *
1921   * @param $id integer the id of the personal event
1922   *
1923   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
1924   * @version june 2010
1925   */
1926  function delete_myagenda_item($id)
1927  {
1928      global $_user;
1929  
1930      // Database table definition
1931      $tbl_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
1932  
1933      $sql = "DELETE FROM $tbl_agenda WHERE id = ".intval($id)." AND user = ".intval($_user['user_id']);
1934      $result = api_sql_query ( $sql, __FILE__, __LINE__ );
1935  }
1936  
1937  /**
1938   * Delete a platform event. Contrary to the course events, the platform events are actually deleted from the database.
1939   *
1940   * @param $id integer the id of the platform event
1941   *
1942   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
1943   * @version june 2010
1944   */
1945  function delete_platformagenda_item($id)
1946  {
1947      global $_user;
1948  
1949      // Database table definition
1950      $tbl_agenda = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
1951          $sql = "DELETE FROM $tbl_agenda WHERE id = ".intval($id);
1952      $result = api_sql_query ( $sql, __FILE__, __LINE__ );
1953  }
1954  
1955  /**
1956   * Enter description here...
1957   *
1958   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
1959   * @version june 2010
1960   */
1961  function change_visibility_agenda_item($id,$current_status)
1962  {
1963      global $_course, $_user;
1964  
1965      if (api_is_allowed_to_edit(false,true)  OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()))
1966      {
1967          if (isset($_GET['id']) && $_GET['id'] && isset($_GET['action']) && $_GET['action']=="visibility")
1968          {
1969              $id=(int)$_GET['id'];
1970  
1971              if ($current_status == 'visible'){
1972                  return change_visibility(TOOL_CALENDAR_EVENT,$id,0);
1973              }
1974              else {
1975                  return change_visibility(TOOL_CALENDAR_EVENT,$id,1);
1976              }
1977          }
1978      }
1979  }
1980  
1981  /**
1982   * Enter description here...
1983   *
1984   * @author move_platformagenda_item
1985   * @version 
1986   */
1987  function move_platformagenda_item($id,$day_delta, $minute_delta)
1988  {
1989          // Database table definition
1990      $tbl_agenda = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
1991  
1992          // we convert the hour delta into minutes and add the minute delta
1993      $delta = ($day_delta * 60 * 24) + $minute_delta;
1994  
1995      $sql = "UPDATE $tbl_agenda SET start_date = DATE_ADD(start_date,INTERVAL $delta MINUTE), end_date = DATE_ADD(end_date,INTERVAL $delta MINUTE) WHERE id = ".intval($id);
1996      $result = api_sql_query ( $sql, __FILE__, __LINE__ );
1997  }
1998  
1999  /**
2000   * Enter description here...
2001   *
2002   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2003   * @version june 2010
2004   */
2005  function move_agenda_item($id,$day_delta, $minute_delta)
2006  {
2007      // table definitions
2008      $table_agenda = Database::get_course_table ( TABLE_AGENDA );
2009  
2010      // we convert the hour delta into minutes and add the minute delta
2011      $delta = ($day_delta * 60 * 24) + $minute_delta;
2012  
2013      $sql = "UPDATE $table_agenda SET start_date = DATE_ADD(start_date,INTERVAL $delta MINUTE), end_date = DATE_ADD(end_date,INTERVAL $delta MINUTE) WHERE id=".Database::escape_string($id);
2014          $result = api_sql_query ( $sql, __FILE__, __LINE__ );
2015  }
2016  
2017  /**
2018   * Enter description here...
2019   *
2020   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2021   * @version june 2010
2022   */
2023  function mymove_agenda_item($id,$day_delta, $minute_delta)
2024  {
2025      // table definitions
2026      $table_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
2027      // we convert the hour delta into minutes and add the minute delta
2028      $delta = ($day_delta * 60 * 24) + $minute_delta;
2029      Database::query("UPDATE $table_agenda SET `date` = DATE_ADD(date,INTERVAL $delta MINUTE), enddate = DATE_ADD(enddate,INTERVAL $delta MINUTE) WHERE id = ".intval($id));
2030          if (Database::affected_rows()) {
2031              Database::query("UPDATE $table_agenda SET `date` = DATE_ADD(date,INTERVAL $delta MINUTE), enddate = DATE_ADD(enddate,INTERVAL $delta MINUTE) WHERE parent_event_id = ".intval($id));
2032            }
2033  }
2034  
2035  /**
2036   * This functions swithes the visibility a course resource using the visible field in 'last_tooledit' values: 0 = invisible
2037   *
2038   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2039   * @version june 2010
2040   */
2041  function change_visibility($tool,$id,$visibility)
2042  {
2043      global $_course;
2044  
2045      // table definition
2046      $TABLE_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
2047  
2048      if ($visibility == 0)
2049      {
2050          $sql_visibility="UPDATE $TABLE_ITEM_PROPERTY SET visibility='0' WHERE tool='".Database::escape_string($tool)."' AND ref='".Database::escape_string($id)."'";
2051          api_item_property_update($_course,TOOL_CALENDAR_EVENT,$id,"invisible",api_get_user_id());
2052      }
2053      else
2054      {
2055          $sql_visibility="UPDATE $TABLE_ITEM_PROPERTY SET visibility='1' WHERE tool='".Database::escape_string($tool)."' AND ref='".Database::escape_string($id)."'";
2056          api_item_property_update($_course,TOOL_CALENDAR_EVENT,$id,"visible",api_get_user_id());
2057      }
2058  }
2059  
2060  /**
2061   * Enter description here...
2062   *
2063   * @author 
2064   * @version 
2065   */
2066  function resize_platformagenda_item($id,$day_delta, $minute_delta)
2067  {
2068      // table definitions
2069      $tbl_agenda = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
2070  
2071      // we convert the hour delta into minutes and add the minute delta
2072      $delta = ($day_delta * 60 * 24) + $minute_delta;
2073  
2074      $sql = "UPDATE $tbl_agenda SET end_date = DATE_ADD(end_date,INTERVAL $delta MINUTE) WHERE id=".Database::escape_string($id);
2075      $result = api_sql_query ( $sql, __FILE__, __LINE__ );
2076  }
2077  
2078  
2079  
2080  /**
2081   * Enter description here...
2082   *
2083   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2084   * @version July 2010
2085   */
2086  function resize_agenda_item($id,$day_delta, $minute_delta)
2087  {
2088      // table definitions
2089      $table_agenda = Database::get_course_table ( TABLE_AGENDA );
2090  
2091      // we convert the hour delta into minutes and add the minute delta
2092      $delta = ($day_delta * 60 * 24) + $minute_delta;
2093  
2094      $sql = "UPDATE $table_agenda SET end_date = DATE_ADD(end_date,INTERVAL $delta MINUTE) WHERE id=".Database::escape_string($id);
2095      $result = api_sql_query ( $sql, __FILE__, __LINE__ );
2096  }
2097  
2098  /**
2099   * Enter description here...
2100   *
2101   * @author Eric Marguin <e.marguin@webapart.fr>, Web à part, France
2102   * @version March 2011
2103   */
2104  function myresize_agenda_item($id,$day_delta, $minute_delta)
2105  {
2106      // table definitions
2107      $table_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
2108  
2109      // we convert the hour delta into minutes and add the minute delta
2110      $delta = ($day_delta * 60 * 24) + $minute_delta;
2111      Database::query("UPDATE $table_agenda SET enddate = DATE_ADD(enddate,INTERVAL $delta MINUTE) WHERE id=".intval($id)); 
2112          if (Database::affected_rows()) {
2113              Database::query("UPDATE $table_agenda SET enddate = DATE_ADD(enddate,INTERVAL $delta MINUTE) WHERE parent_event_id=".intval($id));
2114          }
2115  }
2116  
2117  /**
2118   * Get all the agenda items of the course. If no parameter $course_db is specified
2119   * we assume that we are already inside a course and use $_course
2120   *
2121   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2122   * @version june 2010
2123   */
2124  function get_course_agenda_items($course_db='', $coursecode, $full_information=false,$editable=true){
2125      global $_course, $_user;
2126  
2127      // variable initialisation
2128      $events = array();
2129  
2130      // Additional libraries
2131      require_once(api_get_path(LIBRARY_PATH).'groupmanager.lib.php');
2132  
2133      // Database table definitions
2134      if (empty($course_db)){
2135          if (!empty($_course)){
2136              $table_agenda             = Database::get_course_table(TABLE_AGENDA);
2137              $table_item_property    = Database::get_course_table(TABLE_ITEM_PROPERTY);
2138              $table_user             = Database::get_main_table(TABLE_MAIN_USER);
2139          } else    {
2140              return array();
2141          }
2142          $course_db = $_course['dbName'];
2143      } else{
2144          // Database table definition
2145          $table_agenda             = Database::get_course_table(TABLE_AGENDA,$course_db);
2146          $table_item_property    = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_db);
2147          $table_user             = Database::get_main_table(TABLE_MAIN_USER);
2148      }
2149  
2150      // get all the group memberships of the user
2151      if (api_is_allowed_to_edit(false,true)){
2152          //$group_memberships = '';
2153      } else {
2154          $group_memberships        = GroupManager::get_group_ids($_course['dbName'],$_user['user_id']);
2155          $group_memberships[]    = 0;
2156      }
2157  
2158      // session restriction
2159      $session_condition = intval($_SESSION['id_session'])==0 ? '' : ' AND agenda.session_id IN (0,'.intval($_SESSION['id_session']).') ';        
2160      if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda', $coursecode) == 'true' && !api_is_anonymous()))
2161      {
2162          // A.1. you are a course admin with a USER filter
2163          // => see only the messages of this specific user + the messages of the group (s)he is member of.
2164          if (!empty($_GET['user']))
2165          {
2166              if (is_array($group_memberships) && count($group_memberships)>0)
2167              {
2168                  $sql="SELECT
2169                      agenda.*, UNIX_TIMESTAMP(start_date) as start, UNIX_TIMESTAMP(end_date) as end, toolitemproperties.*
2170                      FROM ".$table_agenda." agenda, ".$table_item_property." toolitemproperties
2171                      WHERE agenda.id = toolitemproperties.ref
2172                      AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
2173                      AND    ( toolitemproperties.to_user_id=".Database::escape_string($_user['user_id'])." OR toolitemproperties.to_group_id IN (0, ".implode(", ", $group_memberships).") )
2174                      AND toolitemproperties.visibility='1'
2175                      $session_condition";
2176              }
2177              else
2178              {
2179                  $sql="SELECT
2180                      agenda.*, UNIX_TIMESTAMP(start_date) as start, UNIX_TIMESTAMP(end_date) as end, toolitemproperties.*
2181                      FROM ".$table_agenda." agenda, ".$table_item_property." toolitemproperties
2182                      WHERE agenda.id = toolitemproperties.ref
2183                      AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
2184                      AND ( toolitemproperties.to_user_id=".Database::escape_string($_user['user_id'])." OR toolitemproperties.to_group_id='0')
2185                      AND toolitemproperties.visibility='1'
2186                      $session_condition";
2187              }
2188          }
2189          // A.2. you are a course admin with a GROUP filter
2190          // => see only the messages of this specific group
2191          elseif (!empty($_GET['group']))
2192          {
2193              $sql="SELECT
2194                  agenda.*, UNIX_TIMESTAMP(start_date) as start, UNIX_TIMESTAMP(end_date) as end, toolitemproperties.*
2195                  FROM ".$table_agenda." agenda, ".$table_item_property." toolitemproperties
2196                  WHERE agenda.id = toolitemproperties.ref
2197                  AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
2198                  AND ( toolitemproperties.to_group_id='".Database::escape_string(Security::Remove_XSS($_GET['group']))."' OR toolitemproperties.to_group_id='0')
2199                  AND toolitemproperties.visibility='1'
2200                  $session_condition";
2201          }
2202          // A.3 you are a course admin without any group or user filter
2203          else
2204          {
2205              // A.3.a you are a course admin without user or group filter but WITH studentview
2206              // => see all the messages of all the users and groups without editing possibilities
2207              if ($_GET['isStudentView']=='true')
2208              {
2209                  $sql="SELECT
2210                      agenda.*, UNIX_TIMESTAMP(start_date) as start, UNIX_TIMESTAMP(end_date) as end, toolitemproperties.*
2211                      FROM ".$table_agenda." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
2212                      WHERE agenda.id = toolitemproperties.ref
2213                      AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
2214                      AND toolitemproperties.visibility<>'1'
2215                      $session_condition";
2216              }
2217              // A.3.b you are a course admin without user or group filter and WITHOUT studentview (= the normal course admin view)
2218              // => see all the messages of all the users and groups with editing possibilities
2219              else
2220              {
2221                  $sql="SELECT
2222                      agenda.*, UNIX_TIMESTAMP(start_date) as start, UNIX_TIMESTAMP(end_date) as end, toolitemproperties.*
2223                      FROM ".$table_agenda." agenda, ".$table_item_property." toolitemproperties
2224                      WHERE agenda.id = toolitemproperties.ref
2225                      AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
2226                      AND ( toolitemproperties.visibility='0' or toolitemproperties.visibility='1')
2227                      $session_condition";
2228              }
2229          }
2230  
2231      } //if (is_allowed_to_edit() OR( api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()))
2232  
2233      // B. you are a student
2234      else
2235      {
2236          if (is_array($group_memberships) and count($group_memberships)>0)
2237          {
2238              $sql="SELECT
2239                  agenda.*, UNIX_TIMESTAMP(start_date) as start, UNIX_TIMESTAMP(end_date) as end, toolitemproperties.*
2240                  FROM ".$table_agenda." agenda, ".$table_item_property." toolitemproperties
2241                  WHERE agenda.id = toolitemproperties.ref
2242                  AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
2243                  AND    ( toolitemproperties.to_user_id=".Database::escape_string($_user['user_id'])." OR toolitemproperties.to_group_id IN (0, ".implode(", ", $group_memberships).") )
2244                  AND toolitemproperties.visibility='1'
2245                  $session_condition";
2246          }
2247          else
2248          {
2249              if ($_user['user_id'])
2250              {
2251                  $sql="SELECT
2252                      agenda.*, UNIX_TIMESTAMP(start_date) as start, UNIX_TIMESTAMP(end_date) as end, toolitemproperties.*
2253                      FROM ".$table_agenda." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
2254                      WHERE agenda.id = toolitemproperties.ref
2255                      AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
2256                      AND ( toolitemproperties.to_user_id=".Database::escape_string($_user['user_id'])." OR toolitemproperties.to_group_id='0')
2257                      AND toolitemproperties.visibility='1'
2258                      $session_condition";
2259              }
2260              else
2261              {
2262                  $sql="SELECT
2263                      agenda.*, UNIX_TIMESTAMP(start_date) as start, UNIX_TIMESTAMP(end_date) as end, toolitemproperties.*
2264                      FROM ".$table_agenda." agenda, ".$table_item_property." toolitemproperties
2265                      WHERE agenda.id = toolitemproperties.ref
2266                      AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
2267                      AND toolitemproperties.to_group_id='0'
2268                      AND toolitemproperties.visibility='1'
2269                      $session_condition";
2270              }
2271          }
2272      } // you are a student
2273  
2274      // filter for the dates (if any)
2275      if (isset($_GET['start']) AND isset($_GET['end']) AND !empty($_GET['start']) AND !empty($_GET['end']))
2276      {
2277          $sql .= " AND start_date >= FROM_UNIXTIME(".$_GET['start'].")
2278                    AND start_date <= FROM_UNIXTIME(".$_GET['end'].")
2279                    ORDER BY start_date DESC";
2280      }
2281      else
2282      {
2283          $sql .= " ORDER BY start_date DESC";
2284      }
2285  
2286      $result=Database::query($sql,__FILE__,__LINE__) or die(Database::error());
2287  
2288      $events = array();
2289      while ($row=Database::fetch_array($result))
2290      {
2291          // additional classes depending on visibility
2292          if ($row['visibility'] == 0){
2293              $class_name = 'invisible courseagenda '.$coursecode;
2294          } else {
2295              $class_name = 'courseagenda '.$coursecode;
2296          }
2297  
2298          // if the course code is not empty we have to provide a link to the course
2299          if (!empty($coursecode)){
2300              $row['title'] = '<span class="'.$coursecode.'">'.$coursecode.' - '.$row['title'].'</span>';
2301          }
2302  
2303          // do we need to get all the information (list view) or only the information that is displayed in the fullcalendar views?
2304          if ($full_information)
2305          {
2306              // if the event already exists we only have to add the receivers without overwriting all the rest (or we lose the previously added receivers)
2307              if (key_exists($row['id'],$events))
2308              {
2309                  if ($row ['to_group_id'] != null and $row ['to_group_id'] != '0') {
2310                      $events[$row['id']] ['send_to'] ['to'] [] = 'G' . $row ['to_group_id'];
2311                  }
2312                  if ($row ['to_user_id'] != null) {
2313                      $events[$row['id']] ['send_to'] ['to'] [] = 'U' . $row ['to_user_id'];
2314                  }
2315              }
2316              else
2317              {
2318                  if ($row ['to_group_id'] == '0' and $row ['to_user_id'] == null) {
2319                      $row ['send_to'] ['receivers'] = 0;
2320                  }
2321                  if ($row ['to_group_id'] != null and $row ['to_group_id'] != '0') {
2322                      $row ['send_to'] ['to'] [] = 'G' . $row ['to_group_id'];
2323                  }
2324                  if ($row ['to_user_id'] != null) {
2325                      $row ['send_to'] ['to'] [] = 'U' . $row ['to_user_id'];
2326                  }
2327                  $row['start_full']     = $row['start'];
2328                  $row['start']         = date('c',$row['start']);
2329                  $row['end_full']     = $row['end'];
2330                  $row['end']         = date('c',$row['end']);
2331                  $row['allDay']         = false;
2332                  $row['className']     = $class_name;
2333                  $row['type']        = 'course';
2334                  $row['editable']    = $editable;
2335                  $events[$row['id']] = $row;
2336              }
2337          }
2338          else
2339          {                                            
2340                      $events[$row['id']] = array('id'=>'course_events'.$row['id'], 'title'=>htmlentities($row['title']), 'start'=>date('c',$row['start']), 'end'=>date('c',$row['start']), "allDay"=>false, 'visibility'=>$row['visibility'],'className'=>$class_name, 'type'=>'course', 'editable'=>$editable);
2341          }
2342      }
2343  
2344      return $events;
2345  }
2346  
2347  /**
2348   * get all the events that need to be displayed int he course calendar
2349   *
2350   * @param $coursedb the database of the course
2351   *
2352   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2353   * @version june 2010
2354   */
2355  function get_all_course_agenda_items($coursedb, $coursecode = null){
2356      global $_user;
2357        global $_course;
2358      // variable initialisation
2359      $events = array();
2360  
2361          if (!isset($coursecode)) {
2362              $coursecode = $_SESSION['sysCode'];
2363              if (empty($coursedb)) {
2364                      $coursedb = $_course['dbName'];
2365              }
2366          }
2367          
2368      // getting all the course events
2369          $editable = api_is_allowed_to_edit()?true:false;
2370          $course_events = get_course_agenda_items($coursedb, $coursecode, false, $editable);
2371          $events = array_merge($events,$course_events);
2372  
2373      // getting the platform events
2374      if (api_get_setting('calendar_types','platformevents') == 'true')
2375      {
2376          $platform_events = get_platform_agenda_items();
2377          $events = array_merge($events,$platform_events);
2378      }
2379  
2380      // getting the session events
2381      if (api_get_setting('calendar_types','sessionevents') == 'true')
2382      {
2383          $session_events = get_session_events($coursecode);
2384          $events = array_merge($events,$session_events);
2385      }
2386  
2387      // getting the quiz events
2388      if (api_get_setting('calendar_types','quizevents') == 'true')
2389      {
2390          $quiz_events = get_quiz_events($coursedb);
2391          $events = array_merge($events,$quiz_events);
2392  
2393      }
2394  
2395      // getting the assignment events
2396      $assignments_events = get_assignment_events($coursedb);
2397      $events = array_merge($events,$assignments_events);
2398  
2399      return $events;
2400  }
2401  
2402  /**
2403   * get the information of the sessions that are linked to this course
2404   *
2405   * @param $coursecode the (sys)code of the course
2406   *
2407   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2408   * @version august 2010
2409   */
2410  function get_session_events($coursecode){
2411      global $_course;
2412  
2413      if (empty($coursecode)){
2414          if (empty($_course)){
2415              return array();
2416          } else {
2417              $coursecode = $_course['sysCode'];
2418          }
2419      }
2420  
2421      // variable initialisation
2422      $events = array();
2423  
2424      // Database table definition
2425      $table_session                 = Database::get_main_table(TABLE_MAIN_SESSION);
2426      $table_session_rel_course     = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2427                  
2428      $sql = "SELECT session.id, session.name, UNIX_TIMESTAMP(session.date_start) as date_start, UNIX_TIMESTAMP(session.date_end) as date_end
2429          FROM $table_session session
2430          LEFT JOIN $table_session_rel_course sessioncourse ON session.id = sessioncourse.id_session
2431          WHERE sessioncourse.course_code = '".Database::escape_string($coursecode)."'";
2432      $result=Database::query($sql,__FILE__,__LINE__) or die(Database::error());
2433          
2434      while ($row=Database::fetch_array($result)) {
2435          //$events[] = array('id'=>'session'.$row['id'], 'title'=>htmlentities($row['name']), 'start'=>date('c',$row['date_start']), 'end'=>date('c',$row['date_end']), "allDay"=>false, 'visibility'=>'1','className'=>'session', 'editable' => false);
2436                  $events[] = array('id'=>'session'.$row['id'], 'title'=>htmlentities($row['name']), 'start'=>date('c',$row['date_start']), 'end'=>date('c',$row['date_start']), "allDay"=>false, 'visibility'=>'1','className'=>'session', 'editable' => false);
2437      }                
2438      return $events;
2439  }
2440  
2441  /**
2442   * get the information of the quizes of this course
2443   *
2444   * @param $coursecode the (sys)code of the course
2445   *
2446   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2447   * @version august 2010
2448   */
2449  function get_quiz_events($coursedb){
2450      global $_course;
2451  
2452      // variable initialisation
2453      $events = array();
2454  
2455      // Database table definition
2456      $table_quiz             = Database :: get_course_table(TABLE_QUIZ_TEST,$coursedb);
2457      $table_item_property     = Database :: get_course_table(TABLE_ITEM_PROPERTY,$coursedb);
2458  
2459  
2460      if (api_is_allowed_to_edit(false,true)){
2461          $sql = "SELECT quiz.id, quiz.title, UNIX_TIMESTAMP(quiz.start_time) as date_start, UNIX_TIMESTAMP(quiz.end_time) as end_start, item_property.visibility as visibilty
2462                  FROM $table_quiz quiz, $table_item_property item_property
2463                  WHERE item_property.tool= '".TOOL_QUIZ."'
2464                  AND item_property.ref=quiz.id
2465                  AND item_property.visibility <> '2'";
2466      } else {
2467          $sql = "SELECT quiz.id,quiz.title, UNIX_TIMESTAMP(quiz.start_time) as date_start, UNIX_TIMESTAMP(quiz.end_time) as end_start, item_property.visibility as visibilty
2468                  FROM $table_quiz quiz, $table_item_property item_property
2469                  WHERE item_property.tool= '".TOOL_QUIZ."'
2470                  AND item_property.ref=quiz.id
2471                  AND item_property.visibility = '1'";
2472      }
2473  
2474      // filter for the dates (if any)
2475      if (isset($_GET['start']) AND isset($_GET['end']) AND !empty($_GET['start']) AND !empty($_GET['end']))
2476      {
2477          $sql .= " AND start_time >= FROM_UNIXTIME(".$_GET['start'].")
2478                    AND start_time <= FROM_UNIXTIME(".$_GET['end'].")
2479                    ORDER BY start_time DESC";
2480      }
2481  
2482      $result=Database::query($sql,__FILE__,__LINE__) or die(Database::error());
2483      while ($row=Database::fetch_array($result))
2484      {
2485          //$events[] = array('id'=>'quiz'.$row['id'], 'title'=>htmlentities($row['title']), 'start'=>date('c',$row['date_start']), 'end'=>date('c',$row['date_end']), "allDay"=>false, 'visibility'=>$row['visiblity'],'className'=>'quiz', 'editable' => false);
2486                  $events[] = array('id'=>'quiz'.$row['id'], 'title'=>htmlentities($row['title']), 'start'=>date('c',$row['date_start']), 'end'=>date('c',$row['date_start']), "allDay"=>false, 'visibility'=>$row['visiblity'],'className'=>'quiz', 'editable' => false);
2487      }
2488  
2489      return $events;
2490  }
2491  
2492  function get_assignment_events($coursedb)
2493  {
2494      $events = array();
2495  
2496      // Database table definition
2497      $table_student_publication                 = Database :: get_course_table(TABLE_STUDENT_PUBLICATION,$coursedb);
2498      $table_student_publication_assignment    = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT,$coursedb);
2499  
2500      $sql = "SELECT
2501                  student_publication.id     AS id,
2502                  student_publication.url AS title,
2503                  UNIX_TIMESTAMP(student_publication.sent_date) AS date_start,
2504                  UNIX_TIMESTAMP(student_publication_assignment.expires_on) AS date_end
2505              FROM $table_student_publication student_publication, $table_student_publication_assignment student_publication_assignment
2506              WHERE student_publication_assignment.add_to_calendar <> 0
2507              AND student_publication.id = student_publication_assignment.publication_id";
2508  
2509      $result=Database::query($sql,__FILE__,__LINE__) or die(Database::error());
2510      while ($row=Database::fetch_array($result))
2511      {
2512          //$events[] = array('id'=>'assignment'.$row['id'], 'title'=>htmlentities(str_replace('/','',$row['title'])), 'start'=>date('c',$row['date_start']), 'end'=>date('c',$row['date_end']), "allDay"=>false, 'visibility'=>'1','className'=>'assignment', 'editable' => false);
2513                  $events[] = array('id'=>'assignment'.$row['id'], 'title'=>htmlentities(str_replace('/','',$row['title'])), 'start'=>date('c',$row['date_start']), 'end'=>date('c',$row['date_start']), "allDay"=>false, 'visibility'=>'1','className'=>'assignment', 'editable' => false);
2514      }
2515      //return array();
2516      return $events;
2517  }
2518  
2519  /**
2520   * get the platform events
2521   *
2522   * @param boolean $full_information should we get all the information or not
2523   * @param boolean $editable determines if the event is editable or not
2524   *
2525   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2526   * @version august 2010
2527   */
2528  function get_platform_agenda_items($full_information=false,$editable = false) {
2529      // variable initialisation
2530      $events = array();
2531  
2532      // table definition
2533      $tbl_main_agenda    = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
2534  
2535      $sql = "SELECT agenda.*, UNIX_TIMESTAMP(start_date) as start, UNIX_TIMESTAMP(end_date) as end
2536                  FROM $tbl_main_agenda agenda";
2537  
2538      // filter for the dates (if any)
2539      if (isset($_GET['start']) AND isset($_GET['end']) AND !empty($_GET['start']) AND !empty($_GET['end']))
2540      {
2541          $sql .= " WHERE start_date >= FROM_UNIXTIME(".Database::escape_string(Security::remove_XSS($_GET['start'])).")
2542                    AND start_date <= FROM_UNIXTIME(".Database::escape_string(Security::remove_XSS($_GET['end'])).")
2543                    ORDER BY start_date DESC";
2544      }
2545      else
2546      {
2547          $sql .= " ORDER BY start_date DESC";
2548      }
2549  
2550      $result=api_sql_query($sql,__FILE__,__LINE__);
2551  
2552      $events = array();
2553      while ($row=mysql_fetch_assoc($result))
2554      {
2555          if ($full_information)
2556          {
2557              $row['start_full']     = $row['start'];
2558              $row['start']         = date('c',$row['start']);
2559              $row['end_full']     = $row['end'];
2560              //$row['end']         = date('c',$row['end']);
2561                          $row['end']         = date('c',$row['start']);
2562              $row['allDay']         = false;
2563              $row['className']     = 'platform';
2564              $row['type']        = 'platform';
2565              $row['editable']    = $editable;
2566              $events[]             = $row;
2567          }
2568          else
2569          {
2570              //$events[] = array('id'=>'platform'.$row['id'], 'title'=>htmlentities($row['title']), 'start'=>date('c',$row['start']), 'end'=>date('c',$row['end']), "allDay"=>false, 'visibility'=>'1','className'=>'platform', 'editable'=>$editable);
2571                          $events[] = array('id'=>'platform'.$row['id'], 'title'=>htmlentities($row['title']), 'start'=>date('c',$row['start']), 'end'=>date('c',$row['start']), "allDay"=>false, 'visibility'=>'1','className'=>'platform', 'editable'=>$editable);
2572      }
2573      }
2574      return $events;
2575  }
2576  
2577  /**
2578   * get the personal events
2579   *
2580   * @param boolean $full_information should we get all the information or not
2581   *
2582   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2583   * @version august 2010
2584   */
2585  function get_personal_agenda_items($full_information=false) {
2586      global $_user;
2587  
2588      // variable initialisation
2589      $events = array();
2590  
2591      // table definition
2592      $tbl_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
2593  
2594      $sql = "SELECT agenda.*, UNIX_TIMESTAMP(date) as start, UNIX_TIMESTAMP(enddate) as end
2595                  FROM $tbl_agenda agenda
2596                  WHERE date >= FROM_UNIXTIME(".$_GET['start'].")
2597                  AND date <= FROM_UNIXTIME(".$_GET['end'].")
2598                  AND user = ".(int)Database::escape_string($_user['user_id']);
2599      $result=api_sql_query($sql,__FILE__,__LINE__);
2600  
2601      $events = array();
2602      while ($row=mysql_fetch_assoc($result))
2603      {
2604          if ($full_information)
2605          {
2606              $row['start_full']     = $row['start'];
2607              $row['start']         = date('c',$row['start']);
2608              $row['end_full']     = $row['end'];
2609              $row['end']         = date('c',$row['end']);
2610              $row['allDay']         = false;
2611              $row['className']     = $class_name;
2612              $row['type']        = 'course';
2613                          $row['parent_event_id'] =  isset($row['parent_event_id'])?intval($row['parent_event_id']):0;
2614                          $row['editable']    = !empty($row['parent_event_id'])?false:true;
2615              $events[$row['id']]     = $row;
2616          }
2617          else
2618          {
2619              $events[$row['id']] = array('id'=>'personal'.$row['id'], 'title'=>htmlentities($row['title']), 'start'=>date('c',$row['start']), 'end'=>date('c',$row['end']), "allDay"=>false, 'visibility'=>'1','className'=>'personal', 'parent_event_id' => isset($row['parent_event_id'])?intval($row['parent_event_id']):0, 'editable' => !empty($row['parent_event_id'])?false:true);
2620          }
2621      }
2622      return $events;
2623  }
2624  
2625  /**
2626   * Get all the agenda items: personal agenda items, platform agenda items and course agenda items
2627   * although the key of the separate types of events ($course_events, $personal_events and $platform_events)
2628   * all contain the id of the event they will not be overwritten thanks to a feature in the the array_merge function
2629   * http://be2.php.net/manual/en/function.array-merge.php
2630   * <quote>
2631   *         If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.
2632   *         If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
2633   *         If all of the arrays contain only numeric keys, the resulting array is given incrementing keys starting from zero.
2634   * </quote>
2635   *
2636   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2637   * @version june 2010
2638   */
2639  
2640  function get_all_agenda_items($full_information=false) {
2641      // getting all the courses that this user is subscribed to
2642      $courses = get_all_courses_of_user();
2643      if (!is_array($courses)) // this is for the special case if the user has no courses (otherwise you get an error)
2644      {
2645          $courses = array ();
2646      }
2647  
2648      // variable initialisation
2649      $events = array();
2650      // getting all the calendar events of the courses
2651          $course_events = array();
2652      foreach ($courses as $key=>$course){                        
2653              $course_events = get_all_course_agenda_items($course['db'], $course['code']);
2654              $events = array_merge($events,$course_events);
2655      }
2656          
2657      // getting the personal calendar events
2658      $personal_events = get_personal_agenda_items($full_information);
2659      $events = array_merge($events,$personal_events);
2660  
2661      // getting the platform agenda items
2662      $platform_events = get_platform_agenda_items($full_information,false);
2663      $events = array_merge($events,$platform_events);
2664  
2665      return $events;
2666  }
2667  
2668  /**
2669   * create output
2670   *
2671   * @param array $events the events of the calendar
2672   * @param string $output determines how the information should be outputted
2673   *
2674   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2675   * @version june 2010
2676   */
2677  function create_agenda_output($events,$output){
2678      switch($output){
2679          case 'json':
2680              echo json_encode($events);
2681              break;
2682          case 'list':
2683              echo list_output($events);
2684              break;
2685      }
2686  }
2687  
2688  /**
2689   * create the list output
2690   *
2691   * @param array $events the events of the calendar
2692   *
2693   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2694   * @version june 2010
2695   */
2696  function list_output($events)
2697  {
2698      ob_start();
2699  
2700      // Defining the months of the year to allow translation of the months. We use camelcase because these are arrays of language variables
2701      $MonthsLong = array (get_lang("JanuaryLong"), get_lang("FebruaryLong"), get_lang("MarchLong"), get_lang("AprilLong"), get_lang("MayLong"), get_lang("JuneLong"), get_lang("JulyLong"), get_lang("AugustLong"), get_lang("SeptemberLong"), get_lang("OctoberLong"), get_lang("NovemberLong"), get_lang("DecemberLong"));
2702  
2703      // defining the colors of the predefined types of events
2704      $color['course']     = 'red';
2705      $color['platform']    = '#FFCC00';
2706      $color['personal']     = 'green';
2707  
2708      // initialisation
2709      $oldmonth     = '';
2710      $oldyear     = '';
2711  
2712      // looping through the events
2713      foreach ($events as $key=>$event)
2714      {
2715          // all the information about the start date
2716          $year         = substr($event['start'],0,4);
2717          $month         = substr($event['start'],5,2);
2718          $day         = substr($event['start'],0,4);
2719          $hour        = substr($event['start'],0,4);
2720          $minutes    = substr($event['start'],0,4);
2721  
2722          // initiate the object
2723          $form = new FormValidator ( 'new_agenda_item', 'post', $_SERVER ['REQUEST_URI'] );
2724          $form->addElement ( 'static', 'start_date', get_lang ( 'StartDate' ),'<strong>'.agenda_date($event,'start').'</strong>');
2725          $form->addElement ( 'static', 'end_date', get_lang ( 'EndDate' ),'<strong>'.agenda_date($event,'end').'</strong>');
2726          $form->addElement ( 'static', 'title', get_lang ( 'Title' ), $event['title']);
2727          $form->addElement ( 'static', 'content', get_lang ( 'Text' ), text_filter(strip_tags($event['content'])));
2728  
2729          // Event action icons
2730          if (api_is_allowed_to_edit() OR $event['type'] == 'personal')
2731          {
2732              if ($event['type'] == 'personal')
2733              {
2734                  $action_edit = 'editpersonal';
2735                  $action_delete = 'deletepersonal';
2736              }
2737              else
2738              {
2739                  $action_edit = 'edit';
2740                  $action_delete = 'delete';
2741              }
2742  
2743              if ($event['type'] <> 'platform')
2744              {
2745                  $actionicons .= '<a href="agenda.php?action='.$action_edit.'&amp;id='.$event['id'].'&amp;view=list&amp;reverse='.$_GET['reverse'].'">'.Display :: return_icon('edit.png', get_lang('Edit')).'</a>';
2746                  $actionicons .= '<a href="agenda.php?action='.$action_delete.'&amp;id='.$event['id'].'&amp;view=list&amp;reverse='.$_GET['reverse'].'">'.Display :: return_icon('delete.png', get_lang('Delete'), array('onclick' => "javascript:if(!confirm('".addslashes(htmlentities(get_lang("ConfirmYourChoice")))."')) return false;")).'</a>';
2747                  if ($event['type'] <> 'personal')
2748                  {
2749                      if ($event['visibility']=='1')
2750                      {
2751                          $actionicons .= '<a href="agenda.php?action=hide&amp;id='.$event['id'].'&amp;view='.$_GET['view'].'&amp;reverse='.$_GET['reverse'].'">'.Display :: return_icon('visible.gif', get_lang('Visible'),array('class'=>'visibility')).'</a>';
2752                      }
2753                      else
2754                      {
2755                          $actionicons .= '<a href="agenda.php?action=show&amp;id='.$event['id'].'&amp;view='.$_GET['view'].'&amp;reverse='.$_GET['reverse'].'">'.Display :: return_icon('invisible.gif', get_lang('Invisible'),array('class'=>'visibility')).'</a>';
2756                      }
2757                  }
2758              }
2759          }
2760          $actionicons .= '<a href="agenda.php?'.api_get_cidreq().'&action=export&amp;id='.$event['id'].'">'.Display :: return_icon('download_manager.gif', get_lang('IcalExport')).' '.get_lang('IcalExport').'</a>';
2761          $form->addElement ( 'static', 'actionicons', '', $actionicons);
2762  
2763  
2764          $form->display();
2765      }
2766      $return = ob_get_contents();
2767      ob_end_clean();
2768  
2769      return $return;
2770  }
2771  
2772  function agenda_date($event,$startend){
2773          if (!is_array($event[$startend.'_date']))
2774          {
2775              // happens when information is retrieved from get_course_agena_itemS()
2776              $return .= $event[$startend.'_date'];
2777          }
2778          else
2779          {
2780              // happens when information is retrieved from get_course_agenda_item() (intended for filling the edit form)
2781              $return .= date('Y-m-d H:i:s',$event[$startend.'_full']);
2782          }
2783      return $return;
2784  }
2785  
2786  /**
2787   * This function finds all the courses (also those of sessions) of the user and returns an array containing the
2788   * database name of the courses.
2789   * @author Noel Dieschburg <noel.dieschburg@dokeos.com>
2790   * @todo there is probably a better function in course.lib.php
2791   */
2792  function get_all_courses_of_user()
2793  {
2794          global $_user;
2795  
2796          // Database table definition
2797          $tbl_course                 = Database :: get_main_table(TABLE_MAIN_COURSE);
2798          $tbl_course_user             = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
2799          $tbl_session_course         = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
2800          $tbl_session_course_user    = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2801          $tbl_session                = Database :: get_main_table(TABLE_MAIN_SESSION);
2802  
2803  
2804          $sql_select_courses = "SELECT c.code k, c.visual_code  vc, c.title i, c.tutor_name t,
2805                                        c.db_name db, c.directory dir, '5' as status
2806                                  FROM $tbl_course c, $tbl_session_course_user srcu
2807                                  WHERE srcu.id_user='".$_user['user_id']."'
2808                                  AND c.code=srcu.course_code
2809                                  UNION
2810                                 SELECT c.code k, c.visual_code  vc, c.title i, c.tutor_name t,
2811                                        c.db_name db, c.directory dir, cru.status status
2812                                  FROM $tbl_course c, $tbl_course_user cru
2813                                  WHERE cru.user_id='".Database::escape_string($_user['user_id'])."'
2814                                  AND c.code=cru.course_code";
2815          $result = Database::query($sql_select_courses);
2816          while ($row = Database::fetch_array($result))
2817          {
2818                  $courses[] = array ('db' => $row['db'], 'code' => $row['k'], 'visual_code' => $row['vc'], 'title' => $row['i'], 'directory' => $row['dir'], 'status' => $row['status']);
2819          }
2820          return $courses;
2821   }
2822  
2823  /**
2824   * export the events to the ical format
2825   *
2826   * @param string $content determines what has to be exported (personal events, platform events, course events)
2827   * @param string $id (optionally) which event has to be exported
2828   *
2829   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2830   * @version june 2010
2831   */
2832  function export_events($content,$id)
2833  {
2834      global $_course, $_user;
2835  
2836      include_once ('ical/class.iCal.inc.php');
2837  
2838      // variable initialisation
2839      $events = array();
2840  
2841      // exporting the course events
2842      if ($content == 'course' AND !empty($_course))
2843      {
2844          if (empty($id))
2845          {
2846              $events = get_course_agenda_items('','', true);
2847          }
2848          else
2849          {
2850              $events[] = get_course_agenda_item($id);
2851          }
2852      }
2853  
2854      // exporting the personal events
2855      if ($content == 'personal')
2856      {
2857          if (empty($id))
2858          {
2859              $events = get_personal_agenda_items(true);
2860          }
2861      }
2862  
2863      // exporting the platform events
2864      if ($content == 'platform')
2865      {
2866          if (empty($id))
2867          {
2868              $events = get_platform_agenda_items(true);
2869          }
2870      }
2871  
2872      // exporting the platform events
2873      if ($content == 'all')
2874      {
2875          $events = get_all_agenda_items(true);
2876      }
2877  
2878      $iCal = (object) new iCal('', 0, ''); // (ProgrammID, Method (1 = Publish | 0 = Request), Download Directory)
2879  
2880      foreach ($events as $key=>$event)
2881      {
2882          $iCal->addEvent(
2883                          '', // Organizer
2884                          (int)$event['start_full'], // Start Time (timestamp; for an allday event the startdate has to start at YYYY-mm-dd 00:00:00)
2885                          (int)$event['end_full'], // End Time (write 'allday' for an allday event instead of a timestamp)
2886                          '', // Location
2887                          0, // Transparancy (0 = OPAQUE | 1 = TRANSPARENT)
2888                          '', // Array with Strings
2889                          $event['content'], // Description
2890                          $event['title'], // Title
2891                          0, // Class (0 = PRIVATE | 1 = PUBLIC | 2 = CONFIDENTIAL)
2892                          '', // Array (key = attendee name, value = e-mail, second value = role of the attendee [0 = CHAIR | 1 = REQ | 2 = OPT | 3 =NON])
2893                          5, // Priority = 0-9
2894                          0, // frequency: 0 = once, secoundly - yearly = 1-7
2895                          10, // recurrency end: ('' = forever | integer = number of times | timestring = explicit date)
2896                          '', // Interval for frequency (every 2,3,4 weeks...)
2897                          '', // Array with the number of the days the event accures (example: array(0,1,5) = Sunday, Monday, Friday
2898                          0, // Startday of the Week ( 0 = Sunday - 6 = Saturday)
2899                          '', // exeption dates: Array with timestamps of dates that should not be includes in the recurring event
2900                          '',  // Sets the time in minutes an alarm appears before the event in the programm. no alarm if empty string or 0
2901                          1, // Status of the event (0 = TENTATIVE, 1 = CONFIRMED, 2 = CANCELLED)
2902                          'http://minerva.ugent.be', // optional URL for that event
2903                          'en', // Language of the Strings
2904                          'Minerva.ugent.be/'.$event['type'].'/'.$_course['code'].'/'.$event['id'] // Optional UID for this event
2905                         );
2906      }
2907      //debug($events);
2908      //debug($iCal);
2909      $iCal->outputFile('ics'); // output file as ics (xcs and rdf possible)
2910  }
2911  
2912  /**
2913   * Display the detail view of an event
2914   *
2915   * @param integer $resouce_id the id of the resource "quiz,assignment,agenda..." that has to be displayed
2916   * @param string $event_type the type of event "quiz,assignment,session,platform,course event" that has to be displayed
2917   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2918   * @author Isaac flores <florespaz_isaac@hotmail.com>
2919   * @version june 2010
2920   */
2921  function display_detail($resouce_id, $event_type)
2922  {       // We display the event detail here
2923          switch ($event_type) {
2924            case 'course_events':
2925          $event = get_course_agenda_item($resouce_id);
2926              break;
2927            case 'quiz':
2928          $event = get_quiz_events_by_quiz_id($resouce_id);
2929              break;
2930            case 'assignment':
2931          $event = get_assignment_events_by_assignment_id($resouce_id);
2932              break;
2933            case 'session':
2934          $event = get_session_events_by_session_id($resouce_id);
2935              break;
2936            case 'platform':
2937          $event = get_platformagenda_item($resouce_id);
2938              break;
2939             default :
2940               $event = array();
2941          }
2942  
2943      // getting the user information and group information if neccessary
2944      if ($event['send_to'] ['receivers'] == '1')
2945      {
2946          $audience = create_audience($event['send_to'] ['to']);
2947      }
2948  
2949      echo list_output(array($event));
2950  }
2951  
2952  /**
2953   * create a list of people / groups that the event has been sent to
2954   *
2955   * @param array $array an array containing all the users and groups that have received the event
2956   * @param string $returnas determines how the information should be outputted
2957   *
2958   * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
2959   * @version june 2010
2960   */
2961  function create_audience($array,$returnas='html')
2962  {
2963      global $_course;
2964  
2965      // Database table definition
2966      $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
2967  
2968      // variable initialisation
2969      $groups = array();
2970      $users = array();
2971      $return = '';
2972  
2973      // first we loop through the array to separate the users and the groups
2974      foreach ($array as $key=>$value)
2975      {
2976          if (substr($value,0,1) == 'U')
2977          {
2978              $users[]=str_ireplace('U','',$value);
2979          }
2980              if (substr($value,0,1) == 'G')
2981          {
2982              $groups[]=str_ireplace('G','',$value);
2983          }
2984      }
2985  
2986      // get all the needed information of the users
2987      if (!empty($users))
2988      {
2989          $sql = "SELECT * FROM $tbl_user WHERE user_id IN ('".Database::escape_string(implode(',',$users))."')";
2990          $result=api_sql_query($sql,__FILE__,__LINE__) or die(Database::error());
2991          while ($userinfo=Database::fetch_array($result))
2992          {
2993              if ($returnas == 'html')
2994              {
2995                  $return_array[] = '<a href="../user/userInfo.php?editMainUserInfo='.$userinfo['user_id'].'">'.$userinfo['firstname'].' '.$userinfo['lastname'].'</a>';
2996              }
2997              if ($returnas == 'array')
2998              {
2999                  $return_array[] = $userinfo;
3000              }
3001          }
3002      }
3003  
3004      // get all the needed information of the groups
3005      if (!empty($groups))
3006      {
3007          $groupinfo = GroupManager::get_group_list(null, $_course['course_code']);
3008  
3009          foreach ($groups as $key=>$groupid)
3010          {
3011              if ($returnas == 'html')
3012              {
3013                  $return_array[] = '<a href="../group/group_space.php?gidReq='.$groupid.'">'.$groupinfo[$groupid]['name'].'</a>';
3014              }
3015              if ($returnas == 'array')
3016              {
3017                  $return_array[] = $groupinfo[$groupid];
3018              }
3019          }
3020      }
3021  
3022      if ($returnas == 'html')
3023      {
3024          return implode(', ',$return_array);
3025      }
3026      if ($returnas == 'array')
3027      {
3028          return $return_array;
3029      }
3030  }
3031  
3032  function calendar_javascript(){
3033      // defaultview (this has to become a platform setting)
3034      if ($_GET ['view'] and in_array ( $_GET ['view'], array ('month', 'agendaWeek', 'agendaDay' ) )) {
3035          $defaultview = 'defaultView: \'' . Security::remove_XSS($_GET ['view']) . '\',';
3036      } else {
3037          $defaultview = 'defaultView: \'' . api_get_setting('agenda_default_view') . '\',';
3038      }
3039  
3040      // edit, delete and visiblity buttons or not
3041      if (api_get_setting('agenda_action_icons') == 'true'){
3042          $actionicons = "$(this).children('a').append('<span class=\"fc-event-actions\"><img src=\"../img/edit.png\" id=\"edit_'+calEvent.id+'\" class=\"edit\" alt=\"" . get_lang ( 'Edit' ) . "\"/><img src=\"../img/delete.png\" id=\"delete_'+calEvent.id+'\" class=\"delete\" alt=\"" . get_lang ( 'Delete' ) . "\"/><img src=\"../img/'+visibility_icon+'\" id=\"visibility_'+calEvent.id+'\" class=\"visibility\" alt=\"" . get_lang ( 'ChangeVisibility' ) . "\"/><img src=\"../img/export.png\" id=\"export_'+calEvent.id+'\" class=\"export\" alt=\"" . get_lang ( 'IcalExport' ) . "\"/></span>');";
3043      }
3044  
3045      // google calendar import
3046      if (api_get_setting('calendar_google_import')=='true'){
3047          $google_calendar_get_id_js = google_calendar_get_id_js();
3048      }
3049  
3050      // detail view
3051      if (api_get_setting('calendar_detail_view') == 'detail'){
3052          $detailview = 'detail';
3053      } else {
3054          $detailview = 'edit';
3055      }
3056  
3057      // how should the calendar header look like
3058      if (api_get_setting('calendar_navigation') == 'actions'){
3059          $header =     "header: {
3060                          left: '',
3061                          center: '',
3062                          right: ''
3063                      },";
3064      } else {
3065          $header =     "header: {
3066                          left: 'prev,next today',
3067                          center: 'title',
3068                          right: 'month,agendaWeek,agendaDay'
3069                      },";
3070      }
3071  
3072      // Sources of the events
3073      global $sources, $htmlHeadXtra;
3074      $sources[] = "'ajax.php?action=getevents&output=json&group=".Security::Remove_XSS($_GET['group'])."'";
3075      if (api_get_setting('calendar_google_import')=='true'){
3076          google_calendar_sources();
3077      }
3078  
3079      if (api_is_allowed_to_edit())
3080      {
3081          return "<script type='text/javascript'>
3082  
3083  		function html_entity_decode (string, quote_style) {
3084              // http://kevin.vanzonneveld.net
3085              // +   original by: john (http://www.jd-tech.net)
3086              // +      input by: ger
3087              // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
3088              // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
3089              // +   bugfixed by: Onno Marsman
3090              // +   improved by: marc andreu
3091              // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
3092              // +      input by: Ratheous
3093              // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
3094              // +      input by: Nick Kolosov (http://sammy.ru)
3095              // +   bugfixed by: Fox
3096              // -    depends on: get_html_translation_table
3097              // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
3098              // *     returns 1: 'Kevin & van Zonneveld'
3099              // *     example 2: html_entity_decode('&amp;lt;');
3100              // *     returns 2: '&lt;'
3101  
3102              var hash_map = {}, symbol = '', tmp_str = '', entity = '';
3103              tmp_str = string.toString();
3104  
3105              if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
3106                  return false;
3107              }
3108  
3109              // fix &amp; problem
3110              // http://phpjs.org/functions/get_html_translation_table:416#comment_97660
3111              delete(hash_map['&']);
3112              hash_map['&'] = '&amp;';
3113  
3114              for (symbol in hash_map) {
3115                  entity = hash_map[symbol];
3116                  tmp_str = tmp_str.split(entity).join(symbol);
3117              }
3118              tmp_str = tmp_str.split('&#039;').join(\"'\");
3119  
3120              return tmp_str;
3121          }
3122  
3123  		function get_html_translation_table (table, quote_style) {
3124              // http://kevin.vanzonneveld.net
3125              // +   original by: Philip Peterson
3126              // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
3127              // +   bugfixed by: noname
3128              // +   bugfixed by: Alex
3129              // +   bugfixed by: Marco
3130              // +   bugfixed by: madipta
3131              // +   improved by: KELAN
3132              // +   improved by: Brett Zamir (http://brett-zamir.me)
3133              // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
3134              // +      input by: Frank Forte
3135              // +   bugfixed by: T.Wild
3136              // +      input by: Ratheous
3137              // %          note: It has been decided that we're not going to add global
3138              // %          note: dependencies to php.js, meaning the constants are not
3139              // %          note: real constants, but strings instead. Integers are also supported if someone
3140              // %          note: chooses to create the constants themselves.
3141              // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
3142              // *     returns 1: {'\"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
3143  
3144              var entities = {}, hash_map = {}, decimal = 0, symbol = '';
3145              var constMappingTable = {}, constMappingQuoteStyle = {};
3146              var useTable = {}, useQuoteStyle = {};
3147  
3148              // Translate arguments
3149              constMappingTable[0]      = 'HTML_SPECIALCHARS';
3150              constMappingTable[1]      = 'HTML_ENTITIES';
3151              constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
3152              constMappingQuoteStyle[2] = 'ENT_COMPAT';
3153              constMappingQuoteStyle[3] = 'ENT_QUOTES';
3154  
3155              useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
3156              useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
3157  
3158              if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
3159              throw new Error(\"Table: \"+useTable+' not supported');
3160              // return false;
3161              }
3162  
3163              entities['38'] = '&amp;';
3164              if (useTable === 'HTML_ENTITIES') {
3165              entities['160'] = '&nbsp;';
3166              entities['161'] = '&iexcl;';
3167              entities['162'] = '&cent;';
3168              entities['163'] = '&pound;';
3169              entities['164'] = '&curren;';
3170              entities['165'] = '&yen;';
3171              entities['166'] = '&brvbar;';
3172              entities['167'] = '&sect;';
3173              entities['168'] = '&uml;';
3174              entities['169'] = '&copy;';
3175              entities['170'] = '&ordf;';
3176              entities['171'] = '&laquo;';
3177              entities['172'] = '&not;';
3178              entities['173'] = '&shy;';
3179              entities['174'] = '&reg;';
3180              entities['175'] = '&macr;';
3181              entities['176'] = '&deg;';
3182              entities['177'] = '&plusmn;';
3183              entities['178'] = '&sup2;';
3184              entities['179'] = '&sup3;';
3185              entities['180'] = '&acute;';
3186              entities['181'] = '&micro;';
3187              entities['182'] = '&para;';
3188              entities['183'] = '&middot;';
3189              entities['184'] = '&cedil;';
3190              entities['185'] = '&sup1;';
3191              entities['186'] = '&ordm;';
3192              entities['187'] = '&raquo;';
3193              entities['188'] = '&frac14;';
3194              entities['189'] = '&frac12;';
3195              entities['190'] = '&frac34;';
3196              entities['191'] = '&iquest;';
3197              entities['192'] = '&Agrave;';
3198              entities['193'] = '&Aacute;';
3199              entities['194'] = '&Acirc;';
3200              entities['195'] = '&Atilde;';
3201              entities['196'] = '&Auml;';
3202              entities['197'] = '&Aring;';
3203              entities['198'] = '&AElig;';
3204              entities['199'] = '&Ccedil;';
3205              entities['200'] = '&Egrave;';
3206              entities['201'] = '&Eacute;';
3207              entities['202'] = '&Ecirc;';
3208              entities['203'] = '&Euml;';
3209              entities['204'] = '&Igrave;';
3210              entities['205'] = '&Iacute;';
3211              entities['206'] = '&Icirc;';
3212              entities['207'] = '&Iuml;';
3213              entities['208'] = '&ETH;';
3214              entities['209'] = '&Ntilde;';
3215              entities['210'] = '&Ograve;';
3216              entities['211'] = '&Oacute;';
3217              entities['212'] = '&Ocirc;';
3218              entities['213'] = '&Otilde;';
3219              entities['214'] = '&Ouml;';
3220              entities['215'] = '&times;';
3221              entities['216'] = '&Oslash;';
3222              entities['217'] = '&Ugrave;';
3223              entities['218'] = '&Uacute;';
3224              entities['219'] = '&Ucirc;';
3225              entities['220'] = '&Uuml;';
3226              entities['221'] = '&Yacute;';
3227              entities['222'] = '&THORN;';
3228              entities['223'] = '&szlig;';
3229              entities['224'] = '&agrave;';
3230              entities['225'] = '&aacute;';
3231              entities['226'] = '&acirc;';
3232              entities['227'] = '&atilde;';
3233              entities['228'] = '&auml;';
3234              entities['229'] = '&aring;';
3235              entities['230'] = '&aelig;';
3236              entities['231'] = '&ccedil;';
3237              entities['232'] = '&egrave;';
3238              entities['233'] = '&eacute;';
3239              entities['234'] = '&ecirc;';
3240              entities['235'] = '&euml;';
3241              entities['236'] = '&igrave;';
3242              entities['237'] = '&iacute;';
3243              entities['238'] = '&icirc;';
3244              entities['239'] = '&iuml;';
3245              entities['240'] = '&eth;';
3246              entities['241'] = '&ntilde;';
3247              entities['242'] = '&ograve;';
3248              entities['243'] = '&oacute;';
3249              entities['244'] = '&ocirc;';
3250              entities['245'] = '&otilde;';
3251              entities['246'] = '&ouml;';
3252              entities['247'] = '&divide;';
3253              entities['248'] = '&oslash;';
3254              entities['249'] = '&ugrave;';
3255              entities['250'] = '&uacute;';
3256              entities['251'] = '&ucirc;';
3257              entities['252'] = '&uuml;';
3258              entities['253'] = '&yacute;';
3259              entities['254'] = '&thorn;';
3260              entities['255'] = '&yuml;';
3261              }
3262  
3263              if (useQuoteStyle !== 'ENT_NOQUOTES') {
3264              entities['34'] = '&quot;';
3265              }
3266              if (useQuoteStyle === 'ENT_QUOTES') {
3267              entities['39'] = '&#39;';
3268              }
3269              entities['60'] = '&lt;';
3270              entities['62'] = '&gt;';
3271  
3272  
3273              // ascii decimals to real symbols
3274              for (decimal in entities) {
3275              symbol = String.fromCharCode(decimal);
3276              hash_map[symbol] = entities[decimal];
3277              }
3278  
3279              return hash_map;
3280          }
3281  
3282              $(document).ready(function() {
3283  
3284                  var date = new Date();
3285                  var d = date.getDate();
3286                  var m = date.getMonth();
3287                  var y = date.getFullYear();
3288  
3289                  var DokeosCalendar = $('#calendar').fullCalendar({
3290                      ".$header."
3291                      buttonText: { today: '".addslashes(get_lang('Today'))."', month: '".addslashes(get_lang('MonthView'))."', week: '".addslashes(get_lang('WeekView'))."', day: '".addslashes(get_lang('DayView'))."'}, 
3292                      monthNames: ['".addslashes(ucfirst(get_lang('JanuaryLong')))."', '".addslashes(ucfirst(get_lang('FebruaryLong')))."', '".addslashes(ucfirst(get_lang('MarchLong')))."', '".addslashes(ucfirst(get_lang('AprilLong')))."', '".addslashes(ucfirst(get_lang('MayLong')))."', '".addslashes(ucfirst(get_lang('JuneLong')))."', '".addslashes(ucfirst(get_lang('JulyLong')))."', '".addslashes(ucfirst(get_lang('AugustLong')))."', '".addslashes(ucfirst(get_lang('SeptemberLong')))."', '".addslashes(ucfirst(get_lang('OctoberLong')))."', '".addslashes(ucfirst(get_lang('NovemberLong')))."', '".addslashes(ucfirst(get_lang('DecemberLong')))."'],
3293                      monthNamesShort: ['".addslashes(ucfirst(get_lang('JanuaryShort')))."', '".addslashes(ucfirst(get_lang('FebruaryShort')))."', '".addslashes(ucfirst(get_lang('MarchShort')))."', '".addslashes(ucfirst(get_lang('AprilShort')))."', '".addslashes(ucfirst(get_lang('MayShort')))."', '".addslashes(ucfirst(get_lang('JuneShort')))."', '".addslashes(ucfirst(get_lang('JulyShort')))."', '".addslashes(ucfirst(get_lang('AugustShort')))."', '".addslashes(ucfirst(get_lang('SeptemberShort')))."', '".addslashes(ucfirst(get_lang('OctoberShort')))."', '".addslashes(ucfirst(get_lang('NovemberShort')))."', '".addslashes(ucfirst(get_lang('DecemberShort')))."'],
3294                      dayNames: ['".addslashes(ucfirst(get_lang('SundayLong')))."', '".addslashes(ucfirst(get_lang('MondayLong')))."', '".addslashes(ucfirst(get_lang('TuesdayLong')))."', '".addslashes(ucfirst(get_lang('WednesdayLong')))."', '".addslashes(ucfirst(get_lang('ThursdayLong')))."', '".addslashes(ucfirst(get_lang('FridayLong')))."', '".addslashes(ucfirst(get_lang('SaturdayLong')))."'],
3295                      dayNamesShort: ['".addslashes(ucfirst(get_lang('SundayShort')))."', '".addslashes(ucfirst(get_lang('MondayShort')))."', '".addslashes(ucfirst(get_lang('TuesdayShort')))."', '".addslashes(ucfirst(get_lang('WednesdayShort')))."', '".addslashes(ucfirst(get_lang('ThursdayShort')))."', '".addslashes(ucfirst(get_lang('FridayShort')))."', '".addslashes(ucfirst(get_lang('SaturdayShort')))."'],
3296                      weekMode: 'variable',
3297                      allDaySlot: false,
3298                      firstDay: 1,
3299                      axisFormat: 'HH(:mm)',
3300                      timeFormat: 'HH:mm{ - HH:mm}',
3301                      height: 1200,
3302                      " . $defaultview . "
3303                      editable: true,
3304                      eventSources: [
3305                          ".implode(",",$sources)."
3306                          ],
3307                      eventMouseover: function(calEvent,jsEvent) {
3308                              // the appropriate visibility icon
3309                              if (calEvent.visibility == 1){
3310                                  var visibility_icon = 'visible.gif';
3311                              } else {
3312                                  var visibility_icon = 'invisible.gif';
3313                              }
3314                          if ($(this).hasClass('courseagenda')){
3315                              ".$actionicons."
3316                          }
3317                          if ($(this).hasClass('gcal-event')) {
3318                              $(this).children('a').append('<span class=\"fc-event-actions\"><img src=\"../img/edit.gif\" id=\"edit_google_'+calEvent.id+'\" class=\"edit gcaledit\" alt=\"" . get_lang ( 'Edit' ) . "\"/><img src=\"../img/delete.gif\" id=\"delete_google_'+calEvent.id+'\" class=\"delete gcaldelete\" alt=\"" . get_lang ( 'Delete' ) . "\"/></span>');
3319                          }
3320                      },
3321                      eventMouseout: function(calEvent,jsEvent) {
3322                              $('.fc-event-actions').remove();
3323                      },
3324                      eventRender: function(calEvent, element) {
3325                          // add the id to the rendered element so that we can use this for the detail
3326                          element.attr('id',calEvent.id);
3327                          $('.fc-event-title',element).html(html_entity_decode(calEvent.title));
3328                      },
3329                      eventDrop: function(event,dayDelta,minuteDelta,allDay,revertFunc) {
3330                          $.ajax({
3331                            url: 'ajax.php',
3332                            data: {action: 'move', id: event.id, daydelta: dayDelta, minutedelta: minuteDelta}
3333                          });
3334                      },
3335                  eventResize: function(event,dayDelta,minuteDelta,revertFunc) {
3336                      $.ajax({
3337                        url: 'ajax.php',
3338                        data: {action: 'resize', id: event.id, daydelta: dayDelta, minutedelta: minuteDelta}
3339                      });
3340                  },
3341                  dayClick: function(date, allDay, jsEvent, view){
3342                      if(view.name == 'month'){
3343                          DokeosCalendar.fullCalendar( 'changeView', 'agendaDay').fullCalendar( 'gotoDate', date );
3344                      }
3345                      //$(location).attr('href','agenda.php?action=add&date='+$.fullCalendar.formatDate( date, 'yyyy/MM/dd/HH/mm'));
3346                  },
3347                  eventClick: function(event,jsEvent,view){
3348  
3349                  }
3350              });
3351  
3352              // clicking the event. We could have used the eventClick functionality of fullcalendar but this caused problems when changing the visibility
3353              $('.courseagenda').live('click', function(){
3354                          id=$(this).attr('id');
3355                          // Generic variables
3356                          var data_id = new  Array();
3357                          var get_id = 0;
3358                          var _event_type = '';
3359                          var find = true;
3360                          // Get the platform event ID
3361                          try {
3362                            _event_type = 'platform';
3363                            data_id = id.split('platform');
3364                            get_id = data_id[1];// Get the ID of the platform event
3365                            if (get_id > 0) {
3366                              find = false;
3367                            }
3368                          } catch(e){get_id = 0;}
3369  
3370                          // Get the assignment event ID
3371                          if (find === true) {
3372                            try {
3373                              _event_type = 'assignment';
3374                              data_id = id.split('assignment');
3375                              get_id = data_id[1];// Get the ID of the assignment
3376                              if (get_id > 0) {
3377                                find = false;
3378                              }
3379                            } catch(e){get_id = 0;}
3380                          }
3381  
3382                          // Get the quiz event ID
3383                          if (find === true) {
3384                            try {
3385                              _event_type = 'quiz';
3386                              data_id = id.split('quiz');
3387                              get_id = data_id[1];// Get the ID of the quiz
3388                              if (get_id > 0) {
3389                                find = false;
3390                              }
3391                            } catch(e){get_id = 0;}
3392                          }
3393  
3394                          // Get the session event ID
3395                          if (find === true) {
3396                            try {
3397                              _event_type = 'session';
3398                              data_id = id.split('session');
3399                              get_id = data_id[1];// Get the ID of the session
3400                              if (get_id > 0) {
3401                                find = false;
3402                              }
3403                            } catch(e){get_id = 0;}
3404                          }
3405  
3406                          // Get the course event ID
3407                          if (find === true) {
3408                            try {
3409                              _event_type = 'course_events';
3410                              data_id = id.split('course_events');
3411                              get_id = data_id[1];// Get the ID of the session
3412                              if (get_id > 0) {
3413                                find = false;
3414                              }
3415                            } catch(e){get_id = 0;}
3416                          }
3417        
3418                  $(location).attr('href','agenda.php?".api_get_cidreq()."&action=".$detailview."&id='+get_id+'&event_type='+_event_type);
3419              });
3420  
3421              // clicking the edit icon
3422                  $('.fc-event-actions .edit').live('click', function(){
3423                      id=$(this).attr('id');
3424                      var gcal_id = '';
3425                      ".$google_calendar_get_id_js."
3426                      $(location).attr('href','agenda.php?".api_get_cidreq()."&action=edit&id='+id.replace('edit_','') + '&calendar=' + gcal_id);
3427                      event.stopPropagation();
3428                      return false;
3429                  });
3430  
3431              // clicking the delete icon
3432              $('.fc-event-actions .delete').live('click', function(){
3433                  id=$(this).attr('id');
3434  
3435                  var gcal_id = '';
3436                  ".$google_calendar_get_id_js."
3437  
3438                  // remove from database
3439                  $.ajax({
3440                    url: 'ajax.php',
3441                    data: {action: 'delete', id: id.replace('delete_',''), calendar: gcal_id},
3442                    success: function(data){
3443                          $('#content').html(data);
3444                      }
3445                  });
3446  
3447                  // get the fc_index
3448                  var fc_index = $('.fc-event').index($(this).parent().parent().parent());
3449  
3450                  // remove the fc-event
3451                  DokeosCalendar.fullCalendar('removeEvents',id.replace('delete_',''));
3452  
3453                  // also updating the list view of the item
3454                  $('#list_'+id.replace('delete_','')).remove();
3455  
3456                  return false;
3457              });
3458  
3459              // clicking the visibility icon
3460              $('.fc-event-actions .visibility').live('click', function(){
3461                  id=$(this).attr('id');
3462                  current_status = $(this).attr('src').replace('../img/','').replace('.gif','');
3463  
3464                  // change visibility
3465                  $.ajax({
3466                    url: 'ajax.php',
3467                    data: {action: 'visibility', id: id.replace('visibility_',''), status: current_status},
3468                    success: function(){
3469                          // change the icon
3470                          if (current_status == 'visible'){
3471                              var new_action_icon = '../img/invisible.gif';
3472                              $(this).attr('src',new_action_icon);
3473                              var new_visibility = 0;
3474                              var list_view_wrapper_class = 'agenda_item_wrapper_hidden';
3475                          } else {
3476                              var new_action_icon = '../img/visible.gif';
3477                              $(this).attr('src',new_action_icon);
3478                              var new_visibility = 1;
3479                              var list_view_wrapper_class = 'agenda_item_wrapper';
3480                          }
3481  
3482                          // toggle the class (invisible) (not needed because handled by 'refetchEvents')
3483                          //$(this).parent().parent().parent().toggleClass('invisible');
3484  
3485                          // get the fc_index
3486                          var fc_index = $('.fc-event').index($(this).parent().parent().parent());
3487  
3488                          // updating the event information
3489                          DokeosCalendar.fullCalendar( 'refetchEvents' );
3490  
3491                          // also updating the list view of the item
3492                          $('#list_'+id.replace('visibility_','')).attr('class',list_view_wrapper_class);
3493                          $('#list_'+id.replace('visibility_','')+' .visibility').attr('src',new_action_icon);
3494                    }
3495                  });
3496                  event.stopPropagation();
3497              });
3498  
3499              // clicking the export icon
3500              $('.fc-event-actions .export').live('click', function(){
3501                  id=$(this).attr('id');
3502                  $(location).attr('href','agenda.php?action=export&id='+id.replace('export_',''));
3503                  event.stopPropagation();
3504              });
3505  
3506              // add the list button
3507              // $('.fc-header-right table tbody tr td').eq(0).before('<td><div class=\"fc-button-list fc-state-default fc-no-right fc-corner-left\"><a><span>" . get_lang ( 'ListView' ) . "</span></a></div></td>');
3508      
3509              // show the list view
3510              $('.fc-button-list').click(function(){
3511                  DokeosCalendar.fullCalendar('changeView','basicWeek');
3512  
3513                  // make all the view buttons inactive
3514                  $('.fc-state-active').toggleClass('fc-state-active');
3515  
3516                  // make the current view button active
3517                  $(this).toggleClass('fc-state-active');
3518  
3519                  // hide all the views
3520                  $('.fc-view').hide();
3521  
3522                  // add a new view or show if if it already exists (but hidden)
3523                  if ( $('.fc-view-list').length ){
3524                      $('.fc-view-list').show();
3525                  } else {
3526                      $.ajax({
3527                        url: 'ajax.php',
3528                        data: {action: 'getevents', output: 'list', full_info: 'true'},
3529                        success: function(data){
3530                              $('.fc-content').append('<div class=\"fc-view fc-view-list\">'+data+'</div>');
3531                              $('.visiblefor').expander({
3532                                  slicePoint:       200,  // default is 100
3533                                  expandText:         '[...]', // default is 'read more...'
3534                                  collapseTimer:    5000, // re-collapses after 5 seconds; default is 0, so no re-collapsing
3535                                  userCollapseText: '[^]'  // default is '[collapse expanded text]'
3536                                });
3537                          }
3538                      });
3539                        }
3540                      });
3541  
3542              // desactive the list button when another button is clicked and hide the list view
3543              $('.fc-button-month, .fc-button-agendaWeek, .fc-button-agendaDay').click(function(){
3544                  $('.fc-button-list').removeClass('fc-state-active');
3545                  $('.fc-view-list').hide();
3546              });
3547  
3548              // change the size if month view is clicked
3549              $('.fc-button-month').click(function(){
3550                  DokeosCalendar.fullCalendar('option', 'height', 500);
3551              });
3552  
3553              // change the size if month view is clicked
3554              $('.fc-button-agendaWeek, .fc-button-agendaDay, .fc-content').click(function(){
3555                  DokeosCalendar.fullCalendar('option', 'height', 1200);
3556              });
3557  
3558          });
3559  
3560      </script>";
3561      } else  { // Code for display the calendar for students
3562          return "<script type='text/javascript'>
3563  
3564  		function html_entity_decode (string, quote_style) {
3565              // http://kevin.vanzonneveld.net
3566              // +   original by: john (http://www.jd-tech.net)
3567              // +      input by: ger
3568              // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
3569              // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
3570              // +   bugfixed by: Onno Marsman
3571              // +   improved by: marc andreu
3572              // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
3573              // +      input by: Ratheous
3574              // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
3575              // +      input by: Nick Kolosov (http://sammy.ru)
3576              // +   bugfixed by: Fox
3577              // -    depends on: get_html_translation_table
3578              // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
3579              // *     returns 1: 'Kevin & van Zonneveld'
3580              // *     example 2: html_entity_decode('&amp;lt;');
3581              // *     returns 2: '&lt;'
3582  
3583              var hash_map = {}, symbol = '', tmp_str = '', entity = '';
3584              tmp_str = string.toString();
3585  
3586              if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
3587                  return false;
3588              }
3589  
3590              // fix &amp; problem
3591              // http://phpjs.org/functions/get_html_translation_table:416#comment_97660
3592              delete(hash_map['&']);
3593              hash_map['&'] = '&amp;';
3594  
3595              for (symbol in hash_map) {
3596                  entity = hash_map[symbol];
3597                  tmp_str = tmp_str.split(entity).join(symbol);
3598              }
3599              tmp_str = tmp_str.split('&#039;').join(\"'\");
3600  
3601              return tmp_str;
3602          }
3603  
3604  		function get_html_translation_table (table, quote_style) {
3605              // http://kevin.vanzonneveld.net
3606              // +   original by: Philip Peterson
3607              // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
3608              // +   bugfixed by: noname
3609              // +   bugfixed by: Alex
3610              // +   bugfixed by: Marco
3611              // +   bugfixed by: madipta
3612              // +   improved by: KELAN
3613              // +   improved by: Brett Zamir (http://brett-zamir.me)
3614              // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
3615              // +      input by: Frank Forte
3616              // +   bugfixed by: T.Wild
3617              // +      input by: Ratheous
3618              // %          note: It has been decided that we're not going to add global
3619              // %          note: dependencies to php.js, meaning the constants are not
3620              // %          note: real constants, but strings instead. Integers are also supported if someone
3621              // %          note: chooses to create the constants themselves.
3622              // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
3623              // *     returns 1: {'\"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
3624  
3625              var entities = {}, hash_map = {}, decimal = 0, symbol = '';
3626              var constMappingTable = {}, constMappingQuoteStyle = {};
3627              var useTable = {}, useQuoteStyle = {};
3628  
3629              // Translate arguments
3630              constMappingTable[0]      = 'HTML_SPECIALCHARS';
3631              constMappingTable[1]      = 'HTML_ENTITIES';
3632              constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
3633              constMappingQuoteStyle[2] = 'ENT_COMPAT';
3634              constMappingQuoteStyle[3] = 'ENT_QUOTES';
3635  
3636              useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
3637              useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
3638  
3639              if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
3640              throw new Error(\"Table: \"+useTable+' not supported');
3641              // return false;
3642              }
3643  
3644              entities['38'] = '&amp;';
3645              if (useTable === 'HTML_ENTITIES') {
3646              entities['160'] = '&nbsp;';
3647              entities['161'] = '&iexcl;';
3648              entities['162'] = '&cent;';
3649              entities['163'] = '&pound;';
3650              entities['164'] = '&curren;';
3651              entities['165'] = '&yen;';
3652              entities['166'] = '&brvbar;';
3653              entities['167'] = '&sect;';
3654              entities['168'] = '&uml;';
3655              entities['169'] = '&copy;';
3656              entities['170'] = '&ordf;';
3657              entities['171'] = '&laquo;';
3658              entities['172'] = '&not;';
3659              entities['173'] = '&shy;';
3660              entities['174'] = '&reg;';
3661              entities['175'] = '&macr;';
3662              entities['176'] = '&deg;';
3663              entities['177'] = '&plusmn;';
3664              entities['178'] = '&sup2;';
3665              entities['179'] = '&sup3;';
3666              entities['180'] = '&acute;';
3667              entities['181'] = '&micro;';
3668              entities['182'] = '&para;';
3669              entities['183'] = '&middot;';
3670              entities['184'] = '&cedil;';
3671              entities['185'] = '&sup1;';
3672              entities['186'] = '&ordm;';
3673              entities['187'] = '&raquo;';
3674              entities['188'] = '&frac14;';
3675              entities['189'] = '&frac12;';
3676              entities['190'] = '&frac34;';
3677              entities['191'] = '&iquest;';
3678              entities['192'] = '&Agrave;';
3679              entities['193'] = '&Aacute;';
3680              entities['194'] = '&Acirc;';
3681              entities['195'] = '&Atilde;';
3682              entities['196'] = '&Auml;';
3683              entities['197'] = '&Aring;';
3684              entities['198'] = '&AElig;';
3685              entities['199'] = '&Ccedil;';
3686              entities['200'] = '&Egrave;';
3687              entities['201'] = '&Eacute;';
3688              entities['202'] = '&Ecirc;';
3689              entities['203'] = '&Euml;';
3690              entities['204'] = '&Igrave;';
3691              entities['205'] = '&Iacute;';
3692              entities['206'] = '&Icirc;';
3693              entities['207'] = '&Iuml;';
3694              entities['208'] = '&ETH;';
3695              entities['209'] = '&Ntilde;';
3696              entities['210'] = '&Ograve;';
3697              entities['211'] = '&Oacute;';
3698              entities['212'] = '&Ocirc;';
3699              entities['213'] = '&Otilde;';
3700              entities['214'] = '&Ouml;';
3701              entities['215'] = '&times;';
3702              entities['216'] = '&Oslash;';
3703              entities['217'] = '&Ugrave;';
3704              entities['218'] = '&Uacute;';
3705              entities['219'] = '&Ucirc;';
3706              entities['220'] = '&Uuml;';
3707              entities['221'] = '&Yacute;';
3708              entities['222'] = '&THORN;';
3709              entities['223'] = '&szlig;';
3710              entities['224'] = '&agrave;';
3711              entities['225'] = '&aacute;';
3712              entities['226'] = '&acirc;';
3713              entities['227'] = '&atilde;';
3714              entities['228'] = '&auml;';
3715              entities['229'] = '&aring;';
3716              entities['230'] = '&aelig;';
3717              entities['231'] = '&ccedil;';
3718              entities['232'] = '&egrave;';
3719              entities['233'] = '&eacute;';
3720              entities['234'] = '&ecirc;';
3721              entities['235'] = '&euml;';
3722              entities['236'] = '&igrave;';
3723              entities['237'] = '&iacute;';
3724              entities['238'] = '&icirc;';
3725              entities['239'] = '&iuml;';
3726              entities['240'] = '&eth;';
3727              entities['241'] = '&ntilde;';
3728              entities['242'] = '&ograve;';
3729              entities['243'] = '&oacute;';
3730              entities['244'] = '&ocirc;';
3731              entities['245'] = '&otilde;';
3732              entities['246'] = '&ouml;';
3733              entities['247'] = '&divide;';
3734              entities['248'] = '&oslash;';
3735              entities['249'] = '&ugrave;';
3736              entities['250'] = '&uacute;';
3737              entities['251'] = '&ucirc;';
3738              entities['252'] = '&uuml;';
3739              entities['253'] = '&yacute;';
3740              entities['254'] = '&thorn;';
3741              entities['255'] = '&yuml;';
3742              }
3743  
3744              if (useQuoteStyle !== 'ENT_NOQUOTES') {
3745              entities['34'] = '&quot;';
3746              }
3747              if (useQuoteStyle === 'ENT_QUOTES') {
3748              entities['39'] = '&#39;';
3749              }
3750              entities['60'] = '&lt;';
3751              entities['62'] = '&gt;';
3752  
3753  
3754              // ascii decimals to real symbols
3755              for (decimal in entities) {
3756              symbol = String.fromCharCode(decimal);
3757              hash_map[symbol] = entities[decimal];
3758              }
3759  
3760              return hash_map;
3761          }
3762  
3763          $(document).ready(function() {
3764  
3765              var date = new Date();
3766              var d = date.getDate();
3767              var m = date.getMonth();
3768              var y = date.getFullYear();
3769  
3770              var DokeosCalendar = $('#calendar').fullCalendar({
3771                  ".$header."
3772                  buttonText: { today: '".addslashes(get_lang('Today'))."', month: '".addslashes(get_lang('MonthView'))."', week: '".addslashes(get_lang('WeekView'))."', day: '".addslashes(get_lang('DayView'))."'}, 
3773                  monthNames: ['".addslashes(ucfirst(get_lang('JanuaryLong')))."', '".addslashes(ucfirst(get_lang('FebruaryLong')))."', '".addslashes(ucfirst(get_lang('MarchLong')))."', '".addslashes(ucfirst(get_lang('AprilLong')))."', '".addslashes(ucfirst(get_lang('MayLong')))."', '".addslashes(ucfirst(get_lang('JuneLong')))."', '".addslashes(ucfirst(get_lang('JulyLong')))."', '".addslashes(ucfirst(get_lang('AugustLong')))."', '".addslashes(ucfirst(get_lang('SeptemberLong')))."', '".addslashes(ucfirst(get_lang('OctoberLong')))."', '".addslashes(ucfirst(get_lang('NovemberLong')))."', '".addslashes(ucfirst(get_lang('DecemberLong')))."'],
3774                  monthNamesShort: ['".addslashes(ucfirst(get_lang('JanuaryShort')))."', '".addslashes(ucfirst(get_lang('FebruaryShort')))."', '".addslashes(ucfirst(get_lang('MarchShort')))."', '".addslashes(ucfirst(get_lang('AprilShort')))."', '".addslashes(ucfirst(get_lang('MayShort')))."', '".addslashes(ucfirst(get_lang('JuneShort')))."', '".addslashes(ucfirst(get_lang('JulyShort')))."', '".addslashes(ucfirst(get_lang('AugustShort')))."', '".addslashes(ucfirst(get_lang('SeptemberShort')))."', '".addslashes(ucfirst(get_lang('OctoberShort')))."', '".addslashes(ucfirst(get_lang('NovemberShort')))."', '".addslashes(ucfirst(get_lang('DecemberShort')))."'],
3775                  dayNames: ['".addslashes(ucfirst(get_lang('SundayLong')))."', '".addslashes(ucfirst(get_lang('MondayLong')))."', '".addslashes(ucfirst(get_lang('TuesdayLong')))."', '".addslashes(ucfirst(get_lang('WednesdayLong')))."', '".addslashes(ucfirst(get_lang('ThursdayLong')))."', '".addslashes(ucfirst(get_lang('FridayLong')))."', '".addslashes(ucfirst(get_lang('SaturdayLong')))."'],
3776                  dayNamesShort: ['".addslashes(ucfirst(get_lang('SundayShort')))."', '".addslashes(ucfirst(get_lang('MondayShort')))."', '".addslashes(ucfirst(get_lang('TuesdayShort')))."', '".addslashes(ucfirst(get_lang('WednesdayShort')))."', '".addslashes(ucfirst(get_lang('ThursdayShort')))."', '".addslashes(ucfirst(get_lang('FridayShort')))."', '".addslashes(ucfirst(get_lang('SaturdayShort')))."'],
3777                  weekMode: 'variable',
3778                  allDaySlot: false,
3779                  firstDay: 1,
3780                  axisFormat: 'HH(:mm)',
3781                  timeFormat: 'HH:mm{ - HH:mm}',
3782                  height: 1200,
3783                  " . $defaultview . "
3784                  editable: false,
3785                  events: \"ajax.php?action=getevents&output=json".$student_view."&group=".Security::Remove_XSS($_GET['group'])."\",
3786                  eventRender: function(calEvent, element) {
3787                      // add the id to the rendered element so that we can use this for the detail
3788                      element.attr('id',calEvent.id);
3789                      $('.fc-event-title',element).html(html_entity_decode(calEvent.title));
3790                  }
3791              });
3792  
3793              // clicking the event. We could have used the eventClick functionality of fullcalendar but this caused problems when changing the visibility
3794              $('.fc-event').live('click', function(){
3795              id = $(this).attr('id');
3796  
3797                          // Generic variables
3798                          var data_id = new  Array();
3799                          var get_id = 0;
3800                          var _event_type = '';
3801                          var find = true;
3802                          // Get the platform event ID
3803                          try {
3804                            _event_type = 'platform';
3805                            data_id = id.split('platform');
3806                            get_id = data_id[1];// Get the ID of the platform event
3807                            if (get_id > 0) {
3808                              find = false;
3809                            }
3810                          } catch(e){get_id = 0;}
3811  
3812                          // Get the assignment event ID
3813                          if (find === true) {
3814                            try {
3815                              _event_type = 'assignment';
3816                              data_id = id.split('assignment');
3817                              get_id = data_id[1];// Get the ID of the assignment
3818                              if (get_id > 0) {
3819                                find = false;
3820                              }
3821                            } catch(e){get_id = 0;}
3822                          }
3823  
3824                          // Get the quiz event ID
3825                          if (find === true) {
3826                            try {
3827                              _event_type = 'quiz';
3828                              data_id = id.split('quiz');
3829                              get_id = data_id[1];// Get the ID of the quiz
3830                              if (get_id > 0) {
3831                                find = false;
3832                              }
3833                            } catch(e){get_id = 0;}
3834                          }
3835  
3836                          // Get the session event ID
3837                          if (find === true) {
3838                            try {
3839                              _event_type = 'session';
3840                              data_id = id.split('session');
3841                              get_id = data_id[1];// Get the ID of the session
3842                              if (get_id > 0) {
3843                                find = false;
3844                              }
3845                            } catch(e){get_id = 0;}
3846                          }
3847  
3848                          // Get the course event ID
3849                          if (find === true) {
3850                            try {
3851                              _event_type = 'course_events';
3852                              data_id = id.split('course_events');
3853                              // Get the ID of the session
3854                              if (data_id[1] == 'undefined') {
3855                                  get_id = id;
3856                              } else {
3857                                  get_id = data_id[1];
3858                              }
3859                              
3860                              if (get_id > 0) {
3861                                find = false;
3862                              }
3863                            } catch(e){get_id = 0;}
3864                          }
3865  
3866                  $(location).attr('href','agenda.php?".api_get_cidreq()."&action=detail&id='+get_id+'&event_type='+_event_type);
3867              });
3868  
3869              // add the list button
3870              //$('.fc-header-right table tbody tr td').eq(0).before('<td><div class=\"fc-button-list fc-state-default fc-no-right fc-corner-left\"><a><span>" . get_lang ( 'ListView' ) . "</span></a></div></td>');
3871  
3872              // show the list view
3873              $('.fc-button-list').click(function(){
3874                  DokeosCalendar.fullCalendar('changeView','basicWeek');
3875  
3876                  // make all the view buttons inactive
3877                  $('.fc-state-active').toggleClass('fc-state-active');
3878  
3879                  // make the current view button active
3880                  $(this).toggleClass('fc-state-active');
3881  
3882                  // hide all the views
3883                  $('.fc-view').hide();
3884  
3885                  // add a new view or show if if it already exists (but hidden)
3886                  if ( $('.fc-view-list').length ){
3887                      $('.fc-view-list').show();
3888                  } else {
3889                      $.ajax({
3890                        url: 'ajax.php',
3891                        data: {action: 'getevents', output: 'list', full_info: 'true'},
3892                        success: function(data){
3893                              $('.fc-content').append('<div class=\"fc-view fc-view-list\">'+data+'</div>');
3894                          }
3895                      });
3896                  }
3897              });
3898  
3899              // desactive the list button when another button is clicked and hide the list view
3900              $('.fc-button-month, .fc-button-agendaWeek, .fc-button-agendaDay').click(function(){
3901                  $('.fc-button-list').removeClass('fc-state-active');
3902                  $('.fc-view-list').hide();
3903                  });
3904  
3905              });
3906  
3907              // change the size if month view is clicked
3908              $('.fc-button-month').click(function(){
3909                  DokeosCalendar.fullCalendar('option', 'height', 500);
3910              });
3911  
3912              // change the size if month view is clicked
3913              $('.fc-button-agendaWeek, .fc-button-agendaDay').click(function(){
3914                  DokeosCalendar.fullCalendar('option', 'height', 1200);
3915              });
3916  
3917          </script>";
3918      }
3919  }
3920  
3921  function mycalendar_javascript(){
3922      // defaultview (this has to become a platform setting)
3923      if ($_GET ['view'] and in_array ( $_GET ['view'], array ('month', 'agendaWeek', 'agendaDay' ) )) {
3924          $defaultview = 'defaultView: \'' . Security::remove_XSS($_GET ['view']) . '\',';
3925      } else {
3926          $defaultview = 'defaultView: \'' . api_get_setting('agenda_default_view') . '\',';
3927      }
3928  
3929      // display action icons or not
3930      if (api_get_setting('agenda_action_icons') == 'true') {                                        
3931              $actionicons = "
3932                  if (calEvent.parent_event_id && calEvent.parent_event_id != 0) {
3933                      $(this).children('a').append('<span class=\"fc-event-actions\"><img src=\"../img/delete.png\" id=\"delete_'+calEvent.id+'\" class=\"delete\" alt=\"" . get_lang ( 'Delete' ) . "\"/></span>');
3934                  } else {
3935                      $(this).children('a').append('<span class=\"fc-event-actions\"><img src=\"../img/edit.png\" id=\"edit_'+calEvent.id+'\" class=\"edit\" alt=\"" . get_lang ( 'Edit' ) . "\"/><img src=\"../img/delete.png\" id=\"delete_'+calEvent.id+'\" class=\"delete\" alt=\"" . get_lang ( 'Delete' ) . "\"/></span>');
3936      }
3937              ";
3938      }
3939  
3940      // detail view
3941      if (api_get_setting('calendar_detail_view') == 'detail'){
3942          $detailview = 'detail';
3943      } else {
3944          $detailview = 'myedit';
3945      }
3946  
3947      // how should the calendar header look like
3948      if (api_get_setting('calendar_navigation') == 'actions'){
3949          $header =     "header: {
3950                          left: '',
3951                          center: '',
3952                          right: ''
3953                      },";
3954      } else {
3955          $header =     "header: {
3956                          left: 'prev,next today',
3957                          center: 'title',
3958                          right: 'month,agendaWeek,agendaDay'
3959                      },";
3960      }
3961  
3962      return "<script type='text/javascript'>
3963  
3964  		function html_entity_decode (string, quote_style) {
3965              // http://kevin.vanzonneveld.net
3966              // +   original by: john (http://www.jd-tech.net)
3967              // +      input by: ger
3968              // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
3969              // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
3970              // +   bugfixed by: Onno Marsman
3971              // +   improved by: marc andreu
3972              // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
3973              // +      input by: Ratheous
3974              // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
3975              // +      input by: Nick Kolosov (http://sammy.ru)
3976              // +   bugfixed by: Fox
3977              // -    depends on: get_html_translation_table
3978              // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
3979              // *     returns 1: 'Kevin & van Zonneveld'
3980              // *     example 2: html_entity_decode('&amp;lt;');
3981              // *     returns 2: '&lt;'
3982  
3983              var hash_map = {}, symbol = '', tmp_str = '', entity = '';
3984              tmp_str = string.toString();
3985  
3986              if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
3987                  return false;
3988              }
3989  
3990              // fix &amp; problem
3991              // http://phpjs.org/functions/get_html_translation_table:416#comment_97660
3992              delete(hash_map['&']);
3993              hash_map['&'] = '&amp;';
3994  
3995              for (symbol in hash_map) {
3996                  entity = hash_map[symbol];
3997                  tmp_str = tmp_str.split(entity).join(symbol);
3998              }
3999              tmp_str = tmp_str.split('&#039;').join(\"'\");
4000  
4001              return tmp_str;
4002          }
4003  
4004  		function get_html_translation_table (table, quote_style) {
4005              // http://kevin.vanzonneveld.net
4006              // +   original by: Philip Peterson
4007              // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
4008              // +   bugfixed by: noname
4009              // +   bugfixed by: Alex
4010              // +   bugfixed by: Marco
4011              // +   bugfixed by: madipta
4012              // +   improved by: KELAN
4013              // +   improved by: Brett Zamir (http://brett-zamir.me)
4014              // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
4015              // +      input by: Frank Forte
4016              // +   bugfixed by: T.Wild
4017              // +      input by: Ratheous
4018              // %          note: It has been decided that we're not going to add global
4019              // %          note: dependencies to php.js, meaning the constants are not
4020              // %          note: real constants, but strings instead. Integers are also supported if someone
4021              // %          note: chooses to create the constants themselves.
4022              // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
4023              // *     returns 1: {'\"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
4024  
4025              var entities = {}, hash_map = {}, decimal = 0, symbol = '';
4026              var constMappingTable = {}, constMappingQuoteStyle = {};
4027              var useTable = {}, useQuoteStyle = {};
4028  
4029              // Translate arguments
4030              constMappingTable[0]      = 'HTML_SPECIALCHARS';
4031              constMappingTable[1]      = 'HTML_ENTITIES';
4032              constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
4033              constMappingQuoteStyle[2] = 'ENT_COMPAT';
4034              constMappingQuoteStyle[3] = 'ENT_QUOTES';
4035  
4036              useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
4037              useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
4038  
4039              if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
4040              throw new Error(\"Table: \"+useTable+' not supported');
4041              // return false;
4042              }
4043  
4044              entities['38'] = '&amp;';
4045              if (useTable === 'HTML_ENTITIES') {
4046              entities['160'] = '&nbsp;';
4047              entities['161'] = '&iexcl;';
4048              entities['162'] = '&cent;';
4049              entities['163'] = '&pound;';
4050              entities['164'] = '&curren;';
4051              entities['165'] = '&yen;';
4052              entities['166'] = '&brvbar;';
4053              entities['167'] = '&sect;';
4054              entities['168'] = '&uml;';
4055              entities['169'] = '&copy;';
4056              entities['170'] = '&ordf;';
4057              entities['171'] = '&laquo;';
4058              entities['172'] = '&not;';
4059              entities['173'] = '&shy;';
4060              entities['174'] = '&reg;';
4061              entities['175'] = '&macr;';
4062              entities['176'] = '&deg;';
4063              entities['177'] = '&plusmn;';
4064              entities['178'] = '&sup2;';
4065              entities['179'] = '&sup3;';
4066              entities['180'] = '&acute;';
4067              entities['181'] = '&micro;';
4068              entities['182'] = '&para;';
4069              entities['183'] = '&middot;';
4070              entities['184'] = '&cedil;';
4071              entities['185'] = '&sup1;';
4072              entities['186'] = '&ordm;';
4073              entities['187'] = '&raquo;';
4074              entities['188'] = '&frac14;';
4075              entities['189'] = '&frac12;';
4076              entities['190'] = '&frac34;';
4077              entities['191'] = '&iquest;';
4078              entities['192'] = '&Agrave;';
4079              entities['193'] = '&Aacute;';
4080              entities['194'] = '&Acirc;';
4081              entities['195'] = '&Atilde;';
4082              entities['196'] = '&Auml;';
4083              entities['197'] = '&Aring;';
4084              entities['198'] = '&AElig;';
4085              entities['199'] = '&Ccedil;';
4086              entities['200'] = '&Egrave;';
4087              entities['201'] = '&Eacute;';
4088              entities['202'] = '&Ecirc;';
4089              entities['203'] = '&Euml;';
4090              entities['204'] = '&Igrave;';
4091              entities['205'] = '&Iacute;';
4092              entities['206'] = '&Icirc;';
4093              entities['207'] = '&Iuml;';
4094              entities['208'] = '&ETH;';
4095              entities['209'] = '&Ntilde;';
4096              entities['210'] = '&Ograve;';
4097              entities['211'] = '&Oacute;';
4098              entities['212'] = '&Ocirc;';
4099              entities['213'] = '&Otilde;';
4100              entities['214'] = '&Ouml;';
4101              entities['215'] = '&times;';
4102              entities['216'] = '&Oslash;';
4103              entities['217'] = '&Ugrave;';
4104              entities['218'] = '&Uacute;';
4105              entities['219'] = '&Ucirc;';
4106              entities['220'] = '&Uuml;';
4107              entities['221'] = '&Yacute;';
4108              entities['222'] = '&THORN;';
4109              entities['223'] = '&szlig;';
4110              entities['224'] = '&agrave;';
4111              entities['225'] = '&aacute;';
4112              entities['226'] = '&acirc;';
4113              entities['227'] = '&atilde;';
4114              entities['228'] = '&auml;';
4115              entities['229'] = '&aring;';
4116              entities['230'] = '&aelig;';
4117              entities['231'] = '&ccedil;';
4118              entities['232'] = '&egrave;';
4119              entities['233'] = '&eacute;';
4120              entities['234'] = '&ecirc;';
4121              entities['235'] = '&euml;';
4122              entities['236'] = '&igrave;';
4123              entities['237'] = '&iacute;';
4124              entities['238'] = '&icirc;';
4125              entities['239'] = '&iuml;';
4126              entities['240'] = '&eth;';
4127              entities['241'] = '&ntilde;';
4128              entities['242'] = '&ograve;';
4129              entities['243'] = '&oacute;';
4130              entities['244'] = '&ocirc;';
4131              entities['245'] = '&otilde;';
4132              entities['246'] = '&ouml;';
4133              entities['247'] = '&divide;';
4134              entities['248'] = '&oslash;';
4135              entities['249'] = '&ugrave;';
4136              entities['250'] = '&uacute;';
4137              entities['251'] = '&ucirc;';
4138              entities['252'] = '&uuml;';
4139              entities['253'] = '&yacute;';
4140              entities['254'] = '&thorn;';
4141              entities['255'] = '&yuml;';
4142              }
4143  
4144              if (useQuoteStyle !== 'ENT_NOQUOTES') {
4145              entities['34'] = '&quot;';
4146              }
4147              if (useQuoteStyle === 'ENT_QUOTES') {
4148              entities['39'] = '&#39;';
4149              }
4150              entities['60'] = '&lt;';
4151              entities['62'] = '&gt;';
4152  
4153  
4154              // ascii decimals to real symbols
4155              for (decimal in entities) {
4156              symbol = String.fromCharCode(decimal);
4157              hash_map[symbol] = entities[decimal];
4158              }
4159  
4160              return hash_map;
4161          }
4162  
4163          $(document).ready(function() {
4164  
4165              var date = new Date();
4166              var d = date.getDate();
4167              var m = date.getMonth();
4168              var y = date.getFullYear();
4169  
4170              var DokeosCalendar = $('#calendar').fullCalendar({
4171                  ".$header."
4172                  buttonText: { today: '".addslashes(get_lang('Today'))."', month: '".addslashes(get_lang('MonthView'))."', week: '".addslashes(get_lang('WeekView'))."', day: '".addslashes(get_lang('DayView'))."'}, 
4173                  monthNames: ['".addslashes(ucfirst(get_lang('JanuaryLong')))."', '".addslashes(ucfirst(get_lang('FebruaryLong')))."', '".addslashes(ucfirst(get_lang('MarchLong')))."', '".addslashes(ucfirst(get_lang('AprilLong')))."', '".addslashes(ucfirst(get_lang('MayLong')))."', '".addslashes(ucfirst(get_lang('JuneLong')))."', '".addslashes(ucfirst(get_lang('JulyLong')))."', '".addslashes(ucfirst(get_lang('AugustLong')))."', '".addslashes(ucfirst(get_lang('SeptemberLong')))."', '".addslashes(ucfirst(get_lang('OctoberLong')))."', '".addslashes(ucfirst(get_lang('NovemberLong')))."', '".addslashes(ucfirst(get_lang('DecemberLong')))."'],
4174                  monthNamesShort: ['".addslashes(ucfirst(get_lang('JanuaryShort')))."', '".addslashes(ucfirst(get_lang('FebruaryShort')))."', '".addslashes(ucfirst(get_lang('MarchShort')))."', '".addslashes(ucfirst(get_lang('AprilShort')))."', '".addslashes(ucfirst(get_lang('MayShort')))."', '".addslashes(ucfirst(get_lang('JuneShort')))."', '".addslashes(ucfirst(get_lang('JulyShort')))."', '".addslashes(ucfirst(get_lang('AugustShort')))."', '".addslashes(ucfirst(get_lang('SeptemberShort')))."', '".addslashes(ucfirst(get_lang('OctoberShort')))."', '".addslashes(ucfirst(get_lang('NovemberShort')))."', '".addslashes(ucfirst(get_lang('DecemberShort')))."'],
4175                  dayNames: ['".addslashes(ucfirst(get_lang('SundayLong')))."', '".addslashes(ucfirst(get_lang('MondayLong')))."', '".addslashes(ucfirst(get_lang('TuesdayLong')))."', '".addslashes(ucfirst(get_lang('WednesdayLong')))."', '".addslashes(ucfirst(get_lang('ThursdayLong')))."', '".addslashes(ucfirst(get_lang('FridayLong')))."', '".addslashes(ucfirst(get_lang('SaturdayLong')))."'],
4176                  dayNamesShort: ['".addslashes(ucfirst(get_lang('SundayShort')))."', '".addslashes(ucfirst(get_lang('MondayShort')))."', '".addslashes(ucfirst(get_lang('TuesdayShort')))."', '".addslashes(ucfirst(get_lang('WednesdayShort')))."', '".addslashes(ucfirst(get_lang('ThursdayShort')))."', '".addslashes(ucfirst(get_lang('FridayShort')))."', '".addslashes(ucfirst(get_lang('SaturdayShort')))."'],
4177                  weekMode: 'variable',
4178                  allDaySlot: false,
4179                  firstDay: 1,
4180                  axisFormat: 'HH(:mm)',
4181                  timeFormat: 'HH:mm{ - HH:mm}',
4182                  height: 1200,
4183                  " . $defaultview . "
4184                  editable: true,
4185                  events: \"ajax.php?action=getallevents&output=json\",
4186                  eventMouseover: function(calEvent,jsEvent) {
4187                          // the appropriate visibility icon
4188                          if (calEvent.visibility == 1){
4189                              var visibility_icon = 'visible.gif';
4190                          } else {
4191                              var visibility_icon = 'invisible.gif';
4192      }
4193                          if ($(this).hasClass('personal')) {
4194                              ".$actionicons."
4195                          }
4196                  },
4197                  eventMouseout: function(calEvent,jsEvent) {
4198                      $('.fc-event-actions').remove();
4199                  },
4200                  eventRender: function(calEvent, element) {
4201                      // add the id to the rendered element so that we can use this for the detail
4202                      element.attr('id',calEvent.id);
4203                      $('.fc-event-title',element).html(html_entity_decode(calEvent.title));
4204                  },
4205                  eventDrop: function(event,dayDelta,minuteDelta,allDay,revertFunc) {
4206                      $.ajax({
4207                        url: 'ajax.php',
4208                        data: {action: 'mymove', id: event.id.replace('personal',''), daydelta: dayDelta, minutedelta: minuteDelta}
4209                      });
4210                  },
4211                  dayClick: function(date, allDay, jsEvent, view){
4212                      $(location).attr('href','myagenda.php?action=myadd&date='+$.fullCalendar.formatDate( date, 'yyyy/MM/dd/HH/mm'));
4213                  },
4214                  eventResize: function(event,dayDelta,minuteDelta,revertFunc) {
4215                      $.ajax({
4216                        url: 'ajax.php',
4217                        data: {action: 'myresize', id: event.id, daydelta: dayDelta, minutedelta: minuteDelta}
4218                      });
4219                  }
4220  
4221              });
4222  
4223              $('.fc-event-actions .edit').live('click', function(){
4224                  id=$(this).attr('id');
4225                  $(location).attr('href','myagenda.php?".api_get_cidreq()."&action=myedit&id='+id.replace('edit_personal',''));
4226              });
4227  
4228              $('.fc-event-actions .delete').live('click', function(){
4229                  id=$(this).attr('id');
4230  
4231                  // remove from database
4232                  $.ajax({
4233                    url: 'ajax.php',
4234                    data: {action: 'mydelete', id: id.replace('delete_personal','')}
4235                  });
4236  
4237                  // get the fc_index
4238                  var fc_index = $('.fc-event').index($(this).parent().parent().parent());
4239  
4240                  // remove the fc-event
4241                  $(this).parent().parent().parent().remove();
4242              });
4243  
4244              $('.fc-event-title span').live('click', function(){
4245                  var coursecode = $(this).attr('class')
4246                  $(location).attr('href','agenda.php?cidReq='+coursecode);
4247              });
4248  
4249              // change the size if month view is clicked
4250              $('.fc-button-month').click(function(){
4251                  DokeosCalendar.fullCalendar('option', 'height', 500);
4252              });
4253  
4254              // change the size if month view is clicked
4255              $('.fc-button-agendaWeek, .fc-button-agendaDay').click(function(){
4256                  DokeosCalendar.fullCalendar('option', 'height', 1200);
4257              });
4258  
4259          });
4260      </script>";
4261  
4262  }
4263  ?>