Explorar el Código

Feature #306 - Line endigs cohrrence, Part 1: Converting \r\n line endings (Windows style) to \n (Unix style) in php, html, js, xml, txt files.

Ivan Tcholakov hace 15 años
padre
commit
588a409e3a
Se han modificado 100 ficheros con 27730 adiciones y 27730 borrados
  1. 666 666
      documentation/installation_guide.html
  2. 728 728
      documentation/installation_guide_es_ES.html
  3. 317 317
      documentation/license.html
  4. 340 340
      documentation/license.txt
  5. 199 199
      main/admin/access_url_add_courses_to_url.php
  6. 201 201
      main/admin/access_url_add_sessions_to_url.php
  7. 201 201
      main/admin/access_url_add_users_to_url.php
  8. 145 145
      main/admin/access_url_edit.php
  9. 473 473
      main/admin/access_url_edit_courses_to_url.php
  10. 469 469
      main/admin/access_url_edit_sessions_to_url.php
  11. 469 469
      main/admin/access_url_edit_users_to_url.php
  12. 208 208
      main/admin/access_urls.php
  13. 538 538
      main/admin/add_courses_to_session.php
  14. 26 26
      main/admin/add_users_to_session.php
  15. 3116 3116
      main/admin/calendar.lib.php
  16. 409 409
      main/admin/calendar.php
  17. 212 212
      main/admin/class_user_import.php
  18. 559 559
      main/admin/configure_extensions.php
  19. 174 174
      main/admin/course_import.php
  20. 183 183
      main/admin/course_user_import.php
  21. 264 264
      main/admin/resume_session.php
  22. 371 371
      main/admin/session_add.php
  23. 136 136
      main/admin/session_course_edit.php
  24. 100 100
      main/admin/session_course_list.php
  25. 1 1
      main/admin/session_edit.php
  26. 332 332
      main/admin/session_export.php
  27. 4 4
      main/admin/session_import.php
  28. 143 143
      main/admin/statistics/index.php
  29. 458 458
      main/admin/statistics/statistics.lib.php
  30. 164 164
      main/admin/style_preview.php
  31. 410 410
      main/admin/user_fields.php
  32. 741 741
      main/admin/user_list.php
  33. 337 337
      main/auth/my_progress.php
  34. 460 460
      main/auth/openid/login.php
  35. 160 160
      main/blog/blog_admin.php
  36. 126 126
      main/blog/calendar.php
  37. 158 158
      main/blog/tbl_change.js
  38. 4678 4678
      main/calendar/agenda.inc.php
  39. 45 45
      main/chat/chat_banner.php
  40. 147 147
      main/chat/chat_chat.php
  41. 39 39
      main/chat/chat_footer.php
  42. 125 125
      main/chat/chat_hidden.php
  43. 268 268
      main/chat/chat_message.php
  44. 119 119
      main/chat/chat_whoisonline.php
  45. 34 34
      main/chat/footer_frame.inc.php
  46. 147 147
      main/chat/header_frame.inc.php
  47. 11 11
      main/conference/index.php
  48. 456 456
      main/course_home/2column.php
  49. 308 308
      main/course_home/3column.php
  50. 514 514
      main/course_home/activity.php
  51. 71 71
      main/course_info/maintenance.php
  52. 5 5
      main/css/academica/images/index.html
  53. 5 5
      main/css/baby_orange/images/index.html
  54. 5 5
      main/css/blue_lagoon/images/index.html
  55. 5 5
      main/css/blue_lagoon/index.html
  56. 5 5
      main/css/cool_blue/images/index.html
  57. 5 5
      main/css/cool_blue/index.html
  58. 5 5
      main/css/corporate/images/index.html
  59. 5 5
      main/css/cosmic_campus/images/index.html
  60. 5 5
      main/css/delicious_bordeaux/images/index.html
  61. 5 5
      main/css/delicious_bordeaux/index.html
  62. 5 5
      main/css/dokeos_blue/images/index.html
  63. 5 5
      main/css/dokeos_blue/index.html
  64. 5 5
      main/css/dokeos_classic/images/index.html
  65. 5 5
      main/css/dokeos_classic/index.html
  66. 5 5
      main/css/dokeos_classic_2D/images/index.html
  67. 5 5
      main/css/dokeos_classic_2D/index.html
  68. 5 5
      main/css/empire_green/images/index.html
  69. 5 5
      main/css/empire_green/index.html
  70. 5 5
      main/css/fruity_orange/images/index.html
  71. 5 5
      main/css/fruity_orange/index.html
  72. 5 5
      main/css/medical/images/index.html
  73. 5 5
      main/css/royal_purple/images/index.html
  74. 5 5
      main/css/royal_purple/index.html
  75. 5 5
      main/css/silver_line/images/index.html
  76. 5 5
      main/css/sober_brown/images/index.html
  77. 5 5
      main/css/steel_grey/images/index.html
  78. 5 5
      main/css/steel_grey/index.html
  79. 5 5
      main/css/tasty_olive/images/index.html
  80. 5 5
      main/css/tasty_olive/index.html
  81. 595 595
      main/dropbox/dropbox_class.inc.php
  82. 54 54
      main/dropbox/dropbox_config.inc.php
  83. 442 442
      main/dropbox/dropbox_download.php
  84. 1513 1513
      main/dropbox/dropbox_functions.inc.php
  85. 311 311
      main/dropbox/dropbox_init.inc.php
  86. 677 677
      main/dropbox/dropbox_submit.php
  87. 5 5
      main/dropbox/dropbox_zipdownload.inc.php
  88. 250 250
      main/exercice/addlimits.php
  89. 966 966
      main/exercice/exercise_show.php
  90. 11 11
      main/exercice/export/index.php
  91. 94 94
      main/exercice/feedback.php
  92. 5 5
      main/exercice/hotspot_actionscript.as.php
  93. 5 5
      main/exercice/hotspot_actionscript_admin.as.php
  94. 226 226
      main/exercice/mark_free_answer.php
  95. 212 212
      main/exercice/multiple_answer.class.php
  96. 166 166
      main/exercice/question_create.php
  97. 293 293
      main/exercice/unique_answer.class.php
  98. 258 258
      main/forum/editpost.php
  99. 301 301
      main/forum/forumqualify.php
  100. 241 241
      main/forum/newthread.php

+ 666 - 666
documentation/installation_guide.html

@@ -1,689 +1,689 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head>
-
-
-  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-
-
-
-
-  <title>Dokeos 1.8.6.1 Installation Guide</title><link rel="stylesheet" href="default.css" type="text/css" media="screen,projection" />
-
-
-  <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon" />
-
-
-  <style type="text/css">
-	<!--
-		page { width: 21cm; height: 29.7cm; margin: 2cm }
-		pre { font-family: "Courier New", monospace }
-		p { margin-bottom: 0.21cm }
-		.code {margin: 1em 1em 1em 2em; padding: 0.5em; background-color: rgb(229, 229, 229); vertical-align: top; border: 1px solid #999999;}
-	--></style></head>
-
-<body>
-
-
-<div id="header1">
-<h1>Dokeos 1.8.6.1 FREE : Installation Guide</h1>
-
-</div>
-
-<a href="index.html">Documentation</a> &gt; Installation Guide
-<div id="outerframe">
-<div id="main">
-<p></p>
-
-
-<p>Thank you for downloading Dokeos Babel FREE.</p>
-
-
-<ul>
-
-  <li>Quick preview of <a href="http://www.dokeos.com/en/node/58">Dokeos features&nbsp;</a></li>
-
-  <li>Test Dokeos on <a href="http://campus.dokeos.com">Free Campus</a></li>
-</ul>
-
-
-<p>This guide explains how to install Dokeos FREE. Please read this fully before proceeding with the installation.</p>Check <a href="http://www.dokeos.com/en/buy.php">Dokeos PRO</a> and <a href="http://www.dokeos.com/en/buy.php">Dokeos MEDICAL</a> for a complete learning suite with a Service Level Agreement. <br />
-
-
-<h2><b>Contents</b></h2>
-
-<ol>
-
-  <li><a href="#1._Pre-requisites">Pre-requisites</a></li>
-
-  <li><a href="#2._Installation_of_Dokeos_LMS">Installation of Dokeos LMS</a></li>
-
-  <li><a href="#3._Upgrade_from_a_previous_version_of">Upgrade from a previous version of Dokeos</a></li>
-
-  <li><a href="#4._Troubleshooting">Troubleshooting</a></li>
-
-  <li><a href="#5._Administration_section">Administration section</a></li>
-
-  <li><a href="#6._LDAP">LDAP&nbsp;</a></li>
-
-  <li><a href="#7._Mathematical_formulas">Mathematical formulas with LaTeX</a></li>
-</ol>
-
-
-<br />
-
-<hr style="width: 100%; height: 2px;" />
-<h2><a name="1._Pre-requisites"></a>1. Pre-requisites</h2>
-
-
-Dokeos
-can be installed on Windows, Linux, Mac OS X and UNIX servers
-indifferently. However, we recommend the use of Linux server for
-optimal flexibility, remote control and scalability. <br />
-
-<br />
-
-Dokeos is mainly a LMS running <span style="font-weight: bold;">Apache</span>, <span style="font-weight: bold;">MySQL</span> and <span style="font-weight: bold;">PHP5</span> (the so called <span style="font-weight: bold;">AMP</span> trilogy). <br />
-
-
-<br />
-
-All these software are open source and freely available. <br />
-
-<br />
-
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head>
+
+
+  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+
+
+
+
+  <title>Dokeos 1.8.6.1 Installation Guide</title><link rel="stylesheet" href="default.css" type="text/css" media="screen,projection" />
+
+
+  <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon" />
+
+
+  <style type="text/css">
+	<!--
+		page { width: 21cm; height: 29.7cm; margin: 2cm }
+		pre { font-family: "Courier New", monospace }
+		p { margin-bottom: 0.21cm }
+		.code {margin: 1em 1em 1em 2em; padding: 0.5em; background-color: rgb(229, 229, 229); vertical-align: top; border: 1px solid #999999;}
+	--></style></head>
+
+<body>
+
+
+<div id="header1">
+<h1>Dokeos 1.8.6.1 FREE : Installation Guide</h1>
+
+</div>
+
+<a href="index.html">Documentation</a> &gt; Installation Guide
+<div id="outerframe">
+<div id="main">
+<p></p>
+
+
+<p>Thank you for downloading Dokeos Babel FREE.</p>
+
+
+<ul>
+
+  <li>Quick preview of <a href="http://www.dokeos.com/en/node/58">Dokeos features&nbsp;</a></li>
+
+  <li>Test Dokeos on <a href="http://campus.dokeos.com">Free Campus</a></li>
+</ul>
+
+
+<p>This guide explains how to install Dokeos FREE. Please read this fully before proceeding with the installation.</p>Check <a href="http://www.dokeos.com/en/buy.php">Dokeos PRO</a> and <a href="http://www.dokeos.com/en/buy.php">Dokeos MEDICAL</a> for a complete learning suite with a Service Level Agreement. <br />
+
+
+<h2><b>Contents</b></h2>
+
+<ol>
+
+  <li><a href="#1._Pre-requisites">Pre-requisites</a></li>
+
+  <li><a href="#2._Installation_of_Dokeos_LMS">Installation of Dokeos LMS</a></li>
+
+  <li><a href="#3._Upgrade_from_a_previous_version_of">Upgrade from a previous version of Dokeos</a></li>
+
+  <li><a href="#4._Troubleshooting">Troubleshooting</a></li>
+
+  <li><a href="#5._Administration_section">Administration section</a></li>
+
+  <li><a href="#6._LDAP">LDAP&nbsp;</a></li>
+
+  <li><a href="#7._Mathematical_formulas">Mathematical formulas with LaTeX</a></li>
+</ol>
+
+
+<br />
+
+<hr style="width: 100%; height: 2px;" />
+<h2><a name="1._Pre-requisites"></a>1. Pre-requisites</h2>
+
+
+Dokeos
+can be installed on Windows, Linux, Mac OS X and UNIX servers
+indifferently. However, we recommend the use of Linux server for
+optimal flexibility, remote control and scalability. <br />
+
+<br />
+
+Dokeos is mainly a LMS running <span style="font-weight: bold;">Apache</span>, <span style="font-weight: bold;">MySQL</span> and <span style="font-weight: bold;">PHP5</span> (the so called <span style="font-weight: bold;">AMP</span> trilogy). <br />
+
+
+<br />
+
+All these software are open source and freely available. <br />
+
+<br />
+
 To run Dokeos <span style="font-weight: bold;">LMS</span> on your server, you need to install WAMP, LAMP or MAMP:
-<ul>
-
-  <li>To install <span style="font-weight: bold;">WAMP</span> (AMP on Windows), we recommend the <a href="http://www.apachefriends.org/en/xampp.html">XAMPP</a> .exe installer<a href="http://www.apachefriends.org/en/xampp.html"></a></li>
-
-  <li>To install <span style="font-weight: bold;">LAMP</span>
-(AMP on Linux), use the Package manager of your favourite distribution (Synaptic, RPMFinder etc.).
-For instance, on a Ubuntu server,&nbsp;use Shell or Synaptic following the
-    <a href="http://ubuntuguide.org/wiki/Ubuntu:Feisty#Apache_HTTP_Server">Ubuntuguide on Apache</a> and the following sections</li>
-
-  <li>To install <span style="font-weight: bold;">MAMP</span> (AMP on Mac OS X), refer to the <a href="http://www.mamp.info/en/index.php">MAMP</a> dedicated website<a href="http://www.mamp.info/en/index.php"></a></li>
-</ul>
-
-
-<br />
-
-
-<h3><span style="font-weight: bold;">MySQL database server</span></h3>
-
-You will need a login and password allowing to administrate and create
-at least one database. By default, Dokeos will create a new database
-for each course created. It means your host should allow you to create
-and administrate several databases. You can also install Dokeos using
-only one database, in that case you have to select this option during
-the installation.<span style="font-weight: bold;"><br />
-
-</span>
-<hr style="width: 100%; height: 2px;" />
-<h2><a name="2._Installation_of_Dokeos_LMS"></a><span style="font-weight: bold;">2. Installation of Dokeos LMS</span></h2>
-
+<ul>
+
+  <li>To install <span style="font-weight: bold;">WAMP</span> (AMP on Windows), we recommend the <a href="http://www.apachefriends.org/en/xampp.html">XAMPP</a> .exe installer<a href="http://www.apachefriends.org/en/xampp.html"></a></li>
+
+  <li>To install <span style="font-weight: bold;">LAMP</span>
+(AMP on Linux), use the Package manager of your favourite distribution (Synaptic, RPMFinder etc.).
+For instance, on a Ubuntu server,&nbsp;use Shell or Synaptic following the
+    <a href="http://ubuntuguide.org/wiki/Ubuntu:Feisty#Apache_HTTP_Server">Ubuntuguide on Apache</a> and the following sections</li>
+
+  <li>To install <span style="font-weight: bold;">MAMP</span> (AMP on Mac OS X), refer to the <a href="http://www.mamp.info/en/index.php">MAMP</a> dedicated website<a href="http://www.mamp.info/en/index.php"></a></li>
+</ul>
+
+
+<br />
+
+
+<h3><span style="font-weight: bold;">MySQL database server</span></h3>
+
+You will need a login and password allowing to administrate and create
+at least one database. By default, Dokeos will create a new database
+for each course created. It means your host should allow you to create
+and administrate several databases. You can also install Dokeos using
+only one database, in that case you have to select this option during
+the installation.<span style="font-weight: bold;"><br />
+
+</span>
+<hr style="width: 100%; height: 2px;" />
+<h2><a name="2._Installation_of_Dokeos_LMS"></a><span style="font-weight: bold;">2. Installation of Dokeos LMS</span></h2>
+
 <a href="http://www.dokeos.com/download.php"></a>
-<ul>
-
-  <li><a href="http://www.dokeos.com/node/33">Download Dokeos LMS</a></li>
-
-  <li>Unzip it</li>
-
-  <li>Copy the dokeos directory in your Apache web directory. This can be
-    <span style="font-weight: bold;">C:\xampp\htdocs\</span> on a Windows server or <span style="font-weight: bold;">/var/www/html/</span> on a Linux server</li>
-
-  <li>Open your web browser (Internet Explorer, Firefox...) and type
-    <span style="font-weight: bold;">http://localhost/dokeos/</span> if you install locally or
-    <span style="font-weight: bold;">http://www.domain.com/dokeos/</span> if you install remotely</li>
-
-  <li>Follow the web installation process. You can accept all default
-values. Consider changing the admin password to remember it.&nbsp;</li>
-</ul>
-
-
-<br />
-
-The following directories need to be readable, writeable and executable for everyone:
-<ul>
-
-  <li>dokeos/main/inc/conf/</li>
-  <li>dokeos/main/upload/users/</li>
-  <li>dokeos/main/default_course_document/</li>
-  <li>dokeos/archive/</li>
-  <li>dokeos/courses/</li>
-  <li>dokeos/home/</li>
-</ul>
-
-(where 'dokeos' is the directory in which you installed Dokeos)
-<p>On Linux, Mac OS X and BSD operating systems you can use the CHMOD
-777 command for this (although we recommend you seek advice from an
-experienced system administrator).
-In Windows, you may need to check the properties of the folders (by
-right-clicking on them).</p>
-
-<p>
+<ul>
+
+  <li><a href="http://www.dokeos.com/node/33">Download Dokeos LMS</a></li>
+
+  <li>Unzip it</li>
+
+  <li>Copy the dokeos directory in your Apache web directory. This can be
+    <span style="font-weight: bold;">C:\xampp\htdocs\</span> on a Windows server or <span style="font-weight: bold;">/var/www/html/</span> on a Linux server</li>
+
+  <li>Open your web browser (Internet Explorer, Firefox...) and type
+    <span style="font-weight: bold;">http://localhost/dokeos/</span> if you install locally or
+    <span style="font-weight: bold;">http://www.domain.com/dokeos/</span> if you install remotely</li>
+
+  <li>Follow the web installation process. You can accept all default
+values. Consider changing the admin password to remember it.&nbsp;</li>
+</ul>
+
+
+<br />
+
+The following directories need to be readable, writeable and executable for everyone:
+<ul>
+
+  <li>dokeos/main/inc/conf/</li>
+  <li>dokeos/main/upload/users/</li>
+  <li>dokeos/main/default_course_document/</li>
+  <li>dokeos/archive/</li>
+  <li>dokeos/courses/</li>
+  <li>dokeos/home/</li>
+</ul>
+
+(where 'dokeos' is the directory in which you installed Dokeos)
+<p>On Linux, Mac OS X and BSD operating systems you can use the CHMOD
+777 command for this (although we recommend you seek advice from an
+experienced system administrator).
+In Windows, you may need to check the properties of the folders (by
+right-clicking on them).</p>
+
+<p>
 2.5. The following files need to be readable and writeable for the web browser,
-only during the installation process:</p>
-
-<ul>
-
-  <li>dokeos/main/inc/conf/configuration.php (if present)</li>
-</ul>
-
-
-<p>On Linux, Mac OS X and BSD operating systems you can use the CHMOD
-666 command for this (although we recommend you seek advice from an
-experienced system administrator).
-In Windows, you may need to check the properties of the files and
-folders (by right-clicking on them).</p>
-
-
-
-
-<p>
-<b>NOTES:</b><br />
-
-Do not modify the home_*.html files directly. Instead,
-choose "Configure the homepage" in the Dokeos administration section.</p>
-
-<p><span style="font-weight: bold;">Windows</span> : with combination packages like XAMPP, out of the box, login and password
-   for MySQL should probably remain empty.</p>
-
-<p></p>
-
-
-<h3><strong> Configuration and security after installation</strong></h3>
-
-<ul>
-
-  <li><strong>Protect your configuration file: </strong>
-make sure no one can overwrite it. You can find the config file in <em>(dokeos folder)</em>/main/inc/conf/configuration.php.
-Make it read-only (windows/xwindows: right-click the file to edit the
-properties. linux/bsd/macosx: use the chmod 444 command). The config
-file is created by Apache so you may need to be root user to change its
-permissions.</li>
-
-  <li><strong>Protect your installation folder: </strong>
-if the <em>(dokeos folder)</em>/main/install
-folder is still accessible, someone could install over your existing
-version (you could lose your data that way). Move the folder somewhere
-out of the web directories so it is not accessible, change its name, or
-edit its properties so no one can read or execute it.</li>
-
-  <li><strong>For better security: </strong>
-making the files world-writable will help you install, and solves many
-issues for people without much admin experience. However, it's better
-security to make the owner of the apache process (often called apache
-or www-data) also owner of all the dokeos files and folders. Ths way,
-these files need only be readable and writable by the Apache process
-owner, not by the entire world.</li>
-
-  <li><strong>Configure your Dokeos installation: </strong>
-in the administration section of Dokeos, you can use the Dokeos Config Settings to adjust the behavior of your installation.</li>
-
-  <li><strong>Configure Dokeos mail: </strong>
-most of Dokeos uses the mail settings from the php.ini file. However,
-the announcements tool uses phpMailer (another free software project)
-and the settings for this tool can be adjusted in <em>(dokeos folder)</em>/main/inc/conf/mail.conf.php.</li>
-</ul>
-
-<br />
-
-
-<h3>PHP configuration</h3>
-
-
-To get the best of Dokeos, you need to finetune PHP settings. Consider : <br />
-
-<ul>
-
-  <li>Editing php.ini file (on windows can be located at <span style="font-weight: bold;">C:\xampp\php\php.ini</span>, on Ubuntu Linux : <span style="font-weight: bold;">/etc/php5/apache2/php.ini</span></li>
-
-  <li>search the word "max" and increase values to optimise the server</li>
-
-  <li>you may want to end up&nbsp;with the following values : </li>
-</ul>
-
-
-
-<div class="code">
-			  max_execution_time = 300&nbsp;&nbsp;&nbsp; ; Maximum execution time of each script, in seconds<br />
-
-			  max_input_time = 600 ; Maximum amount of time each script may spend parsing request data<br />
-
-			  memory_limit = 256M&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ; Maximum amount of memory a script may consume (128MB)<br />
-
-			  post_max_size = 64M<br />
-
-			  upload_max_filesize = 100M</div>
-
-
-
-<p>
-Some users could meet problems if their PHP settings don't fit
-these ones:</p>
-
-<ul>
-
-  <li>short_open_tag       = On</li>
-
-  <li>safe_mode            = Off</li>
-
-  <li>magic_quotes_gpc     = On</li>
-
-  <li>magic_quotes_runtime = Off</li>
-</ul>
-
-
-
-<p>
-Past Dokeos versions required register_globals to be set to On. This is
-no longer necessary, this can be set to Off and Dokeos will work fine.</p>
-
-
-<p><strong>BSD users:</strong> these php libraries have to be included during php installation:</p>
-
-
-<ul>
-
-  <li>php-mysql The mysql shared extension for php</li>
-
-  <li>php-pcre The pcre shared extension for php</li>
-
-  <li>php-session The session shared extension for php</li>
-
-  <li>php-zlib The zlib shared extension for php</li>
-
-  <li>(optional) php-ldap if you want to be able to use LDAP authentication</li>
-</ul>
-
-
-<p><a href="http://dev.mysql.com/doc/mysql/en/index.html"></a><br />
-</p>
-
-
-<hr />
-<h2><a name="3._Upgrade_from_a_previous_version_of"></a>3. Upgrade from a previous version of Dokeos</h2>
-Before upgrading we <b>heavily</b> recommend you do a full backup of the previous
-Dokeos directories and databases. If you are unsure how to achieve this
-please ask your hosting provider for advice.<br />
-
-<p></p>
-
-
-<h3>3.1 Upgrading from Dokeos 1.8.x</h3>
-
-
-<em>If you upgrade from Dokeos 1.8.x</em> :&nbsp;
-<ul>
-  <li> check that you haven't left any customised stylesheet or image*</li>
-  <li> download the Dokeos 1.8.6 Svalbard install package from the <a href="http://www.dokeos.com/en/node/33">Dokeos download page</a></li>
-  <li> unzip the new files of Dokeos 1.8.6 over the files of the older version</li>
-  <li> point your browser on your portal URL + main/install/</li>
-  <li> choose your language and click&nbsp;<span style="font-style: italic;">Upgrade from 1.8.x</span></li>
-</ul>
-
-<br />
-
+only during the installation process:</p>
+
+<ul>
+
+  <li>dokeos/main/inc/conf/configuration.php (if present)</li>
+</ul>
+
+
+<p>On Linux, Mac OS X and BSD operating systems you can use the CHMOD
+666 command for this (although we recommend you seek advice from an
+experienced system administrator).
+In Windows, you may need to check the properties of the files and
+folders (by right-clicking on them).</p>
+
+
+
+
+<p>
+<b>NOTES:</b><br />
+
+Do not modify the home_*.html files directly. Instead,
+choose "Configure the homepage" in the Dokeos administration section.</p>
+
+<p><span style="font-weight: bold;">Windows</span> : with combination packages like XAMPP, out of the box, login and password
+   for MySQL should probably remain empty.</p>
+
+<p></p>
+
+
+<h3><strong> Configuration and security after installation</strong></h3>
+
+<ul>
+
+  <li><strong>Protect your configuration file: </strong>
+make sure no one can overwrite it. You can find the config file in <em>(dokeos folder)</em>/main/inc/conf/configuration.php.
+Make it read-only (windows/xwindows: right-click the file to edit the
+properties. linux/bsd/macosx: use the chmod 444 command). The config
+file is created by Apache so you may need to be root user to change its
+permissions.</li>
+
+  <li><strong>Protect your installation folder: </strong>
+if the <em>(dokeos folder)</em>/main/install
+folder is still accessible, someone could install over your existing
+version (you could lose your data that way). Move the folder somewhere
+out of the web directories so it is not accessible, change its name, or
+edit its properties so no one can read or execute it.</li>
+
+  <li><strong>For better security: </strong>
+making the files world-writable will help you install, and solves many
+issues for people without much admin experience. However, it's better
+security to make the owner of the apache process (often called apache
+or www-data) also owner of all the dokeos files and folders. Ths way,
+these files need only be readable and writable by the Apache process
+owner, not by the entire world.</li>
+
+  <li><strong>Configure your Dokeos installation: </strong>
+in the administration section of Dokeos, you can use the Dokeos Config Settings to adjust the behavior of your installation.</li>
+
+  <li><strong>Configure Dokeos mail: </strong>
+most of Dokeos uses the mail settings from the php.ini file. However,
+the announcements tool uses phpMailer (another free software project)
+and the settings for this tool can be adjusted in <em>(dokeos folder)</em>/main/inc/conf/mail.conf.php.</li>
+</ul>
+
+<br />
+
+
+<h3>PHP configuration</h3>
+
+
+To get the best of Dokeos, you need to finetune PHP settings. Consider : <br />
+
+<ul>
+
+  <li>Editing php.ini file (on windows can be located at <span style="font-weight: bold;">C:\xampp\php\php.ini</span>, on Ubuntu Linux : <span style="font-weight: bold;">/etc/php5/apache2/php.ini</span></li>
+
+  <li>search the word "max" and increase values to optimise the server</li>
+
+  <li>you may want to end up&nbsp;with the following values : </li>
+</ul>
+
+
+
+<div class="code">
+			  max_execution_time = 300&nbsp;&nbsp;&nbsp; ; Maximum execution time of each script, in seconds<br />
+
+			  max_input_time = 600 ; Maximum amount of time each script may spend parsing request data<br />
+
+			  memory_limit = 256M&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ; Maximum amount of memory a script may consume (128MB)<br />
+
+			  post_max_size = 64M<br />
+
+			  upload_max_filesize = 100M</div>
+
+
+
+<p>
+Some users could meet problems if their PHP settings don't fit
+these ones:</p>
+
+<ul>
+
+  <li>short_open_tag       = On</li>
+
+  <li>safe_mode            = Off</li>
+
+  <li>magic_quotes_gpc     = On</li>
+
+  <li>magic_quotes_runtime = Off</li>
+</ul>
+
+
+
+<p>
+Past Dokeos versions required register_globals to be set to On. This is
+no longer necessary, this can be set to Off and Dokeos will work fine.</p>
+
+
+<p><strong>BSD users:</strong> these php libraries have to be included during php installation:</p>
+
+
+<ul>
+
+  <li>php-mysql The mysql shared extension for php</li>
+
+  <li>php-pcre The pcre shared extension for php</li>
+
+  <li>php-session The session shared extension for php</li>
+
+  <li>php-zlib The zlib shared extension for php</li>
+
+  <li>(optional) php-ldap if you want to be able to use LDAP authentication</li>
+</ul>
+
+
+<p><a href="http://dev.mysql.com/doc/mysql/en/index.html"></a><br />
+</p>
+
+
+<hr />
+<h2><a name="3._Upgrade_from_a_previous_version_of"></a>3. Upgrade from a previous version of Dokeos</h2>
+Before upgrading we <b>heavily</b> recommend you do a full backup of the previous
+Dokeos directories and databases. If you are unsure how to achieve this
+please ask your hosting provider for advice.<br />
+
+<p></p>
+
+
+<h3>3.1 Upgrading from Dokeos 1.8.x</h3>
+
+
+<em>If you upgrade from Dokeos 1.8.x</em> :&nbsp;
+<ul>
+  <li> check that you haven't left any customised stylesheet or image*</li>
+  <li> download the Dokeos 1.8.6 Svalbard install package from the <a href="http://www.dokeos.com/en/node/33">Dokeos download page</a></li>
+  <li> unzip the new files of Dokeos 1.8.6 over the files of the older version</li>
+  <li> point your browser on your portal URL + main/install/</li>
+  <li> choose your language and click&nbsp;<span style="font-style: italic;">Upgrade from 1.8.x</span></li>
+</ul>
+
+<br />
+
 <font size="-1">* Styles and images are located in the main/css or main/img
-directories. You can still recover them from your backup if you have made it.
+directories. You can still recover them from your backup if you have made it.
  Any modified style or image that uses the default style/image name will be
  overwritten by the next step. To avoid loosing your customisations, always
  ensure you copy the styles/images under a new name and use and modify the
  copy, not the original. The original will always be overwritten by newer
- versions. In Dokeos 1.8.5, we have changed the name of several CSS themes.
- Backwards compatibility is ensured by the fact that an upgrade only adds the
-new themes, but you should try and use these new themes rather than sticking
-to the old ones which will be deprecated shortly (not maintained).</font>
-<br />
-
-<p></p>
-
-<h3>3.2 Upgrading from Dokeos 1.6.x</h3>
-
-
+ versions. In Dokeos 1.8.5, we have changed the name of several CSS themes.
+ Backwards compatibility is ensured by the fact that an upgrade only adds the
+new themes, but you should try and use these new themes rather than sticking
+to the old ones which will be deprecated shortly (not maintained).</font>
+<br />
+
+<p></p>
+
+<h3>3.2 Upgrading from Dokeos 1.6.x</h3>
+
+
 <em>If you upgrade from a lower version of Dokeos (1.6.x)</em>, the first
 and most important thing to do is to *move* your current directory to another
-place.<br />
-An easy way to do that is to create a subdirectory called "old_version"
-in your current Dokeos directory and move everything in there using a
-simple "move" command (i.e. under Linux: mkdir old_version; mv *
-old_verion/), then make the old_version/ directory writeable by the web
-server so that courses/ and upload/ directories can be moved from the
-old to the new installation.<br />
-<br />
-The complete process is as follow:
-<ul>
+place.<br />
+An easy way to do that is to create a subdirectory called "old_version"
+in your current Dokeos directory and move everything in there using a
+simple "move" command (i.e. under Linux: mkdir old_version; mv *
+old_verion/), then make the old_version/ directory writeable by the web
+server so that courses/ and upload/ directories can be moved from the
+old to the new installation.<br />
+<br />
+The complete process is as follow:
+<ul>
   <li> move the current Dokeos directory contents to a subdirectory called
-    <em>old_version</em> and make it writeable by the web server. This
-is important to allow the move of the courses/ and upload/ directories
-to the new install</li>
+    <em>old_version</em> and make it writeable by the web server. This
+is important to allow the move of the courses/ and upload/ directories
+to the new install</li>
   <li> download the Dokeos 1.8.6 install package from the
-    <a href="http://www.dokeos.com/en/node/33">Dokeos download page</a></li>
+    <a href="http://www.dokeos.com/en/node/33">Dokeos download page</a></li>
   <li> unzip the new files of Dokeos 1.8.6 in the main Dokeos directory. The
 new directory <em>main</em> should be located directly inside your
-Dokeos root folder</li>
-  <li> point your browser on your portal URL</li>
+Dokeos root folder</li>
+  <li> point your browser on your portal URL</li>
   <li> choose your language and click&nbsp;<span style="font-style: italic;">Upgrade from 1.6.x</span> and confirm the
-current directory of the old version</li>
-</ul>
-
-<br />
-
+current directory of the old version</li>
+</ul>
+
+<br />
+
 <em> NOTE: </em> The upgrade from 1.6.x to 1.8.x implies a revision of
 the customised graphics and styles. The new version uses a complete new
 set of icons and styles, which means the ones from version 1.6 cannot be
 simply reused. The good news is the version 1.8.x allows you to create
 your own style in a separate css folder, that you can then reuse through
-all the 1.8.x versions
-<br />
-
-<p></p>
-
-<p>
-<b>WARNING:</b><br />
-
-Do not delete the previous Dokeos installation directory before installing
-the new one. When the update is successfully finished, you can remove
-the old path.</p>
-
-
-<p>
-<b>NOTE:</b><br />
-
-Do not modify the home_*.html files directly. Instead,
-choose "Configure the homepage" in the Dokeos administration section.</p>
-
-<p></p>
-<h3>3.3 In both cases</h3>
-
-The following directories need to be readable, writeable and executable for the web server:
-<ul>
-  <li>dokeos/main/inc/conf/</li>
-  <li>dokeos/main/upload/users/</li>
-  <li>dokeos/main/default_course_document/</li>
-  <li>dokeos/archive/</li>
-  <li>dokeos/courses/</li>
-  <li>dokeos/home/</li>
-</ul>
-
+all the 1.8.x versions
+<br />
+
+<p></p>
+
+<p>
+<b>WARNING:</b><br />
+
+Do not delete the previous Dokeos installation directory before installing
+the new one. When the update is successfully finished, you can remove
+the old path.</p>
+
+
+<p>
+<b>NOTE:</b><br />
+
+Do not modify the home_*.html files directly. Instead,
+choose "Configure the homepage" in the Dokeos administration section.</p>
+
+<p></p>
+<h3>3.3 In both cases</h3>
+
+The following directories need to be readable, writeable and executable for the web server:
+<ul>
+  <li>dokeos/main/inc/conf/</li>
+  <li>dokeos/main/upload/users/</li>
+  <li>dokeos/main/default_course_document/</li>
+  <li>dokeos/archive/</li>
+  <li>dokeos/courses/</li>
+  <li>dokeos/home/</li>
+</ul>
+
 On Linux, Mac OS X and BSD operating systems you can quick-fix this using the
 CHMOD 777 command, but if you are unsure, we recommend you seek advice for
-your own OS on <a href="http://www.dokeos.com/en/node/66">our forum</a>.
-In Windows, you may need to check the properties of the folders.
-<p></p>
-<h3>3.4 Quick-upgrade from 1.6.x guide for Linux</h3>
-
-
-The following quick-upgrade guide assumes that:
-<ul>
-  <li>the Dokeos database username (for MySQL) is "dokeos_db_user" and your login is "dokeos_user"</li>
-  <li>the Dokeos installation is currently in /var/www/dokeos/ and it has 777 permissions</li>
-  <li>your portal's URL is http://www.portalurl.com/</li>
-</ul>
-
-<br />
-
-
-On the command-line, type:
-<ul>
-  <li>cd /tmp</li>
-  <li>mysqldump -u dokeos_db_user -p --all-databases --result-file=/home/dokeos_user/dokeos_old.sql</li>
-  <li>cp -ra /var/www/dokeos /home/dokeos_user/backup_dokeos</li>
-  <li>mkdir /var/www/dokeos/old_version</li>
-  <li>mv /var/www/dokeos/* /var/www/dokeos/old_version/</li>
-  <li>chmod -R 0777 /var/www/dokeos/old_version/</li>
-  <li>wget http://www.dokeos.com/download/dokeos-1.8.6.tar.gz</li>
-  <li>tar zxvf dokeos-1.8.6.tar.gz</li>
-  <li>sudo cp -ra dokeos-1.8.6/* /var/www/dokeos/</li>
-  <li>rm dokeos-1.8.6.tar.gz</li>
-  <li>sudo rm -r dokeos-1.8.6/</li>
-</ul>
-
-<br />
-
-Then:
-<ul>
-  <li>Direct your browser to http://www.portalurl.com/main/install/</li>
-  <li>Proceed with the installation</li>
-  <li>Review the directories permissions</li>
-</ul>
-
-<p></p>
-
-<p></p>
-
-
-<hr style="width: 100%; height: 2px;" />
-
-<h2><a name="4._Troubleshooting"></a>4. Troubleshooting</h2>
-
-
-<p>If you have&nbsp;problems, go to the <a href="http://www.dokeos.com">Dokeos website</a> and ask a question on the
-<a href="http://www.dokeos.com/en/node/66">support forum</a>. Please read the previous messages first to see if there is
-already an answer to your question. We also maintain a list of
-<a href="http://www.dokeos.com/wiki/index.php/FAQ">Frequently Asked Questions</a>.</p>
-
-
-<h2></h2>
-
-
-<hr style="width: 100%; height: 2px;" />
-<h2><a name="5._Administration_section"></a>5. Administration section</h2>
-
-<p>To access the Dokeos administration section, open browser,
-go to your Dokeos adress and log in with the admin user.
-Then you will see a "Platform admin section" link in the header of the
-web page. There you can manage users, courses, sessions, portal look
-and feel, homepage content, course categories etc.&nbsp;</p>
-
-<p></p>
-<hr style="width: 100%; height: 2px;" />
-<h2><a name="6._LDAP"></a>6. LDAP</h2>
-
-<p>
-<i>This part is optional, only organisations with an LDAP server will need to read this.</i><br />
-
-An LDAP module is already provided in Dokeos, but it has to be configured to make it work.</p>
-
-
-<h3><b>Compiling</b></h3>
-
-<p>
-Linux servers: It's possible that you have to recompile php with ldap support.
-Newer distributions also allow downloading rpms for additional packages.</p>
-
-
-<h3><b>Activating LDAP in Dokeos</b></h3>
-
-
-<p>
-In (dokeos folder)/main/inc/conf/configuration.php, around line 90, you see<br />
-
-//for new login module<br />
-
-//uncomment these to activate ldap<br />
-
-//$extAuthSource['ldap']['login'] = "./main/auth/ldap/login.php";<br />
-
-//$extAuthSource['ldap']['newUser'] = "./main/auth/ldap/newUser.php";<br />
-
-<br />
-
-remove the // from the last two lines to activate LDAP.<br />
-</p>
-
-
-<h3><b>Settings</b></h3>
-
-<p>
-Ask the LDAP server admin for the settings:</p>
-
-<ul>
-
-  <li>ldap server name</li>
-
-  <li>ldap server port (usually 389)</li>
-
-  <li>ldap dc</li>
-</ul>
-Since 1.8.5, you have to change the LDAP settings inside the "Portal
-administration" panel, under "Dokeos configuration settings", section
-"LDAP".
-<br />
-
-As an example, you should find the following kind of values:<br />
-
-LDAP main server's address: "myldapserver.com";  // your ldap server<br />
-
-LDAP main server's port: 389;                 // your ldap server's port number<br />
-
-LDAP domain: "dc=xx, dc=yy, dc=zz"; //domain<br />
-
-<br />
-
-
-<h3><b>Teacher/student status</b></h3>
-
-<p>
-By default, Dokeos will check if the "employeenumber" field has a value. If it has, then Dokeos will
-consider this user as being a teacher.<br />
-
-If you want to change this behaviour, you can edit main/auth/ldap/authldap.php, function ldap_put_user_info_locally(),
-and change the <em>if (empty($info_array[$tutor_field]))</em> condition to whatever suits you.<br />
-
-You can also remove this check by removing the condition and leaving only the <em>$status = STUDENT;</em> line.</p>
-
-
-<h3><b>Protected LDAP servers</b></h3>
-
-
-<p>
-Some LDAP servers do not support anonymous use of the directory services.<br />
-In this case, you should fill in the appropriate fields in the
-administration panel (e.g. "manager" and "mypassword") and Dokeos will
-try to authenticate using these, or fall back to anonymous mode before
-giving up.</p>
-
-
-<h3>LDAP import into sessions</h3>
-
-<p>There is a new set of scripts now that allow you to insert users
-from LDAP directly into a Dokeos session. This, however, relies on a
-set of static choices in the LDAP contact attributes.<br />
-
-The fields used intensively by the Dokeos module are:<br />
-</p>
-
-<ul>
-
-	<li>uid, which is matched to the username in Dokeos</li>
-
-	<li>userPassword, which is matched to the user password, although
-this part will only work for non-encrypted passwords for now, but it
-shouldn't be necessary if using the LDAP server as authentication</li>
-
-	<li>ou should end with the year of the person registration or any
-criteria you will use to filter users, so that they can be retrieved on
-that criteria</li>
-
-	<li>sn is used as the lastname field in Dokeos</li>
-
-	<li>givenName is used as the firstname field in Dokeos</li>
-
-	<li>mail is used as the email field in Dokeos</li>
-</ul>
-
-
-<hr style="width: 100%; height: 2px;" />
-<h2><a name="7._Mathematical_formulas"></a>7. Mathematical formulas with LaTeX</h2>
-
-<i>This part is optional, only organisations planning to use mathematical formulas inside the online editor might want to read this.</i><br /><br />
-
-You can enable mathematical equations writing inside the Dokeos online editor (FCKEditor) by applying the following steps:
-<ul>
-
-	<li>1. Configure your Apache installation to add a cgi-bin directory that contains a symbolic link to the mimetex.cgi in
-<i>dokeos/main/inc/lib/mimetex/</i> (*see below, step 4)</li>
-
-	<li>2. Reload your Apache configuration</li>
-
-	<li>3. Edit the online editor's configuration file <i>dokeos/main/inc/lib/fckeditor/myconfig.php</i> and
-
-    <ul>
-			<li>3.1. Enable the mimetex plugin, find the line //$config['LoadPlugin'][] = 'mimetex'; and modify it to be:
-<b>$config['LoadPlugin'][] = 'mimetex';</b> (remove the double slash)</li>
-
-			<li>3.2. The additional settings <b>$config['MimetexExecutableInstalled']</b> , <b>$config['MimetexExecutableDetectionMethod']</b>
-and <b>$config['MimetexExecutableDetectionTimeout']</b> are configured for best probability
-of automatic detection of the installed on the server file <i>mimetex.cgi</i> or <i>mimetex.exe</i>.
-In rare cases these options might need to be twicked, see the acccompanying comments abou
-these options within the file <i>myconfig.php</i></li>
-
-			<li>3.3. Once the plugin has been activated, almost in all toolbars the corresponding button appears.
-If you need to edit some toolbars, see the configuration files (php) within the directory <i>dokeos/main/inc/lib/fckeditor/toolbars/</i> .
-Here is an example:
-        <div class="code">$config['ToolbarSets']['Normal'] = array(<br />
-&nbsp;&nbsp;array('FitWindow','Bold','Image','Link','PasteWord','MP3',<b>'mimetex'</b>,'Table','Subscript','Superscript','ShowBlocks')<br />
-);</div>
-
-				The item <b>'mimetex'</b> represents the button, you may add it to or remove it from any toolbar.<br /><br />
-			</li>
-    </ul>
-
-    <li>4. To install mimetex executable file, make these changes:</li>
-
-<p>Add the corresponding cgi-bin directory to your Apache configuration could be done, in Apache 2, like this:
-
-    </p>
-<div class="code">
-      ScriptAlias /cgi-bin/ /var/www/cgi-bin/<br />
-&lt;Directory "/var/www/cgi-bin"&gt;<br />
-&nbsp;&nbsp;AllowOverride None<br />
-&nbsp;&nbsp;Options ExecCGI -MultiViews +SymLinksIfOwnerMatch<br />
-&nbsp;&nbsp;Order allow,deny<br />
-&nbsp;&nbsp;Allow from all<br />
-&lt;/Directory&gt;<br />
-    </div>
-
-
-<p>Adding a symbolic link can be done, under Windows, by creating a
-  shortcut to the mimetex.exe file from the cgi-bin directory, or under
-  Linux by issuing the following command:
-
-</p>
-<div class="code">
-  <p>ln -s /var/www/dokeos/main/inc/lib/mimetex/mimetex.cgi /var/www/cgi-bin/mimetex.cgi</p>
-</div>
-<p>If you are reluctant to modify your Apache configuration, alternately you may do at step 4 the following:
-copy mimetex.exe (for windows) or mimetex.cgi (for linux) from <i>dokeos/main/inc/lib/mimetex/</i> directory to your <i>cgi-bin/</i></p>
-    <li>5. Make sure that the file mimetex.cgi (or mimetex.exe) has right to be executed by the web-server process. For example, on a Ubuntu Linux system you may write a command like the following:</li>
-<div class="code">
-  <p>sudo chmod a+x mimetex.cgi</p>
-</div>
-	</ul>
-
-<p>As a result of this procedure, a new button becomes available in your Dokeos online editor, that gives you possibility
-to insert mathematical formulas into your documents.<br />
-
-
-  <br />
-  <br />
-  Contact address: Dokeos, Rue Victor Hugo, 201,&nbsp;B-1030 Brussels, Belgium<br />
-
-  Mail: info@dokeos.com<br />
-
-  Tel. +32 (0)2 669 69 55<br />
-  <br />
-
-</p>
-<hr />
-</div>
-
-</div>
-
-<hr />
-    <a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" style="margin: 1em; float: right;" height="31" width="88" /></a>
-	<a href="http://jigsaw.w3.org/css-validator/">
-		<img src="http://jigsaw.w3.org/css-validator/images/vcss-blue" style="margin: 1em; float: right;" alt="Valid CSS" />
-	</a>
+your own OS on <a href="http://www.dokeos.com/en/node/66">our forum</a>.
+In Windows, you may need to check the properties of the folders.
+<p></p>
+<h3>3.4 Quick-upgrade from 1.6.x guide for Linux</h3>
+
+
+The following quick-upgrade guide assumes that:
+<ul>
+  <li>the Dokeos database username (for MySQL) is "dokeos_db_user" and your login is "dokeos_user"</li>
+  <li>the Dokeos installation is currently in /var/www/dokeos/ and it has 777 permissions</li>
+  <li>your portal's URL is http://www.portalurl.com/</li>
+</ul>
+
+<br />
+
+
+On the command-line, type:
+<ul>
+  <li>cd /tmp</li>
+  <li>mysqldump -u dokeos_db_user -p --all-databases --result-file=/home/dokeos_user/dokeos_old.sql</li>
+  <li>cp -ra /var/www/dokeos /home/dokeos_user/backup_dokeos</li>
+  <li>mkdir /var/www/dokeos/old_version</li>
+  <li>mv /var/www/dokeos/* /var/www/dokeos/old_version/</li>
+  <li>chmod -R 0777 /var/www/dokeos/old_version/</li>
+  <li>wget http://www.dokeos.com/download/dokeos-1.8.6.tar.gz</li>
+  <li>tar zxvf dokeos-1.8.6.tar.gz</li>
+  <li>sudo cp -ra dokeos-1.8.6/* /var/www/dokeos/</li>
+  <li>rm dokeos-1.8.6.tar.gz</li>
+  <li>sudo rm -r dokeos-1.8.6/</li>
+</ul>
+
+<br />
+
+Then:
+<ul>
+  <li>Direct your browser to http://www.portalurl.com/main/install/</li>
+  <li>Proceed with the installation</li>
+  <li>Review the directories permissions</li>
+</ul>
+
+<p></p>
+
+<p></p>
+
+
+<hr style="width: 100%; height: 2px;" />
+
+<h2><a name="4._Troubleshooting"></a>4. Troubleshooting</h2>
+
+
+<p>If you have&nbsp;problems, go to the <a href="http://www.dokeos.com">Dokeos website</a> and ask a question on the
+<a href="http://www.dokeos.com/en/node/66">support forum</a>. Please read the previous messages first to see if there is
+already an answer to your question. We also maintain a list of
+<a href="http://www.dokeos.com/wiki/index.php/FAQ">Frequently Asked Questions</a>.</p>
+
+
+<h2></h2>
+
+
+<hr style="width: 100%; height: 2px;" />
+<h2><a name="5._Administration_section"></a>5. Administration section</h2>
+
+<p>To access the Dokeos administration section, open browser,
+go to your Dokeos adress and log in with the admin user.
+Then you will see a "Platform admin section" link in the header of the
+web page. There you can manage users, courses, sessions, portal look
+and feel, homepage content, course categories etc.&nbsp;</p>
+
+<p></p>
+<hr style="width: 100%; height: 2px;" />
+<h2><a name="6._LDAP"></a>6. LDAP</h2>
+
+<p>
+<i>This part is optional, only organisations with an LDAP server will need to read this.</i><br />
+
+An LDAP module is already provided in Dokeos, but it has to be configured to make it work.</p>
+
+
+<h3><b>Compiling</b></h3>
+
+<p>
+Linux servers: It's possible that you have to recompile php with ldap support.
+Newer distributions also allow downloading rpms for additional packages.</p>
+
+
+<h3><b>Activating LDAP in Dokeos</b></h3>
+
+
+<p>
+In (dokeos folder)/main/inc/conf/configuration.php, around line 90, you see<br />
+
+//for new login module<br />
+
+//uncomment these to activate ldap<br />
+
+//$extAuthSource['ldap']['login'] = "./main/auth/ldap/login.php";<br />
+
+//$extAuthSource['ldap']['newUser'] = "./main/auth/ldap/newUser.php";<br />
+
+<br />
+
+remove the // from the last two lines to activate LDAP.<br />
+</p>
+
+
+<h3><b>Settings</b></h3>
+
+<p>
+Ask the LDAP server admin for the settings:</p>
+
+<ul>
+
+  <li>ldap server name</li>
+
+  <li>ldap server port (usually 389)</li>
+
+  <li>ldap dc</li>
+</ul>
+Since 1.8.5, you have to change the LDAP settings inside the "Portal
+administration" panel, under "Dokeos configuration settings", section
+"LDAP".
+<br />
+
+As an example, you should find the following kind of values:<br />
+
+LDAP main server's address: "myldapserver.com";  // your ldap server<br />
+
+LDAP main server's port: 389;                 // your ldap server's port number<br />
+
+LDAP domain: "dc=xx, dc=yy, dc=zz"; //domain<br />
+
+<br />
+
+
+<h3><b>Teacher/student status</b></h3>
+
+<p>
+By default, Dokeos will check if the "employeenumber" field has a value. If it has, then Dokeos will
+consider this user as being a teacher.<br />
+
+If you want to change this behaviour, you can edit main/auth/ldap/authldap.php, function ldap_put_user_info_locally(),
+and change the <em>if (empty($info_array[$tutor_field]))</em> condition to whatever suits you.<br />
+
+You can also remove this check by removing the condition and leaving only the <em>$status = STUDENT;</em> line.</p>
+
+
+<h3><b>Protected LDAP servers</b></h3>
+
+
+<p>
+Some LDAP servers do not support anonymous use of the directory services.<br />
+In this case, you should fill in the appropriate fields in the
+administration panel (e.g. "manager" and "mypassword") and Dokeos will
+try to authenticate using these, or fall back to anonymous mode before
+giving up.</p>
+
+
+<h3>LDAP import into sessions</h3>
+
+<p>There is a new set of scripts now that allow you to insert users
+from LDAP directly into a Dokeos session. This, however, relies on a
+set of static choices in the LDAP contact attributes.<br />
+
+The fields used intensively by the Dokeos module are:<br />
+</p>
+
+<ul>
+
+	<li>uid, which is matched to the username in Dokeos</li>
+
+	<li>userPassword, which is matched to the user password, although
+this part will only work for non-encrypted passwords for now, but it
+shouldn't be necessary if using the LDAP server as authentication</li>
+
+	<li>ou should end with the year of the person registration or any
+criteria you will use to filter users, so that they can be retrieved on
+that criteria</li>
+
+	<li>sn is used as the lastname field in Dokeos</li>
+
+	<li>givenName is used as the firstname field in Dokeos</li>
+
+	<li>mail is used as the email field in Dokeos</li>
+</ul>
+
+
+<hr style="width: 100%; height: 2px;" />
+<h2><a name="7._Mathematical_formulas"></a>7. Mathematical formulas with LaTeX</h2>
+
+<i>This part is optional, only organisations planning to use mathematical formulas inside the online editor might want to read this.</i><br /><br />
+
+You can enable mathematical equations writing inside the Dokeos online editor (FCKEditor) by applying the following steps:
+<ul>
+
+	<li>1. Configure your Apache installation to add a cgi-bin directory that contains a symbolic link to the mimetex.cgi in
+<i>dokeos/main/inc/lib/mimetex/</i> (*see below, step 4)</li>
+
+	<li>2. Reload your Apache configuration</li>
+
+	<li>3. Edit the online editor's configuration file <i>dokeos/main/inc/lib/fckeditor/myconfig.php</i> and
+
+    <ul>
+			<li>3.1. Enable the mimetex plugin, find the line //$config['LoadPlugin'][] = 'mimetex'; and modify it to be:
+<b>$config['LoadPlugin'][] = 'mimetex';</b> (remove the double slash)</li>
+
+			<li>3.2. The additional settings <b>$config['MimetexExecutableInstalled']</b> , <b>$config['MimetexExecutableDetectionMethod']</b>
+and <b>$config['MimetexExecutableDetectionTimeout']</b> are configured for best probability
+of automatic detection of the installed on the server file <i>mimetex.cgi</i> or <i>mimetex.exe</i>.
+In rare cases these options might need to be twicked, see the acccompanying comments abou
+these options within the file <i>myconfig.php</i></li>
+
+			<li>3.3. Once the plugin has been activated, almost in all toolbars the corresponding button appears.
+If you need to edit some toolbars, see the configuration files (php) within the directory <i>dokeos/main/inc/lib/fckeditor/toolbars/</i> .
+Here is an example:
+        <div class="code">$config['ToolbarSets']['Normal'] = array(<br />
+&nbsp;&nbsp;array('FitWindow','Bold','Image','Link','PasteWord','MP3',<b>'mimetex'</b>,'Table','Subscript','Superscript','ShowBlocks')<br />
+);</div>
+
+				The item <b>'mimetex'</b> represents the button, you may add it to or remove it from any toolbar.<br /><br />
+			</li>
+    </ul>
+
+    <li>4. To install mimetex executable file, make these changes:</li>
+
+<p>Add the corresponding cgi-bin directory to your Apache configuration could be done, in Apache 2, like this:
+
+    </p>
+<div class="code">
+      ScriptAlias /cgi-bin/ /var/www/cgi-bin/<br />
+&lt;Directory "/var/www/cgi-bin"&gt;<br />
+&nbsp;&nbsp;AllowOverride None<br />
+&nbsp;&nbsp;Options ExecCGI -MultiViews +SymLinksIfOwnerMatch<br />
+&nbsp;&nbsp;Order allow,deny<br />
+&nbsp;&nbsp;Allow from all<br />
+&lt;/Directory&gt;<br />
+    </div>
+
+
+<p>Adding a symbolic link can be done, under Windows, by creating a
+  shortcut to the mimetex.exe file from the cgi-bin directory, or under
+  Linux by issuing the following command:
+
+</p>
+<div class="code">
+  <p>ln -s /var/www/dokeos/main/inc/lib/mimetex/mimetex.cgi /var/www/cgi-bin/mimetex.cgi</p>
+</div>
+<p>If you are reluctant to modify your Apache configuration, alternately you may do at step 4 the following:
+copy mimetex.exe (for windows) or mimetex.cgi (for linux) from <i>dokeos/main/inc/lib/mimetex/</i> directory to your <i>cgi-bin/</i></p>
+    <li>5. Make sure that the file mimetex.cgi (or mimetex.exe) has right to be executed by the web-server process. For example, on a Ubuntu Linux system you may write a command like the following:</li>
+<div class="code">
+  <p>sudo chmod a+x mimetex.cgi</p>
+</div>
+	</ul>
+
+<p>As a result of this procedure, a new button becomes available in your Dokeos online editor, that gives you possibility
+to insert mathematical formulas into your documents.<br />
+
+
+  <br />
+  <br />
+  Contact address: Dokeos, Rue Victor Hugo, 201,&nbsp;B-1030 Brussels, Belgium<br />
+
+  Mail: info@dokeos.com<br />
+
+  Tel. +32 (0)2 669 69 55<br />
+  <br />
+
+</p>
+<hr />
+</div>
+
+</div>
+
+<hr />
+    <a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" style="margin: 1em; float: right;" height="31" width="88" /></a>
+	<a href="http://jigsaw.w3.org/css-validator/">
+		<img src="http://jigsaw.w3.org/css-validator/images/vcss-blue" style="margin: 1em; float: right;" alt="Valid CSS" />
+	</a>
 </body></html>

+ 728 - 728
documentation/installation_guide_es_ES.html

@@ -1,763 +1,763 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-<head>
-
-
-  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-
-
-
-  <title>Guia de Instalación de Dokeos 1.8.6.1 Babel</title>
-  <link rel="stylesheet" href="default.css" type="text/css" media="screen,projection" />
-
-
-  <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon" />
-
-
-  <style type="text/css">
-	<!--
-		page { width: 21cm; height: 29.7cm; margin: 2cm }
-		pre { font-family: "Courier New", monospace }
-		p { margin-bottom: 0.21cm }
-		.code {margin: 1em 1em 1em 2em; padding: 0.5em; background-color: rgb(229, 229, 229); vertical-align: top; border: 1px solid #999999;}
-	--></style>
-</head>
-
-<body>
-
-
-<div id="header1">
-<h1>Guía de Instalación de Dokeos 1.8.6.1 Babel</h1>
-
-</div>
-
-<a href="index.html">Documentación</a> &gt; Guía de Instalación
-<div id="outerframe">
-<div id="main">
-<p></p>
-
-
-<p>Gracias por descargar Dokeos, la suite de aprendizaje de código abierto profesional.</p>
-
-
-<ul>
-
-  <li>Vista rapida de las <a href="http://www.dokeos.com/en/node/58">Características de Dokeos&nbsp;</a></li>
-
-  <li>Prueba Dokeos en <a href="http://campus.dokeos.com">Free Campus</a></li>
-
-</ul>
-
-
-<p>Esta guía explica como instalar la Gestión de Aprendizaje de Dokeos. Explica como instalar la conversión a PowerPoint Dokeos Oogie
-y la videoconferencia de Dokeos sin embargo estos paquetes
-no son requeridos para usar Dokeos LMS. &nbsp;Por favor lea completamente este documento antes de proceder con la instalación. </p>
-
-
-Si desea ahorrar tiempo, problemas y dinero, alternativamente puede tener su Portal de Dokeos <a href="http://www.dokeos.com/en/node/6">desplegado</a> o <a href="http://www.dokeos.com/en/node/32">instalado</a> por Dokeos o alguno de sus socios.<br />
-
-
-<h2><b>Contenidos</b></h2>
-
-<ol>
-
-  <li><a href="#1._Pre-requisites">Pre-requisitos</a></li>
-
-  <li><a href="#2._Installation_of_Dokeos_LMS">Instalación de Dokeos LMS</a></li>
-
-  <li><a href="#3._Upgrade_from_a_previous_version_of">Actualizar desde una versión previa de Dokeos</a></li>
-
-  <li><a href="#4._Troubleshooting">Solución de Problemas</a></li>
-
-  <li><a href="#5._Administration_section">Sección de administración</a></li>
-
-  <li><a href="#6._LDAP">LDAP&nbsp;</a></li>
-
-  <li><a href="#7._Mathematical_formulas">Formulas Matemáticas con LaTeX</a></li>
-
-</ol>
-
-
-<br />
-
-<hr style="width: 100%; height: 2px;" />
-<h2><a name="1._Pre-requisites"></a>1. Pre-requisitos</h2>
-
-
-Dokeos
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+
+
+  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+
+
+
+  <title>Guia de Instalación de Dokeos 1.8.6.1 Babel</title>
+  <link rel="stylesheet" href="default.css" type="text/css" media="screen,projection" />
+
+
+  <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon" />
+
+
+  <style type="text/css">
+	<!--
+		page { width: 21cm; height: 29.7cm; margin: 2cm }
+		pre { font-family: "Courier New", monospace }
+		p { margin-bottom: 0.21cm }
+		.code {margin: 1em 1em 1em 2em; padding: 0.5em; background-color: rgb(229, 229, 229); vertical-align: top; border: 1px solid #999999;}
+	--></style>
+</head>
+
+<body>
+
+
+<div id="header1">
+<h1>Guía de Instalación de Dokeos 1.8.6.1 Babel</h1>
+
+</div>
+
+<a href="index.html">Documentación</a> &gt; Guía de Instalación
+<div id="outerframe">
+<div id="main">
+<p></p>
+
+
+<p>Gracias por descargar Dokeos, la suite de aprendizaje de código abierto profesional.</p>
+
+
+<ul>
+
+  <li>Vista rapida de las <a href="http://www.dokeos.com/en/node/58">Características de Dokeos&nbsp;</a></li>
+
+  <li>Prueba Dokeos en <a href="http://campus.dokeos.com">Free Campus</a></li>
+
+</ul>
+
+
+<p>Esta guía explica como instalar la Gestión de Aprendizaje de Dokeos. Explica como instalar la conversión a PowerPoint Dokeos Oogie
+y la videoconferencia de Dokeos sin embargo estos paquetes
+no son requeridos para usar Dokeos LMS. &nbsp;Por favor lea completamente este documento antes de proceder con la instalación. </p>
+
+
+Si desea ahorrar tiempo, problemas y dinero, alternativamente puede tener su Portal de Dokeos <a href="http://www.dokeos.com/en/node/6">desplegado</a> o <a href="http://www.dokeos.com/en/node/32">instalado</a> por Dokeos o alguno de sus socios.<br />
+
+
+<h2><b>Contenidos</b></h2>
+
+<ol>
+
+  <li><a href="#1._Pre-requisites">Pre-requisitos</a></li>
+
+  <li><a href="#2._Installation_of_Dokeos_LMS">Instalación de Dokeos LMS</a></li>
+
+  <li><a href="#3._Upgrade_from_a_previous_version_of">Actualizar desde una versión previa de Dokeos</a></li>
+
+  <li><a href="#4._Troubleshooting">Solución de Problemas</a></li>
+
+  <li><a href="#5._Administration_section">Sección de administración</a></li>
+
+  <li><a href="#6._LDAP">LDAP&nbsp;</a></li>
+
+  <li><a href="#7._Mathematical_formulas">Formulas Matemáticas con LaTeX</a></li>
+
+</ol>
+
+
+<br />
+
+<hr style="width: 100%; height: 2px;" />
+<h2><a name="1._Pre-requisites"></a>1. Pre-requisitos</h2>
+
+
+Dokeos
 puede ser instalado indiferentemente en servidores Windows, Linux, Mac OS X y UNIX.
 Sin embargo, nosotros recomendamos el uso de un servidor Linux para una óptima flexibilidad,
-control remoto y escalabilidad. <br />
-
-<br />
-
-Dokeos es principalmente un LMS que se ejecuta con <span style="font-weight: bold;">Apache</span>, <span style="font-weight: bold;">MySQL</span> y <span style="font-weight: bold;">PHP5</span> (tambien llamada la trilogía <span style="font-weight: bold;">AMP</span>). <br />
-
-<br />
-
-
-Puede ser enriquecida con conversión a &nbsp;PowerPoint (característica llamada Dokeos
-Oogie) mediante el uso de <span style="font-weight: bold;">OpenOffice.org</span> + Java. Quizas usted también desee agregar el plugin de Videoconferencia de Dokeos mediante el uso de <span style="font-weight: bold;">RED5</span>
-servidor de codigo abierto de Flash. <br />
-
-
-<br />
-
-Todo este software es software de código abierto y está disponible libremente. <br />
-
-<br />
-
+control remoto y escalabilidad. <br />
+
+<br />
+
+Dokeos es principalmente un LMS que se ejecuta con <span style="font-weight: bold;">Apache</span>, <span style="font-weight: bold;">MySQL</span> y <span style="font-weight: bold;">PHP5</span> (tambien llamada la trilogía <span style="font-weight: bold;">AMP</span>). <br />
+
+<br />
+
+
+Puede ser enriquecida con conversión a &nbsp;PowerPoint (característica llamada Dokeos
+Oogie) mediante el uso de <span style="font-weight: bold;">OpenOffice.org</span> + Java. Quizas usted también desee agregar el plugin de Videoconferencia de Dokeos mediante el uso de <span style="font-weight: bold;">RED5</span>
+servidor de codigo abierto de Flash. <br />
+
+
+<br />
+
+Todo este software es software de código abierto y está disponible libremente. <br />
+
+<br />
+
 Para ejecutar Dokeos <span style="font-weight: bold;">LMS</span> en su servidor, usted necesita instalar WAMP, LAMP o MAMP:
-<ul>
-
-  <li>Para instalar <span style="font-weight: bold;">WAMP</span> (AMP en Windows), nosotros recomendamos el instalador <a href="http://www.apachefriends.org/en/xampp.html">XAMPP</a> .exe<a href="http://www.apachefriends.org/en/xampp.html"></a></li>
-
-  <li>Para instalar <span style="font-weight: bold;">LAMP</span>
-(AMP en Linux), use el administrador de paquetes de su distribución favorita (Synaptic, RPMFinder etc.).
-Por ejemplo, en un servidor Ubuntu,&nbsp;use Shell o Synaptic siguiendo la
-    <a href="http://ubuntuguide.org/wiki/Ubuntu:Feisty#Apache_HTTP_Server">Ubuntuguide on Apache</a> y las secciones siguientes.</li>
-
-  <li>Para instalar <span style="font-weight: bold;">MAMP</span> (AMP en Mac OS X), referirse al sitio web dedicado a <a href="http://www.mamp.info/en/index.php">MAMP</a><a href="http://www.mamp.info/en/index.php"></a></li>
-
-</ul>
-
-
-<br />
-
-
-<h3><span style="font-weight: bold;">Servidor de Base de Datos MySQL</span></h3>
-
-Usted necesitará una cuenta de acceso y una contraseña que le permita administrar y crear
-al menos una base de datos. De manera predeterminada, Dokeos creará una nueva base de datos
-para cada curso creado. Esto significa que su proveedor debera permitirle crear y
-administrar varias bases de datos. Usted también puede instalar Dokeos y usar
-sólo una base de datos, en ese caso, usted tiene que seleccionar esta opción durante
-la instalación.
-<br />
-
-
-<br />
-
-Para aprovechar la ventaja de la conversión <span style="font-weight: bold;">Oogie</span> de PowerPoint / Impress, usted necesita: <br />
-
-
-<ul>
-
-  <li><a href="http://www.openoffice.org/">OpenOffice.org</a><a href="http://www.openoffice.org/"></a></li>
-
-  <li><a href="http://www.java.com/en/download/manual.jsp">Java Runtime Environment</a><a href="../*%20http://www.java.com/en/download/manual.jsp"></a></li>
-
-</ul>
-
-
-<br />
-
-Para aprovechar la ventaja de la <span style="font-weight: bold;">Videoconferencia</span> de Dokeos, usted necesita:<br />
-
-
-<ul>
-
-  <li><a href="http://osflash.org/red5">Servidor de Flash de Codigo Abierto RED5</a><a href="http://osflash.org/red5"></a></li>
-
-</ul>
-
-
-<span style="font-weight: bold;"><br />
-
-</span>
-<hr style="width: 100%; height: 2px;" />
-<h2><a name="2._Installation_of_Dokeos_LMS"></a><span style="font-weight: bold;">2. Instalación de Dokeos LMS</span></h2>
-
+<ul>
+
+  <li>Para instalar <span style="font-weight: bold;">WAMP</span> (AMP en Windows), nosotros recomendamos el instalador <a href="http://www.apachefriends.org/en/xampp.html">XAMPP</a> .exe<a href="http://www.apachefriends.org/en/xampp.html"></a></li>
+
+  <li>Para instalar <span style="font-weight: bold;">LAMP</span>
+(AMP en Linux), use el administrador de paquetes de su distribución favorita (Synaptic, RPMFinder etc.).
+Por ejemplo, en un servidor Ubuntu,&nbsp;use Shell o Synaptic siguiendo la
+    <a href="http://ubuntuguide.org/wiki/Ubuntu:Feisty#Apache_HTTP_Server">Ubuntuguide on Apache</a> y las secciones siguientes.</li>
+
+  <li>Para instalar <span style="font-weight: bold;">MAMP</span> (AMP en Mac OS X), referirse al sitio web dedicado a <a href="http://www.mamp.info/en/index.php">MAMP</a><a href="http://www.mamp.info/en/index.php"></a></li>
+
+</ul>
+
+
+<br />
+
+
+<h3><span style="font-weight: bold;">Servidor de Base de Datos MySQL</span></h3>
+
+Usted necesitará una cuenta de acceso y una contraseña que le permita administrar y crear
+al menos una base de datos. De manera predeterminada, Dokeos creará una nueva base de datos
+para cada curso creado. Esto significa que su proveedor debera permitirle crear y
+administrar varias bases de datos. Usted también puede instalar Dokeos y usar
+sólo una base de datos, en ese caso, usted tiene que seleccionar esta opción durante
+la instalación.
+<br />
+
+
+<br />
+
+Para aprovechar la ventaja de la conversión <span style="font-weight: bold;">Oogie</span> de PowerPoint / Impress, usted necesita: <br />
+
+
+<ul>
+
+  <li><a href="http://www.openoffice.org/">OpenOffice.org</a><a href="http://www.openoffice.org/"></a></li>
+
+  <li><a href="http://www.java.com/en/download/manual.jsp">Java Runtime Environment</a><a href="../*%20http://www.java.com/en/download/manual.jsp"></a></li>
+
+</ul>
+
+
+<br />
+
+Para aprovechar la ventaja de la <span style="font-weight: bold;">Videoconferencia</span> de Dokeos, usted necesita:<br />
+
+
+<ul>
+
+  <li><a href="http://osflash.org/red5">Servidor de Flash de Codigo Abierto RED5</a><a href="http://osflash.org/red5"></a></li>
+
+</ul>
+
+
+<span style="font-weight: bold;"><br />
+
+</span>
+<hr style="width: 100%; height: 2px;" />
+<h2><a name="2._Installation_of_Dokeos_LMS"></a><span style="font-weight: bold;">2. Instalación de Dokeos LMS</span></h2>
+
 <a href="http://www.dokeos.com/download.php"></a>
-<ul>
-
-  <li><a href="http://www.dokeos.com/node/33">Descargar Dokeos LMS</a></li>
-
-  <li>Descomprimirlo</li>
-
+<ul>
+
+  <li><a href="http://www.dokeos.com/node/33">Descargar Dokeos LMS</a></li>
+
+  <li>Descomprimirlo</li>
+
   <li>Copiar el directorio de dokeos en su directorio web de Apache. Este puede ser
-    <span style="font-weight: bold;">C:\xampp\htdocs\</span> en un servidor Windows o <span style="font-weight: bold;">/var/www/html/</span> en un servidor Linux</li>
-
-  <li>Abrir su navegador web (Internet Explorer, Firefox...) y escribir
-    <span style="font-weight: bold;">http://localhost/dokeos/</span> si se instala de manera local o
-    <span style="font-weight: bold;">http://www.domain.com/dokeos/</span> si se instala remotamente</li>
-
-  <li>Seguir el proceso de instalación web. Usted puede aceptar todos los valores
-predeterminados. Considere cambiar la contraseña de administrador y recuerdela.&nbsp;</li>
-
-</ul>
-
-
-<br />
-
-Los siguientes directorios necesitan tener permisos de lectura, escritura y ejecución para todos:
-<ul>
-  <li>dokeos/main/inc/conf/</li>
-  <li>dokeos/main/upload/users/</li>
-  <li>dokeos/main/default_course_document/</li>
-  <li>dokeos/archive/</li>
-  <li>dokeos/courses/</li>
-  <li>dokeos/home/</li>
-</ul>
-
-(donde 'dokeos' es el directorio en el cual usted instaló Dokeos)
-<p>En Linux, Mac OS X y sistemas operativos BSD usted puede usar el comando CHMOD
-777 para esto (aunque nosotros recomendamos que busque asistencia de un
-administrador de sistemas con experiencia).
-En Windows, es probable que usted necesite revisar las propiedades de las carpetas (mediante el uso
-del clic derecho en ellas).
-</p>
-
-<p>
+    <span style="font-weight: bold;">C:\xampp\htdocs\</span> en un servidor Windows o <span style="font-weight: bold;">/var/www/html/</span> en un servidor Linux</li>
+
+  <li>Abrir su navegador web (Internet Explorer, Firefox...) y escribir
+    <span style="font-weight: bold;">http://localhost/dokeos/</span> si se instala de manera local o
+    <span style="font-weight: bold;">http://www.domain.com/dokeos/</span> si se instala remotamente</li>
+
+  <li>Seguir el proceso de instalación web. Usted puede aceptar todos los valores
+predeterminados. Considere cambiar la contraseña de administrador y recuerdela.&nbsp;</li>
+
+</ul>
+
+
+<br />
+
+Los siguientes directorios necesitan tener permisos de lectura, escritura y ejecución para todos:
+<ul>
+  <li>dokeos/main/inc/conf/</li>
+  <li>dokeos/main/upload/users/</li>
+  <li>dokeos/main/default_course_document/</li>
+  <li>dokeos/archive/</li>
+  <li>dokeos/courses/</li>
+  <li>dokeos/home/</li>
+</ul>
+
+(donde 'dokeos' es el directorio en el cual usted instaló Dokeos)
+<p>En Linux, Mac OS X y sistemas operativos BSD usted puede usar el comando CHMOD
+777 para esto (aunque nosotros recomendamos que busque asistencia de un
+administrador de sistemas con experiencia).
+En Windows, es probable que usted necesite revisar las propiedades de las carpetas (mediante el uso
+del clic derecho en ellas).
+</p>
+
+<p>
 2.5. Los siguientes archivos necesitan tener permisos de lectura y escritura
-para el navegador web, solo durante la instalación de Dokeos:
-</p>
-
-<ul>
-
-  <li>dokeos/main/inc/conf/configuration.php (si esta presente)</li>
-
-</ul>
-
-
-<p>En Linux, Mac OS X y sistemas operativos BSD usted puede usar el comando CHMOD
-666 para esto (aunque nosotros recomendamos que busque asistencia de un
-administrador de sistemas con experiencia).
-En Windows, es probable que usted necesite revisar las propiedades de las carpetas (mediante el uso
-del clic derecho en ellas).
-
-</p>
-
-
-
-
-<p>
-<b>NOTAS:</b><br />
-
-No modifique los archivos home_*.html directamente. En vez de ello,
-seleccione "Configurar la pagina de inicio" en la sección de administración de Dokeos.</p>
-
-<p><span style="font-weight: bold;">Windows</span> : con paquetes combinados como XAMPP, disponibles por todo lado, la cuenta de acceso y contraseña
-   para MySQL probablemente permanecera vacia.</p>
-
-<p></p>
-
-
-<h3><strong> Configuración y seguridad despues de la instalación</strong></h3>
-
-<ul>
-
-  <li><strong>Proteger su archivo de configuración: </strong>
-asegurarse que nadie pueda sobreescribirlo. Usted puede encontrar el archivo de configuración en la <em>(carpeta de dokeos)</em>/main/inc/conf/configuration.php.
+para el navegador web, solo durante la instalación de Dokeos:
+</p>
+
+<ul>
+
+  <li>dokeos/main/inc/conf/configuration.php (si esta presente)</li>
+
+</ul>
+
+
+<p>En Linux, Mac OS X y sistemas operativos BSD usted puede usar el comando CHMOD
+666 para esto (aunque nosotros recomendamos que busque asistencia de un
+administrador de sistemas con experiencia).
+En Windows, es probable que usted necesite revisar las propiedades de las carpetas (mediante el uso
+del clic derecho en ellas).
+
+</p>
+
+
+
+
+<p>
+<b>NOTAS:</b><br />
+
+No modifique los archivos home_*.html directamente. En vez de ello,
+seleccione "Configurar la pagina de inicio" en la sección de administración de Dokeos.</p>
+
+<p><span style="font-weight: bold;">Windows</span> : con paquetes combinados como XAMPP, disponibles por todo lado, la cuenta de acceso y contraseña
+   para MySQL probablemente permanecera vacia.</p>
+
+<p></p>
+
+
+<h3><strong> Configuración y seguridad despues de la instalación</strong></h3>
+
+<ul>
+
+  <li><strong>Proteger su archivo de configuración: </strong>
+asegurarse que nadie pueda sobreescribirlo. Usted puede encontrar el archivo de configuración en la <em>(carpeta de dokeos)</em>/main/inc/conf/configuration.php.
 Hacerla de solo lectura (windows/xwindows: clic derecho en el archivo para editar las propiedades.
 linux/bsd/macosx: usar el comando chmod 444). El archivo de
-configuración es creado por Apache, por lo tanto usted necesita ser adminitrador para cambiar sus
-permisos.</li>
-
-  <li><strong>Proteger su carpeta de instalación: </strong>
-si la <em>(carpeta de dokeos)</em>carpeta /main/install
-es aun accesible, alguien podria instalar de nuevo sobre su versión existente
+configuración es creado por Apache, por lo tanto usted necesita ser adminitrador para cambiar sus
+permisos.</li>
+
+  <li><strong>Proteger su carpeta de instalación: </strong>
+si la <em>(carpeta de dokeos)</em>carpeta /main/install
+es aun accesible, alguien podria instalar de nuevo sobre su versión existente
 (usted puede perder sus datos de esta manera). Mover la carpeta a algún lugar
 fuera de los directorios web para que no se encuentre accesible, cambiar su nombre, o
-editar sus propiedades para que nadie pueda leerlo o ejecutarlo.</li>
-
-  <li><strong>Para mayor seguridad: </strong>
-hacer que los archivos posean permisos de escritura por todos ayudaria a instalar, y resolveria varias
-dudas a las personas sin mucha experiencia en administracion. Sin embargo, es mas seguro
-hacer al propietario del proceso de apache (usualmente llamado apache
-o www-data) tambien propietario de todos los archivos y carpetas de dokeos. De esta manera,
-estos archivos solo tendrian permisos de lectura y escritura por el propietario
-del proceso Apache, y ya no permiso a todo el mundo.</li>
-
-  <li><strong>Configurar su instalación de Dokeos: </strong>
-en la sección de administración de Dokeos, usted puede usar las Opciones de Configuración de Dokeos para ajustar el comportamiento de su instalación.</li>
-
-  <li><strong>Configurar correo de Dokeos: </strong>
-por lo general Dokeos usa las configuraciones de correo del archivo php.ini. Sin embargo,
-la herramienta de anuncios usa phpMailer (otro proyecto de software libre)
-y las configuraciones para esta herramienta pueden ser ajustadas en <em>(la carpeta de dokeos)</em>/main/inc/conf/mail.conf.php.</li>
-
-
-</ul>
-
-<br />
-
-
-<h3>Configuración PHP</h3>
-
-
-Para obtener lo mejor de Dokeos, usted necesita afinar las configuraciones de PHP. Considerar: <br />
-
-<ul>
-
-  <li>Editar el archivo php.ini (en windows puede ser ubicado en <span style="font-weight: bold;">C:\xampp\php\php.ini</span>, en Ubuntu Linux : <span style="font-weight: bold;">/etc/php5/apache2/php.ini</span></li>
-
-  <li>buscar la palabra "max" y incrementar los valores para optimizar el servidor</li>
-
-  <li>quizas usted desee terminar; con los siguiente valores: </li>
-
-</ul>
-
-<br />
-
-<div class="code">
-			  max_execution_time = 300&nbsp;&nbsp;&nbsp; ; Maximo tiempo de ejecucion para cada script, en segundos<br />
-
-			  max_input_time = 600 ; Maxima cantidad de tiempo para cada script que pueda gastar analizando datos solicitados<br />
-
-			  memory_limit = 256M&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ; Maxima cantidad de memoria que un script puede consumir (128MB)<br />
-
-			  post_max_size = 64M<br />
-
-			  upload_max_filesize = 100M
-</div>
-
-<br />
-
-<p>
-Algunos usuarios pueden encontrar problemas si en sus configuraciones de PHP no
-encajan las siguientes:</p>
-
-<ul>
-
-  <li>short_open_tag       = On</li>
-
-  <li>safe_mode            = Off</li>
-
-  <li>magic_quotes_gpc     = On</li>
-
-  <li>magic_quotes_runtime = Off</li>
-
-</ul>
-
-
-
-<p>
-En versiones de Dokeos anteriores se requería que register_globals estuviera configurada en On. Esto ya no
-necesario, puede estar configurado en Off y Dokeos funcionará bien.
-</p>
-
-
-<p><strong>Usuarios BSD:</strong> estas bibliotecas de php tienen que ser incluidas durante la instalación de php:</p>
-
-
-<ul>
-
-  <li>php-mysql La extensión compartida de mysql para php</li>
-
-  <li>php-pcre La extensión compartida de pcre para php</li>
-
-  <li>php-session La extensión compartida de sesión para php</li>
-
-  <li>php-zlib La extensión compartida de zlib para php</li>
-
-  <li>(opcional) php-ldap si se desea habilitar el uso de la autenticación de LDAP</li>
-
-</ul>
-
-
-<p><a href="http://dev.mysql.com/doc/mysql/en/index.html"></a><br />
-
-
-</p>
-
-
-<hr />
-<h2><a name="3._Upgrade_from_a_previous_version_of"></a>3. Actualizar desde una versión previa de Dokeos</h2>
-Antes de actualizar, nosotros recomendamos <b>seriamente</b> hacer una copia de seguridad de los directorios
+editar sus propiedades para que nadie pueda leerlo o ejecutarlo.</li>
+
+  <li><strong>Para mayor seguridad: </strong>
+hacer que los archivos posean permisos de escritura por todos ayudaria a instalar, y resolveria varias
+dudas a las personas sin mucha experiencia en administracion. Sin embargo, es mas seguro
+hacer al propietario del proceso de apache (usualmente llamado apache
+o www-data) tambien propietario de todos los archivos y carpetas de dokeos. De esta manera,
+estos archivos solo tendrian permisos de lectura y escritura por el propietario
+del proceso Apache, y ya no permiso a todo el mundo.</li>
+
+  <li><strong>Configurar su instalación de Dokeos: </strong>
+en la sección de administración de Dokeos, usted puede usar las Opciones de Configuración de Dokeos para ajustar el comportamiento de su instalación.</li>
+
+  <li><strong>Configurar correo de Dokeos: </strong>
+por lo general Dokeos usa las configuraciones de correo del archivo php.ini. Sin embargo,
+la herramienta de anuncios usa phpMailer (otro proyecto de software libre)
+y las configuraciones para esta herramienta pueden ser ajustadas en <em>(la carpeta de dokeos)</em>/main/inc/conf/mail.conf.php.</li>
+
+
+</ul>
+
+<br />
+
+
+<h3>Configuración PHP</h3>
+
+
+Para obtener lo mejor de Dokeos, usted necesita afinar las configuraciones de PHP. Considerar: <br />
+
+<ul>
+
+  <li>Editar el archivo php.ini (en windows puede ser ubicado en <span style="font-weight: bold;">C:\xampp\php\php.ini</span>, en Ubuntu Linux : <span style="font-weight: bold;">/etc/php5/apache2/php.ini</span></li>
+
+  <li>buscar la palabra "max" y incrementar los valores para optimizar el servidor</li>
+
+  <li>quizas usted desee terminar; con los siguiente valores: </li>
+
+</ul>
+
+<br />
+
+<div class="code">
+			  max_execution_time = 300&nbsp;&nbsp;&nbsp; ; Maximo tiempo de ejecucion para cada script, en segundos<br />
+
+			  max_input_time = 600 ; Maxima cantidad de tiempo para cada script que pueda gastar analizando datos solicitados<br />
+
+			  memory_limit = 256M&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ; Maxima cantidad de memoria que un script puede consumir (128MB)<br />
+
+			  post_max_size = 64M<br />
+
+			  upload_max_filesize = 100M
+</div>
+
+<br />
+
+<p>
+Algunos usuarios pueden encontrar problemas si en sus configuraciones de PHP no
+encajan las siguientes:</p>
+
+<ul>
+
+  <li>short_open_tag       = On</li>
+
+  <li>safe_mode            = Off</li>
+
+  <li>magic_quotes_gpc     = On</li>
+
+  <li>magic_quotes_runtime = Off</li>
+
+</ul>
+
+
+
+<p>
+En versiones de Dokeos anteriores se requería que register_globals estuviera configurada en On. Esto ya no
+necesario, puede estar configurado en Off y Dokeos funcionará bien.
+</p>
+
+
+<p><strong>Usuarios BSD:</strong> estas bibliotecas de php tienen que ser incluidas durante la instalación de php:</p>
+
+
+<ul>
+
+  <li>php-mysql La extensión compartida de mysql para php</li>
+
+  <li>php-pcre La extensión compartida de pcre para php</li>
+
+  <li>php-session La extensión compartida de sesión para php</li>
+
+  <li>php-zlib La extensión compartida de zlib para php</li>
+
+  <li>(opcional) php-ldap si se desea habilitar el uso de la autenticación de LDAP</li>
+
+</ul>
+
+
+<p><a href="http://dev.mysql.com/doc/mysql/en/index.html"></a><br />
+
+
+</p>
+
+
+<hr />
+<h2><a name="3._Upgrade_from_a_previous_version_of"></a>3. Actualizar desde una versión previa de Dokeos</h2>
+Antes de actualizar, nosotros recomendamos <b>seriamente</b> hacer una copia de seguridad de los directorios
 previos de Dokeos y las bases de datos. Si no esta seguro de como hacer esto, por favor solicite
-asistencia a su proveedor de servicios de almacenamiento.<br />
-
-<p></p>
-
-
-<h3>3.1 Actualizar desde Dokeos 1.8.x</h3>
-
-
-<em>Si usted actualiza desde Dokeos 1.8.x</em> :&nbsp;
-<ul>
-  <li> revisar que usted no haya dejado alguna hoja de estilo personalizada o imagen*</li>
-  <li> descargar el paquete de instalación de Dokeos 1.8.6 desde la <a href="http://www.dokeos.com/en/node/33">pagina de descarga de Dokeos</a></li>
-  <li> descomprimir los nuevos archivos de Dokeos 1.8.6 sobre los archivos de la version anterior</li>
-  <li> apunte su navegador a su portal URL + main/install/</li>
-  <li> escoja su idioma y clic en&nbsp;<span style="font-style: italic;">Actualizar desde 1.8.x</span></li>
-</ul>
-
-<br />
-
-<font size="-1">* Los estilos e imagenes están ubicados en el directorio main/css o main/img.
- Usted aun puede recuperarlos desde la copia de seguridad si es que usted la hizo.
- Cualquier estilo o imagen modificada que use el nombre predeterminado style/image sera
- sobreescrita en el siguiente paso. Para evitar perder cualquier personalizacion, siempre
+asistencia a su proveedor de servicios de almacenamiento.<br />
+
+<p></p>
+
+
+<h3>3.1 Actualizar desde Dokeos 1.8.x</h3>
+
+
+<em>Si usted actualiza desde Dokeos 1.8.x</em> :&nbsp;
+<ul>
+  <li> revisar que usted no haya dejado alguna hoja de estilo personalizada o imagen*</li>
+  <li> descargar el paquete de instalación de Dokeos 1.8.6 desde la <a href="http://www.dokeos.com/en/node/33">pagina de descarga de Dokeos</a></li>
+  <li> descomprimir los nuevos archivos de Dokeos 1.8.6 sobre los archivos de la version anterior</li>
+  <li> apunte su navegador a su portal URL + main/install/</li>
+  <li> escoja su idioma y clic en&nbsp;<span style="font-style: italic;">Actualizar desde 1.8.x</span></li>
+</ul>
+
+<br />
+
+<font size="-1">* Los estilos e imagenes están ubicados en el directorio main/css o main/img.
+ Usted aun puede recuperarlos desde la copia de seguridad si es que usted la hizo.
+ Cualquier estilo o imagen modificada que use el nombre predeterminado style/image sera
+ sobreescrita en el siguiente paso. Para evitar perder cualquier personalizacion, siempre
  asegurese de copiar styles/images bajo un nuevo nombre y use y modifique la copia,
- no el original. El original siempre sera sobreescrito por nuevas versiones.
- En Dokeos 1.8.5, hemos cambiado el nombre de varios temas CSS.
- La compatibilidad hacia atras esta asegurada por el hecho de que una actualizacion solo agrega
- los nuevos temas, sin embargo usted debe tratar y usar estos nuevos temas en lugar de quedarse con los
- antiguos que estaran obsoletos dentro de poco (sin mantenimiento).</font>
-<br />
-
-<p></p>
-
-<h3>3.2 Actualizar desde Dokeos 1.6.x</h3>
-
-
+ no el original. El original siempre sera sobreescrito por nuevas versiones.
+ En Dokeos 1.8.5, hemos cambiado el nombre de varios temas CSS.
+ La compatibilidad hacia atras esta asegurada por el hecho de que una actualizacion solo agrega
+ los nuevos temas, sin embargo usted debe tratar y usar estos nuevos temas en lugar de quedarse con los
+ antiguos que estaran obsoletos dentro de poco (sin mantenimiento).</font>
+<br />
+
+<p></p>
+
+<h3>3.2 Actualizar desde Dokeos 1.6.x</h3>
+
+
 <em>Si usted actualiza desde una version anterior a Dokeos (1.6.x)</em>, lo primero
-y mas importante por hacer es *mover* su directorio actual hacia otro
-lugar.<br />
-Una manera simple de hacer esto es crear un subdirectorio llamado "version_antigua"
-en su directorio actual de Dokeos y luego mover todo dentro de este, usando un
-sencillo comando "mover" (ejem. en Linux: mkdir version_antigua; mv *
-version_antigua/), luego dar permisos de escritura al directorio version_antigua para el servidor web
-para que los directorios courses/ y upload/ puedan moverse desde la antigua instalacion a la nueva.<br />
-<br />
-El proceso completo es como sigue:
-<ul>
+y mas importante por hacer es *mover* su directorio actual hacia otro
+lugar.<br />
+Una manera simple de hacer esto es crear un subdirectorio llamado "version_antigua"
+en su directorio actual de Dokeos y luego mover todo dentro de este, usando un
+sencillo comando "mover" (ejem. en Linux: mkdir version_antigua; mv *
+version_antigua/), luego dar permisos de escritura al directorio version_antigua para el servidor web
+para que los directorios courses/ y upload/ puedan moverse desde la antigua instalacion a la nueva.<br />
+<br />
+El proceso completo es como sigue:
+<ul>
   <li> mover los contenidos del directorio de Dokeos a un subdirectorio llamado
     <em>version_antigua</em> y darle permisos de escritura por el servidor web. Esto
-es importante para permitir mover los directorios courses/ y upload/
-a la nueva instalacion</li>
+es importante para permitir mover los directorios courses/ y upload/
+a la nueva instalacion</li>
   <li> descargar el paquete de instalacion de Dokeos 1.8.6 desde la
-    <a href="http://www.dokeos.com/en/node/33">pagina de descarga de Dokeos</a></li>
+    <a href="http://www.dokeos.com/en/node/33">pagina de descarga de Dokeos</a></li>
   <li> descomprimir los nuevos archivos de Dokeos 1.8.6 en el directorio principal de Dokeos. El nuevo
 directorio <em>principal</em> debe estar ubicado directamente dentro de su
-carpeta raiz de Dokeos</li>
-  <li> apuntar su navegador a la URL de su portal</li>
-  <li> escoja su idioma y clic en&nbsp;<span style="font-style: italic;">Actualizar desde 1.6.x</span> y confirmar el
-directorio actual de la version antigua</li>
-</ul>
-
-<br />
-
+carpeta raiz de Dokeos</li>
+  <li> apuntar su navegador a la URL de su portal</li>
+  <li> escoja su idioma y clic en&nbsp;<span style="font-style: italic;">Actualizar desde 1.6.x</span> y confirmar el
+directorio actual de la version antigua</li>
+</ul>
+
+<br />
+
 <em> NOTA: </em> La actualizacion desde 1.6.x a 1.8.x implica una revision de
-los graficos y estilos personalizados. La nueva version usa un nuevo conjunto completo
-de iconos y estilos, lo cual significa que aquellos provenientes de la version 1.6 no pueden ser
-simplemente reusados. La buena noticia es que la version 1.8.x le permite crear
+los graficos y estilos personalizados. La nueva version usa un nuevo conjunto completo
+de iconos y estilos, lo cual significa que aquellos provenientes de la version 1.6 no pueden ser
+simplemente reusados. La buena noticia es que la version 1.8.x le permite crear
 su propio estilo en una carpeta css separada, la cual se puede reusar en
-todas las versiones 1.8.x
-<br />
-
-<p></p>
-
-<p>
-<b>ADVERTENCIA:</b><br />
-
-No elimine el directorio de instalacion previo de Dokeos antes de instalar
+todas las versiones 1.8.x
+<br />
+
+<p></p>
+
+<p>
+<b>ADVERTENCIA:</b><br />
+
+No elimine el directorio de instalacion previo de Dokeos antes de instalar
 el nuevo. Usted puede remover la ruta antigua, cuando la actualizacion sea finalizada satisfactoriamente.
-</p>
-
-
-<p>
-<b>NOTA:</b><br />
-
+</p>
+
+
+<p>
+<b>NOTA:</b><br />
+
 No modifique los archivos de home_*.html directamente. En lugar de ello,
-seleccione "Configurar la pagina de inicio" en la sección de administración de Dokeos.
-</p>
-
-<p>
-</p>
-<h3>3.3 En ambos casos</h3>
-
-Los siguientes directorios necesitan permisos de lectura, escritura y ejecución para el servidor web:
-<ul>
-  <li>dokeos/main/inc/conf/</li>
-  <li>dokeos/main/upload/users/</li>
-  <li>dokeos/main/default_course_document/</li>
-  <li>dokeos/archive/</li>
-  <li>dokeos/courses/</li>
-  <li>dokeos/home/</li>
-</ul>
-
-En Linux, Mac OS X y sistemas operativos BSD se puede arreglar rapidamente esto, mediante el uso
-del comando CHMOD 777, sin embargo si usted esta inseguro, nosotros le recomandamos que busque
-asistencia para su propio SO en <a href="http://www.dokeos.com/en/node/66">nuestro foro</a>.
-En Windows, quizas usted necesite revisar las propiedades de las carpetas.
-<p>
-</p>
-<h3>3.4 Guía de Actualizacion Rapida desde 1.6.x para Linux</h3>
-
-
-La siguiente guía de actualizacion rapida asume lo siguiente:
-<ul>
-  <li>el nombre de usuario de la base de datos de Dokeos (para MySQL) es "dokeos_db_user" y su acceso es "dokeos_user"</li>
-  <li>actualmente la instalacion de Dokeos esta en /var/www/dokeos/ y tiene permisos 777</li>
-  <li>la URL de su portal es http://www.portalurl.com/</li>
-</ul>
-
-<br />
-
-
-Escribir en la linea de comandos:
-<ul>
-  <li>cd /tmp</li>
-  <li>mysqldump -u dokeos_db_user -p --all-databases --result-file=/home/dokeos_user/dokeos_old.sql</li>
-  <li>cp -ra /var/www/dokeos /home/dokeos_user/backup_dokeos</li>
-  <li>mkdir /var/www/dokeos/version_antigua</li>
-  <li>mv /var/www/dokeos/* /var/www/dokeos/version_antigua/</li>
-  <li>chmod -R 0777 /var/www/dokeos/version_antigua/</li>
-  <li>wget http://www.dokeos.com/download/dokeos-1.8.6.tar.gz</li>
-  <li>tar zxvf dokeos-1.8.6.tar.gz</li>
-  <li>sudo cp -ra dokeos-1.8.6/* /var/www/dokeos/</li>
-  <li>rm dokeos-1.8.6.tar.gz</li>
-  <li>sudo rm -r dokeos-1.8.6/</li>
-</ul>
-
-<br />
-
-Luego:
-<ul>
-  <li>Direccionar su navegador web hacia http://www.portalurl.com/main/install/</li>
-  <li>Proceder con la instalación</li>
-  <li>Revisar los permisos de los directorios</li>
-</ul>
-
-<p></p>
-
-<p></p>
-
-
-<hr style="width: 100%; height: 2px;" />
-
-<h2><a name="4._Troubleshooting"></a>4. Solución de problemas</h2>
-
-
+seleccione "Configurar la pagina de inicio" en la sección de administración de Dokeos.
+</p>
+
+<p>
+</p>
+<h3>3.3 En ambos casos</h3>
+
+Los siguientes directorios necesitan permisos de lectura, escritura y ejecución para el servidor web:
+<ul>
+  <li>dokeos/main/inc/conf/</li>
+  <li>dokeos/main/upload/users/</li>
+  <li>dokeos/main/default_course_document/</li>
+  <li>dokeos/archive/</li>
+  <li>dokeos/courses/</li>
+  <li>dokeos/home/</li>
+</ul>
+
+En Linux, Mac OS X y sistemas operativos BSD se puede arreglar rapidamente esto, mediante el uso
+del comando CHMOD 777, sin embargo si usted esta inseguro, nosotros le recomandamos que busque
+asistencia para su propio SO en <a href="http://www.dokeos.com/en/node/66">nuestro foro</a>.
+En Windows, quizas usted necesite revisar las propiedades de las carpetas.
+<p>
+</p>
+<h3>3.4 Guía de Actualizacion Rapida desde 1.6.x para Linux</h3>
+
+
+La siguiente guía de actualizacion rapida asume lo siguiente:
+<ul>
+  <li>el nombre de usuario de la base de datos de Dokeos (para MySQL) es "dokeos_db_user" y su acceso es "dokeos_user"</li>
+  <li>actualmente la instalacion de Dokeos esta en /var/www/dokeos/ y tiene permisos 777</li>
+  <li>la URL de su portal es http://www.portalurl.com/</li>
+</ul>
+
+<br />
+
+
+Escribir en la linea de comandos:
+<ul>
+  <li>cd /tmp</li>
+  <li>mysqldump -u dokeos_db_user -p --all-databases --result-file=/home/dokeos_user/dokeos_old.sql</li>
+  <li>cp -ra /var/www/dokeos /home/dokeos_user/backup_dokeos</li>
+  <li>mkdir /var/www/dokeos/version_antigua</li>
+  <li>mv /var/www/dokeos/* /var/www/dokeos/version_antigua/</li>
+  <li>chmod -R 0777 /var/www/dokeos/version_antigua/</li>
+  <li>wget http://www.dokeos.com/download/dokeos-1.8.6.tar.gz</li>
+  <li>tar zxvf dokeos-1.8.6.tar.gz</li>
+  <li>sudo cp -ra dokeos-1.8.6/* /var/www/dokeos/</li>
+  <li>rm dokeos-1.8.6.tar.gz</li>
+  <li>sudo rm -r dokeos-1.8.6/</li>
+</ul>
+
+<br />
+
+Luego:
+<ul>
+  <li>Direccionar su navegador web hacia http://www.portalurl.com/main/install/</li>
+  <li>Proceder con la instalación</li>
+  <li>Revisar los permisos de los directorios</li>
+</ul>
+
+<p></p>
+
+<p></p>
+
+
+<hr style="width: 100%; height: 2px;" />
+
+<h2><a name="4._Troubleshooting"></a>4. Solución de problemas</h2>
+
+
 <p>Si usted tiene problemas, ir al <a href="http://www.dokeos.com">Sitio Web de Dokeos</a> y haga una pregunta en el
-<a href="http://www.dokeos.com/en/node/66">foro de soporte</a>. Por favor primero lea los mensajes previos para ver si existe ya
+<a href="http://www.dokeos.com/en/node/66">foro de soporte</a>. Por favor primero lea los mensajes previos para ver si existe ya
 una respuesta a su pregunta. Nosotros tambien mantenemos una lista de
-<a href="http://www.dokeos.com/wiki/index.php/FAQ">Preguntas Frecuentes</a>.
-</p>
-
-
-<h2></h2>
-
-
-<hr style="width: 100%; height: 2px;" />
-<h2><a name="5._Administration_section"></a>5. Sección de Administración</h2>
-
-<p>Para acceder a la sección de administracion de Dokeos, abra el navegador,
-dirijase a su direccion de Dokeos y acceda a el con el usuario admin.
-Luego usted vera un enlace a la "Seccion de administracion de la plataforma" en la parte superior
-de la pagina web. En ese lugar usted puede administrar usuarios, cursos, secciones, apariencia del portal
-contenido de la pagina principal, categorias de cursos, entre otros.</p>
-
-<p>
-</p>
-<hr style="width: 100%; height: 2px;" />
-<h2><a name="6._LDAP"></a>6. LDAP</h2>
-
-<p>
-<i>Esta parte es opcional, solamente organizaciones con un servidor LDAP necesitan leer esto.</i><br />
-
-Un modulo LDAP esta ya provisto en Dokeos, pero tiene que ser configurado para hacerlo funcionar.
-</p>
-
-
-<h3><b>Compilar</b></h3>
-
-<p>
-Servidores Linux: Es posible que se requiera recompilar php con soporte ldap.
-Distribuciones nuevas tambien permiten descargar rpms para los paquetes adicionales.
-</p>
-
-
-<h3><b>Activar LDAP en Dokeos</b></h3>
-
-
-<p>
-En (la carpeta de dokeos)/main/inc/conf/configuration.php, aproximadamente en la line 90, se puede ver<br />
-
-//for new login module<br />
-
-//uncomment these to activate ldap<br />
-
-//$extAuthSource['ldap']['login'] = "./main/auth/ldap/login.php";<br />
-
-//$extAuthSource['ldap']['newUser'] = "./main/auth/ldap/newUser.php";<br />
-
-<br />
-
-remover // de las dos ultimas lineas para activar LDAP.<br />
-
-</p>
-
-
-<h3><b>Configuraciones</b></h3>
-
-<p>
-Solicitar al administrador del servidor LDAP los siguientes datos:
-</p>
-
-<ul>
-
-  <li>nombre del servidor ldap</li>
-
-  <li>puerto del servidor ldap (usualmente 389)</li>
-
-  <li>dc del ldap</li>
-
-</ul>
-Desde 1.8.5, usted tiene que cambiar las configuraciones de LDAP dentro del panel
-"Administración del Portal", bajo "Opciones de configuración de Dokeos", sección
-"LDAP".
-<br />
-
-Como ejemplo, usted debe encontrar tipos de valores como los siguientes:<br />
-
-Dirección principal del servidor LDAP: "miservidorldap.com";  // su servidor ldap<br />
-
-Puerto principal del servidor LDAP: 389;                 // su numero de puerto de su servidor ldap<br />
-
-dominio LDAP: "dc=xx, dc=yy, dc=zz"; //dominio<br />
-
-<br />
-
-
-<h3><b>Estado Profesor/Estudiante</b></h3>
-
-<p>
-De manera predeterminada, Dokeos revisará si el campo "employeenumber" tiene un valor. Si lo tiene, entonces Dokeos
-considerara que este usuario es profesor.<br />
-
-Si usted desea cambiar este comportamiento, usted puede editar main/auth/ldap/authldap.php, la función ldap_put_user_info_locally(),
-y cambiar la condición <em>if (empty($info_array[$tutor_field]))</em> a lo que encaje para usted.<br />
-
-Adicionalmente usted puede remover esta revisión, eliminando la condicion y dejando solamente la linea <em>$status = STUDENT;</em>
-</p>
-
-
-<h3><b>Servidores LDAP protegidos</b></h3>
-
-
-<p>
-Algunos servidores LDAP no permiten usos anonimos de los servicios del directorio.<br />
+<a href="http://www.dokeos.com/wiki/index.php/FAQ">Preguntas Frecuentes</a>.
+</p>
+
+
+<h2></h2>
+
+
+<hr style="width: 100%; height: 2px;" />
+<h2><a name="5._Administration_section"></a>5. Sección de Administración</h2>
+
+<p>Para acceder a la sección de administracion de Dokeos, abra el navegador,
+dirijase a su direccion de Dokeos y acceda a el con el usuario admin.
+Luego usted vera un enlace a la "Seccion de administracion de la plataforma" en la parte superior
+de la pagina web. En ese lugar usted puede administrar usuarios, cursos, secciones, apariencia del portal
+contenido de la pagina principal, categorias de cursos, entre otros.</p>
+
+<p>
+</p>
+<hr style="width: 100%; height: 2px;" />
+<h2><a name="6._LDAP"></a>6. LDAP</h2>
+
+<p>
+<i>Esta parte es opcional, solamente organizaciones con un servidor LDAP necesitan leer esto.</i><br />
+
+Un modulo LDAP esta ya provisto en Dokeos, pero tiene que ser configurado para hacerlo funcionar.
+</p>
+
+
+<h3><b>Compilar</b></h3>
+
+<p>
+Servidores Linux: Es posible que se requiera recompilar php con soporte ldap.
+Distribuciones nuevas tambien permiten descargar rpms para los paquetes adicionales.
+</p>
+
+
+<h3><b>Activar LDAP en Dokeos</b></h3>
+
+
+<p>
+En (la carpeta de dokeos)/main/inc/conf/configuration.php, aproximadamente en la line 90, se puede ver<br />
+
+//for new login module<br />
+
+//uncomment these to activate ldap<br />
+
+//$extAuthSource['ldap']['login'] = "./main/auth/ldap/login.php";<br />
+
+//$extAuthSource['ldap']['newUser'] = "./main/auth/ldap/newUser.php";<br />
+
+<br />
+
+remover // de las dos ultimas lineas para activar LDAP.<br />
+
+</p>
+
+
+<h3><b>Configuraciones</b></h3>
+
+<p>
+Solicitar al administrador del servidor LDAP los siguientes datos:
+</p>
+
+<ul>
+
+  <li>nombre del servidor ldap</li>
+
+  <li>puerto del servidor ldap (usualmente 389)</li>
+
+  <li>dc del ldap</li>
+
+</ul>
+Desde 1.8.5, usted tiene que cambiar las configuraciones de LDAP dentro del panel
+"Administración del Portal", bajo "Opciones de configuración de Dokeos", sección
+"LDAP".
+<br />
+
+Como ejemplo, usted debe encontrar tipos de valores como los siguientes:<br />
+
+Dirección principal del servidor LDAP: "miservidorldap.com";  // su servidor ldap<br />
+
+Puerto principal del servidor LDAP: 389;                 // su numero de puerto de su servidor ldap<br />
+
+dominio LDAP: "dc=xx, dc=yy, dc=zz"; //dominio<br />
+
+<br />
+
+
+<h3><b>Estado Profesor/Estudiante</b></h3>
+
+<p>
+De manera predeterminada, Dokeos revisará si el campo "employeenumber" tiene un valor. Si lo tiene, entonces Dokeos
+considerara que este usuario es profesor.<br />
+
+Si usted desea cambiar este comportamiento, usted puede editar main/auth/ldap/authldap.php, la función ldap_put_user_info_locally(),
+y cambiar la condición <em>if (empty($info_array[$tutor_field]))</em> a lo que encaje para usted.<br />
+
+Adicionalmente usted puede remover esta revisión, eliminando la condicion y dejando solamente la linea <em>$status = STUDENT;</em>
+</p>
+
+
+<h3><b>Servidores LDAP protegidos</b></h3>
+
+
+<p>
+Algunos servidores LDAP no permiten usos anonimos de los servicios del directorio.<br />
 En este caso, usted debe rellenar los campos apropiados en el
-panel de administracion (ejm. "manager" y "mypassword") y Dokeos tratará
-de autenticarse usando esto, o volver al modo anonimo antes de darse por vencido.</p>
-
-
-<h3>Importar LDAP en sesiones</h3>
-
-<p>Existe un nuevo grupo de scripts que permiten ahora insertar usuarios
+panel de administracion (ejm. "manager" y "mypassword") y Dokeos tratará
+de autenticarse usando esto, o volver al modo anonimo antes de darse por vencido.</p>
+
+
+<h3>Importar LDAP en sesiones</h3>
+
+<p>Existe un nuevo grupo de scripts que permiten ahora insertar usuarios
 desde LDAP directamente a una sesion de Dokeos. Sin embargo, esto se basa en un
-conjunto de opciones estaticas en los atributos de contacto de LDAP.<br />
-
-Los campos usados intensivamente por el modulo de Dokeos son:<br />
-
-</p>
-
-<ul>
-
-	<li>uid, el cual encaja con el username en Dokeos</li>
-
-	<li>userPassword, el cual encaja con la contraseña del usuario, aunque
-esta parte solamente funcionara con contraseñas no encriptadas por ahora, pero no seria
-necesario si se usa el servidor LDAP para autenticación.</li>
-
-	<li>ou debe terminar con el año de registro de la persona o cualquier
-criterio que usted use para filtrar a los usuarios, de manera que ellos puedan ser obtenidos
-con ese criterio</li>
-
-	<li>sn es usadl como el campo lastname en Dokeos</li>
-
-	<li>givenName es usado como el campo firstname en Dokeos</li>
-
-	<li>mail es usado como el campo email en Dokeos</li>
-
-</ul>
-
-
-<hr style="width: 100%; height: 2px;" />
-<h2><a name="7._Mathematical_formulas"></a>7. Formulas Matemáticas con LaTeX</h2>
-
-<i>Esta parte es opcional, solo las organizaciones que deseen usar formulas matemáticas dentro del editor en linea podran querer leer esto.</i><br />
-
-Usted puede habilitar la escritura de ecuaciones matemáticas dentro del editor en linea de Dokeos (FCKEditor) aplicando los siguientes pasos:
-<ul>
-
-	<li>1. Configurar su instalación de Apache para agregar un directorio cgi-bin que contenga un enlace simbólico a mimetex.cgi en <i>dokeos/main/inc/lib/mimetex/</i>(*ver debajo)</li>
-
-	<li>2. Recargar su configuración de Apache</li>
-
-	<li>3. Editar <i>dokeos/main/inc/lib/fckeditor/myconfig.js</i> y
-
-    <ul>
-
-			<li>3.1. Agregar <b>FCKConfig.Plugins.Add("mimetex", "en", sOtherPluginPath ) ;</b> al final del archivo</li>
-
-			<li>3.2. Agregar <b>'mimetex'</b> al final de las lineas
-FCKConfig.ToolbarSets donde usted desee que el icono de LaTeX aparezca
-(existe un FCKConfig.ToolbarSets por herramienta). Por ejemplo:
-        <div class="code">FCKConfig.ToolbarSets["Test"] = [<br />
-['Bold','Italic','Underline','StrikeThrough','Subscript','Superscript','Link','Unlink','ImageManager','MP3','OrderedList','UnorderedList','Table','mimetex']<br />
-
-] ;</div>
-
-				Usted puede agregarlo a todas las herramientas, o solamente a las herramientas de documentos y pruebas, por ejemplo<br />
-        <br />
-			</li>
-    </ul>
-	  </li>
-
-	<li>4. En raras ocasiones (sólo si se detecta algún problema), las opciones de configuración del fichero /dokeos/main/inc/lib/fckeditor/fckeditor.php tendrán que ser editadas manualmente</li>
-
-	<li>5. Limpiar la cache de su navegador para probarlo (muy importante). Esto se puede hacer mediante el uso de la página de configuraciones de su navegador</li>
-
-    <li>6. Realice estos cambios:</li>
-</ul>
-
-<i>Agregar el directorio cgi-bin correspondiente a su configuración de Apache puede ser lograda de esta manera, en Apache 2:</i>
-
-<div class="code">
-		  ScriptAlias /cgi-bin/ /var/www/cgi-bin/<br />
-
-  &lt;Directory "/var/www/cgi-bin"&gt;<br />
-
-        &nbsp;&nbsp;AllowOverride None<br />
-
-        &nbsp;&nbsp;Options ExecCGI -MultiViews +SymLinksIfOwnerMatch<br />
-
-        &nbsp;&nbsp;Order allow,deny<br />
-
-        &nbsp;&nbsp;Allow from all<br />
-
-  &lt;/Directory&gt;<br />
-
-	</div>
-
-
+conjunto de opciones estaticas en los atributos de contacto de LDAP.<br />
+
+Los campos usados intensivamente por el modulo de Dokeos son:<br />
+
+</p>
+
+<ul>
+
+	<li>uid, el cual encaja con el username en Dokeos</li>
+
+	<li>userPassword, el cual encaja con la contraseña del usuario, aunque
+esta parte solamente funcionara con contraseñas no encriptadas por ahora, pero no seria
+necesario si se usa el servidor LDAP para autenticación.</li>
+
+	<li>ou debe terminar con el año de registro de la persona o cualquier
+criterio que usted use para filtrar a los usuarios, de manera que ellos puedan ser obtenidos
+con ese criterio</li>
+
+	<li>sn es usadl como el campo lastname en Dokeos</li>
+
+	<li>givenName es usado como el campo firstname en Dokeos</li>
+
+	<li>mail es usado como el campo email en Dokeos</li>
+
+</ul>
+
+
+<hr style="width: 100%; height: 2px;" />
+<h2><a name="7._Mathematical_formulas"></a>7. Formulas Matemáticas con LaTeX</h2>
+
+<i>Esta parte es opcional, solo las organizaciones que deseen usar formulas matemáticas dentro del editor en linea podran querer leer esto.</i><br />
+
+Usted puede habilitar la escritura de ecuaciones matemáticas dentro del editor en linea de Dokeos (FCKEditor) aplicando los siguientes pasos:
+<ul>
+
+	<li>1. Configurar su instalación de Apache para agregar un directorio cgi-bin que contenga un enlace simbólico a mimetex.cgi en <i>dokeos/main/inc/lib/mimetex/</i>(*ver debajo)</li>
+
+	<li>2. Recargar su configuración de Apache</li>
+
+	<li>3. Editar <i>dokeos/main/inc/lib/fckeditor/myconfig.js</i> y
+
+    <ul>
+
+			<li>3.1. Agregar <b>FCKConfig.Plugins.Add("mimetex", "en", sOtherPluginPath ) ;</b> al final del archivo</li>
+
+			<li>3.2. Agregar <b>'mimetex'</b> al final de las lineas
+FCKConfig.ToolbarSets donde usted desee que el icono de LaTeX aparezca
+(existe un FCKConfig.ToolbarSets por herramienta). Por ejemplo:
+        <div class="code">FCKConfig.ToolbarSets["Test"] = [<br />
+['Bold','Italic','Underline','StrikeThrough','Subscript','Superscript','Link','Unlink','ImageManager','MP3','OrderedList','UnorderedList','Table','mimetex']<br />
+
+] ;</div>
+
+				Usted puede agregarlo a todas las herramientas, o solamente a las herramientas de documentos y pruebas, por ejemplo<br />
+        <br />
+			</li>
+    </ul>
+	  </li>
+
+	<li>4. En raras ocasiones (sólo si se detecta algún problema), las opciones de configuración del fichero /dokeos/main/inc/lib/fckeditor/fckeditor.php tendrán que ser editadas manualmente</li>
+
+	<li>5. Limpiar la cache de su navegador para probarlo (muy importante). Esto se puede hacer mediante el uso de la página de configuraciones de su navegador</li>
+
+    <li>6. Realice estos cambios:</li>
+</ul>
+
+<i>Agregar el directorio cgi-bin correspondiente a su configuración de Apache puede ser lograda de esta manera, en Apache 2:</i>
+
+<div class="code">
+		  ScriptAlias /cgi-bin/ /var/www/cgi-bin/<br />
+
+  &lt;Directory "/var/www/cgi-bin"&gt;<br />
+
+        &nbsp;&nbsp;AllowOverride None<br />
+
+        &nbsp;&nbsp;Options ExecCGI -MultiViews +SymLinksIfOwnerMatch<br />
+
+        &nbsp;&nbsp;Order allow,deny<br />
+
+        &nbsp;&nbsp;Allow from all<br />
+
+  &lt;/Directory&gt;<br />
+
+	</div>
+
+
 <i>Agregar un enlace simbólico bajo Windows, puede ser logrado mediante la creación de un
-acceso directo al archivo mimetex.exe desde el directorio cgi-bin, o bajo
-Linux usando el siguiente comando:</i>
+acceso directo al archivo mimetex.exe desde el directorio cgi-bin, o bajo
+Linux usando el siguiente comando:</i>
+
+<div class="code">ln -s /var/www/dokeos/main/inc/lib/mimetex/mimetex.cgi /var/www/cgi-bin/mimetex.cgi</div>
+<p>Si no quiere modificar su Apache, alternativamente a  este punto 6: copie mimetex.exe (para Windows) o mimetex.cgi (para Linux) en su cgi-bin/ </p>
+<p>&nbsp;</p>
+<p>Este procedimiento creará un nuevo icono disponible en su editor en linea de Dokeos
+  , el cual hara posible la inserción de formulas matemáticas en sus documentos.<br />
+  <br />
+
 
-<div class="code">ln -s /var/www/dokeos/main/inc/lib/mimetex/mimetex.cgi /var/www/cgi-bin/mimetex.cgi</div>
-<p>Si no quiere modificar su Apache, alternativamente a  este punto 6: copie mimetex.exe (para Windows) o mimetex.cgi (para Linux) en su cgi-bin/ </p>
-<p>&nbsp;</p>
-<p>Este procedimiento creará un nuevo icono disponible en su editor en linea de Dokeos
-  , el cual hara posible la inserción de formulas matemáticas en sus documentos.<br />
-  <br />
 
+  <br />
+  <br />
 
+  Dirección de Contacto: Dokeos, Rue du Corbeau, 108, B-1030 Brussels, Belgium<br />
 
-  <br />
-  <br />
+  Correo: info@dokeos.com<br />
 
-  Dirección de Contacto: Dokeos, Rue du Corbeau, 108, B-1030 Brussels, Belgium<br />
+  Tel. +32 (0)2 669 69 55<br />
+  <br />
 
-  Correo: info@dokeos.com<br />
+</p>
+<hr />
+</div>
 
-  Tel. +32 (0)2 669 69 55<br />
-  <br />
+</div>
 
-</p>
-<hr />
-</div>
-
-</div>
-
-<hr />
-    <a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" style="margin: 1em; float: right;" height="31" width="88" /></a>
-	<a href="http://jigsaw.w3.org/css-validator/">
-		<img src="http://jigsaw.w3.org/css-validator/images/vcss-blue" style="margin: 1em; float: right;" alt="Valid CSS" />
-	</a>
-</body>
-</html>
+<hr />
+    <a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" style="margin: 1em; float: right;" height="31" width="88" /></a>
+	<a href="http://jigsaw.w3.org/css-validator/">
+		<img src="http://jigsaw.w3.org/css-validator/images/vcss-blue" style="margin: 1em; float: right;" alt="Valid CSS" />
+	</a>
+</body>
+</html>

+ 317 - 317
documentation/license.html

@@ -1,318 +1,318 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-<head>
-  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-  <title>Dokeos License</title>
-  <link rel="stylesheet" href="default.css" type="text/css" media="screen,projection" />
-  <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon" />
-  <style type="text/css">
-	<!--
-		@page { size: 21cm 29.7cm; margin: 2cm }
-		pre { font-family: "Courier New", monospace }
-		p { margin-bottom: 0.21cm }
-		.code {margin: 1em 1em 1em 2em; padding: 0.5em; background-color: rgb(229, 229, 229); vertical-align: top; border: 1px solid #999999;}
-	--></style>
-</head>
-<body>
-<div id="header1">
-<h1>Dokeos License</h1>
-</div>
-<a href="index.html">Documentation</a> &gt; Gnu General Public License
-<div id="outerframe">
-  <div id="main">
-    <blockquote> </blockquote>
-    <p> GNU GENERAL PUBLIC LICENSE<br />
-      Version 2, June 1991</p>
-    <p>Copyright (C) 1989, 1991 Free Software Foundation, Inc.<br />
-      59 Temple Place, Suite 330, Boston, MA  02111-1307  USA<br />
-      Everyone is permitted to copy and distribute verbatim copies<br />
-      of this license document, but changing it is not allowed.</p>
-    <p> Preamble</p>
-    <p> The licenses for most software are designed to take away your<br />
-      freedom to share and change it.  By contrast, the GNU General Public<br />
-      License is intended to guarantee your freedom to share and change free<br />
-      software--to make sure the software is free for all its users.  This<br />
-      General Public License applies to most of the Free Software<br />
-      Foundation's software and to any other program whose authors commit to<br />
-      using it.  (Some other Free Software Foundation software is covered by<br />
-      the GNU Library General Public License instead.)  You can apply it to<br />
-      your programs, too.</p>
-    <p> When we speak of free software, we are referring to freedom, not<br />
-      price.  Our General Public Licenses are designed to make sure that you<br />
-      have the freedom to distribute copies of free software (and charge for<br />
-      this service if you wish), that you receive source code or can get it<br />
-      if you want it, that you can change the software or use pieces of it<br />
-      in new free programs; and that you know you can do these things.</p>
-    <p> To protect your rights, we need to make restrictions that forbid<br />
-      anyone to deny you these rights or to ask you to surrender the rights.<br />
-      These restrictions translate to certain responsibilities for you if you<br />
-      distribute copies of the software, or if you modify it.</p>
-    <p> For example, if you distribute copies of such a program, whether<br />
-      gratis or for a fee, you must give the recipients all the rights that<br />
-      you have.  You must make sure that they, too, receive or can get the<br />
-      source code.  And you must show them these terms so they know their<br />
-      rights.</p>
-    <p> We protect your rights with two steps: (1) copyright the software, and<br />
-      (2) offer you this license which gives you legal permission to copy,<br />
-      distribute and/or modify the software.</p>
-    <p> Also, for each author's protection and ours, we want to make certain<br />
-      that everyone understands that there is no warranty for this free<br />
-      software.  If the software is modified by someone else and passed on, we<br />
-      want its recipients to know that what they have is not the original, so<br />
-      that any problems introduced by others will not reflect on the original<br />
-      authors' reputations.</p>
-    <p> Finally, any free program is threatened constantly by software<br />
-      patents.  We wish to avoid the danger that redistributors of a free<br />
-      program will individually obtain patent licenses, in effect making the<br />
-      program proprietary.  To prevent this, we have made it clear that any<br />
-      patent must be licensed for everyone's free use or not licensed at all.</p>
-    <p> The precise terms and conditions for copying, distribution and<br />
-      modification follow.</p>
-    <p> GNU GENERAL PUBLIC LICENSE<br />
-      TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION</p>
-    <p> 0. This License applies to any program or other work which contains<br />
-      a notice placed by the copyright holder saying it may be distributed<br />
-      under the terms of this General Public License.  The &quot;Program&quot;, below,<br />
-      refers to any such program or work, and a &quot;work based on the Program&quot;<br />
-      means either the Program or any derivative work under copyright law:<br />
-      that is to say, a work containing the Program or a portion of it,<br />
-      either verbatim or with modifications and/or translated into another<br />
-      language.  (Hereinafter, translation is included without limitation in<br />
-      the term &quot;modification&quot;.)  Each licensee is addressed as &quot;you&quot;.</p>
-    <p>Activities other than copying, distribution and modification are not<br />
-      covered by this License; they are outside its scope.  The act of<br />
-      running the Program is not restricted, and the output from the Program<br />
-      is covered only if its contents constitute a work based on the<br />
-      Program (independent of having been made by running the Program).<br />
-      Whether that is true depends on what the Program does.</p>
-    <p> 1. You may copy and distribute verbatim copies of the Program's<br />
-      source code as you receive it, in any medium, provided that you<br />
-      conspicuously and appropriately publish on each copy an appropriate<br />
-      copyright notice and disclaimer of warranty; keep intact all the<br />
-      notices that refer to this License and to the absence of any warranty;<br />
-      and give any other recipients of the Program a copy of this License<br />
-      along with the Program.</p>
-    <p>You may charge a fee for the physical act of transferring a copy, and<br />
-      you may at your option offer warranty protection in exchange for a fee.</p>
-    <p> 2. You may modify your copy or copies of the Program or any portion<br />
-      of it, thus forming a work based on the Program, and copy and<br />
-      distribute such modifications or work under the terms of Section 1<br />
-      above, provided that you also meet all of these conditions:</p>
-    <p> a) You must cause the modified files to carry prominent notices<br />
-      stating that you changed the files and the date of any change.</p>
-    <p> b) You must cause any work that you distribute or publish, that in<br />
-      whole or in part contains or is derived from the Program or any<br />
-      part thereof, to be licensed as a whole at no charge to all third<br />
-      parties under the terms of this License.</p>
-    <p> c) If the modified program normally reads commands interactively<br />
-      when run, you must cause it, when started running for such<br />
-      interactive use in the most ordinary way, to print or display an<br />
-      announcement including an appropriate copyright notice and a<br />
-      notice that there is no warranty (or else, saying that you provide<br />
-      a warranty) and that users may redistribute the program under<br />
-      these conditions, and telling the user how to view a copy of this<br />
-      License.  (Exception: if the Program itself is interactive but<br />
-      does not normally print such an announcement, your work based on<br />
-      the Program is not required to print an announcement.)</p>
-    <p>These requirements apply to the modified work as a whole.  If<br />
-      identifiable sections of that work are not derived from the Program,<br />
-      and can be reasonably considered independent and separate works in<br />
-      themselves, then this License, and its terms, do not apply to those<br />
-      sections when you distribute them as separate works.  But when you<br />
-      distribute the same sections as part of a whole which is a work based<br />
-      on the Program, the distribution of the whole must be on the terms of<br />
-      this License, whose permissions for other licensees extend to the<br />
-      entire whole, and thus to each and every part regardless of who wrote it.</p>
-    <p>Thus, it is not the intent of this section to claim rights or contest<br />
-      your rights to work written entirely by you; rather, the intent is to<br />
-      exercise the right to control the distribution of derivative or<br />
-      collective works based on the Program.</p>
-    <p>In addition, mere aggregation of another work not based on the Program<br />
-      with the Program (or with a work based on the Program) on a volume of<br />
-      a storage or distribution medium does not bring the other work under<br />
-      the scope of this License.</p>
-    <p> 3. You may copy and distribute the Program (or a work based on it,<br />
-      under Section 2) in object code or executable form under the terms of<br />
-      Sections 1 and 2 above provided that you also do one of the following:</p>
-    <p> a) Accompany it with the complete corresponding machine-readable<br />
-      source code, which must be distributed under the terms of Sections<br />
-      1 and 2 above on a medium customarily used for software interchange; or,</p>
-    <p> b) Accompany it with a written offer, valid for at least three<br />
-      years, to give any third party, for a charge no more than your<br />
-      cost of physically performing source distribution, a complete<br />
-      machine-readable copy of the corresponding source code, to be<br />
-      distributed under the terms of Sections 1 and 2 above on a medium<br />
-      customarily used for software interchange; or,</p>
-    <p> c) Accompany it with the information you received as to the offer<br />
-      to distribute corresponding source code.  (This alternative is<br />
-      allowed only for noncommercial distribution and only if you<br />
-      received the program in object code or executable form with such<br />
-      an offer, in accord with Subsection b above.)</p>
-    <p>The source code for a work means the preferred form of the work for<br />
-      making modifications to it.  For an executable work, complete source<br />
-      code means all the source code for all modules it contains, plus any<br />
-      associated interface definition files, plus the scripts used to<br />
-      control compilation and installation of the executable.  However, as a<br />
-      special exception, the source code distributed need not include<br />
-      anything that is normally distributed (in either source or binary<br />
-      form) with the major components (compiler, kernel, and so on) of the<br />
-      operating system on which the executable runs, unless that component<br />
-      itself accompanies the executable.</p>
-    <p>If distribution of executable or object code is made by offering<br />
-      access to copy from a designated place, then offering equivalent<br />
-      access to copy the source code from the same place counts as<br />
-      distribution of the source code, even though third parties are not<br />
-      compelled to copy the source along with the object code.</p>
-    <p> 4. You may not copy, modify, sublicense, or distribute the Program<br />
-      except as expressly provided under this License.  Any attempt<br />
-      otherwise to copy, modify, sublicense or distribute the Program is<br />
-      void, and will automatically terminate your rights under this License.<br />
-      However, parties who have received copies, or rights, from you under<br />
-      this License will not have their licenses terminated so long as such<br />
-      parties remain in full compliance.</p>
-    <p> 5. You are not required to accept this License, since you have not<br />
-      signed it.  However, nothing else grants you permission to modify or<br />
-      distribute the Program or its derivative works.  These actions are<br />
-      prohibited by law if you do not accept this License.  Therefore, by<br />
-      modifying or distributing the Program (or any work based on the<br />
-      Program), you indicate your acceptance of this License to do so, and<br />
-      all its terms and conditions for copying, distributing or modifying<br />
-      the Program or works based on it.</p>
-    <p> 6. Each time you redistribute the Program (or any work based on the<br />
-      Program), the recipient automatically receives a license from the<br />
-      original licensor to copy, distribute or modify the Program subject to<br />
-      these terms and conditions.  You may not impose any further<br />
-      restrictions on the recipients' exercise of the rights granted herein.<br />
-      You are not responsible for enforcing compliance by third parties to<br />
-      this License.</p>
-    <p> 7. If, as a consequence of a court judgment or allegation of patent<br />
-      infringement or for any other reason (not limited to patent issues),<br />
-      conditions are imposed on you (whether by court order, agreement or<br />
-      otherwise) that contradict the conditions of this License, they do not<br />
-      excuse you from the conditions of this License.  If you cannot<br />
-      distribute so as to satisfy simultaneously your obligations under this<br />
-      License and any other pertinent obligations, then as a consequence you<br />
-      may not distribute the Program at all.  For example, if a patent<br />
-      license would not permit royalty-free redistribution of the Program by<br />
-      all those who receive copies directly or indirectly through you, then<br />
-      the only way you could satisfy both it and this License would be to<br />
-      refrain entirely from distribution of the Program.</p>
-    <p>If any portion of this section is held invalid or unenforceable under<br />
-      any particular circumstance, the balance of the section is intended to<br />
-      apply and the section as a whole is intended to apply in other<br />
-      circumstances.</p>
-    <p>It is not the purpose of this section to induce you to infringe any<br />
-      patents or other property right claims or to contest validity of any<br />
-      such claims; this section has the sole purpose of protecting the<br />
-      integrity of the free software distribution system, which is<br />
-      implemented by public license practices.  Many people have made<br />
-      generous contributions to the wide range of software distributed<br />
-      through that system in reliance on consistent application of that<br />
-      system; it is up to the author/donor to decide if he or she is willing<br />
-      to distribute software through any other system and a licensee cannot<br />
-      impose that choice.</p>
-    <p>This section is intended to make thoroughly clear what is believed to<br />
-      be a consequence of the rest of this License.</p>
-    <p> 8. If the distribution and/or use of the Program is restricted in<br />
-      certain countries either by patents or by copyrighted interfaces, the<br />
-      original copyright holder who places the Program under this License<br />
-      may add an explicit geographical distribution limitation excluding<br />
-      those countries, so that distribution is permitted only in or among<br />
-      countries not thus excluded.  In such case, this License incorporates<br />
-      the limitation as if written in the body of this License.</p>
-    <p> 9. The Free Software Foundation may publish revised and/or new versions<br />
-      of the General Public License from time to time.  Such new versions will<br />
-      be similar in spirit to the present version, but may differ in detail to<br />
-      address new problems or concerns.</p>
-    <p>Each version is given a distinguishing version number.  If the Program<br />
-      specifies a version number of this License which applies to it and &quot;any<br />
-      later version&quot;, you have the option of following the terms and conditions<br />
-      either of that version or of any later version published by the Free<br />
-      Software Foundation.  If the Program does not specify a version number of<br />
-      this License, you may choose any version ever published by the Free Software<br />
-      Foundation.</p>
-    <p> 10. If you wish to incorporate parts of the Program into other free<br />
-      programs whose distribution conditions are different, write to the author<br />
-      to ask for permission.  For software which is copyrighted by the Free<br />
-      Software Foundation, write to the Free Software Foundation; we sometimes<br />
-      make exceptions for this.  Our decision will be guided by the two goals<br />
-      of preserving the free status of all derivatives of our free software and<br />
-      of promoting the sharing and reuse of software generally.</p>
-    <p> NO WARRANTY</p>
-    <p> 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY<br />
-      FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN<br />
-      OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES<br />
-      PROVIDE THE PROGRAM &quot;AS IS&quot; WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED<br />
-      OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF<br />
-      MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS<br />
-      TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE<br />
-      PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,<br />
-      REPAIR OR CORRECTION.</p>
-    <p> 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING<br />
-      WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR<br />
-      REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,<br />
-      INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING<br />
-      OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED<br />
-      TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY<br />
-      YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER<br />
-      PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE<br />
-      POSSIBILITY OF SUCH DAMAGES.</p>
-    <p> END OF TERMS AND CONDITIONS</p>
-    <p> How to Apply These Terms to Your New Programs</p>
-    <p> If you develop a new program, and you want it to be of the greatest<br />
-      possible use to the public, the best way to achieve this is to make it<br />
-      free software which everyone can redistribute and change under these terms.</p>
-    <p> To do so, attach the following notices to the program.  It is safest<br />
-      to attach them to the start of each source file to most effectively<br />
-      convey the exclusion of warranty; and each file should have at least<br />
-      the &quot;copyright&quot; line and a pointer to where the full notice is found.</p>
-    <p> &lt;one line to give the program's name and a brief idea of what it does.&gt;<br />
-      Copyright (C) &lt;year&gt;  &lt;name of author&gt;</p>
-    <p> This program is free software; you can redistribute it and/or modify<br />
-      it under the terms of the GNU General Public License as published by<br />
-      the Free Software Foundation; either version 2 of the License, or<br />
-      (at your option) any later version.</p>
-    <p> This program is distributed in the hope that it will be useful,<br />
-      but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
-      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the<br />
-      GNU General Public License for more details.</p>
-    <p> You should have received a copy of the GNU General Public License<br />
-      along with this program; if not, write to the Free Software<br />
-      Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA<br />
-    </p>
-    <p>Also add information on how to contact you by electronic and paper mail.</p>
-    <p>If the program is interactive, make it output a short notice like this<br />
-      when it starts in an interactive mode:</p>
-    <p> Gnomovision version 69, Copyright (C) year name of author<br />
-      Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.<br />
-      This is free software, and you are welcome to redistribute it<br />
-      under certain conditions; type `show c' for details.</p>
-    <p>The hypothetical commands `show w' and `show c' should show the appropriate<br />
-      parts of the General Public License.  Of course, the commands you use may<br />
-      be called something other than `show w' and `show c'; they could even be<br />
-      mouse-clicks or menu items--whatever suits your program.</p>
-    <p>You should also get your employer (if you work as a programmer) or your<br />
-      school, if any, to sign a &quot;copyright disclaimer&quot; for the program, if<br />
-      necessary.  Here is a sample; alter the names:</p>
-    <p> Yoyodyne, Inc., hereby disclaims all copyright interest in the program<br />
-      `Gnomovision' (which makes passes at compilers) written by James Hacker.</p>
-    <p> &lt;signature of Ty Coon&gt;, 1 April 1989<br />
-      Ty Coon, President of Vice</p>
-    <p>This General Public License does not permit incorporating your program into<br />
-      proprietary programs.  If your program is a subroutine library, you may<br />
-      consider it more useful to permit linking proprietary applications with the<br />
-      library.  If this is what you want to do, use the GNU Library General<br />
-      Public License instead of this License.<br />
-    </p>
-  </div>
-</div>
-<hr/>
-    <a href="http://validator.w3.org/check?uri=referer"><img
-        src="http://www.w3.org/Icons/valid-xhtml10-blue"
-        alt="Valid XHTML 1.0 Transitional" height="31" width="88" style="float: right; margin: 1em;" /></a>
-	<a href="http://jigsaw.w3.org/css-validator/">
-		<img src="http://jigsaw.w3.org/css-validator/images/vcss-blue"  style="float: right; margin: 1em;"
-        alt="Valid CSS" />
-	</a>
-</body>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+  <title>Dokeos License</title>
+  <link rel="stylesheet" href="default.css" type="text/css" media="screen,projection" />
+  <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon" />
+  <style type="text/css">
+	<!--
+		@page { size: 21cm 29.7cm; margin: 2cm }
+		pre { font-family: "Courier New", monospace }
+		p { margin-bottom: 0.21cm }
+		.code {margin: 1em 1em 1em 2em; padding: 0.5em; background-color: rgb(229, 229, 229); vertical-align: top; border: 1px solid #999999;}
+	--></style>
+</head>
+<body>
+<div id="header1">
+<h1>Dokeos License</h1>
+</div>
+<a href="index.html">Documentation</a> &gt; Gnu General Public License
+<div id="outerframe">
+  <div id="main">
+    <blockquote> </blockquote>
+    <p> GNU GENERAL PUBLIC LICENSE<br />
+      Version 2, June 1991</p>
+    <p>Copyright (C) 1989, 1991 Free Software Foundation, Inc.<br />
+      59 Temple Place, Suite 330, Boston, MA  02111-1307  USA<br />
+      Everyone is permitted to copy and distribute verbatim copies<br />
+      of this license document, but changing it is not allowed.</p>
+    <p> Preamble</p>
+    <p> The licenses for most software are designed to take away your<br />
+      freedom to share and change it.  By contrast, the GNU General Public<br />
+      License is intended to guarantee your freedom to share and change free<br />
+      software--to make sure the software is free for all its users.  This<br />
+      General Public License applies to most of the Free Software<br />
+      Foundation's software and to any other program whose authors commit to<br />
+      using it.  (Some other Free Software Foundation software is covered by<br />
+      the GNU Library General Public License instead.)  You can apply it to<br />
+      your programs, too.</p>
+    <p> When we speak of free software, we are referring to freedom, not<br />
+      price.  Our General Public Licenses are designed to make sure that you<br />
+      have the freedom to distribute copies of free software (and charge for<br />
+      this service if you wish), that you receive source code or can get it<br />
+      if you want it, that you can change the software or use pieces of it<br />
+      in new free programs; and that you know you can do these things.</p>
+    <p> To protect your rights, we need to make restrictions that forbid<br />
+      anyone to deny you these rights or to ask you to surrender the rights.<br />
+      These restrictions translate to certain responsibilities for you if you<br />
+      distribute copies of the software, or if you modify it.</p>
+    <p> For example, if you distribute copies of such a program, whether<br />
+      gratis or for a fee, you must give the recipients all the rights that<br />
+      you have.  You must make sure that they, too, receive or can get the<br />
+      source code.  And you must show them these terms so they know their<br />
+      rights.</p>
+    <p> We protect your rights with two steps: (1) copyright the software, and<br />
+      (2) offer you this license which gives you legal permission to copy,<br />
+      distribute and/or modify the software.</p>
+    <p> Also, for each author's protection and ours, we want to make certain<br />
+      that everyone understands that there is no warranty for this free<br />
+      software.  If the software is modified by someone else and passed on, we<br />
+      want its recipients to know that what they have is not the original, so<br />
+      that any problems introduced by others will not reflect on the original<br />
+      authors' reputations.</p>
+    <p> Finally, any free program is threatened constantly by software<br />
+      patents.  We wish to avoid the danger that redistributors of a free<br />
+      program will individually obtain patent licenses, in effect making the<br />
+      program proprietary.  To prevent this, we have made it clear that any<br />
+      patent must be licensed for everyone's free use or not licensed at all.</p>
+    <p> The precise terms and conditions for copying, distribution and<br />
+      modification follow.</p>
+    <p> GNU GENERAL PUBLIC LICENSE<br />
+      TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION</p>
+    <p> 0. This License applies to any program or other work which contains<br />
+      a notice placed by the copyright holder saying it may be distributed<br />
+      under the terms of this General Public License.  The &quot;Program&quot;, below,<br />
+      refers to any such program or work, and a &quot;work based on the Program&quot;<br />
+      means either the Program or any derivative work under copyright law:<br />
+      that is to say, a work containing the Program or a portion of it,<br />
+      either verbatim or with modifications and/or translated into another<br />
+      language.  (Hereinafter, translation is included without limitation in<br />
+      the term &quot;modification&quot;.)  Each licensee is addressed as &quot;you&quot;.</p>
+    <p>Activities other than copying, distribution and modification are not<br />
+      covered by this License; they are outside its scope.  The act of<br />
+      running the Program is not restricted, and the output from the Program<br />
+      is covered only if its contents constitute a work based on the<br />
+      Program (independent of having been made by running the Program).<br />
+      Whether that is true depends on what the Program does.</p>
+    <p> 1. You may copy and distribute verbatim copies of the Program's<br />
+      source code as you receive it, in any medium, provided that you<br />
+      conspicuously and appropriately publish on each copy an appropriate<br />
+      copyright notice and disclaimer of warranty; keep intact all the<br />
+      notices that refer to this License and to the absence of any warranty;<br />
+      and give any other recipients of the Program a copy of this License<br />
+      along with the Program.</p>
+    <p>You may charge a fee for the physical act of transferring a copy, and<br />
+      you may at your option offer warranty protection in exchange for a fee.</p>
+    <p> 2. You may modify your copy or copies of the Program or any portion<br />
+      of it, thus forming a work based on the Program, and copy and<br />
+      distribute such modifications or work under the terms of Section 1<br />
+      above, provided that you also meet all of these conditions:</p>
+    <p> a) You must cause the modified files to carry prominent notices<br />
+      stating that you changed the files and the date of any change.</p>
+    <p> b) You must cause any work that you distribute or publish, that in<br />
+      whole or in part contains or is derived from the Program or any<br />
+      part thereof, to be licensed as a whole at no charge to all third<br />
+      parties under the terms of this License.</p>
+    <p> c) If the modified program normally reads commands interactively<br />
+      when run, you must cause it, when started running for such<br />
+      interactive use in the most ordinary way, to print or display an<br />
+      announcement including an appropriate copyright notice and a<br />
+      notice that there is no warranty (or else, saying that you provide<br />
+      a warranty) and that users may redistribute the program under<br />
+      these conditions, and telling the user how to view a copy of this<br />
+      License.  (Exception: if the Program itself is interactive but<br />
+      does not normally print such an announcement, your work based on<br />
+      the Program is not required to print an announcement.)</p>
+    <p>These requirements apply to the modified work as a whole.  If<br />
+      identifiable sections of that work are not derived from the Program,<br />
+      and can be reasonably considered independent and separate works in<br />
+      themselves, then this License, and its terms, do not apply to those<br />
+      sections when you distribute them as separate works.  But when you<br />
+      distribute the same sections as part of a whole which is a work based<br />
+      on the Program, the distribution of the whole must be on the terms of<br />
+      this License, whose permissions for other licensees extend to the<br />
+      entire whole, and thus to each and every part regardless of who wrote it.</p>
+    <p>Thus, it is not the intent of this section to claim rights or contest<br />
+      your rights to work written entirely by you; rather, the intent is to<br />
+      exercise the right to control the distribution of derivative or<br />
+      collective works based on the Program.</p>
+    <p>In addition, mere aggregation of another work not based on the Program<br />
+      with the Program (or with a work based on the Program) on a volume of<br />
+      a storage or distribution medium does not bring the other work under<br />
+      the scope of this License.</p>
+    <p> 3. You may copy and distribute the Program (or a work based on it,<br />
+      under Section 2) in object code or executable form under the terms of<br />
+      Sections 1 and 2 above provided that you also do one of the following:</p>
+    <p> a) Accompany it with the complete corresponding machine-readable<br />
+      source code, which must be distributed under the terms of Sections<br />
+      1 and 2 above on a medium customarily used for software interchange; or,</p>
+    <p> b) Accompany it with a written offer, valid for at least three<br />
+      years, to give any third party, for a charge no more than your<br />
+      cost of physically performing source distribution, a complete<br />
+      machine-readable copy of the corresponding source code, to be<br />
+      distributed under the terms of Sections 1 and 2 above on a medium<br />
+      customarily used for software interchange; or,</p>
+    <p> c) Accompany it with the information you received as to the offer<br />
+      to distribute corresponding source code.  (This alternative is<br />
+      allowed only for noncommercial distribution and only if you<br />
+      received the program in object code or executable form with such<br />
+      an offer, in accord with Subsection b above.)</p>
+    <p>The source code for a work means the preferred form of the work for<br />
+      making modifications to it.  For an executable work, complete source<br />
+      code means all the source code for all modules it contains, plus any<br />
+      associated interface definition files, plus the scripts used to<br />
+      control compilation and installation of the executable.  However, as a<br />
+      special exception, the source code distributed need not include<br />
+      anything that is normally distributed (in either source or binary<br />
+      form) with the major components (compiler, kernel, and so on) of the<br />
+      operating system on which the executable runs, unless that component<br />
+      itself accompanies the executable.</p>
+    <p>If distribution of executable or object code is made by offering<br />
+      access to copy from a designated place, then offering equivalent<br />
+      access to copy the source code from the same place counts as<br />
+      distribution of the source code, even though third parties are not<br />
+      compelled to copy the source along with the object code.</p>
+    <p> 4. You may not copy, modify, sublicense, or distribute the Program<br />
+      except as expressly provided under this License.  Any attempt<br />
+      otherwise to copy, modify, sublicense or distribute the Program is<br />
+      void, and will automatically terminate your rights under this License.<br />
+      However, parties who have received copies, or rights, from you under<br />
+      this License will not have their licenses terminated so long as such<br />
+      parties remain in full compliance.</p>
+    <p> 5. You are not required to accept this License, since you have not<br />
+      signed it.  However, nothing else grants you permission to modify or<br />
+      distribute the Program or its derivative works.  These actions are<br />
+      prohibited by law if you do not accept this License.  Therefore, by<br />
+      modifying or distributing the Program (or any work based on the<br />
+      Program), you indicate your acceptance of this License to do so, and<br />
+      all its terms and conditions for copying, distributing or modifying<br />
+      the Program or works based on it.</p>
+    <p> 6. Each time you redistribute the Program (or any work based on the<br />
+      Program), the recipient automatically receives a license from the<br />
+      original licensor to copy, distribute or modify the Program subject to<br />
+      these terms and conditions.  You may not impose any further<br />
+      restrictions on the recipients' exercise of the rights granted herein.<br />
+      You are not responsible for enforcing compliance by third parties to<br />
+      this License.</p>
+    <p> 7. If, as a consequence of a court judgment or allegation of patent<br />
+      infringement or for any other reason (not limited to patent issues),<br />
+      conditions are imposed on you (whether by court order, agreement or<br />
+      otherwise) that contradict the conditions of this License, they do not<br />
+      excuse you from the conditions of this License.  If you cannot<br />
+      distribute so as to satisfy simultaneously your obligations under this<br />
+      License and any other pertinent obligations, then as a consequence you<br />
+      may not distribute the Program at all.  For example, if a patent<br />
+      license would not permit royalty-free redistribution of the Program by<br />
+      all those who receive copies directly or indirectly through you, then<br />
+      the only way you could satisfy both it and this License would be to<br />
+      refrain entirely from distribution of the Program.</p>
+    <p>If any portion of this section is held invalid or unenforceable under<br />
+      any particular circumstance, the balance of the section is intended to<br />
+      apply and the section as a whole is intended to apply in other<br />
+      circumstances.</p>
+    <p>It is not the purpose of this section to induce you to infringe any<br />
+      patents or other property right claims or to contest validity of any<br />
+      such claims; this section has the sole purpose of protecting the<br />
+      integrity of the free software distribution system, which is<br />
+      implemented by public license practices.  Many people have made<br />
+      generous contributions to the wide range of software distributed<br />
+      through that system in reliance on consistent application of that<br />
+      system; it is up to the author/donor to decide if he or she is willing<br />
+      to distribute software through any other system and a licensee cannot<br />
+      impose that choice.</p>
+    <p>This section is intended to make thoroughly clear what is believed to<br />
+      be a consequence of the rest of this License.</p>
+    <p> 8. If the distribution and/or use of the Program is restricted in<br />
+      certain countries either by patents or by copyrighted interfaces, the<br />
+      original copyright holder who places the Program under this License<br />
+      may add an explicit geographical distribution limitation excluding<br />
+      those countries, so that distribution is permitted only in or among<br />
+      countries not thus excluded.  In such case, this License incorporates<br />
+      the limitation as if written in the body of this License.</p>
+    <p> 9. The Free Software Foundation may publish revised and/or new versions<br />
+      of the General Public License from time to time.  Such new versions will<br />
+      be similar in spirit to the present version, but may differ in detail to<br />
+      address new problems or concerns.</p>
+    <p>Each version is given a distinguishing version number.  If the Program<br />
+      specifies a version number of this License which applies to it and &quot;any<br />
+      later version&quot;, you have the option of following the terms and conditions<br />
+      either of that version or of any later version published by the Free<br />
+      Software Foundation.  If the Program does not specify a version number of<br />
+      this License, you may choose any version ever published by the Free Software<br />
+      Foundation.</p>
+    <p> 10. If you wish to incorporate parts of the Program into other free<br />
+      programs whose distribution conditions are different, write to the author<br />
+      to ask for permission.  For software which is copyrighted by the Free<br />
+      Software Foundation, write to the Free Software Foundation; we sometimes<br />
+      make exceptions for this.  Our decision will be guided by the two goals<br />
+      of preserving the free status of all derivatives of our free software and<br />
+      of promoting the sharing and reuse of software generally.</p>
+    <p> NO WARRANTY</p>
+    <p> 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY<br />
+      FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN<br />
+      OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES<br />
+      PROVIDE THE PROGRAM &quot;AS IS&quot; WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED<br />
+      OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF<br />
+      MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS<br />
+      TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE<br />
+      PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,<br />
+      REPAIR OR CORRECTION.</p>
+    <p> 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING<br />
+      WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR<br />
+      REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,<br />
+      INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING<br />
+      OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED<br />
+      TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY<br />
+      YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER<br />
+      PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE<br />
+      POSSIBILITY OF SUCH DAMAGES.</p>
+    <p> END OF TERMS AND CONDITIONS</p>
+    <p> How to Apply These Terms to Your New Programs</p>
+    <p> If you develop a new program, and you want it to be of the greatest<br />
+      possible use to the public, the best way to achieve this is to make it<br />
+      free software which everyone can redistribute and change under these terms.</p>
+    <p> To do so, attach the following notices to the program.  It is safest<br />
+      to attach them to the start of each source file to most effectively<br />
+      convey the exclusion of warranty; and each file should have at least<br />
+      the &quot;copyright&quot; line and a pointer to where the full notice is found.</p>
+    <p> &lt;one line to give the program's name and a brief idea of what it does.&gt;<br />
+      Copyright (C) &lt;year&gt;  &lt;name of author&gt;</p>
+    <p> This program is free software; you can redistribute it and/or modify<br />
+      it under the terms of the GNU General Public License as published by<br />
+      the Free Software Foundation; either version 2 of the License, or<br />
+      (at your option) any later version.</p>
+    <p> This program is distributed in the hope that it will be useful,<br />
+      but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
+      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the<br />
+      GNU General Public License for more details.</p>
+    <p> You should have received a copy of the GNU General Public License<br />
+      along with this program; if not, write to the Free Software<br />
+      Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA<br />
+    </p>
+    <p>Also add information on how to contact you by electronic and paper mail.</p>
+    <p>If the program is interactive, make it output a short notice like this<br />
+      when it starts in an interactive mode:</p>
+    <p> Gnomovision version 69, Copyright (C) year name of author<br />
+      Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.<br />
+      This is free software, and you are welcome to redistribute it<br />
+      under certain conditions; type `show c' for details.</p>
+    <p>The hypothetical commands `show w' and `show c' should show the appropriate<br />
+      parts of the General Public License.  Of course, the commands you use may<br />
+      be called something other than `show w' and `show c'; they could even be<br />
+      mouse-clicks or menu items--whatever suits your program.</p>
+    <p>You should also get your employer (if you work as a programmer) or your<br />
+      school, if any, to sign a &quot;copyright disclaimer&quot; for the program, if<br />
+      necessary.  Here is a sample; alter the names:</p>
+    <p> Yoyodyne, Inc., hereby disclaims all copyright interest in the program<br />
+      `Gnomovision' (which makes passes at compilers) written by James Hacker.</p>
+    <p> &lt;signature of Ty Coon&gt;, 1 April 1989<br />
+      Ty Coon, President of Vice</p>
+    <p>This General Public License does not permit incorporating your program into<br />
+      proprietary programs.  If your program is a subroutine library, you may<br />
+      consider it more useful to permit linking proprietary applications with the<br />
+      library.  If this is what you want to do, use the GNU Library General<br />
+      Public License instead of this License.<br />
+    </p>
+  </div>
+</div>
+<hr/>
+    <a href="http://validator.w3.org/check?uri=referer"><img
+        src="http://www.w3.org/Icons/valid-xhtml10-blue"
+        alt="Valid XHTML 1.0 Transitional" height="31" width="88" style="float: right; margin: 1em;" /></a>
+	<a href="http://jigsaw.w3.org/css-validator/">
+		<img src="http://jigsaw.w3.org/css-validator/images/vcss-blue"  style="float: right; margin: 1em;"
+        alt="Valid CSS" />
+	</a>
+</body>
 </html>

+ 340 - 340
documentation/license.txt

@@ -1,340 +1,340 @@
-		    GNU GENERAL PUBLIC LICENSE
-		       Version 2, June 1991
-
-Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-Everyone is permitted to copy and distribute verbatim copies
-of this license document, but changing it is not allowed.
-
-			    Preamble
-
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users.  This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it.  (Some other Free Software Foundation software is covered by
-the GNU Library General Public License instead.)  You can apply it to
-your programs, too.
-
-  When we speak of free software, we are referring to freedom, not
-price.  Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
-  To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have.  You must make sure that they, too, receive or can get the
-source code.  And you must show them these terms so they know their
-rights.
-
-  We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
-  Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software.  If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
-  Finally, any free program is threatened constantly by software
-patents.  We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary.  To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.
-
-		    GNU GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
-  0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License.  The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language.  (Hereinafter, translation is included without limitation in
-the term "modification".)  Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
-  1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
-  2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
-    a) You must cause the modified files to carry prominent notices
-    stating that you changed the files and the date of any change.
-
-    b) You must cause any work that you distribute or publish, that in
-    whole or in part contains or is derived from the Program or any
-    part thereof, to be licensed as a whole at no charge to all third
-    parties under the terms of this License.
-
-    c) If the modified program normally reads commands interactively
-    when run, you must cause it, when started running for such
-    interactive use in the most ordinary way, to print or display an
-    announcement including an appropriate copyright notice and a
-    notice that there is no warranty (or else, saying that you provide
-    a warranty) and that users may redistribute the program under
-    these conditions, and telling the user how to view a copy of this
-    License.  (Exception: if the Program itself is interactive but
-    does not normally print such an announcement, your work based on
-    the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
-  3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
-    a) Accompany it with the complete corresponding machine-readable
-    source code, which must be distributed under the terms of Sections
-    1 and 2 above on a medium customarily used for software interchange; or,
-
-    b) Accompany it with a written offer, valid for at least three
-    years, to give any third party, for a charge no more than your
-    cost of physically performing source distribution, a complete
-    machine-readable copy of the corresponding source code, to be
-    distributed under the terms of Sections 1 and 2 above on a medium
-    customarily used for software interchange; or,
-
-    c) Accompany it with the information you received as to the offer
-    to distribute corresponding source code.  (This alternative is
-    allowed only for noncommercial distribution and only if you
-    received the program in object code or executable form with such
-    an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it.  For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable.  However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
-  4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License.  Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
-  5. You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Program or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
-  6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
-  7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
-  8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded.  In such case, this License incorporates
-the limitation as if written in the body of this License.
-
-  9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time.  Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number.  If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation.  If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
-  10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission.  For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this.  Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
-			    NO WARRANTY
-
-  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
-  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
-		     END OF TERMS AND CONDITIONS
-
-	    How to Apply These Terms to Your New Programs
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  To do so, attach the following notices to the program.  It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the program's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program; if not, write to the Free Software
-    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
-    Gnomovision version 69, Copyright (C) year name of author
-    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
-    This is free software, and you are welcome to redistribute it
-    under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License.  Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary.  Here is a sample; alter the names:
-
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
-  `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
-  <signature of Ty Coon>, 1 April 1989
-  Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs.  If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library.  If this is what you want to do, use the GNU Library General
-Public License instead of this License.
+		    GNU GENERAL PUBLIC LICENSE
+		       Version 2, June 1991
+
+Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+		    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+			    NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+	    How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Library General
+Public License instead of this License.

+ 199 - 199
main/admin/access_url_add_courses_to_url.php

@@ -1,200 +1,200 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2009 Dokeos SPRL
-	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	This script allows platform admins to add users to urls.
-*	It displays a list of users and a list of courses;
-*	you can select multiple users and courses and then click on
-*	@package dokeos.admin
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file = 'admin';
-$cidReset = true;
-require ('../inc/global.inc.php');
-$this_section=SECTION_PLATFORM_ADMIN;
-
-require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
-api_protect_admin_script();
-if (!$_configuration['multiple_access_urls'])
-	header('Location: index.php');
-
-/*
------------------------------------------------------------
-	Global constants and variables
------------------------------------------------------------
-*/
-
-$form_sent = 0;
-$first_letter_course = '';
-$courses = array ();
-$url_list = array();
-$users = array();
-
-$tbl_access_url_rel_course 	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-$tbl_access_url 			= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
-$tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
-$tbl_course					= Database :: get_main_table(TABLE_MAIN_COURSE);
-
-/*
------------------------------------------------------------
-	Header
------------------------------------------------------------
-*/
-$tool_name = get_lang('AddCoursesToURL');
-$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
-
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
-*/
-
-Display :: display_header($tool_name);
-
-echo '<div class="actions" style="height:22px;">';
-echo '<div style="float:right;">
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_courses_to_url.php">'.Display::return_icon('edit.gif',get_lang('AddUserToURL'),'').get_lang('EditCoursesToURL').'</a>
-	  </div><br />';
-echo '</div>';
-
-api_display_tool_title($tool_name);
-
-if ($_POST['form_sent']) {
-	$form_sent = $_POST['form_sent'];
-	$courses = is_array($_POST['course_list']) ? $_POST['course_list'] : array() ;
-	$url_list = is_array($_POST['url_list']) ? $_POST['url_list'] : array() ;
-	$first_letter_course = $_POST['first_letter_course'];
-
-	foreach($users as $key => $value) {
-		$users[$key] = intval($value);
-	}
-
-	if ($form_sent == 1) {
-		if ( count($courses) == 0 || count($url_list) == 0) {
-			Display :: display_error_message(get_lang('AtLeastOneCourseAndOneURL'));
-			//header('Location: access_urls.php?action=show_message&message='.get_lang('AtLeastOneUserAndOneURL'));
-		} else {
-			UrlManager::add_courses_to_urls($courses,$url_list);
-			Display :: display_confirmation_message(get_lang('CourseBelongURL'));
-			//header('Location: access_urls.php?action=show_message&message='.get_lang('UsersBelongURL'));
-		}
-	}
-}
-
-
-
-/*
------------------------------------------------------------
-	Display GUI
------------------------------------------------------------
-*/
-
-if(empty($first_letter_user))
-{
-	$sql = "SELECT count(*) as num_courses FROM $tbl_course";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	$num_row = Database::fetch_array($result);
-	if($num_row['num_courses']>1000)
-	{//if there are too much num_courses to gracefully handle with the HTML select list,
-	 // assign a default filter on users names
-		$first_letter_user = 'A';
-	}
-	unset($result);
-}
-
-$first_letter_course = Database::escape_string($first_letter_course);
-$sql = "SELECT code, title FROM $tbl_course
-		WHERE title LIKE '".$first_letter_course."%' OR title LIKE '".api_strtolower($first_letter_course)."%'
-		ORDER BY title, code DESC ";
-
-$result = Database::query($sql, __FILE__, __LINE__);
-$db_courses = Database::store_result($result);
-unset($result);
-
-$sql = "SELECT id, url FROM $tbl_access_url  WHERE active=1 ORDER BY url";
-$result = Database::query($sql, __FILE__, __LINE__);
-$db_urls = Database::store_result($result);
-unset($result);
-?>
-
-<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;">
- <input type="hidden" name="form_sent" value="1"/>
-  <table border="0" cellpadding="5" cellspacing="0" width="100%">
-   <tr>
-    <td width="40%" align="center">
-     <b><?php echo get_lang('CourseList'); ?></b>
-     <br/><br/>
-     <?php echo get_lang('FirstLetterCourse'); ?> :
-     <select name="first_letter_course" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
-      <option value="">--</option>
-      <?php
-        echo Display :: get_alphabet_options($first_letter_course);
-        echo Display :: get_numeric_options(0,9,$first_letter_course);
-      ?>
-     </select>
-    </td>
-        <td width="20%">&nbsp;</td>
-    <td width="40%" align="center">
-     <b><?php echo get_lang('URLList'); ?> :</b>
-    </td>
-   </tr>
-   <tr>
-    <td width="40%" align="center">
-     <select name="course_list[]" multiple="multiple" size="20" style="width:230px;">
-		<?php
-		foreach ($db_courses as $course) {
-			?>
-			<option value="<?php echo $course['code']; ?>" <?php if(in_array($course['code'],$courses)) echo 'selected="selected"'; ?>><?php echo $course['title'].' ('.$course['code'].')'; ?></option>
-			<?php
-		}
-		?>
-    </select>
-   </td>
-   <td width="20%" valign="middle" align="center">
-    <input type="submit" value="<?php echo get_lang('AddCoursesToThatURL'); ?> &gt;&gt;"/>
-   </td>
-   <td width="40%" align="center">
-    <select name="url_list[]" multiple="multiple" size="20" style="width:230px;">
-		<?php
-		foreach ($db_urls as $url_obj) {
-			?>
-			<option value="<?php echo $url_obj['id']; ?>" <?php if(in_array($url_obj['id'],$url_list)) echo 'selected="selected"'; ?>><?php echo $url_obj['url']; ?></option>
-			<?php
-		}
-		?>
-    </select>
-   </td>
-  </tr>
- </table>
-</form>
-<?php
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display :: display_footer();
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2009 Dokeos SPRL
+	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	This script allows platform admins to add users to urls.
+*	It displays a list of users and a list of courses;
+*	you can select multiple users and courses and then click on
+*	@package dokeos.admin
+==============================================================================
+*/
+
+// name of the language file that needs to be included
+$language_file = 'admin';
+$cidReset = true;
+require ('../inc/global.inc.php');
+$this_section=SECTION_PLATFORM_ADMIN;
+
+require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
+api_protect_admin_script();
+if (!$_configuration['multiple_access_urls'])
+	header('Location: index.php');
+
+/*
+-----------------------------------------------------------
+	Global constants and variables
+-----------------------------------------------------------
+*/
+
+$form_sent = 0;
+$first_letter_course = '';
+$courses = array ();
+$url_list = array();
+$users = array();
+
+$tbl_access_url_rel_course 	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+$tbl_access_url 			= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+$tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
+$tbl_course					= Database :: get_main_table(TABLE_MAIN_COURSE);
+
+/*
+-----------------------------------------------------------
+	Header
+-----------------------------------------------------------
+*/
+$tool_name = get_lang('AddCoursesToURL');
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
+
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
+*/
+
+Display :: display_header($tool_name);
+
+echo '<div class="actions" style="height:22px;">';
+echo '<div style="float:right;">
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_courses_to_url.php">'.Display::return_icon('edit.gif',get_lang('AddUserToURL'),'').get_lang('EditCoursesToURL').'</a>
+	  </div><br />';
+echo '</div>';
+
+api_display_tool_title($tool_name);
+
+if ($_POST['form_sent']) {
+	$form_sent = $_POST['form_sent'];
+	$courses = is_array($_POST['course_list']) ? $_POST['course_list'] : array() ;
+	$url_list = is_array($_POST['url_list']) ? $_POST['url_list'] : array() ;
+	$first_letter_course = $_POST['first_letter_course'];
+
+	foreach($users as $key => $value) {
+		$users[$key] = intval($value);
+	}
+
+	if ($form_sent == 1) {
+		if ( count($courses) == 0 || count($url_list) == 0) {
+			Display :: display_error_message(get_lang('AtLeastOneCourseAndOneURL'));
+			//header('Location: access_urls.php?action=show_message&message='.get_lang('AtLeastOneUserAndOneURL'));
+		} else {
+			UrlManager::add_courses_to_urls($courses,$url_list);
+			Display :: display_confirmation_message(get_lang('CourseBelongURL'));
+			//header('Location: access_urls.php?action=show_message&message='.get_lang('UsersBelongURL'));
+		}
+	}
+}
+
+
+
+/*
+-----------------------------------------------------------
+	Display GUI
+-----------------------------------------------------------
+*/
+
+if(empty($first_letter_user))
+{
+	$sql = "SELECT count(*) as num_courses FROM $tbl_course";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	$num_row = Database::fetch_array($result);
+	if($num_row['num_courses']>1000)
+	{//if there are too much num_courses to gracefully handle with the HTML select list,
+	 // assign a default filter on users names
+		$first_letter_user = 'A';
+	}
+	unset($result);
+}
+
+$first_letter_course = Database::escape_string($first_letter_course);
+$sql = "SELECT code, title FROM $tbl_course
+		WHERE title LIKE '".$first_letter_course."%' OR title LIKE '".api_strtolower($first_letter_course)."%'
+		ORDER BY title, code DESC ";
+
+$result = Database::query($sql, __FILE__, __LINE__);
+$db_courses = Database::store_result($result);
+unset($result);
+
+$sql = "SELECT id, url FROM $tbl_access_url  WHERE active=1 ORDER BY url";
+$result = Database::query($sql, __FILE__, __LINE__);
+$db_urls = Database::store_result($result);
+unset($result);
+?>
+
+<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;">
+ <input type="hidden" name="form_sent" value="1"/>
+  <table border="0" cellpadding="5" cellspacing="0" width="100%">
+   <tr>
+    <td width="40%" align="center">
+     <b><?php echo get_lang('CourseList'); ?></b>
+     <br/><br/>
+     <?php echo get_lang('FirstLetterCourse'); ?> :
+     <select name="first_letter_course" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
+      <option value="">--</option>
+      <?php
+        echo Display :: get_alphabet_options($first_letter_course);
+        echo Display :: get_numeric_options(0,9,$first_letter_course);
+      ?>
+     </select>
+    </td>
+        <td width="20%">&nbsp;</td>
+    <td width="40%" align="center">
+     <b><?php echo get_lang('URLList'); ?> :</b>
+    </td>
+   </tr>
+   <tr>
+    <td width="40%" align="center">
+     <select name="course_list[]" multiple="multiple" size="20" style="width:230px;">
+		<?php
+		foreach ($db_courses as $course) {
+			?>
+			<option value="<?php echo $course['code']; ?>" <?php if(in_array($course['code'],$courses)) echo 'selected="selected"'; ?>><?php echo $course['title'].' ('.$course['code'].')'; ?></option>
+			<?php
+		}
+		?>
+    </select>
+   </td>
+   <td width="20%" valign="middle" align="center">
+    <input type="submit" value="<?php echo get_lang('AddCoursesToThatURL'); ?> &gt;&gt;"/>
+   </td>
+   <td width="40%" align="center">
+    <select name="url_list[]" multiple="multiple" size="20" style="width:230px;">
+		<?php
+		foreach ($db_urls as $url_obj) {
+			?>
+			<option value="<?php echo $url_obj['id']; ?>" <?php if(in_array($url_obj['id'],$url_list)) echo 'selected="selected"'; ?>><?php echo $url_obj['url']; ?></option>
+			<?php
+		}
+		?>
+    </select>
+   </td>
+  </tr>
+ </table>
+</form>
+<?php
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display :: display_footer();
 ?>

+ 201 - 201
main/admin/access_url_add_sessions_to_url.php

@@ -1,202 +1,202 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2009 Dokeos SPRL
-	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	This script allows platform admins to add users to urls.
-*	It displays a list of users and a list of courses;
-*	you can select multiple users and courses and then click on
-*	@package dokeos.admin
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file = 'admin';
-$cidReset = true;
-require ('../inc/global.inc.php');
-$this_section=SECTION_PLATFORM_ADMIN;
-
-require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
-api_protect_admin_script();
-if (!$_configuration['multiple_access_urls'])
-	header('Location: index.php');
-
-/*
------------------------------------------------------------
-	Global constants and variables
------------------------------------------------------------
-*/
-
-$form_sent = 0;
-$first_letter_session = '';
-$sessions = array ();
-$url_list = array();
-$users = array();
-
-$tbl_access_url_rel_session = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
-$tbl_access_url 			= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
-$tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
-$tbl_session				= Database :: get_main_table(TABLE_MAIN_SESSION);
-
-/*
------------------------------------------------------------
-	Header
------------------------------------------------------------
-*/
-$tool_name = get_lang('AddSessionToURL');
-$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
-
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
-*/
-
-Display :: display_header($tool_name);
-echo '<div class="actions" style="height:22px;">';
-echo '<div style="float:right;">
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_sessions_to_url.php">'.Display::return_icon('course_del.gif',get_lang('EditSessionToURL'),'').get_lang('EditSessionToURL').'</a>
-	  </div><br />';
-echo '</div>';
-
-api_display_tool_title($tool_name);
-
-if ($_POST['form_sent']) {
-	$form_sent = $_POST['form_sent'];
-	$sessions = is_array($_POST['session_list']) ? $_POST['session_list'] : array() ;
-	$url_list = is_array($_POST['url_list']) ? $_POST['url_list'] : array() ;
-	$first_letter_session = $_POST['first_letter_session'];
-
-	foreach($users as $key => $value) {
-		$users[$key] = intval($value);
-	}
-
-	if ($form_sent == 1) {
-		if ( count($sessions) == 0 || count($url_list) == 0) {
-			Display :: display_error_message(get_lang('AtLeastOneSessionAndOneURL'));
-			//header('Location: access_urls.php?action=show_message&message='.get_lang('AtLeastOneUserAndOneURL'));
-		} else {
-			UrlManager::add_sessions_to_urls($sessions,$url_list);
-			Display :: display_confirmation_message(get_lang('SessionBelongURL'));
-			//header('Location: access_urls.php?action=show_message&message='.get_lang('UsersBelongURL'));
-		}
-	}
-}
-
-
-
-/*
------------------------------------------------------------
-	Display GUI
------------------------------------------------------------
-*/
-/*
-if(empty($first_letter_user)) {
-	$sql = "SELECT count(*) as num_courses FROM $tbl_course";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	$num_row = Database::fetch_array($result);
-	if($num_row['num_courses']>1000)
-	{//if there are too much num_courses to gracefully handle with the HTML select list,
-	 // assign a default filter on users names
-		$first_letter_user = 'A';
-	}
-	unset($result);
-}
-*/
-$first_letter_session = Database::escape_string($first_letter_session);
-$sql = "SELECT id, name FROM $tbl_session
-		WHERE name LIKE '".$first_letter_session."%' OR name LIKE '".api_strtolower($first_letter_session)."%'
-		ORDER BY name DESC ";
-
-$result = Database::query($sql, __FILE__, __LINE__);
-$db_sessions = Database::store_result($result);
-unset($result);
-
-$sql = "SELECT id, url FROM $tbl_access_url  WHERE active=1 ORDER BY url";
-$result = Database::query($sql, __FILE__, __LINE__);
-$db_urls = Database::store_result($result);
-unset($result);
-?>
-
-<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;">
- <input type="hidden" name="form_sent" value="1"/>
-  <table border="0" cellpadding="5" cellspacing="0" width="100%">
-   <tr>
-    <td width="40%" align="center">
-     <b><?php echo get_lang('SessionList'); ?></b>
-     <br/><br/>
-     <?php echo get_lang('FirstLetterSession'); ?> :
-     <select name="first_letter_session" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
-      <option value="">--</option>
-      <?php
-        echo Display :: get_alphabet_options($first_letter_session);
-        echo Display :: get_numeric_options(0,9,$first_letter_session);
-      ?>
-     </select>
-    </td>
-        <td width="20%">&nbsp;</td>
-    <td width="40%" align="center">
-     <b><?php echo get_lang('URLList'); ?> :</b>
-    </td>
-   </tr>
-   <tr>
-    <td width="40%" align="center">
-     <select name="session_list[]" multiple="multiple" size="20" style="width:230px;">
-		<?php
-
-		foreach ($db_sessions as $session) {
-			?>
-			<option value="<?php echo $session['id']; ?>"
-			<?php if(in_array($session['id'],$sessions))
-			echo 'selected="selected"'; ?>>
-			<?php echo $session['name']; ?></option>
-			<?php
-		}
-		?>
-    </select>
-   </td>
-   <td width="20%" valign="middle" align="center">
-    <input type="submit" value="<?php echo get_lang('AddSessionsToThatURL'); ?> &gt;&gt;"/>
-   </td>
-   <td width="40%" align="center">
-    <select name="url_list[]" multiple="multiple" size="20" style="width:230px;">
-		<?php
-		foreach ($db_urls as $url_obj) {
-			?>
-			<option value="<?php echo $url_obj['id']; ?>" <?php if(in_array($url_obj['id'],$url_list)) echo 'selected="selected"'; ?>><?php echo $url_obj['url']; ?></option>
-			<?php
-		}
-		?>
-    </select>
-   </td>
-  </tr>
- </table>
-</form>
-<?php
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display :: display_footer();
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2009 Dokeos SPRL
+	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	This script allows platform admins to add users to urls.
+*	It displays a list of users and a list of courses;
+*	you can select multiple users and courses and then click on
+*	@package dokeos.admin
+==============================================================================
+*/
+
+// name of the language file that needs to be included
+$language_file = 'admin';
+$cidReset = true;
+require ('../inc/global.inc.php');
+$this_section=SECTION_PLATFORM_ADMIN;
+
+require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
+api_protect_admin_script();
+if (!$_configuration['multiple_access_urls'])
+	header('Location: index.php');
+
+/*
+-----------------------------------------------------------
+	Global constants and variables
+-----------------------------------------------------------
+*/
+
+$form_sent = 0;
+$first_letter_session = '';
+$sessions = array ();
+$url_list = array();
+$users = array();
+
+$tbl_access_url_rel_session = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+$tbl_access_url 			= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+$tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
+$tbl_session				= Database :: get_main_table(TABLE_MAIN_SESSION);
+
+/*
+-----------------------------------------------------------
+	Header
+-----------------------------------------------------------
+*/
+$tool_name = get_lang('AddSessionToURL');
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
+
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
+*/
+
+Display :: display_header($tool_name);
+echo '<div class="actions" style="height:22px;">';
+echo '<div style="float:right;">
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_sessions_to_url.php">'.Display::return_icon('course_del.gif',get_lang('EditSessionToURL'),'').get_lang('EditSessionToURL').'</a>
+	  </div><br />';
+echo '</div>';
+
+api_display_tool_title($tool_name);
+
+if ($_POST['form_sent']) {
+	$form_sent = $_POST['form_sent'];
+	$sessions = is_array($_POST['session_list']) ? $_POST['session_list'] : array() ;
+	$url_list = is_array($_POST['url_list']) ? $_POST['url_list'] : array() ;
+	$first_letter_session = $_POST['first_letter_session'];
+
+	foreach($users as $key => $value) {
+		$users[$key] = intval($value);
+	}
+
+	if ($form_sent == 1) {
+		if ( count($sessions) == 0 || count($url_list) == 0) {
+			Display :: display_error_message(get_lang('AtLeastOneSessionAndOneURL'));
+			//header('Location: access_urls.php?action=show_message&message='.get_lang('AtLeastOneUserAndOneURL'));
+		} else {
+			UrlManager::add_sessions_to_urls($sessions,$url_list);
+			Display :: display_confirmation_message(get_lang('SessionBelongURL'));
+			//header('Location: access_urls.php?action=show_message&message='.get_lang('UsersBelongURL'));
+		}
+	}
+}
+
+
+
+/*
+-----------------------------------------------------------
+	Display GUI
+-----------------------------------------------------------
+*/
+/*
+if(empty($first_letter_user)) {
+	$sql = "SELECT count(*) as num_courses FROM $tbl_course";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	$num_row = Database::fetch_array($result);
+	if($num_row['num_courses']>1000)
+	{//if there are too much num_courses to gracefully handle with the HTML select list,
+	 // assign a default filter on users names
+		$first_letter_user = 'A';
+	}
+	unset($result);
+}
+*/
+$first_letter_session = Database::escape_string($first_letter_session);
+$sql = "SELECT id, name FROM $tbl_session
+		WHERE name LIKE '".$first_letter_session."%' OR name LIKE '".api_strtolower($first_letter_session)."%'
+		ORDER BY name DESC ";
+
+$result = Database::query($sql, __FILE__, __LINE__);
+$db_sessions = Database::store_result($result);
+unset($result);
+
+$sql = "SELECT id, url FROM $tbl_access_url  WHERE active=1 ORDER BY url";
+$result = Database::query($sql, __FILE__, __LINE__);
+$db_urls = Database::store_result($result);
+unset($result);
+?>
+
+<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;">
+ <input type="hidden" name="form_sent" value="1"/>
+  <table border="0" cellpadding="5" cellspacing="0" width="100%">
+   <tr>
+    <td width="40%" align="center">
+     <b><?php echo get_lang('SessionList'); ?></b>
+     <br/><br/>
+     <?php echo get_lang('FirstLetterSession'); ?> :
+     <select name="first_letter_session" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
+      <option value="">--</option>
+      <?php
+        echo Display :: get_alphabet_options($first_letter_session);
+        echo Display :: get_numeric_options(0,9,$first_letter_session);
+      ?>
+     </select>
+    </td>
+        <td width="20%">&nbsp;</td>
+    <td width="40%" align="center">
+     <b><?php echo get_lang('URLList'); ?> :</b>
+    </td>
+   </tr>
+   <tr>
+    <td width="40%" align="center">
+     <select name="session_list[]" multiple="multiple" size="20" style="width:230px;">
+		<?php
+
+		foreach ($db_sessions as $session) {
+			?>
+			<option value="<?php echo $session['id']; ?>"
+			<?php if(in_array($session['id'],$sessions))
+			echo 'selected="selected"'; ?>>
+			<?php echo $session['name']; ?></option>
+			<?php
+		}
+		?>
+    </select>
+   </td>
+   <td width="20%" valign="middle" align="center">
+    <input type="submit" value="<?php echo get_lang('AddSessionsToThatURL'); ?> &gt;&gt;"/>
+   </td>
+   <td width="40%" align="center">
+    <select name="url_list[]" multiple="multiple" size="20" style="width:230px;">
+		<?php
+		foreach ($db_urls as $url_obj) {
+			?>
+			<option value="<?php echo $url_obj['id']; ?>" <?php if(in_array($url_obj['id'],$url_list)) echo 'selected="selected"'; ?>><?php echo $url_obj['url']; ?></option>
+			<?php
+		}
+		?>
+    </select>
+   </td>
+  </tr>
+ </table>
+</form>
+<?php
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display :: display_footer();
 ?>

+ 201 - 201
main/admin/access_url_add_users_to_url.php

@@ -1,202 +1,202 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2009 Dokeos SPRL
-	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	This script allows platform admins to add users to urls.
-*	It displays a list of users and a list of courses;
-*	you can select multiple users and courses and then click on
-*	@package dokeos.admin
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file = 'admin';
-$cidReset = true;
-require ('../inc/global.inc.php');
-$this_section=SECTION_PLATFORM_ADMIN;
-
-require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
-api_protect_admin_script();
-if (!$_configuration['multiple_access_urls'])
-	header('Location: index.php');
-
-/*
------------------------------------------------------------
-	Global constants and variables
------------------------------------------------------------
-*/
-
-$form_sent = 0;
-$first_letter_user = '';
-$first_letter_course = '';
-$courses = array ();
-$url_list = array();
-$users = array();
-
-$tbl_access_url_rel_user = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-$tbl_access_url = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
-$tbl_user 		= Database :: get_main_table(TABLE_MAIN_USER);
-
-/*
------------------------------------------------------------
-	Header
------------------------------------------------------------
-*/
-$tool_name = get_lang('AddUsersToURL');
-$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
-
-
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
-*/
-
-Display :: display_header($tool_name);
-
-echo '<div class="actions" style="height:22px;">';
-echo '<div style="float:right;">
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_users_to_url.php">'.Display::return_icon('edit.gif',get_lang('EditUsersToURL'),'').get_lang('EditUsersToURL').'</a>
-	  </div><br />';
-echo '</div>';
-
-api_display_tool_title($tool_name);
-
-
-
-if ($_POST['form_sent']) {
-	$form_sent = $_POST['form_sent'];
-	$users = is_array($_POST['user_list']) ? $_POST['user_list'] : array() ;
-	$url_list = is_array($_POST['url_list']) ? $_POST['url_list'] : array() ;
-	$first_letter_user = $_POST['first_letter_user'];
-
-	foreach($users as $key => $value) {
-		$users[$key] = intval($value);
-	}
-
-	if ($form_sent == 1)
-	{
-		if ( count($users) == 0 || count($url_list) == 0) {
-			Display :: display_error_message(get_lang('AtLeastOneUserAndOneURL'));
-			//header('Location: access_urls.php?action=show_message&message='.get_lang('AtLeastOneUserAndOneURL'));
-		} else {
-			UrlManager::add_users_to_urls($users,$url_list);
-			Display :: display_confirmation_message(get_lang('UsersBelongURL'));
-			//header('Location: access_urls.php?action=show_message&message='.get_lang('UsersBelongURL'));
-		}
-	}
-}
-
-
-
-/*
------------------------------------------------------------
-	Display GUI
------------------------------------------------------------
-*/
-
-
-if(empty($first_letter_user)) {
-	$sql = "SELECT count(*) as nb_users FROM $tbl_user";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	$num_row = Database::fetch_array($result);
-	if($num_row['nb_users']>1000) {
-		//if there are too much users to gracefully handle with the HTML select list,
-	    // assign a default filter on users names
-		$first_letter_user = 'A';
-	}
-	unset($result);
-}
-$first_letter_user = Database::escape_string($first_letter_user);
-
-$target_name = api_sort_by_first_name() ? 'firstname' : 'lastname';
-$sql = "SELECT user_id,lastname,firstname,username FROM $tbl_user
-	    WHERE ".$target_name." LIKE '".$first_letter_user."%' OR ".$target_name." LIKE '".api_strtolower($first_letter_user)."%'
-		ORDER BY ". (count($users) > 0 ? "(user_id IN(".implode(',', $users).")) DESC," : "")." ".$target_name;
-$result = Database::query($sql, __FILE__, __LINE__);
-$db_users = Database::store_result($result);
-unset($result);
-
-$sql = "SELECT id, url FROM $tbl_access_url  WHERE active=1 ORDER BY url";
-$result = Database::query($sql, __FILE__, __LINE__);
-$db_urls = Database::store_result($result);
-unset($result);
-?>
-
-<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;">
- <input type="hidden" name="form_sent" value="1"/>
-  <table border="0" cellpadding="5" cellspacing="0" width="100%">
-   <tr>
-    <td width="40%" align="center">
-     <b><?php echo get_lang('UserList'); ?></b>
-     <br/><br/>
-     <?php echo get_lang('FirstLetterUser'); ?> :
-     <select name="first_letter_user" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
-      <option value="">--</option>
-      <?php
-        echo Display :: get_alphabet_options($first_letter_user);
-      ?>
-     </select>
-    </td>
-        <td width="20%">&nbsp;</td>
-    <td width="40%" align="center">
-     <b><?php echo get_lang('URLList'); ?> :</b>
-    </td>
-   </tr>
-   <tr>
-    <td width="40%" align="center">
-     <select name="user_list[]" multiple="multiple" size="20" style="width:250px;">
-		<?php
-		foreach ($db_users as $user) {
-		?>
-			  <option value="<?php echo $user['user_id']; ?>" <?php if(in_array($user['user_id'],$users)) echo 'selected="selected"'; ?>><?php echo api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')'; ?></option>
-		<?php
-		}
-		?>
-    </select>
-   </td>
-   <td width="20%" valign="middle" align="center">
-    <input type="submit" value="<?php echo get_lang('AddToThatURL'); ?> &gt;&gt;"/>
-   </td>
-   <td width="40%" align="center">
-    <select name="url_list[]" multiple="multiple" size="20" style="width:230px;">
-		<?php
-		foreach ($db_urls as $url_obj) {
-			?>
-			<option value="<?php echo $url_obj['id']; ?>" <?php if(in_array($url_obj['id'],$url_list)) echo 'selected="selected"'; ?>><?php echo $url_obj['url']; ?></option>
-			<?php
-		}
-		?>
-    </select>
-   </td>
-  </tr>
- </table>
-</form>
-<?php
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display :: display_footer();
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2009 Dokeos SPRL
+	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	This script allows platform admins to add users to urls.
+*	It displays a list of users and a list of courses;
+*	you can select multiple users and courses and then click on
+*	@package dokeos.admin
+==============================================================================
+*/
+
+// name of the language file that needs to be included
+$language_file = 'admin';
+$cidReset = true;
+require ('../inc/global.inc.php');
+$this_section=SECTION_PLATFORM_ADMIN;
+
+require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
+api_protect_admin_script();
+if (!$_configuration['multiple_access_urls'])
+	header('Location: index.php');
+
+/*
+-----------------------------------------------------------
+	Global constants and variables
+-----------------------------------------------------------
+*/
+
+$form_sent = 0;
+$first_letter_user = '';
+$first_letter_course = '';
+$courses = array ();
+$url_list = array();
+$users = array();
+
+$tbl_access_url_rel_user = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+$tbl_access_url = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+$tbl_user 		= Database :: get_main_table(TABLE_MAIN_USER);
+
+/*
+-----------------------------------------------------------
+	Header
+-----------------------------------------------------------
+*/
+$tool_name = get_lang('AddUsersToURL');
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
+
+
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
+*/
+
+Display :: display_header($tool_name);
+
+echo '<div class="actions" style="height:22px;">';
+echo '<div style="float:right;">
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_users_to_url.php">'.Display::return_icon('edit.gif',get_lang('EditUsersToURL'),'').get_lang('EditUsersToURL').'</a>
+	  </div><br />';
+echo '</div>';
+
+api_display_tool_title($tool_name);
+
+
+
+if ($_POST['form_sent']) {
+	$form_sent = $_POST['form_sent'];
+	$users = is_array($_POST['user_list']) ? $_POST['user_list'] : array() ;
+	$url_list = is_array($_POST['url_list']) ? $_POST['url_list'] : array() ;
+	$first_letter_user = $_POST['first_letter_user'];
+
+	foreach($users as $key => $value) {
+		$users[$key] = intval($value);
+	}
+
+	if ($form_sent == 1)
+	{
+		if ( count($users) == 0 || count($url_list) == 0) {
+			Display :: display_error_message(get_lang('AtLeastOneUserAndOneURL'));
+			//header('Location: access_urls.php?action=show_message&message='.get_lang('AtLeastOneUserAndOneURL'));
+		} else {
+			UrlManager::add_users_to_urls($users,$url_list);
+			Display :: display_confirmation_message(get_lang('UsersBelongURL'));
+			//header('Location: access_urls.php?action=show_message&message='.get_lang('UsersBelongURL'));
+		}
+	}
+}
+
+
+
+/*
+-----------------------------------------------------------
+	Display GUI
+-----------------------------------------------------------
+*/
+
+
+if(empty($first_letter_user)) {
+	$sql = "SELECT count(*) as nb_users FROM $tbl_user";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	$num_row = Database::fetch_array($result);
+	if($num_row['nb_users']>1000) {
+		//if there are too much users to gracefully handle with the HTML select list,
+	    // assign a default filter on users names
+		$first_letter_user = 'A';
+	}
+	unset($result);
+}
+$first_letter_user = Database::escape_string($first_letter_user);
+
+$target_name = api_sort_by_first_name() ? 'firstname' : 'lastname';
+$sql = "SELECT user_id,lastname,firstname,username FROM $tbl_user
+	    WHERE ".$target_name." LIKE '".$first_letter_user."%' OR ".$target_name." LIKE '".api_strtolower($first_letter_user)."%'
+		ORDER BY ". (count($users) > 0 ? "(user_id IN(".implode(',', $users).")) DESC," : "")." ".$target_name;
+$result = Database::query($sql, __FILE__, __LINE__);
+$db_users = Database::store_result($result);
+unset($result);
+
+$sql = "SELECT id, url FROM $tbl_access_url  WHERE active=1 ORDER BY url";
+$result = Database::query($sql, __FILE__, __LINE__);
+$db_urls = Database::store_result($result);
+unset($result);
+?>
+
+<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;">
+ <input type="hidden" name="form_sent" value="1"/>
+  <table border="0" cellpadding="5" cellspacing="0" width="100%">
+   <tr>
+    <td width="40%" align="center">
+     <b><?php echo get_lang('UserList'); ?></b>
+     <br/><br/>
+     <?php echo get_lang('FirstLetterUser'); ?> :
+     <select name="first_letter_user" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
+      <option value="">--</option>
+      <?php
+        echo Display :: get_alphabet_options($first_letter_user);
+      ?>
+     </select>
+    </td>
+        <td width="20%">&nbsp;</td>
+    <td width="40%" align="center">
+     <b><?php echo get_lang('URLList'); ?> :</b>
+    </td>
+   </tr>
+   <tr>
+    <td width="40%" align="center">
+     <select name="user_list[]" multiple="multiple" size="20" style="width:250px;">
+		<?php
+		foreach ($db_users as $user) {
+		?>
+			  <option value="<?php echo $user['user_id']; ?>" <?php if(in_array($user['user_id'],$users)) echo 'selected="selected"'; ?>><?php echo api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')'; ?></option>
+		<?php
+		}
+		?>
+    </select>
+   </td>
+   <td width="20%" valign="middle" align="center">
+    <input type="submit" value="<?php echo get_lang('AddToThatURL'); ?> &gt;&gt;"/>
+   </td>
+   <td width="40%" align="center">
+    <select name="url_list[]" multiple="multiple" size="20" style="width:230px;">
+		<?php
+		foreach ($db_urls as $url_obj) {
+			?>
+			<option value="<?php echo $url_obj['id']; ?>" <?php if(in_array($url_obj['id'],$url_list)) echo 'selected="selected"'; ?>><?php echo $url_obj['url']; ?></option>
+			<?php
+		}
+		?>
+    </select>
+   </td>
+  </tr>
+ </table>
+</form>
+<?php
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display :: display_footer();
 ?>

+ 145 - 145
main/admin/access_url_edit.php

@@ -1,146 +1,146 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2009 Dokeos SPRL
-	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	@package dokeos.admin
-==============================================================================
-*/
-
-$language_file = 'admin';
-$cidReset = true;
-require ('../inc/global.inc.php');
-$this_section = SECTION_PLATFORM_ADMIN;
-
-api_protect_admin_script();
-if (!$_configuration['multiple_access_urls'])
-	header('Location: index.php');
-
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-require_once (api_get_path(LIBRARY_PATH).'security.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
-
-// Create the form
-$form = new FormValidator('add_url');
-
-if( $form->validate()) {
-	$check = Security::check_token('post');
-	if($check) {
-		$url_array = $form->getSubmitValues();
-		$url = Security::remove_XSS($url_array['url']);
-		$description = Security::remove_XSS($url_array['description']);
-		$active = intval($url_array['active']);
-		$url_id = $url_array['id'];
-		$url_to_go='access_urls.php';
-		if ($url_id!='') {
-			//we can't change the status of the url with id=1
-			if ($url_id==1)
-				$active=1;
-			//checking url
-			if (substr($url,strlen($url)-1, strlen($url))=='/') {
-				UrlManager::udpate($url_id, $url, $description, $active);
-			} else {
-				UrlManager::udpate($url_id, $url.'/', $description, $active);
-			}
-			$url_to_go='access_urls.php';
-			$message=get_lang('URLEdited');
-		} else {
-			$num = UrlManager::url_exist($url);
-			if ($num == 0) {
-				//checking url
-				if (substr($url,strlen($url)-1, strlen($url))=='/') {
-					UrlManager::add($url, $description, $active);
-				} else {
-					//create
-					UrlManager::add($url.'/', $description, $active);
-				}
-				$message = get_lang('URLAdded');
-				$url_to_go='access_urls.php';
-			} else {
-				$url_to_go='access_url_edit.php';
-				$message = get_lang('URLAlreadyAdded');
-			}
-		}
-		Security::clear_token();
-		$tok = Security::get_token();
-		header('Location: '.$url_to_go.'?action=show_message&message='.urlencode($message).'&sec_token='.$tok);
-		exit();
-	}
-}
-else
-{
-	if(isset($_POST['submit'])) {
-		Security::clear_token();
-	}
-	$token = Security::get_token();
-	$form->addElement('hidden','sec_token');
-	$form->setConstants(array('sec_token' => $token));
-}
-
-$form->addElement('text','url',get_lang('URL'),array('size'=>'30'));
-$form->addRule('url', get_lang('ThisFieldIsRequired'), 'required');
-$form->addRule('url', '', 'maxlength',254);
-$form->addElement('textarea','description',get_lang('Description'));
-$form->addElement('checkbox','active',get_lang('Active'));
-$form->addRule('checkbox', get_lang('ThisFieldIsRequired'), 'required');
-
-$defaults['url']='http://';
-$form->setDefaults($defaults);
-
-$submit_name = get_lang('Add');
-if (isset($_GET['url_id']))
-{
-	$url_id = Database::escape_string($_GET['url_id']);
-	$num_url_id = UrlManager::url_id_exist($url_id);
-	if($num_url_id != 1)
-	{
-		header('Location: access_urls.php');
-		exit();
-	}
-	$url_data = UrlManager::get_url_data_from_id($url_id);
-	$form->addElement('hidden','id',$url_data['id']);
-	$form->setDefaults($url_data);
-	$submit_name = get_lang('Edit');
-}
-
-if (!$_configuration['multiple_access_urls'])
-	header('Location: index.php');
-
-$tool_name = get_lang('AddUrl');
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ("url" => 'access_urls.php', "name" => get_lang('MultipleAccessURLs'));
-Display :: display_header($tool_name);
-
-if (isset ($_GET['action']))
-{
-	switch ($_GET['action'])
-	{
-		case 'show_message' :
-			Display :: display_normal_message(stripslashes($_GET['message']));
-			break;
-	}
-}
-
-// Submit button
-$form->addElement('submit', 'submit', $submit_name);
-$form->display();
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2009 Dokeos SPRL
+	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	@package dokeos.admin
+==============================================================================
+*/
+
+$language_file = 'admin';
+$cidReset = true;
+require ('../inc/global.inc.php');
+$this_section = SECTION_PLATFORM_ADMIN;
+
+api_protect_admin_script();
+if (!$_configuration['multiple_access_urls'])
+	header('Location: index.php');
+
+require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+require_once (api_get_path(LIBRARY_PATH).'security.lib.php');
+require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
+
+// Create the form
+$form = new FormValidator('add_url');
+
+if( $form->validate()) {
+	$check = Security::check_token('post');
+	if($check) {
+		$url_array = $form->getSubmitValues();
+		$url = Security::remove_XSS($url_array['url']);
+		$description = Security::remove_XSS($url_array['description']);
+		$active = intval($url_array['active']);
+		$url_id = $url_array['id'];
+		$url_to_go='access_urls.php';
+		if ($url_id!='') {
+			//we can't change the status of the url with id=1
+			if ($url_id==1)
+				$active=1;
+			//checking url
+			if (substr($url,strlen($url)-1, strlen($url))=='/') {
+				UrlManager::udpate($url_id, $url, $description, $active);
+			} else {
+				UrlManager::udpate($url_id, $url.'/', $description, $active);
+			}
+			$url_to_go='access_urls.php';
+			$message=get_lang('URLEdited');
+		} else {
+			$num = UrlManager::url_exist($url);
+			if ($num == 0) {
+				//checking url
+				if (substr($url,strlen($url)-1, strlen($url))=='/') {
+					UrlManager::add($url, $description, $active);
+				} else {
+					//create
+					UrlManager::add($url.'/', $description, $active);
+				}
+				$message = get_lang('URLAdded');
+				$url_to_go='access_urls.php';
+			} else {
+				$url_to_go='access_url_edit.php';
+				$message = get_lang('URLAlreadyAdded');
+			}
+		}
+		Security::clear_token();
+		$tok = Security::get_token();
+		header('Location: '.$url_to_go.'?action=show_message&message='.urlencode($message).'&sec_token='.$tok);
+		exit();
+	}
+}
+else
+{
+	if(isset($_POST['submit'])) {
+		Security::clear_token();
+	}
+	$token = Security::get_token();
+	$form->addElement('hidden','sec_token');
+	$form->setConstants(array('sec_token' => $token));
+}
+
+$form->addElement('text','url',get_lang('URL'),array('size'=>'30'));
+$form->addRule('url', get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule('url', '', 'maxlength',254);
+$form->addElement('textarea','description',get_lang('Description'));
+$form->addElement('checkbox','active',get_lang('Active'));
+$form->addRule('checkbox', get_lang('ThisFieldIsRequired'), 'required');
+
+$defaults['url']='http://';
+$form->setDefaults($defaults);
+
+$submit_name = get_lang('Add');
+if (isset($_GET['url_id']))
+{
+	$url_id = Database::escape_string($_GET['url_id']);
+	$num_url_id = UrlManager::url_id_exist($url_id);
+	if($num_url_id != 1)
+	{
+		header('Location: access_urls.php');
+		exit();
+	}
+	$url_data = UrlManager::get_url_data_from_id($url_id);
+	$form->addElement('hidden','id',$url_data['id']);
+	$form->setDefaults($url_data);
+	$submit_name = get_lang('Edit');
+}
+
+if (!$_configuration['multiple_access_urls'])
+	header('Location: index.php');
+
+$tool_name = get_lang('AddUrl');
+$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ("url" => 'access_urls.php', "name" => get_lang('MultipleAccessURLs'));
+Display :: display_header($tool_name);
+
+if (isset ($_GET['action']))
+{
+	switch ($_GET['action'])
+	{
+		case 'show_message' :
+			Display :: display_normal_message(stripslashes($_GET['message']));
+			break;
+	}
+}
+
+// Submit button
+$form->addElement('submit', 'submit', $submit_name);
+$form->display();
 ?>

+ 473 - 473
main/admin/access_url_edit_courses_to_url.php

@@ -1,473 +1,473 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2009 Dokeos SPRL
-	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	@package dokeos.admin
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file='admin';
-
-// resetting the course id
-$cidReset=true;
-
-// including some necessary dokeos files
-require('../inc/global.inc.php');
-
-require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
-require_once ('../inc/lib/xajax/xajax.inc.php');
-$xajax = new xajax();
-//$xajax->debugOn();
-$xajax -> registerFunction ('search_courses');
-
-// setting the section (for the tabs)
-$this_section = SECTION_PLATFORM_ADMIN;
-
-// Access restrictions
-api_protect_admin_script();
-if (!$_configuration['multiple_access_urls'])
-	header('Location: index.php');
-
-
-// Database Table Definitions
-$tbl_access_url_rel_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-$tbl_course 			 = Database :: get_main_table(TABLE_MAIN_COURSE);
-$tbl_access_url 		 = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
-
-// setting breadcrumbs
-$tool_name = get_lang('EditCoursesToURL');
-$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
-
-$add_type = 'multiple';
-if(isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
-	$add_type = Security::remove_XSS($_REQUEST['add_type']);
-
-}
-
-$access_url_id=1;
-if(isset($_REQUEST['access_url_id']) && $_REQUEST['access_url_id']!=''){
-	$access_url_id = Security::remove_XSS($_REQUEST['access_url_id']);
-}
-
-function search_courses($needle, $id)
-{
-	global $tbl_course;
-	$xajax_response = new XajaxResponse();
-	$return = '';
-
-	if(!empty($needle)) {
-		// xajax send utf8 datas... datas in db can be non-utf8 datas
-		$charset = api_get_setting('platform_charset');
-		$needle = api_convert_encoding($needle, $charset, 'utf-8');
-		$needle = Database::escape_string($needle);
-		// search courses where username or firstname or lastname begins likes $needle
-		$sql = 'SELECT code, title FROM '.$tbl_course.' u
-				WHERE (title LIKE "'.$needle.'%"
-				OR code LIKE "'.$needle.'%"
-				)
-				ORDER BY title, code
-				LIMIT 11';
-		$rs = Database::query($sql, __FILE__, __LINE__);
-        $i=0;
-		while ($course = Database :: fetch_array($rs)) {
-			$i++;
-            if ($i<=10) {
-			     $return .= '<a href="javascript: void(0);" onclick="javascript: add_user_to_url(\''.addslashes($course['code']).'\',\''.addslashes($course['title']).' ('.addslashes($course['code']).')'.'\')">'.$course['title'].' ('.$course['code'].')</a><br />';
-            } else {
-            	$return .= '...<br />';
-            }
-		}
-	}
-	$xajax_response -> addAssign('ajax_list_courses','innerHTML',api_utf8_encode($return));
-	return $xajax_response;
-}
-
-$xajax -> processRequests();
-$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
-$htmlHeadXtra[] = '
-<script type="text/javascript">
-function add_user_to_url(code, content) {
-
-	document.getElementById("course_to_add").value = "";
-	document.getElementById("ajax_list_courses").innerHTML = "";
-
-	destination = document.getElementById("destination_users");
-	destination.options[destination.length] = new Option(content,code);
-
-	destination.selectedIndex = -1;
-	sortOptions(destination.options);
-}
-
-function send() {
-
-	if (document.formulaire.access_url_id.value!=0) {
-		document.formulaire.form_sent.value=0;
-		document.formulaire.add_type.value=\''.$add_type.'\';
-		document.formulaire.submit();
-	}
-}
-
-function remove_item(origin)
-{
-	for(var i = 0 ; i<origin.options.length ; i++) {
-		if(origin.options[i].selected) {
-			origin.options[i]=null;
-			i = i-1;
-		}
-	}
-}
-</script>';
-
-$form_sent=0;
-$errorMsg='';
-$UserList=$SessionList=array();
-$users=$sessions=array();
-
-if($_POST['form_sent']) {
-	$form_sent=$_POST['form_sent'];
-	$course_list=$_POST['course_list'];
-
-	if(!is_array($course_list)) {
-		$course_list=array();
-	}
-
-	if($form_sent == 1) {
-		if ($access_url_id==0) {
-			header('Location: access_url_edit_users_to_url.php?action=show_message&message='.get_lang('SelectURL'));
-		}
-		elseif(is_array($course_list) ) {
-			UrlManager::update_urls_rel_course($course_list,$access_url_id);
-			header('Location: access_urls.php?action=show_message&message='.get_lang('CoursesWereEdited'));
-		}
-	}
-}
-
-Display::display_header($tool_name);
-
-echo '<div class="actions" style="height:22px;">';
-echo '<div style="float:right;">
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_add_courses_to_url.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddUserToURL'),'').get_lang('AddCoursesToURL').'</a>
-	  </div><br />';
-echo '</div>';
-
-api_display_tool_title($tool_name);
-
-if ($_GET['action'] == 'show_message')
-	Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
-
-$no_course_list = $course_list = array();
-$ajax_search = $add_type == 'unique' ? true : false;
-
-if($ajax_search) {
-	$courses=UrlManager::get_url_rel_course_data($access_url_id);
-	foreach($courses as $course) {
-		$course_list[$course['course_code']] = $course ;
-	}
-} else {
-	$courses=UrlManager::get_url_rel_course_data();
-
-	foreach($courses as $course) {
-		if($course['access_url_id'] == $access_url_id) {
-			$course_list[$course['course_code']] = $course ;
-		}
-	}
-
-	$tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
-	$sql="SELECT code, title
-	  	  	FROM $tbl_course u
-			ORDER BY title, code";
-	$result=Database::query($sql,__FILE__,__LINE__);
-	$courses=Database::store_result($result);
-	$course_list_leys = array_keys($course_list);
-	foreach($courses as $course) {
-		if (!in_array($course['code'],$course_list_leys))
-			$no_course_list[$course['code']] = $course ;
-	}
-}
-
-
-if($add_type == 'multiple') {
-	$link_add_type_unique = '<a href="'.api_get_self().'?add_type=unique&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeUnique').'</a>';
-	$link_add_type_multiple = get_lang('SessionAddTypeMultiple');
-} else {
-	$link_add_type_unique = get_lang('SessionAddTypeUnique');
-	$link_add_type_multiple = '<a href="'.api_get_self().'?add_type=multiple&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeMultiple').'</a>';
-}
-
-$url_list = UrlManager::get_url_data();
-
-?>
-
-<div style="text-align: left;">
-	<?php echo $link_add_type_unique ?>&nbsp;|&nbsp;<?php echo $link_add_type_multiple ?>
-</div>
-<br /><br />
-<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;" <?php if($ajax_search){echo ' onsubmit="valide();"';}?> >
-<?php echo get_lang('SelectUrl').' : '; ?>
-<select name="access_url_id" onchange="javascript:send();">
-<option value="0"> <?php echo get_lang('SelectUrl')?></option>
-	<?php
-	$url_selected='';
-	foreach ($url_list as $url_obj) {
-		$checked = '';
-		if (!empty($access_url_id)) {
-			if ($url_obj[0]==$access_url_id) {
-			$checked = 'selected=true';
-			$url_selected=$url_obj[1];
-			}
-		}
-		if ($url_obj['active']==1) {
-			?>
-				<option <?php echo $checked;?> value="<?php echo $url_obj[0]; ?>"> <?php echo $url_obj[1]; ?></option>
-			<?php
-		}
-	}
-	?>
-</select>
-<br /><br />
-<input type="hidden" name="form_sent" value="1" />
-<input type="hidden" name="add_type" value = "<?php echo $add_type ?>" />
-
-<?php
-if(!empty($errorMsg)) {
-	Display::display_normal_message($errorMsg); //main API
-}
-?>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
-<!-- Users -->
-<tr>
-  <td align="center"><b><?php echo get_lang('CourseListInPlatform') ?> :</b>
-  </td>
-  <td></td>
-  <td align="center"><b><?php echo get_lang('CourseListIn').' '.$url_selected; ?></b></td>
-</tr>
-
-<tr>
-  <td align="center">
-  <div id="content_source">
-  	  <?php
-  	  if($ajax_search) {
-  	  	?>
-		<input type="text" id="course_to_add" onkeyup="xajax_search_courses(this.value,document.formulaire.access_url_id.options[document.formulaire.access_url_id.selectedIndex].value)" />
-		<div id="ajax_list_courses"></div>
-		<?php
-  	  } else {
-  	  ?>
-	  <select id="origin_users" name="no_course_list[]" multiple="multiple" size="15" style="width:300px;">
-		<?php
-		foreach($no_course_list as $no_course) {
-		?>
-			<option value="<?php echo $no_course['code']; ?>"><?php echo $no_course['title'].' ('.$no_course['code'].')'; ?></option>
-
-$xajax -> processRequests();
-
-$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
-$htmlHeadXtra[] = '
-<script type="text/javascript">
-function add_user_to_url (code, content) {
-
-	document.getElementById("course_to_add").value = "";
-	document.getElementById("ajax_list_courses").innerHTML = "";
-
-	destination = document.getElementById("destination_users");
-	destination.options[destination.length] = new Option(content,code);
-
-	destination.selectedIndex = -1;
-	sortOptions(destination.options);
-
-}
-function remove_item(origin)
-{
-	for(var i = 0 ; i<origin.options.length ; i++) {
-		if(origin.options[i].selected) {
-			origin.options[i]=null;
-			i = i-1;
-		}
-	}
-}
-</script>';
-		<?php
-		}
-		unset($no_course_list);
-		?>
-
-	  </select>
-	<?php
-  	  }
-  	 ?>
-  </div>
-  </td>
-  <td width="10%" valign="middle" align="center">
-  <?php
-  if($ajax_search) {
-	?>
-	<input type="button" onclick="remove_item(document.getElementById('destination_users'))" value="<<" />
-  	<?php
-  } else {
-  	?>
-	<input type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" value=">>" />
-	<br /><br />
-	<input type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" value="<<" />
-	<?php
-  }
-  ?>
-	<br /><br /><br /><br /><br /><br />
-  </td>
-  <td align="center">
-  <select id="destination_users" name="course_list[]" multiple="multiple" size="15" style="width:300px;">
-
-<?php
-
-foreach($course_list as $course) {
-?>
-	<option value="<?php echo $course['course_code']; ?>"><?php echo $course['title'].' ('.$course['course_code'].')'; ?></option>
-
-<?php
-}
-unset($course_list);
-?>
-
-  </select></td>
-</tr>
-
-<tr>
-	<td colspan="3" align="center">
-		<br />
-		<?php
-		if(isset($_GET['add']))
-			echo '<input type="button" value="'.get_lang('EditCourses').'" onclick="valide()" />';
-		else
-			echo '<input type="button" value="'.get_lang('EditCourses').'" onclick="valide()" />';
-		?>
-	</td>
-</tr>
-
-
-
-
-</table>
-
-</form>
-<script type="text/javascript">
-<!--
-function moveItem(origin , destination) {
-	for(var i = 0 ; i<origin.options.length ; i++) {
-		if(origin.options[i].selected) {
-			destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
-			origin.options[i]=null;
-			i = i-1;
-		}
-	}
-	destination.selectedIndex = -1;
-	sortOptions(destination.options);
-}
-
-function sortOptions(options) {
-	newOptions = new Array();
-	for (i = 0 ; i<options.length ; i++)
-		newOptions[i] = options[i];
-
-	newOptions = newOptions.sort(mysort);
-	options.length = 0;
-	for(i = 0 ; i < newOptions.length ; i++)
-		options[i] = newOptions[i];
-
-}
-
-function mysort(a, b) {
-	if(a.text.toLowerCase() > b.text.toLowerCase()){
-		return 1;
-	}
-	if(a.text.toLowerCase() < b.text.toLowerCase()){
-		return -1;
-	}
-	return 0;
-}
-
-function valide(){
-	var options = document.getElementById('destination_users').options;
-	for (i = 0 ; i<options.length ; i++)
-		options[i].selected = true;
-	/*
-	var options = document.getElementById('destination_classes').options;
-	for (i = 0 ; i<options.length ; i++)
-		options[i].selected = true;
-		*/
-	document.forms.formulaire.submit();
-}
-
-
-function loadUsersInSelect(select){
-
-	var xhr_object = null;
-
-	if(window.XMLHttpRequest) // Firefox
-		xhr_object = new XMLHttpRequest();
-	else if(window.ActiveXObject) // Internet Explorer
-		xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
-	else  // XMLHttpRequest non supporté par le navigateur
-	alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
-
-	//xhr_object.open("GET", "loadUsersInSelect.ajax.php?id_session=<?php echo $id_session ?>&letter="+select.options[select.selectedIndex].text, false);
-	xhr_object.open("POST", "loadUsersInSelect.ajax.php");
-
-	xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
-
-
-	nosessionUsers = makepost(document.getElementById('origin_users'));
-	sessionUsers = makepost(document.getElementById('destination_users'));
-	nosessionClasses = makepost(document.getElementById('origin_classes'));
-	sessionClasses = makepost(document.getElementById('destination_classes'));
-	xhr_object.send("nosessionusers="+nosessionUsers+"&sessionusers="+sessionUsers+"&nosessionclasses="+nosessionClasses+"&sessionclasses="+sessionClasses);
-
-	xhr_object.onreadystatechange = function() {
-		if(xhr_object.readyState == 4) {
-			document.getElementById('content_source').innerHTML = result = xhr_object.responseText;
-			//alert(xhr_object.responseText);
-		}
-	}
-}
-
-function makepost(select){
-	var options = select.options;
-	var ret = "";
-	for (i = 0 ; i<options.length ; i++)
-		ret = ret + options[i].value +'::'+options[i].text+";;";
-
-	return ret;
-
-}
--->
-
-</script>
-<?php
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display::display_footer();
-?>
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2009 Dokeos SPRL
+	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	@package dokeos.admin
+==============================================================================
+*/
+
+// name of the language file that needs to be included
+$language_file='admin';
+
+// resetting the course id
+$cidReset=true;
+
+// including some necessary dokeos files
+require('../inc/global.inc.php');
+
+require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
+require_once ('../inc/lib/xajax/xajax.inc.php');
+$xajax = new xajax();
+//$xajax->debugOn();
+$xajax -> registerFunction ('search_courses');
+
+// setting the section (for the tabs)
+$this_section = SECTION_PLATFORM_ADMIN;
+
+// Access restrictions
+api_protect_admin_script();
+if (!$_configuration['multiple_access_urls'])
+	header('Location: index.php');
+
+
+// Database Table Definitions
+$tbl_access_url_rel_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+$tbl_course 			 = Database :: get_main_table(TABLE_MAIN_COURSE);
+$tbl_access_url 		 = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+
+// setting breadcrumbs
+$tool_name = get_lang('EditCoursesToURL');
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
+
+$add_type = 'multiple';
+if(isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
+	$add_type = Security::remove_XSS($_REQUEST['add_type']);
+
+}
+
+$access_url_id=1;
+if(isset($_REQUEST['access_url_id']) && $_REQUEST['access_url_id']!=''){
+	$access_url_id = Security::remove_XSS($_REQUEST['access_url_id']);
+}
+
+function search_courses($needle, $id)
+{
+	global $tbl_course;
+	$xajax_response = new XajaxResponse();
+	$return = '';
+
+	if(!empty($needle)) {
+		// xajax send utf8 datas... datas in db can be non-utf8 datas
+		$charset = api_get_setting('platform_charset');
+		$needle = api_convert_encoding($needle, $charset, 'utf-8');
+		$needle = Database::escape_string($needle);
+		// search courses where username or firstname or lastname begins likes $needle
+		$sql = 'SELECT code, title FROM '.$tbl_course.' u
+				WHERE (title LIKE "'.$needle.'%"
+				OR code LIKE "'.$needle.'%"
+				)
+				ORDER BY title, code
+				LIMIT 11';
+		$rs = Database::query($sql, __FILE__, __LINE__);
+        $i=0;
+		while ($course = Database :: fetch_array($rs)) {
+			$i++;
+            if ($i<=10) {
+			     $return .= '<a href="javascript: void(0);" onclick="javascript: add_user_to_url(\''.addslashes($course['code']).'\',\''.addslashes($course['title']).' ('.addslashes($course['code']).')'.'\')">'.$course['title'].' ('.$course['code'].')</a><br />';
+            } else {
+            	$return .= '...<br />';
+            }
+		}
+	}
+	$xajax_response -> addAssign('ajax_list_courses','innerHTML',api_utf8_encode($return));
+	return $xajax_response;
+}
+
+$xajax -> processRequests();
+$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
+$htmlHeadXtra[] = '
+<script type="text/javascript">
+function add_user_to_url(code, content) {
+
+	document.getElementById("course_to_add").value = "";
+	document.getElementById("ajax_list_courses").innerHTML = "";
+
+	destination = document.getElementById("destination_users");
+	destination.options[destination.length] = new Option(content,code);
+
+	destination.selectedIndex = -1;
+	sortOptions(destination.options);
+}
+
+function send() {
+
+	if (document.formulaire.access_url_id.value!=0) {
+		document.formulaire.form_sent.value=0;
+		document.formulaire.add_type.value=\''.$add_type.'\';
+		document.formulaire.submit();
+	}
+}
+
+function remove_item(origin)
+{
+	for(var i = 0 ; i<origin.options.length ; i++) {
+		if(origin.options[i].selected) {
+			origin.options[i]=null;
+			i = i-1;
+		}
+	}
+}
+</script>';
+
+$form_sent=0;
+$errorMsg='';
+$UserList=$SessionList=array();
+$users=$sessions=array();
+
+if($_POST['form_sent']) {
+	$form_sent=$_POST['form_sent'];
+	$course_list=$_POST['course_list'];
+
+	if(!is_array($course_list)) {
+		$course_list=array();
+	}
+
+	if($form_sent == 1) {
+		if ($access_url_id==0) {
+			header('Location: access_url_edit_users_to_url.php?action=show_message&message='.get_lang('SelectURL'));
+		}
+		elseif(is_array($course_list) ) {
+			UrlManager::update_urls_rel_course($course_list,$access_url_id);
+			header('Location: access_urls.php?action=show_message&message='.get_lang('CoursesWereEdited'));
+		}
+	}
+}
+
+Display::display_header($tool_name);
+
+echo '<div class="actions" style="height:22px;">';
+echo '<div style="float:right;">
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_add_courses_to_url.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddUserToURL'),'').get_lang('AddCoursesToURL').'</a>
+	  </div><br />';
+echo '</div>';
+
+api_display_tool_title($tool_name);
+
+if ($_GET['action'] == 'show_message')
+	Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
+
+$no_course_list = $course_list = array();
+$ajax_search = $add_type == 'unique' ? true : false;
+
+if($ajax_search) {
+	$courses=UrlManager::get_url_rel_course_data($access_url_id);
+	foreach($courses as $course) {
+		$course_list[$course['course_code']] = $course ;
+	}
+} else {
+	$courses=UrlManager::get_url_rel_course_data();
+
+	foreach($courses as $course) {
+		if($course['access_url_id'] == $access_url_id) {
+			$course_list[$course['course_code']] = $course ;
+		}
+	}
+
+	$tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
+	$sql="SELECT code, title
+	  	  	FROM $tbl_course u
+			ORDER BY title, code";
+	$result=Database::query($sql,__FILE__,__LINE__);
+	$courses=Database::store_result($result);
+	$course_list_leys = array_keys($course_list);
+	foreach($courses as $course) {
+		if (!in_array($course['code'],$course_list_leys))
+			$no_course_list[$course['code']] = $course ;
+	}
+}
+
+
+if($add_type == 'multiple') {
+	$link_add_type_unique = '<a href="'.api_get_self().'?add_type=unique&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeUnique').'</a>';
+	$link_add_type_multiple = get_lang('SessionAddTypeMultiple');
+} else {
+	$link_add_type_unique = get_lang('SessionAddTypeUnique');
+	$link_add_type_multiple = '<a href="'.api_get_self().'?add_type=multiple&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeMultiple').'</a>';
+}
+
+$url_list = UrlManager::get_url_data();
+
+?>
+
+<div style="text-align: left;">
+	<?php echo $link_add_type_unique ?>&nbsp;|&nbsp;<?php echo $link_add_type_multiple ?>
+</div>
+<br /><br />
+<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;" <?php if($ajax_search){echo ' onsubmit="valide();"';}?> >
+<?php echo get_lang('SelectUrl').' : '; ?>
+<select name="access_url_id" onchange="javascript:send();">
+<option value="0"> <?php echo get_lang('SelectUrl')?></option>
+	<?php
+	$url_selected='';
+	foreach ($url_list as $url_obj) {
+		$checked = '';
+		if (!empty($access_url_id)) {
+			if ($url_obj[0]==$access_url_id) {
+			$checked = 'selected=true';
+			$url_selected=$url_obj[1];
+			}
+		}
+		if ($url_obj['active']==1) {
+			?>
+				<option <?php echo $checked;?> value="<?php echo $url_obj[0]; ?>"> <?php echo $url_obj[1]; ?></option>
+			<?php
+		}
+	}
+	?>
+</select>
+<br /><br />
+<input type="hidden" name="form_sent" value="1" />
+<input type="hidden" name="add_type" value = "<?php echo $add_type ?>" />
+
+<?php
+if(!empty($errorMsg)) {
+	Display::display_normal_message($errorMsg); //main API
+}
+?>
+
+<table border="0" cellpadding="5" cellspacing="0" width="100%">
+
+<!-- Users -->
+<tr>
+  <td align="center"><b><?php echo get_lang('CourseListInPlatform') ?> :</b>
+  </td>
+  <td></td>
+  <td align="center"><b><?php echo get_lang('CourseListIn').' '.$url_selected; ?></b></td>
+</tr>
+
+<tr>
+  <td align="center">
+  <div id="content_source">
+  	  <?php
+  	  if($ajax_search) {
+  	  	?>
+		<input type="text" id="course_to_add" onkeyup="xajax_search_courses(this.value,document.formulaire.access_url_id.options[document.formulaire.access_url_id.selectedIndex].value)" />
+		<div id="ajax_list_courses"></div>
+		<?php
+  	  } else {
+  	  ?>
+	  <select id="origin_users" name="no_course_list[]" multiple="multiple" size="15" style="width:300px;">
+		<?php
+		foreach($no_course_list as $no_course) {
+		?>
+			<option value="<?php echo $no_course['code']; ?>"><?php echo $no_course['title'].' ('.$no_course['code'].')'; ?></option>
+
+$xajax -> processRequests();
+
+$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
+$htmlHeadXtra[] = '
+<script type="text/javascript">
+function add_user_to_url (code, content) {
+
+	document.getElementById("course_to_add").value = "";
+	document.getElementById("ajax_list_courses").innerHTML = "";
+
+	destination = document.getElementById("destination_users");
+	destination.options[destination.length] = new Option(content,code);
+
+	destination.selectedIndex = -1;
+	sortOptions(destination.options);
+
+}
+function remove_item(origin)
+{
+	for(var i = 0 ; i<origin.options.length ; i++) {
+		if(origin.options[i].selected) {
+			origin.options[i]=null;
+			i = i-1;
+		}
+	}
+}
+</script>';
+		<?php
+		}
+		unset($no_course_list);
+		?>
+
+	  </select>
+	<?php
+  	  }
+  	 ?>
+  </div>
+  </td>
+  <td width="10%" valign="middle" align="center">
+  <?php
+  if($ajax_search) {
+	?>
+	<input type="button" onclick="remove_item(document.getElementById('destination_users'))" value="<<" />
+  	<?php
+  } else {
+  	?>
+	<input type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" value=">>" />
+	<br /><br />
+	<input type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" value="<<" />
+	<?php
+  }
+  ?>
+	<br /><br /><br /><br /><br /><br />
+  </td>
+  <td align="center">
+  <select id="destination_users" name="course_list[]" multiple="multiple" size="15" style="width:300px;">
+
+<?php
+
+foreach($course_list as $course) {
+?>
+	<option value="<?php echo $course['course_code']; ?>"><?php echo $course['title'].' ('.$course['course_code'].')'; ?></option>
+
+<?php
+}
+unset($course_list);
+?>
+
+  </select></td>
+</tr>
+
+<tr>
+	<td colspan="3" align="center">
+		<br />
+		<?php
+		if(isset($_GET['add']))
+			echo '<input type="button" value="'.get_lang('EditCourses').'" onclick="valide()" />';
+		else
+			echo '<input type="button" value="'.get_lang('EditCourses').'" onclick="valide()" />';
+		?>
+	</td>
+</tr>
+
+
+
+
+</table>
+
+</form>
+<script type="text/javascript">
+<!--
+function moveItem(origin , destination) {
+	for(var i = 0 ; i<origin.options.length ; i++) {
+		if(origin.options[i].selected) {
+			destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
+			origin.options[i]=null;
+			i = i-1;
+		}
+	}
+	destination.selectedIndex = -1;
+	sortOptions(destination.options);
+}
+
+function sortOptions(options) {
+	newOptions = new Array();
+	for (i = 0 ; i<options.length ; i++)
+		newOptions[i] = options[i];
+
+	newOptions = newOptions.sort(mysort);
+	options.length = 0;
+	for(i = 0 ; i < newOptions.length ; i++)
+		options[i] = newOptions[i];
+
+}
+
+function mysort(a, b) {
+	if(a.text.toLowerCase() > b.text.toLowerCase()){
+		return 1;
+	}
+	if(a.text.toLowerCase() < b.text.toLowerCase()){
+		return -1;
+	}
+	return 0;
+}
+
+function valide(){
+	var options = document.getElementById('destination_users').options;
+	for (i = 0 ; i<options.length ; i++)
+		options[i].selected = true;
+	/*
+	var options = document.getElementById('destination_classes').options;
+	for (i = 0 ; i<options.length ; i++)
+		options[i].selected = true;
+		*/
+	document.forms.formulaire.submit();
+}
+
+
+function loadUsersInSelect(select){
+
+	var xhr_object = null;
+
+	if(window.XMLHttpRequest) // Firefox
+		xhr_object = new XMLHttpRequest();
+	else if(window.ActiveXObject) // Internet Explorer
+		xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
+	else  // XMLHttpRequest non supporté par le navigateur
+	alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
+
+	//xhr_object.open("GET", "loadUsersInSelect.ajax.php?id_session=<?php echo $id_session ?>&letter="+select.options[select.selectedIndex].text, false);
+	xhr_object.open("POST", "loadUsersInSelect.ajax.php");
+
+	xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+
+
+	nosessionUsers = makepost(document.getElementById('origin_users'));
+	sessionUsers = makepost(document.getElementById('destination_users'));
+	nosessionClasses = makepost(document.getElementById('origin_classes'));
+	sessionClasses = makepost(document.getElementById('destination_classes'));
+	xhr_object.send("nosessionusers="+nosessionUsers+"&sessionusers="+sessionUsers+"&nosessionclasses="+nosessionClasses+"&sessionclasses="+sessionClasses);
+
+	xhr_object.onreadystatechange = function() {
+		if(xhr_object.readyState == 4) {
+			document.getElementById('content_source').innerHTML = result = xhr_object.responseText;
+			//alert(xhr_object.responseText);
+		}
+	}
+}
+
+function makepost(select){
+	var options = select.options;
+	var ret = "";
+	for (i = 0 ; i<options.length ; i++)
+		ret = ret + options[i].value +'::'+options[i].text+";;";
+
+	return ret;
+
+}
+-->
+
+</script>
+<?php
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display::display_footer();
+?>

+ 469 - 469
main/admin/access_url_edit_sessions_to_url.php

@@ -1,469 +1,469 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2009 Dokeos SPRL
-	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	@package dokeos.admin
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file='admin';
-
-// resetting the course id
-$cidReset=true;
-
-// including some necessary dokeos files
-require('../inc/global.inc.php');
-
-require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
-require_once ('../inc/lib/xajax/xajax.inc.php');
-$xajax = new xajax();
-//$xajax->debugOn();
-$xajax -> registerFunction ('search_sessions');
-
-// setting the section (for the tabs)
-$this_section = SECTION_PLATFORM_ADMIN;
-
-// Access restrictions
-api_protect_admin_script();
-if (!$_configuration['multiple_access_urls'])
-	header('Location: index.php');
-
-
-// Database Table Definitions
-$tbl_access_url_rel_session = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
-$tbl_session 			 	= Database :: get_main_table(TABLE_MAIN_SESSION);
-$tbl_access_url 		 	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
-
-// setting breadcrumbs
-$tool_name = get_lang('EditSessionsToURL');
-$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
-
-$add_type = 'multiple';
-if(isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
-	$add_type = Security::remove_XSS($_REQUEST['add_type']);
-}
-
-$access_url_id=1;
-if(isset($_REQUEST['access_url_id']) && $_REQUEST['access_url_id']!=''){
-	$access_url_id = Security::remove_XSS(intval($_REQUEST['access_url_id']));
-}
-
-function search_sessions($needle, $id)
-{
-	global $tbl_session;
-	$xajax_response = new XajaxResponse();
-	$return = '';
-
-	if(!empty($needle)) {
-		// xajax send utf8 datas... datas in db can be non-utf8 datas
-		$charset = api_get_setting('platform_charset');
-		$needle = api_convert_encoding($needle, $charset, 'utf-8');
-		$needle = Database::escape_string($needle);
-		// search sessiones where username or firstname or lastname begins likes $needle
-		$sql = 'SELECT id, name FROM '.$tbl_session.' u
-				WHERE (name LIKE "'.$needle.'%")
-				ORDER BY name, id
-				LIMIT 11';
-		$rs = Database::query($sql, __FILE__, __LINE__);
-        $i=0;
-		while ($session = Database :: fetch_array($rs)) {
-			$i++;
-            if ($i<=10) {
-			     $return .= '<a href="#" onclick="add_user_to_url(\''.addslashes($session['id']).'\',\''.addslashes($session['name']).' ('.addslashes($session['id']).')'.'\')">'.$session['name'].' </a><br />';
-            } else {
-            	$return .= '...<br />';
-            }
-		}
-	}
-	$xajax_response -> addAssign('ajax_list_courses','innerHTML',api_utf8_encode($return));
-	return $xajax_response;
-}
-
-$xajax -> processRequests();
-$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
-$htmlHeadXtra[] = '
-<script type="text/javascript">
-function add_user_to_url(code, content) {
-
-	document.getElementById("course_to_add").value = "";
-	document.getElementById("ajax_list_courses").innerHTML = "";
-
-	destination = document.getElementById("destination_users");
-	destination.options[destination.length] = new Option(content,code);
-
-	destination.selectedIndex = -1;
-	sortOptions(destination.options);
-}
-
-function send() {
-
-	if (document.formulaire.access_url_id.value!=0) {
-		document.formulaire.form_sent.value=0;
-		document.formulaire.add_type.value=\''.$add_type.'\';
-		document.formulaire.submit();
-	}
-}
-
-function remove_item(origin)
-{
-	for(var i = 0 ; i<origin.options.length ; i++) {
-		if(origin.options[i].selected) {
-			origin.options[i]=null;
-			i = i-1;
-		}
-	}
-}
-</script>';
-
-$form_sent=0;
-$errorMsg='';
-$UserList=$SessionList=array();
-$users=$sessions=array();
-
-if($_POST['form_sent']) {
-	$form_sent=$_POST['form_sent'];
-	$session_list=$_POST['session_list'];
-
-	if(!is_array($session_list)) {
-		$session_list=array();
-	}
-
-	if($form_sent == 1) {
-		if ($access_url_id==0) {
-			header('Location: access_url_edit_users_to_url.php?action=show_message&message='.get_lang('SelectURL'));
-		}
-		elseif(is_array($session_list) ) {
-			UrlManager::update_urls_rel_session($session_list,$access_url_id);
-			header('Location: access_urls.php?action=show_message&message='.get_lang('SessionsWereEdited'));
-		}
-	}
-}
-
-Display::display_header($tool_name);
-
-echo '<div class="actions" style="height:22px;">';
-echo '<div style="float:right;">
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_add_sessions_to_url.php">'.Display::return_icon('course_add.gif',get_lang('AddSessionsToURL'),'').get_lang('AddSessionsToURL').'</a>
-	  </div><br />';
-echo '</div>';
-
-api_display_tool_title($tool_name);
-
-if ($_GET['action'] == 'show_message')
-	Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
-
-$no_session_list = $session_list = array();
-$ajax_search = $add_type == 'unique' ? true : false;
-
-if($ajax_search) {
-	$sessions=UrlManager::get_url_rel_session_data($access_url_id);
-	foreach($sessions as $session) {
-		$session_list[$session['id']] = $session ;
-	}
-} else {
-	$sessions=UrlManager::get_url_rel_session_data();
-	foreach($sessions as $session) {
-		if($session['access_url_id'] == $access_url_id) {
-			$session_list[$session['id']] = $session ;
-		}
-	}
-
-	$tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
-	$sql="SELECT id, name
-	  	  	FROM $tbl_session u
-			ORDER BY name, id";
-	$result=Database::query($sql,__FILE__,__LINE__);
-	$sessions=Database::store_result($result);
-	$session_list_leys = array_keys($session_list);
-	foreach($sessions as $session) {
-		if (!in_array($session['id'],$session_list_leys))
-			$no_session_list[$session['id']] = $session ;
-	}
-}
-
-
-if($add_type == 'multiple') {
-	$link_add_type_unique = '<a href="'.api_get_self().'?add_type=unique&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeUnique').'</a>';
-	$link_add_type_multiple = get_lang('SessionAddTypeMultiple');
-} else {
-	$link_add_type_unique = get_lang('SessionAddTypeUnique');
-	$link_add_type_multiple = '<a href="'.api_get_self().'?add_type=multiple&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeMultiple').'</a>';
-}
-
-$url_list = UrlManager::get_url_data();
-
-?>
-
-<div style="text-align: left;">
-	<?php echo $link_add_type_unique ?>&nbsp;|&nbsp;<?php echo $link_add_type_multiple ?>
-</div>
-<br /><br />
-<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;" <?php if($ajax_search){echo ' onsubmit="valide();"';}?> >
-<?php echo get_lang('SelectUrl').' : '; ?>
-<select name="access_url_id" onchange="javascript:send();">
-<option value="0"> <?php echo get_lang('SelectUrl')?></option>
-	<?php
-	$url_selected='';
-	foreach ($url_list as $url_obj) {
-		$checked = '';
-		if (!empty($access_url_id)) {
-			if ($url_obj[0]==$access_url_id) {
-			$checked = 'selected=true';
-			$url_selected=$url_obj[1];
-			}
-		}
-		if ($url_obj['active']==1) {
-			?>
-				<option <?php echo $checked;?> value="<?php echo $url_obj[0]; ?>"> <?php echo $url_obj[1]; ?></option>
-			<?php
-		}
-	}
-	?>
-</select>
-<br /><br />
-<input type="hidden" name="form_sent" value="1" />
-<input type="hidden" name="add_type" value = "<?php echo $add_type ?>" />
-
-<?php
-if(!empty($errorMsg)) {
-	Display::display_normal_message($errorMsg); //main API
-}
-?>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
-<!-- Users -->
-<tr>
-  <td align="center"><b><?php echo get_lang('SessionListInPlatform') ?> :</b>
-  </td>
-  <td></td>
-  <td align="center"><b><?php echo get_lang('SessionListIn').' '.$url_selected; ?></b></td>
-</tr>
-
-<tr>
-  <td align="center">
-  <div id="content_source">
-  	  <?php
-  	  if($ajax_search) {
-  	  	?>
-		<input type="text" id="course_to_add" onkeyup="xajax_search_sessions(this.value,document.formulaire.access_url_id.options[document.formulaire.access_url_id.selectedIndex].value)" />
-		<div id="ajax_list_courses"></div>
-		<?php
-  	  } else {
-  	  ?>
-	  <select id="origin_users" name="no_session_list[]" multiple="multiple" size="15" style="width:300px;">
-		<?php
-		foreach($no_session_list as $no_session) {
-		?>
-			<option value="<?php echo $no_session['id']; ?>"><?php echo $no_session['name'].''; ?></option>
-
-$xajax -> processRequests();
-
-$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
-$htmlHeadXtra[] = '
-<script type="text/javascript">
-function add_user_to_url (code, content) {
-
-	document.getElementById("course_to_add").value = "";
-	document.getElementById("ajax_list_courses").innerHTML = "";
-
-	destination = document.getElementById("destination_users");
-	destination.options[destination.length] = new Option(content,code);
-
-	destination.selectedIndex = -1;
-	sortOptions(destination.options);
-
-}
-function remove_item(origin)
-{
-	for(var i = 0 ; i<origin.options.length ; i++) {
-		if(origin.options[i].selected) {
-			origin.options[i]=null;
-			i = i-1;
-		}
-	}
-}
-</script>';
-		<?php
-		}
-		unset($no_session_list);
-		?>
-
-	  </select>
-	<?php
-  	  }
-  	 ?>
-  </div>
-  </td>
-  <td width="10%" valign="middle" align="center">
-  <?php
-  if($ajax_search) {
-	?>
-	<input type="button" onclick="remove_item(document.getElementById('destination_users'))" value="<<" />
-  	<?php
-  } else {
-  	?>
-	<input type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" value=">>" />
-	<br /><br />
-	<input type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" value="<<" />
-	<?php
-  }
-  ?>
-	<br /><br /><br /><br /><br /><br />
-  </td>
-  <td align="center">
-  <select id="destination_users" name="session_list[]" multiple="multiple" size="15" style="width:300px;">
-
-<?php
-
-foreach($session_list as $session) {
-?>
-	<option value="<?php echo $session['id']; ?>"><?php echo $session['name']; ?></option>
-
-<?php
-}
-unset($session_list);
-?>
-
-  </select></td>
-</tr>
-
-<tr>
-	<td colspan="3" align="center">
-		<br />
-		<?php
-		if(isset($_GET['add']))
-			echo '<input type="button" value="'.get_lang('EditSessions').'" onclick="valide()" />';
-		else
-			echo '<input type="button" value="'.get_lang('EditSessions').'" onclick="valide()" />';
-		?>
-	</td>
-</tr>
-
-
-
-
-</table>
-
-</form>
-<script type="text/javascript">
-<!--
-function moveItem(origin , destination) {
-	for(var i = 0 ; i<origin.options.length ; i++) {
-		if(origin.options[i].selected) {
-			destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
-			origin.options[i]=null;
-			i = i-1;
-		}
-	}
-	destination.selectedIndex = -1;
-	sortOptions(destination.options);
-}
-
-function sortOptions(options) {
-	newOptions = new Array();
-	for (i = 0 ; i<options.length ; i++)
-		newOptions[i] = options[i];
-
-	newOptions = newOptions.sort(mysort);
-	options.length = 0;
-	for(i = 0 ; i < newOptions.length ; i++)
-		options[i] = newOptions[i];
-
-}
-
-function mysort(a, b) {
-	if(a.text.toLowerCase() > b.text.toLowerCase()){
-		return 1;
-	}
-	if(a.text.toLowerCase() < b.text.toLowerCase()){
-		return -1;
-	}
-	return 0;
-}
-
-function valide(){
-	var options = document.getElementById('destination_users').options;
-	for (i = 0 ; i<options.length ; i++)
-		options[i].selected = true;
-	/*
-	var options = document.getElementById('destination_classes').options;
-	for (i = 0 ; i<options.length ; i++)
-		options[i].selected = true;
-		*/
-	document.forms.formulaire.submit();
-}
-
-
-function loadUsersInSelect(select){
-
-	var xhr_object = null;
-
-	if(window.XMLHttpRequest) // Firefox
-		xhr_object = new XMLHttpRequest();
-	else if(window.ActiveXObject) // Internet Explorer
-		xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
-	else  // XMLHttpRequest non supporté par le navigateur
-	alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
-
-	//xhr_object.open("GET", "loadUsersInSelect.ajax.php?id_session=<?php echo $id_session ?>&letter="+select.options[select.selectedIndex].text, false);
-	xhr_object.open("POST", "loadUsersInSelect.ajax.php");
-
-	xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
-
-
-	nosessionUsers = makepost(document.getElementById('origin_users'));
-	sessionUsers = makepost(document.getElementById('destination_users'));
-	nosessionClasses = makepost(document.getElementById('origin_classes'));
-	sessionClasses = makepost(document.getElementById('destination_classes'));
-	xhr_object.send("nosessionusers="+nosessionUsers+"&sessionusers="+sessionUsers+"&nosessionclasses="+nosessionClasses+"&sessionclasses="+sessionClasses);
-
-	xhr_object.onreadystatechange = function() {
-		if(xhr_object.readyState == 4) {
-			document.getElementById('content_source').innerHTML = result = xhr_object.responseText;
-			//alert(xhr_object.responseText);
-		}
-	}
-}
-
-function makepost(select){
-	var options = select.options;
-	var ret = "";
-	for (i = 0 ; i<options.length ; i++)
-		ret = ret + options[i].value +'::'+options[i].text+";;";
-
-	return ret;
-
-}
--->
-
-</script>
-<?php
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display::display_footer();
-?>
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2009 Dokeos SPRL
+	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	@package dokeos.admin
+==============================================================================
+*/
+
+// name of the language file that needs to be included
+$language_file='admin';
+
+// resetting the course id
+$cidReset=true;
+
+// including some necessary dokeos files
+require('../inc/global.inc.php');
+
+require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
+require_once ('../inc/lib/xajax/xajax.inc.php');
+$xajax = new xajax();
+//$xajax->debugOn();
+$xajax -> registerFunction ('search_sessions');
+
+// setting the section (for the tabs)
+$this_section = SECTION_PLATFORM_ADMIN;
+
+// Access restrictions
+api_protect_admin_script();
+if (!$_configuration['multiple_access_urls'])
+	header('Location: index.php');
+
+
+// Database Table Definitions
+$tbl_access_url_rel_session = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+$tbl_session 			 	= Database :: get_main_table(TABLE_MAIN_SESSION);
+$tbl_access_url 		 	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+
+// setting breadcrumbs
+$tool_name = get_lang('EditSessionsToURL');
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
+
+$add_type = 'multiple';
+if(isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
+	$add_type = Security::remove_XSS($_REQUEST['add_type']);
+}
+
+$access_url_id=1;
+if(isset($_REQUEST['access_url_id']) && $_REQUEST['access_url_id']!=''){
+	$access_url_id = Security::remove_XSS(intval($_REQUEST['access_url_id']));
+}
+
+function search_sessions($needle, $id)
+{
+	global $tbl_session;
+	$xajax_response = new XajaxResponse();
+	$return = '';
+
+	if(!empty($needle)) {
+		// xajax send utf8 datas... datas in db can be non-utf8 datas
+		$charset = api_get_setting('platform_charset');
+		$needle = api_convert_encoding($needle, $charset, 'utf-8');
+		$needle = Database::escape_string($needle);
+		// search sessiones where username or firstname or lastname begins likes $needle
+		$sql = 'SELECT id, name FROM '.$tbl_session.' u
+				WHERE (name LIKE "'.$needle.'%")
+				ORDER BY name, id
+				LIMIT 11';
+		$rs = Database::query($sql, __FILE__, __LINE__);
+        $i=0;
+		while ($session = Database :: fetch_array($rs)) {
+			$i++;
+            if ($i<=10) {
+			     $return .= '<a href="#" onclick="add_user_to_url(\''.addslashes($session['id']).'\',\''.addslashes($session['name']).' ('.addslashes($session['id']).')'.'\')">'.$session['name'].' </a><br />';
+            } else {
+            	$return .= '...<br />';
+            }
+		}
+	}
+	$xajax_response -> addAssign('ajax_list_courses','innerHTML',api_utf8_encode($return));
+	return $xajax_response;
+}
+
+$xajax -> processRequests();
+$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
+$htmlHeadXtra[] = '
+<script type="text/javascript">
+function add_user_to_url(code, content) {
+
+	document.getElementById("course_to_add").value = "";
+	document.getElementById("ajax_list_courses").innerHTML = "";
+
+	destination = document.getElementById("destination_users");
+	destination.options[destination.length] = new Option(content,code);
+
+	destination.selectedIndex = -1;
+	sortOptions(destination.options);
+}
+
+function send() {
+
+	if (document.formulaire.access_url_id.value!=0) {
+		document.formulaire.form_sent.value=0;
+		document.formulaire.add_type.value=\''.$add_type.'\';
+		document.formulaire.submit();
+	}
+}
+
+function remove_item(origin)
+{
+	for(var i = 0 ; i<origin.options.length ; i++) {
+		if(origin.options[i].selected) {
+			origin.options[i]=null;
+			i = i-1;
+		}
+	}
+}
+</script>';
+
+$form_sent=0;
+$errorMsg='';
+$UserList=$SessionList=array();
+$users=$sessions=array();
+
+if($_POST['form_sent']) {
+	$form_sent=$_POST['form_sent'];
+	$session_list=$_POST['session_list'];
+
+	if(!is_array($session_list)) {
+		$session_list=array();
+	}
+
+	if($form_sent == 1) {
+		if ($access_url_id==0) {
+			header('Location: access_url_edit_users_to_url.php?action=show_message&message='.get_lang('SelectURL'));
+		}
+		elseif(is_array($session_list) ) {
+			UrlManager::update_urls_rel_session($session_list,$access_url_id);
+			header('Location: access_urls.php?action=show_message&message='.get_lang('SessionsWereEdited'));
+		}
+	}
+}
+
+Display::display_header($tool_name);
+
+echo '<div class="actions" style="height:22px;">';
+echo '<div style="float:right;">
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_add_sessions_to_url.php">'.Display::return_icon('course_add.gif',get_lang('AddSessionsToURL'),'').get_lang('AddSessionsToURL').'</a>
+	  </div><br />';
+echo '</div>';
+
+api_display_tool_title($tool_name);
+
+if ($_GET['action'] == 'show_message')
+	Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
+
+$no_session_list = $session_list = array();
+$ajax_search = $add_type == 'unique' ? true : false;
+
+if($ajax_search) {
+	$sessions=UrlManager::get_url_rel_session_data($access_url_id);
+	foreach($sessions as $session) {
+		$session_list[$session['id']] = $session ;
+	}
+} else {
+	$sessions=UrlManager::get_url_rel_session_data();
+	foreach($sessions as $session) {
+		if($session['access_url_id'] == $access_url_id) {
+			$session_list[$session['id']] = $session ;
+		}
+	}
+
+	$tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
+	$sql="SELECT id, name
+	  	  	FROM $tbl_session u
+			ORDER BY name, id";
+	$result=Database::query($sql,__FILE__,__LINE__);
+	$sessions=Database::store_result($result);
+	$session_list_leys = array_keys($session_list);
+	foreach($sessions as $session) {
+		if (!in_array($session['id'],$session_list_leys))
+			$no_session_list[$session['id']] = $session ;
+	}
+}
+
+
+if($add_type == 'multiple') {
+	$link_add_type_unique = '<a href="'.api_get_self().'?add_type=unique&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeUnique').'</a>';
+	$link_add_type_multiple = get_lang('SessionAddTypeMultiple');
+} else {
+	$link_add_type_unique = get_lang('SessionAddTypeUnique');
+	$link_add_type_multiple = '<a href="'.api_get_self().'?add_type=multiple&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeMultiple').'</a>';
+}
+
+$url_list = UrlManager::get_url_data();
+
+?>
+
+<div style="text-align: left;">
+	<?php echo $link_add_type_unique ?>&nbsp;|&nbsp;<?php echo $link_add_type_multiple ?>
+</div>
+<br /><br />
+<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;" <?php if($ajax_search){echo ' onsubmit="valide();"';}?> >
+<?php echo get_lang('SelectUrl').' : '; ?>
+<select name="access_url_id" onchange="javascript:send();">
+<option value="0"> <?php echo get_lang('SelectUrl')?></option>
+	<?php
+	$url_selected='';
+	foreach ($url_list as $url_obj) {
+		$checked = '';
+		if (!empty($access_url_id)) {
+			if ($url_obj[0]==$access_url_id) {
+			$checked = 'selected=true';
+			$url_selected=$url_obj[1];
+			}
+		}
+		if ($url_obj['active']==1) {
+			?>
+				<option <?php echo $checked;?> value="<?php echo $url_obj[0]; ?>"> <?php echo $url_obj[1]; ?></option>
+			<?php
+		}
+	}
+	?>
+</select>
+<br /><br />
+<input type="hidden" name="form_sent" value="1" />
+<input type="hidden" name="add_type" value = "<?php echo $add_type ?>" />
+
+<?php
+if(!empty($errorMsg)) {
+	Display::display_normal_message($errorMsg); //main API
+}
+?>
+
+<table border="0" cellpadding="5" cellspacing="0" width="100%">
+
+<!-- Users -->
+<tr>
+  <td align="center"><b><?php echo get_lang('SessionListInPlatform') ?> :</b>
+  </td>
+  <td></td>
+  <td align="center"><b><?php echo get_lang('SessionListIn').' '.$url_selected; ?></b></td>
+</tr>
+
+<tr>
+  <td align="center">
+  <div id="content_source">
+  	  <?php
+  	  if($ajax_search) {
+  	  	?>
+		<input type="text" id="course_to_add" onkeyup="xajax_search_sessions(this.value,document.formulaire.access_url_id.options[document.formulaire.access_url_id.selectedIndex].value)" />
+		<div id="ajax_list_courses"></div>
+		<?php
+  	  } else {
+  	  ?>
+	  <select id="origin_users" name="no_session_list[]" multiple="multiple" size="15" style="width:300px;">
+		<?php
+		foreach($no_session_list as $no_session) {
+		?>
+			<option value="<?php echo $no_session['id']; ?>"><?php echo $no_session['name'].''; ?></option>
+
+$xajax -> processRequests();
+
+$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
+$htmlHeadXtra[] = '
+<script type="text/javascript">
+function add_user_to_url (code, content) {
+
+	document.getElementById("course_to_add").value = "";
+	document.getElementById("ajax_list_courses").innerHTML = "";
+
+	destination = document.getElementById("destination_users");
+	destination.options[destination.length] = new Option(content,code);
+
+	destination.selectedIndex = -1;
+	sortOptions(destination.options);
+
+}
+function remove_item(origin)
+{
+	for(var i = 0 ; i<origin.options.length ; i++) {
+		if(origin.options[i].selected) {
+			origin.options[i]=null;
+			i = i-1;
+		}
+	}
+}
+</script>';
+		<?php
+		}
+		unset($no_session_list);
+		?>
+
+	  </select>
+	<?php
+  	  }
+  	 ?>
+  </div>
+  </td>
+  <td width="10%" valign="middle" align="center">
+  <?php
+  if($ajax_search) {
+	?>
+	<input type="button" onclick="remove_item(document.getElementById('destination_users'))" value="<<" />
+  	<?php
+  } else {
+  	?>
+	<input type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" value=">>" />
+	<br /><br />
+	<input type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" value="<<" />
+	<?php
+  }
+  ?>
+	<br /><br /><br /><br /><br /><br />
+  </td>
+  <td align="center">
+  <select id="destination_users" name="session_list[]" multiple="multiple" size="15" style="width:300px;">
+
+<?php
+
+foreach($session_list as $session) {
+?>
+	<option value="<?php echo $session['id']; ?>"><?php echo $session['name']; ?></option>
+
+<?php
+}
+unset($session_list);
+?>
+
+  </select></td>
+</tr>
+
+<tr>
+	<td colspan="3" align="center">
+		<br />
+		<?php
+		if(isset($_GET['add']))
+			echo '<input type="button" value="'.get_lang('EditSessions').'" onclick="valide()" />';
+		else
+			echo '<input type="button" value="'.get_lang('EditSessions').'" onclick="valide()" />';
+		?>
+	</td>
+</tr>
+
+
+
+
+</table>
+
+</form>
+<script type="text/javascript">
+<!--
+function moveItem(origin , destination) {
+	for(var i = 0 ; i<origin.options.length ; i++) {
+		if(origin.options[i].selected) {
+			destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
+			origin.options[i]=null;
+			i = i-1;
+		}
+	}
+	destination.selectedIndex = -1;
+	sortOptions(destination.options);
+}
+
+function sortOptions(options) {
+	newOptions = new Array();
+	for (i = 0 ; i<options.length ; i++)
+		newOptions[i] = options[i];
+
+	newOptions = newOptions.sort(mysort);
+	options.length = 0;
+	for(i = 0 ; i < newOptions.length ; i++)
+		options[i] = newOptions[i];
+
+}
+
+function mysort(a, b) {
+	if(a.text.toLowerCase() > b.text.toLowerCase()){
+		return 1;
+	}
+	if(a.text.toLowerCase() < b.text.toLowerCase()){
+		return -1;
+	}
+	return 0;
+}
+
+function valide(){
+	var options = document.getElementById('destination_users').options;
+	for (i = 0 ; i<options.length ; i++)
+		options[i].selected = true;
+	/*
+	var options = document.getElementById('destination_classes').options;
+	for (i = 0 ; i<options.length ; i++)
+		options[i].selected = true;
+		*/
+	document.forms.formulaire.submit();
+}
+
+
+function loadUsersInSelect(select){
+
+	var xhr_object = null;
+
+	if(window.XMLHttpRequest) // Firefox
+		xhr_object = new XMLHttpRequest();
+	else if(window.ActiveXObject) // Internet Explorer
+		xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
+	else  // XMLHttpRequest non supporté par le navigateur
+	alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
+
+	//xhr_object.open("GET", "loadUsersInSelect.ajax.php?id_session=<?php echo $id_session ?>&letter="+select.options[select.selectedIndex].text, false);
+	xhr_object.open("POST", "loadUsersInSelect.ajax.php");
+
+	xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+
+
+	nosessionUsers = makepost(document.getElementById('origin_users'));
+	sessionUsers = makepost(document.getElementById('destination_users'));
+	nosessionClasses = makepost(document.getElementById('origin_classes'));
+	sessionClasses = makepost(document.getElementById('destination_classes'));
+	xhr_object.send("nosessionusers="+nosessionUsers+"&sessionusers="+sessionUsers+"&nosessionclasses="+nosessionClasses+"&sessionclasses="+sessionClasses);
+
+	xhr_object.onreadystatechange = function() {
+		if(xhr_object.readyState == 4) {
+			document.getElementById('content_source').innerHTML = result = xhr_object.responseText;
+			//alert(xhr_object.responseText);
+		}
+	}
+}
+
+function makepost(select){
+	var options = select.options;
+	var ret = "";
+	for (i = 0 ; i<options.length ; i++)
+		ret = ret + options[i].value +'::'+options[i].text+";;";
+
+	return ret;
+
+}
+-->
+
+</script>
+<?php
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display::display_footer();
+?>

+ 469 - 469
main/admin/access_url_edit_users_to_url.php

@@ -1,469 +1,469 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2009 Dokeos SPRL
-	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	@package dokeos.admin
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file='admin';
-
-// resetting the course id
-$cidReset=true;
-
-// including some necessary dokeos files
-require('../inc/global.inc.php');
-
-require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
-require_once ('../inc/lib/xajax/xajax.inc.php');
-$xajax = new xajax();
-//$xajax->debugOn();
-$xajax -> registerFunction ('search_users');
-
-// setting the section (for the tabs)
-$this_section = SECTION_PLATFORM_ADMIN;
-
-// Access restrictions
-api_protect_admin_script();
-if (!$_configuration['multiple_access_urls'])
-	header('Location: index.php');
-
-
-// Database Table Definitions
-$tbl_user				 = Database::get_main_table(TABLE_MAIN_USER);
-$tbl_access_url_rel_user = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-$tbl_access_url 		 = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
-
-// setting breadcrumbs
-$tool_name = get_lang('EditUsersToURL');
-$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
-
-$add_type = 'multiple';
-if(isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
-	$add_type = Security::remove_XSS($_REQUEST['add_type']);
-}
-
-$access_url_id=1;
-if(isset($_REQUEST['access_url_id']) && $_REQUEST['access_url_id']!=''){
-	$access_url_id = Security::remove_XSS($_REQUEST['access_url_id']);
-}
-
-function search_users($needle, $id)
-{
-	global $tbl_user, $tbl_access_url_rel_user;
-	$xajax_response = new XajaxResponse();
-	$return = '';
-
-	if(!empty($needle)) {
-		// xajax send utf8 datas... datas in db can be non-utf8 datas
-		$charset = api_get_setting('platform_charset');
-		$needle = api_convert_encoding($needle, $charset, 'utf-8');
-		$needle = Database::escape_string($needle);
-		// search users where username or firstname or lastname begins likes $needle
-		$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
-		$sql = 'SELECT u.user_id, username, lastname, firstname FROM '.$tbl_user.' u
-				WHERE (username LIKE "'.$needle.'%"
-				OR firstname LIKE "'.$needle.'%"
-				OR lastname LIKE "'.$needle.'%")'.
-				$order_clause.
-				' LIMIT 11';
-
-		$rs = Database::query($sql, __FILE__, __LINE__);
-        $i=0;
-
-		while ($user = Database :: fetch_array($rs)) {
-			$i++;
-            if ($i<=10) {
-			    $return .= '<a href="javascript: void(0);" onclick="javascript: add_user_to_url(\''.addslashes($user['user_id']).'\',\''.api_get_person_name(addslashes($user['firstname']), addslashes($user['lastname'])).' ('.addslashes($user['username']).')'.'\')">'.api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')</a><br />';
-            } else {
-            	$return .= '...<br />';
-            }
-		}
-	}
-	$xajax_response -> addAssign('ajax_list_users','innerHTML',api_utf8_encode($return));
-	return $xajax_response;
-}
-
-$xajax -> processRequests();
-$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
-$htmlHeadXtra[] = '
-<script type="text/javascript">
-function add_user_to_url(code, content) {
-
-	document.getElementById("user_to_add").value = "";
-	document.getElementById("ajax_list_users").innerHTML = "";
-
-	destination = document.getElementById("destination_users");
-	destination.options[destination.length] = new Option(content,code);
-
-	destination.selectedIndex = -1;
-	sortOptions(destination.options);
-}
-
-function send() {
-
-	if (document.formulaire.access_url_id.value!=0) {
-		document.formulaire.form_sent.value=0;
-		document.formulaire.add_type.value=\''.$add_type.'\';
-		document.formulaire.submit();
-	}
-}
-
-function remove_item(origin)
-{
-	for(var i = 0 ; i<origin.options.length ; i++) {
-		if(origin.options[i].selected) {
-			origin.options[i]=null;
-			i = i-1;
-		}
-	}
-}
-</script>';
-
-$form_sent=0;
-$errorMsg='';
-$UserList=$SessionList=array();
-$users=$sessions=array();
-
-if($_POST['form_sent']) {
-	$form_sent=$_POST['form_sent'];
-	$UserList=$_POST['sessionUsersList'];
-	if(!is_array($UserList)) {
-		$UserList=array();
-	}
-	if($form_sent == 1) {
-		if ($access_url_id==0) {
-			header('Location: access_url_edit_users_to_url.php?action=show_message&message='.get_lang('SelectURL'));
-		}
-		elseif(is_array($UserList) ) {
-			UrlManager::update_urls_rel_user($UserList,$access_url_id);
-			header('Location: access_urls.php?action=show_message&message='.get_lang('UsersWereEdited'));
-		}
-	}
-}
-
-Display::display_header($tool_name);
-
-echo '<div class="actions" style="height:22px;">';
-echo '<div style="float:right;">
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_add_users_to_url.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddUserToURL'),'').get_lang('AddUsersToURL').'</a>
-	  </div><br />';
-echo '</div>';
-
-api_display_tool_title($tool_name);
-
-if ($_GET['action'] == 'show_message')
-	Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
-
-$nosessionUsersList = $sessionUsersList = array();
-$ajax_search = $add_type == 'unique' ? true : false;
-
-if($ajax_search) {
-	$Users=UrlManager::get_url_rel_user_data($access_url_id);
-	foreach($Users as $user) {
-		$sessionUsersList[$user['user_id']] = $user ;
-	}
-} else {
-	$Users=UrlManager::get_url_rel_user_data();
-	foreach($Users as $user) {
-		if($user['access_url_id'] == $access_url_id) {
-			$sessionUsersList[$user['user_id']] = $user ;
-		}
-	}
-	$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
-	$sql="SELECT u.user_id, lastname, firstname, username
-	  	  	FROM $tbl_user u".
-			$order_clause;
-	$result=Database::query($sql,__FILE__,__LINE__);
-	$Users=Database::store_result($result);
-	$user_list_leys = array_keys($sessionUsersList);
-	foreach($Users as $user) {
-		if (!in_array($user['user_id'],$user_list_leys))
-			$nosessionUsersList[$user['user_id']] = $user ;
-	}
-}
-
-
-if($add_type == 'multiple') {
-	$link_add_type_unique = '<a href="'.api_get_self().'?add_type=unique&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeUnique').'</a>';
-	$link_add_type_multiple = get_lang('SessionAddTypeMultiple');
-} else {
-	$link_add_type_unique = get_lang('SessionAddTypeUnique');
-	$link_add_type_multiple = '<a href="'.api_get_self().'?add_type=multiple&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeMultiple').'</a>';
-}
-
-$url_list = UrlManager::get_url_data();
-
-?>
-
-<div style="text-align: left;">
-	<?php echo $link_add_type_unique ?>&nbsp;|&nbsp;<?php echo $link_add_type_multiple ?>
-</div>
-<br /><br />
-<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;" <?php if($ajax_search){echo ' onsubmit="valide();"';}?> >
-<?php echo get_lang('SelectUrl').' : '; ?>
-<select name="access_url_id" onchange="javascript:send();">
-<option value="0"> <?php echo get_lang('SelectUrl')?></option>
-	<?php
-	$url_selected='';
-	foreach ($url_list as $url_obj) {
-		$checked = '';
-		if (!empty($access_url_id)) {
-			if ($url_obj['id']==$access_url_id) {
-			$checked = 'selected=true';
-			$url_selected=	$url_obj[1];
-			}
-		}
-		if ($url_obj['active']==1) {
-	?>
-		<option <?php echo $checked;?> value="<?php echo $url_obj[0]; ?>"> <?php echo $url_obj[1]; ?></option>
-	<?php
-		}
-	}
-	?>
-</select>
-<br /><br />
-<input type="hidden" name="form_sent" value="1" />
-<input type="hidden" name="add_type" value = "<?php echo $add_type ?>" />
-
-<?php
-if(!empty($errorMsg)) {
-	Display::display_normal_message($errorMsg); //main API
-}
-?>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
-<!-- Users -->
-<tr>
-  <td align="center"><b><?php echo get_lang('UserListInPlatform') ?> :</b>
-  </td>
-  <td></td>
-  <td align="center"><b><?php echo get_lang('UserListIn').' '.$url_selected; ?> :</b></td>
-</tr>
-
-<tr>
-  <td align="center">
-  <div id="content_source">
-  	  <?php
-  	  if($ajax_search) {
-  	  	?>
-		<input type="text" id="user_to_add" onkeyup="xajax_search_users(this.value,document.formulaire.access_url_id.options[document.formulaire.access_url_id.selectedIndex].value)" />
-		<div id="ajax_list_users"></div>
-		<?php
-  	  } else {
-  	  ?>
-	  <select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:300px;">
-		<?php
-		foreach($nosessionUsersList as $enreg) {
-		?>
-			<option value="<?php echo $enreg['user_id']; ?>"><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
-
-$xajax -> processRequests();
-
-$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
-$htmlHeadXtra[] = '
-<script type="text/javascript">
-function add_user_to_url (code, content) {
-
-	document.getElementById("user_to_add").value = "";
-	document.getElementById("ajax_list_users").innerHTML = "";
-
-	destination = document.getElementById("destination_users");
-	destination.options[destination.length] = new Option(content,code);
-
-	destination.selectedIndex = -1;
-	sortOptions(destination.options);
-
-}
-function remove_item(origin)
-{
-	for(var i = 0 ; i<origin.options.length ; i++) {
-		if(origin.options[i].selected) {
-			origin.options[i]=null;
-			i = i-1;
-		}
-	}
-}
-</script>';
-		<?php
-		}
-		unset($nosessionUsersList);
-		?>
-
-	  </select>
-	<?php
-  	  }
-  	 ?>
-  </div>
-  </td>
-  <td width="10%" valign="middle" align="center">
-  <?php
-  if($ajax_search) {
-	?>
-	<input type="button" onclick="remove_item(document.getElementById('destination_users'))" value="<<" />
-  	<?php
-  } else {
-  	?>
-	<input type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" value=">>" />
-	<br /><br />
-	<input type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" value="<<" />
-	<?php
-  }
-  ?>
-	<br /><br /><br /><br /><br /><br />
-  </td>
-  <td align="center">
-  <select id="destination_users" name="sessionUsersList[]" multiple="multiple" size="15" style="width:300px;">
-
-<?php
-foreach($sessionUsersList as $enreg) {
-?>
-	<option value="<?php echo $enreg['user_id']; ?>"><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
-
-<?php
-}
-unset($sessionUsersList);
-?>
-
-  </select></td>
-</tr>
-
-<tr>
-	<td colspan="3" align="center">
-		<br />
-		<?php
-		if(isset($_GET['add']))
-			echo '<input type="button" value="'.get_lang('EditUsers').'" onclick="valide()" />';
-		else
-			echo '<input type="button" value="'.get_lang('EditUsers').'" onclick="valide()" />';
-		?>
-	</td>
-</tr>
-
-
-
-
-</table>
-
-</form>
-<script type="text/javascript">
-<!--
-function moveItem(origin , destination) {
-	for(var i = 0 ; i<origin.options.length ; i++) {
-		if(origin.options[i].selected) {
-			destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
-			origin.options[i]=null;
-			i = i-1;
-		}
-	}
-	destination.selectedIndex = -1;
-	sortOptions(destination.options);
-}
-
-function sortOptions(options) {
-	newOptions = new Array();
-	for (i = 0 ; i<options.length ; i++)
-		newOptions[i] = options[i];
-	newOptions = newOptions.sort(mysort);
-	options.length = 0;
-	for(i = 0 ; i < newOptions.length ; i++)
-		options[i] = newOptions[i];
-
-}
-
-function mysort(a, b) {
-	if(a.text.toLowerCase() > b.text.toLowerCase()){
-		return 1;
-	}
-	if(a.text.toLowerCase() < b.text.toLowerCase()){
-		return -1;
-	}
-	return 0;
-}
-
-function valide(){
-	var options = document.getElementById('destination_users').options;
-	for (i = 0 ; i<options.length ; i++)
-		options[i].selected = true;
-	/*
-	var options = document.getElementById('destination_classes').options;
-	for (i = 0 ; i<options.length ; i++)
-		options[i].selected = true;
-		*/
-	document.forms.formulaire.submit();
-}
-
-
-function loadUsersInSelect(select){
-
-	var xhr_object = null;
-
-	if(window.XMLHttpRequest) // Firefox
-		xhr_object = new XMLHttpRequest();
-	else if(window.ActiveXObject) // Internet Explorer
-		xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
-	else  // XMLHttpRequest non supporté par le navigateur
-	alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
-
-	//xhr_object.open("GET", "loadUsersInSelect.ajax.php?id_session=<?php echo $id_session ?>&letter="+select.options[select.selectedIndex].text, false);
-	xhr_object.open("POST", "loadUsersInSelect.ajax.php");
-
-	xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
-
-
-	nosessionUsers = makepost(document.getElementById('origin_users'));
-	sessionUsers = makepost(document.getElementById('destination_users'));
-	nosessionClasses = makepost(document.getElementById('origin_classes'));
-	sessionClasses = makepost(document.getElementById('destination_classes'));
-	xhr_object.send("nosessionusers="+nosessionUsers+"&sessionusers="+sessionUsers+"&nosessionclasses="+nosessionClasses+"&sessionclasses="+sessionClasses);
-
-	xhr_object.onreadystatechange = function() {
-		if(xhr_object.readyState == 4) {
-			document.getElementById('content_source').innerHTML = result = xhr_object.responseText;
-			//alert(xhr_object.responseText);
-		}
-	}
-}
-
-function makepost(select){
-	var options = select.options;
-	var ret = "";
-	for (i = 0 ; i<options.length ; i++)
-		ret = ret + options[i].value +'::'+options[i].text+";;";
-
-	return ret;
-
-}
--->
-
-</script>
-<?php
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display::display_footer();
-?>
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2009 Dokeos SPRL
+	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	@package dokeos.admin
+==============================================================================
+*/
+
+// name of the language file that needs to be included
+$language_file='admin';
+
+// resetting the course id
+$cidReset=true;
+
+// including some necessary dokeos files
+require('../inc/global.inc.php');
+
+require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
+require_once ('../inc/lib/xajax/xajax.inc.php');
+$xajax = new xajax();
+//$xajax->debugOn();
+$xajax -> registerFunction ('search_users');
+
+// setting the section (for the tabs)
+$this_section = SECTION_PLATFORM_ADMIN;
+
+// Access restrictions
+api_protect_admin_script();
+if (!$_configuration['multiple_access_urls'])
+	header('Location: index.php');
+
+
+// Database Table Definitions
+$tbl_user				 = Database::get_main_table(TABLE_MAIN_USER);
+$tbl_access_url_rel_user = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+$tbl_access_url 		 = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+
+// setting breadcrumbs
+$tool_name = get_lang('EditUsersToURL');
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
+
+$add_type = 'multiple';
+if(isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
+	$add_type = Security::remove_XSS($_REQUEST['add_type']);
+}
+
+$access_url_id=1;
+if(isset($_REQUEST['access_url_id']) && $_REQUEST['access_url_id']!=''){
+	$access_url_id = Security::remove_XSS($_REQUEST['access_url_id']);
+}
+
+function search_users($needle, $id)
+{
+	global $tbl_user, $tbl_access_url_rel_user;
+	$xajax_response = new XajaxResponse();
+	$return = '';
+
+	if(!empty($needle)) {
+		// xajax send utf8 datas... datas in db can be non-utf8 datas
+		$charset = api_get_setting('platform_charset');
+		$needle = api_convert_encoding($needle, $charset, 'utf-8');
+		$needle = Database::escape_string($needle);
+		// search users where username or firstname or lastname begins likes $needle
+		$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
+		$sql = 'SELECT u.user_id, username, lastname, firstname FROM '.$tbl_user.' u
+				WHERE (username LIKE "'.$needle.'%"
+				OR firstname LIKE "'.$needle.'%"
+				OR lastname LIKE "'.$needle.'%")'.
+				$order_clause.
+				' LIMIT 11';
+
+		$rs = Database::query($sql, __FILE__, __LINE__);
+        $i=0;
+
+		while ($user = Database :: fetch_array($rs)) {
+			$i++;
+            if ($i<=10) {
+			    $return .= '<a href="javascript: void(0);" onclick="javascript: add_user_to_url(\''.addslashes($user['user_id']).'\',\''.api_get_person_name(addslashes($user['firstname']), addslashes($user['lastname'])).' ('.addslashes($user['username']).')'.'\')">'.api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')</a><br />';
+            } else {
+            	$return .= '...<br />';
+            }
+		}
+	}
+	$xajax_response -> addAssign('ajax_list_users','innerHTML',api_utf8_encode($return));
+	return $xajax_response;
+}
+
+$xajax -> processRequests();
+$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
+$htmlHeadXtra[] = '
+<script type="text/javascript">
+function add_user_to_url(code, content) {
+
+	document.getElementById("user_to_add").value = "";
+	document.getElementById("ajax_list_users").innerHTML = "";
+
+	destination = document.getElementById("destination_users");
+	destination.options[destination.length] = new Option(content,code);
+
+	destination.selectedIndex = -1;
+	sortOptions(destination.options);
+}
+
+function send() {
+
+	if (document.formulaire.access_url_id.value!=0) {
+		document.formulaire.form_sent.value=0;
+		document.formulaire.add_type.value=\''.$add_type.'\';
+		document.formulaire.submit();
+	}
+}
+
+function remove_item(origin)
+{
+	for(var i = 0 ; i<origin.options.length ; i++) {
+		if(origin.options[i].selected) {
+			origin.options[i]=null;
+			i = i-1;
+		}
+	}
+}
+</script>';
+
+$form_sent=0;
+$errorMsg='';
+$UserList=$SessionList=array();
+$users=$sessions=array();
+
+if($_POST['form_sent']) {
+	$form_sent=$_POST['form_sent'];
+	$UserList=$_POST['sessionUsersList'];
+	if(!is_array($UserList)) {
+		$UserList=array();
+	}
+	if($form_sent == 1) {
+		if ($access_url_id==0) {
+			header('Location: access_url_edit_users_to_url.php?action=show_message&message='.get_lang('SelectURL'));
+		}
+		elseif(is_array($UserList) ) {
+			UrlManager::update_urls_rel_user($UserList,$access_url_id);
+			header('Location: access_urls.php?action=show_message&message='.get_lang('UsersWereEdited'));
+		}
+	}
+}
+
+Display::display_header($tool_name);
+
+echo '<div class="actions" style="height:22px;">';
+echo '<div style="float:right;">
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_add_users_to_url.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddUserToURL'),'').get_lang('AddUsersToURL').'</a>
+	  </div><br />';
+echo '</div>';
+
+api_display_tool_title($tool_name);
+
+if ($_GET['action'] == 'show_message')
+	Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
+
+$nosessionUsersList = $sessionUsersList = array();
+$ajax_search = $add_type == 'unique' ? true : false;
+
+if($ajax_search) {
+	$Users=UrlManager::get_url_rel_user_data($access_url_id);
+	foreach($Users as $user) {
+		$sessionUsersList[$user['user_id']] = $user ;
+	}
+} else {
+	$Users=UrlManager::get_url_rel_user_data();
+	foreach($Users as $user) {
+		if($user['access_url_id'] == $access_url_id) {
+			$sessionUsersList[$user['user_id']] = $user ;
+		}
+	}
+	$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
+	$sql="SELECT u.user_id, lastname, firstname, username
+	  	  	FROM $tbl_user u".
+			$order_clause;
+	$result=Database::query($sql,__FILE__,__LINE__);
+	$Users=Database::store_result($result);
+	$user_list_leys = array_keys($sessionUsersList);
+	foreach($Users as $user) {
+		if (!in_array($user['user_id'],$user_list_leys))
+			$nosessionUsersList[$user['user_id']] = $user ;
+	}
+}
+
+
+if($add_type == 'multiple') {
+	$link_add_type_unique = '<a href="'.api_get_self().'?add_type=unique&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeUnique').'</a>';
+	$link_add_type_multiple = get_lang('SessionAddTypeMultiple');
+} else {
+	$link_add_type_unique = get_lang('SessionAddTypeUnique');
+	$link_add_type_multiple = '<a href="'.api_get_self().'?add_type=multiple&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeMultiple').'</a>';
+}
+
+$url_list = UrlManager::get_url_data();
+
+?>
+
+<div style="text-align: left;">
+	<?php echo $link_add_type_unique ?>&nbsp;|&nbsp;<?php echo $link_add_type_multiple ?>
+</div>
+<br /><br />
+<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;" <?php if($ajax_search){echo ' onsubmit="valide();"';}?> >
+<?php echo get_lang('SelectUrl').' : '; ?>
+<select name="access_url_id" onchange="javascript:send();">
+<option value="0"> <?php echo get_lang('SelectUrl')?></option>
+	<?php
+	$url_selected='';
+	foreach ($url_list as $url_obj) {
+		$checked = '';
+		if (!empty($access_url_id)) {
+			if ($url_obj['id']==$access_url_id) {
+			$checked = 'selected=true';
+			$url_selected=	$url_obj[1];
+			}
+		}
+		if ($url_obj['active']==1) {
+	?>
+		<option <?php echo $checked;?> value="<?php echo $url_obj[0]; ?>"> <?php echo $url_obj[1]; ?></option>
+	<?php
+		}
+	}
+	?>
+</select>
+<br /><br />
+<input type="hidden" name="form_sent" value="1" />
+<input type="hidden" name="add_type" value = "<?php echo $add_type ?>" />
+
+<?php
+if(!empty($errorMsg)) {
+	Display::display_normal_message($errorMsg); //main API
+}
+?>
+
+<table border="0" cellpadding="5" cellspacing="0" width="100%">
+
+<!-- Users -->
+<tr>
+  <td align="center"><b><?php echo get_lang('UserListInPlatform') ?> :</b>
+  </td>
+  <td></td>
+  <td align="center"><b><?php echo get_lang('UserListIn').' '.$url_selected; ?> :</b></td>
+</tr>
+
+<tr>
+  <td align="center">
+  <div id="content_source">
+  	  <?php
+  	  if($ajax_search) {
+  	  	?>
+		<input type="text" id="user_to_add" onkeyup="xajax_search_users(this.value,document.formulaire.access_url_id.options[document.formulaire.access_url_id.selectedIndex].value)" />
+		<div id="ajax_list_users"></div>
+		<?php
+  	  } else {
+  	  ?>
+	  <select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:300px;">
+		<?php
+		foreach($nosessionUsersList as $enreg) {
+		?>
+			<option value="<?php echo $enreg['user_id']; ?>"><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
+
+$xajax -> processRequests();
+
+$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
+$htmlHeadXtra[] = '
+<script type="text/javascript">
+function add_user_to_url (code, content) {
+
+	document.getElementById("user_to_add").value = "";
+	document.getElementById("ajax_list_users").innerHTML = "";
+
+	destination = document.getElementById("destination_users");
+	destination.options[destination.length] = new Option(content,code);
+
+	destination.selectedIndex = -1;
+	sortOptions(destination.options);
+
+}
+function remove_item(origin)
+{
+	for(var i = 0 ; i<origin.options.length ; i++) {
+		if(origin.options[i].selected) {
+			origin.options[i]=null;
+			i = i-1;
+		}
+	}
+}
+</script>';
+		<?php
+		}
+		unset($nosessionUsersList);
+		?>
+
+	  </select>
+	<?php
+  	  }
+  	 ?>
+  </div>
+  </td>
+  <td width="10%" valign="middle" align="center">
+  <?php
+  if($ajax_search) {
+	?>
+	<input type="button" onclick="remove_item(document.getElementById('destination_users'))" value="<<" />
+  	<?php
+  } else {
+  	?>
+	<input type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" value=">>" />
+	<br /><br />
+	<input type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" value="<<" />
+	<?php
+  }
+  ?>
+	<br /><br /><br /><br /><br /><br />
+  </td>
+  <td align="center">
+  <select id="destination_users" name="sessionUsersList[]" multiple="multiple" size="15" style="width:300px;">
+
+<?php
+foreach($sessionUsersList as $enreg) {
+?>
+	<option value="<?php echo $enreg['user_id']; ?>"><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
+
+<?php
+}
+unset($sessionUsersList);
+?>
+
+  </select></td>
+</tr>
+
+<tr>
+	<td colspan="3" align="center">
+		<br />
+		<?php
+		if(isset($_GET['add']))
+			echo '<input type="button" value="'.get_lang('EditUsers').'" onclick="valide()" />';
+		else
+			echo '<input type="button" value="'.get_lang('EditUsers').'" onclick="valide()" />';
+		?>
+	</td>
+</tr>
+
+
+
+
+</table>
+
+</form>
+<script type="text/javascript">
+<!--
+function moveItem(origin , destination) {
+	for(var i = 0 ; i<origin.options.length ; i++) {
+		if(origin.options[i].selected) {
+			destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
+			origin.options[i]=null;
+			i = i-1;
+		}
+	}
+	destination.selectedIndex = -1;
+	sortOptions(destination.options);
+}
+
+function sortOptions(options) {
+	newOptions = new Array();
+	for (i = 0 ; i<options.length ; i++)
+		newOptions[i] = options[i];
+	newOptions = newOptions.sort(mysort);
+	options.length = 0;
+	for(i = 0 ; i < newOptions.length ; i++)
+		options[i] = newOptions[i];
+
+}
+
+function mysort(a, b) {
+	if(a.text.toLowerCase() > b.text.toLowerCase()){
+		return 1;
+	}
+	if(a.text.toLowerCase() < b.text.toLowerCase()){
+		return -1;
+	}
+	return 0;
+}
+
+function valide(){
+	var options = document.getElementById('destination_users').options;
+	for (i = 0 ; i<options.length ; i++)
+		options[i].selected = true;
+	/*
+	var options = document.getElementById('destination_classes').options;
+	for (i = 0 ; i<options.length ; i++)
+		options[i].selected = true;
+		*/
+	document.forms.formulaire.submit();
+}
+
+
+function loadUsersInSelect(select){
+
+	var xhr_object = null;
+
+	if(window.XMLHttpRequest) // Firefox
+		xhr_object = new XMLHttpRequest();
+	else if(window.ActiveXObject) // Internet Explorer
+		xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
+	else  // XMLHttpRequest non supporté par le navigateur
+	alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
+
+	//xhr_object.open("GET", "loadUsersInSelect.ajax.php?id_session=<?php echo $id_session ?>&letter="+select.options[select.selectedIndex].text, false);
+	xhr_object.open("POST", "loadUsersInSelect.ajax.php");
+
+	xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+
+
+	nosessionUsers = makepost(document.getElementById('origin_users'));
+	sessionUsers = makepost(document.getElementById('destination_users'));
+	nosessionClasses = makepost(document.getElementById('origin_classes'));
+	sessionClasses = makepost(document.getElementById('destination_classes'));
+	xhr_object.send("nosessionusers="+nosessionUsers+"&sessionusers="+sessionUsers+"&nosessionclasses="+nosessionClasses+"&sessionclasses="+sessionClasses);
+
+	xhr_object.onreadystatechange = function() {
+		if(xhr_object.readyState == 4) {
+			document.getElementById('content_source').innerHTML = result = xhr_object.responseText;
+			//alert(xhr_object.responseText);
+		}
+	}
+}
+
+function makepost(select){
+	var options = select.options;
+	var ret = "";
+	for (i = 0 ; i<options.length ; i++)
+		ret = ret + options[i].value +'::'+options[i].text+";;";
+
+	return ret;
+
+}
+-->
+
+</script>
+<?php
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display::display_footer();
+?>

+ 208 - 208
main/admin/access_urls.php

@@ -1,208 +1,208 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2009 Dokeos SPRL
-	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	@package dokeos.admin
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file = 'admin';
-$cidReset = true;
-require ('../inc/global.inc.php');
-$this_section = SECTION_PLATFORM_ADMIN;
-
-api_protect_admin_script();
-if (!$_configuration['multiple_access_urls'])
-	header('Location: index.php');
-
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
-$tool_name = get_lang('MultipleAccessURLs');
-Display :: display_header($tool_name);
-
-require_once (api_get_path(LIBRARY_PATH).'sortabletable.class.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-require_once (api_get_path(LIBRARY_PATH).'security.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
-
-$my_user_url_list = api_get_access_url_from_user(api_get_user_id());
-$current_access_url_id = api_get_current_access_url_id();
-$url_list = UrlManager::get_url_data();
-
-// Actions
-if (isset ($_GET['action'])) {
-	if ($_GET['action'] == 'show_message')
-		Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
-
-	$check = Security::check_token('get');
-	if ($check) {
-		$url_id=Database::escape_string($_GET['url_id']);
-
-		switch ($_GET['action']) {
-			case 'delete_url' :
-				$result = UrlManager::delete($url_id);
-				if ($result) {
-					Display :: display_normal_message(get_lang('URLDeleted'));
-				} else {
-					Display :: display_error_message(get_lang('CannotDeleteURL'));
-				}
-				break;
-			case 'lock' :
-				UrlManager::set_url_status('lock',$url_id);
-				Display :: display_normal_message(get_lang('URLInactive'));
-				break;
-			case 'unlock';
-				UrlManager::set_url_status('unlock',$url_id);
-				Display :: display_normal_message(get_lang('URLActive'));
-				break;
-			case 'register';
-				// we are going to register the admin
-				if(api_is_platform_admin()) {
-					if($current_access_url_id!=-1) {
-						$url_str = '';
-						foreach($url_list as $my_url) {
-							if (!in_array($my_url['id'],$my_user_url_list)){
-								UrlManager::add_user_to_url(api_get_user_id(),$my_url['id']);
-									$url_str.=$my_url['url'].' ';
-							}
-						}
-						Display :: display_normal_message(get_lang('AdminUserRegisteredToThisURL').': '.$url_str.'<br />',false);
-					}
-				}
-				break;
-			}
-
-		}
-		Security::clear_token();
-}
-
-$parameters['sec_token'] = Security::get_token();
-
-// checking if the admin is registered in all sites
-
-$url_string='';
-$my_user_url_list = api_get_access_url_from_user(api_get_user_id());
-foreach($url_list as $my_url) {
-	if (!in_array($my_url['id'],$my_user_url_list)){
-		$url_string.=$my_url['url'].' ';
-	}
-}
-if(!empty($url_string)) {
-	Display :: display_warning_message(get_lang('AdminShouldBeRegisterInSite').':<br />'.$url_string,false);
-}
-
-// checking the current installation
-if ($current_access_url_id==-1) {
-	Display :: display_warning_message(get_lang('URLNotConfiguredPleaseChangedTo').': '.api_get_path(WEB_PATH));
-} elseif(api_is_platform_admin()) {
-	$quant= UrlManager::relation_url_user_exist(api_get_user_id(),$current_access_url_id);
-	if ($quant==0) {
-		Display :: display_warning_message('<a href="'.api_get_self().'?action=register&sec_token='.$parameters['sec_token'].'">'.get_lang('ClickToRegisterAdmin').'</a>',false);
-	}
-}
-
-//<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_sessions_to_url.php">'.Display::return_icon('sessions.gif',get_lang('ManageSessions'),'').get_lang('ManageSessions').'</a>
-// action menu
-echo '<div class="actions" style="height:22px;">';
-echo '<div style="float:right;">
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddUrl'),'').get_lang('AddUrl').'</a>&nbsp;&nbsp;
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_users_to_url.php">'.Display::return_icon('members.gif',get_lang('ManageUsers'),'').get_lang('ManageUsers').'</a>
-	    <a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_courses_to_url.php">'.Display::return_icon('courses.gif',get_lang('ManageCourses'),'').get_lang('ManageCourses').'</a>
-	  </div><br />';
-echo '</div>';
-
-$table = new SortableTable('urls', 'url_count_mask', 'get_url_data_mask',2);
-$table->set_additional_parameters($parameters);
-$table->set_header(0, '', false);
-
-$table->set_header(1, get_lang('URL'));
-$table->set_header(2, get_lang('Description'));
-$table->set_header(3, get_lang('Active'));
-//$table->set_header(4, get_lang('Status'));
-$table->set_header(4, get_lang('Modify'));
-
-$table->set_column_filter(3, 'active_filter');
-//$table->set_column_filter(4, 'status_filter');
-$table->set_column_filter(4, 'modify_filter');
-
-//$table->set_form_actions(array ('delete' => get_lang('DeleteFromPlatform')));
-$table->display();
-/*
-function status_filter($active, $url_params, $row) {
-	$url_id =UrlManager::get_url_id($row[1]);
-	if ($row[0] == $url_id ) {
-		$action='lock';
-		$image='right';
-	} else {
-		$image='wrong';
-	}
-	// you cannot lock the default
-	$result = Display::return_icon($image.'.gif', get_lang(ucfirst($action)));
-
-	return $result;
-}
-*/
-function modify_filter($active, $url_params, $row) {
-	global $charset;
-	$url_id = $row['0'];
-	$result .= '<a href="access_url_edit.php?url_id='.$url_id.'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>&nbsp;';
-	if ($url_id != '1') {
-		$result .= '<a href="access_urls.php?action=delete_url&amp;url_id='.$url_id.'&amp;sec_token='.$_SESSION['sec_token'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
-	}
-	return $result;
-}
-
-function active_filter($active, $url_params, $row) {
-	$active = $row['3'];
-	if ($active=='1') {
-		$action='lock';
-		$image='right';
-	}
-	if ($active=='0') {
-		$action='unlock';
-		$image='wrong';
-	}
-	// you cannot lock the default
-	if ($row['0']=='1') {
-		$result = Display::return_icon($image.'.gif', get_lang(ucfirst($action)));
-	} else {
-		$result = '<a href="access_urls.php?action='.$action.'&amp;url_id='.$row['0'].'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon($image.'.gif', get_lang(ucfirst($action))).'</a>';
-	}
-	return $result;
-}
-
-// this 2 "mask" function are here just because the SortableTable
-function get_url_data_mask($id, $url_params=null, $row=null) {
-	return UrlManager::get_url_data();
-}
-function url_count_mask() {
-	return UrlManager::url_count();
-}
-
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display :: display_footer();
-?>
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2009 Dokeos SPRL
+	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	@package dokeos.admin
+==============================================================================
+*/
+
+// name of the language file that needs to be included
+$language_file = 'admin';
+$cidReset = true;
+require ('../inc/global.inc.php');
+$this_section = SECTION_PLATFORM_ADMIN;
+
+api_protect_admin_script();
+if (!$_configuration['multiple_access_urls'])
+	header('Location: index.php');
+
+$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$tool_name = get_lang('MultipleAccessURLs');
+Display :: display_header($tool_name);
+
+require_once (api_get_path(LIBRARY_PATH).'sortabletable.class.php');
+require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+require_once (api_get_path(LIBRARY_PATH).'security.lib.php');
+require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
+
+$my_user_url_list = api_get_access_url_from_user(api_get_user_id());
+$current_access_url_id = api_get_current_access_url_id();
+$url_list = UrlManager::get_url_data();
+
+// Actions
+if (isset ($_GET['action'])) {
+	if ($_GET['action'] == 'show_message')
+		Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
+
+	$check = Security::check_token('get');
+	if ($check) {
+		$url_id=Database::escape_string($_GET['url_id']);
+
+		switch ($_GET['action']) {
+			case 'delete_url' :
+				$result = UrlManager::delete($url_id);
+				if ($result) {
+					Display :: display_normal_message(get_lang('URLDeleted'));
+				} else {
+					Display :: display_error_message(get_lang('CannotDeleteURL'));
+				}
+				break;
+			case 'lock' :
+				UrlManager::set_url_status('lock',$url_id);
+				Display :: display_normal_message(get_lang('URLInactive'));
+				break;
+			case 'unlock';
+				UrlManager::set_url_status('unlock',$url_id);
+				Display :: display_normal_message(get_lang('URLActive'));
+				break;
+			case 'register';
+				// we are going to register the admin
+				if(api_is_platform_admin()) {
+					if($current_access_url_id!=-1) {
+						$url_str = '';
+						foreach($url_list as $my_url) {
+							if (!in_array($my_url['id'],$my_user_url_list)){
+								UrlManager::add_user_to_url(api_get_user_id(),$my_url['id']);
+									$url_str.=$my_url['url'].' ';
+							}
+						}
+						Display :: display_normal_message(get_lang('AdminUserRegisteredToThisURL').': '.$url_str.'<br />',false);
+					}
+				}
+				break;
+			}
+
+		}
+		Security::clear_token();
+}
+
+$parameters['sec_token'] = Security::get_token();
+
+// checking if the admin is registered in all sites
+
+$url_string='';
+$my_user_url_list = api_get_access_url_from_user(api_get_user_id());
+foreach($url_list as $my_url) {
+	if (!in_array($my_url['id'],$my_user_url_list)){
+		$url_string.=$my_url['url'].' ';
+	}
+}
+if(!empty($url_string)) {
+	Display :: display_warning_message(get_lang('AdminShouldBeRegisterInSite').':<br />'.$url_string,false);
+}
+
+// checking the current installation
+if ($current_access_url_id==-1) {
+	Display :: display_warning_message(get_lang('URLNotConfiguredPleaseChangedTo').': '.api_get_path(WEB_PATH));
+} elseif(api_is_platform_admin()) {
+	$quant= UrlManager::relation_url_user_exist(api_get_user_id(),$current_access_url_id);
+	if ($quant==0) {
+		Display :: display_warning_message('<a href="'.api_get_self().'?action=register&sec_token='.$parameters['sec_token'].'">'.get_lang('ClickToRegisterAdmin').'</a>',false);
+	}
+}
+
+//<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_sessions_to_url.php">'.Display::return_icon('sessions.gif',get_lang('ManageSessions'),'').get_lang('ManageSessions').'</a>
+// action menu
+echo '<div class="actions" style="height:22px;">';
+echo '<div style="float:right;">
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddUrl'),'').get_lang('AddUrl').'</a>&nbsp;&nbsp;
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_users_to_url.php">'.Display::return_icon('members.gif',get_lang('ManageUsers'),'').get_lang('ManageUsers').'</a>
+	    <a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_courses_to_url.php">'.Display::return_icon('courses.gif',get_lang('ManageCourses'),'').get_lang('ManageCourses').'</a>
+	  </div><br />';
+echo '</div>';
+
+$table = new SortableTable('urls', 'url_count_mask', 'get_url_data_mask',2);
+$table->set_additional_parameters($parameters);
+$table->set_header(0, '', false);
+
+$table->set_header(1, get_lang('URL'));
+$table->set_header(2, get_lang('Description'));
+$table->set_header(3, get_lang('Active'));
+//$table->set_header(4, get_lang('Status'));
+$table->set_header(4, get_lang('Modify'));
+
+$table->set_column_filter(3, 'active_filter');
+//$table->set_column_filter(4, 'status_filter');
+$table->set_column_filter(4, 'modify_filter');
+
+//$table->set_form_actions(array ('delete' => get_lang('DeleteFromPlatform')));
+$table->display();
+/*
+function status_filter($active, $url_params, $row) {
+	$url_id =UrlManager::get_url_id($row[1]);
+	if ($row[0] == $url_id ) {
+		$action='lock';
+		$image='right';
+	} else {
+		$image='wrong';
+	}
+	// you cannot lock the default
+	$result = Display::return_icon($image.'.gif', get_lang(ucfirst($action)));
+
+	return $result;
+}
+*/
+function modify_filter($active, $url_params, $row) {
+	global $charset;
+	$url_id = $row['0'];
+	$result .= '<a href="access_url_edit.php?url_id='.$url_id.'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>&nbsp;';
+	if ($url_id != '1') {
+		$result .= '<a href="access_urls.php?action=delete_url&amp;url_id='.$url_id.'&amp;sec_token='.$_SESSION['sec_token'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
+	}
+	return $result;
+}
+
+function active_filter($active, $url_params, $row) {
+	$active = $row['3'];
+	if ($active=='1') {
+		$action='lock';
+		$image='right';
+	}
+	if ($active=='0') {
+		$action='unlock';
+		$image='wrong';
+	}
+	// you cannot lock the default
+	if ($row['0']=='1') {
+		$result = Display::return_icon($image.'.gif', get_lang(ucfirst($action)));
+	} else {
+		$result = '<a href="access_urls.php?action='.$action.'&amp;url_id='.$row['0'].'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon($image.'.gif', get_lang(ucfirst($action))).'</a>';
+	}
+	return $result;
+}
+
+// this 2 "mask" function are here just because the SortableTable
+function get_url_data_mask($id, $url_params=null, $row=null) {
+	return UrlManager::get_url_data();
+}
+function url_count_mask() {
+	return UrlManager::url_count();
+}
+
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display :: display_footer();
+?>

+ 538 - 538
main/admin/add_courses_to_session.php

@@ -1,538 +1,538 @@
-<?php //$id: $
-/* For licensing terms, see /dokeos_license.txt */
-/**
-==============================================================================
-*	@package dokeos.admin
-* 	@todo use formvalidator
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file='admin';
-
-// resetting the course id
-$cidReset=true;
-
-// including some necessary dokeos files
-require '../inc/global.inc.php';
-
-// including additonal libraries
-require_once '../inc/lib/xajax/xajax.inc.php';
-require_once api_get_path(LIBRARY_PATH).'sessionmanager.lib.php';
-$xajax = new xajax();
-//$xajax->debugOn();
-$xajax -> registerFunction ('search_courses');
-
-// setting the section (for the tabs)
-$this_section = SECTION_PLATFORM_ADMIN;
-
-// Access restrictions
-api_protect_admin_script(true);
-
-// setting breadcrumbs
-$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array('url' => 'session_list.php','name' => get_lang('SessionList'));
-
-// Database Table Definitions
-$tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-$tbl_session						= Database::get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_rel_user				= Database::get_main_table(TABLE_MAIN_SESSION_USER);
-$tbl_session_rel_course				= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_course							= Database::get_main_table(TABLE_MAIN_COURSE);
-
-// setting the name of the tool
-$tool_name= get_lang('SubscribeCoursesToSession');
-$id_session=intval($_GET['id_session']);
-
-$add_type = 'multiple';
-if(isset($_GET['add_type']) && $_GET['add_type']!=''){
-	$add_type = Security::remove_XSS($_REQUEST['add_type']);
-}
-
-if (!api_is_platform_admin()) {
-	$sql = 'SELECT session_admin_id FROM '.Database :: get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$id_session;
-	$rs = Database::query($sql,__FILE__,__LINE__);
-	if (Database::result($rs,0,0)!=$_user['user_id']) {
-		api_not_allowed(true);
-	}
-}
-
-function search_courses($needle,$type)
-{
-	global $tbl_course, $tbl_session_rel_course, $id_session;
-
-	$xajax_response = new XajaxResponse();
-	$return = '';
-	if(!empty($needle) && !empty($type)) {
-		// xajax send utf8 datas... datas in db can be non-utf8 datas
-		$charset = api_get_setting('platform_charset');
-		$needle = api_convert_encoding($needle, $charset, 'utf-8');
-
-		$cond_course_code = '';
-		if (!empty($id_session)) {
-		$id_session = Database::escape_string($id_session);
-			// check course_code from session_rel_course table
-			$sql = 'SELECT course_code FROM '.$tbl_session_rel_course.' WHERE id_session ="'.(int)$id_session.'"';
-			$res = Database::query($sql,__FILE__,__LINE__);
-			$course_codes = '';
-			if (Database::num_rows($res) > 0) {
-				while ($row = Database::fetch_row($res)) {
-					$course_codes .= '\''.$row[0].'\',';
-				}
-				$course_codes = substr($course_codes,0,(strlen($course_codes)-1));
-
-				$cond_course_code = ' AND course.code NOT IN('.$course_codes.') ';
-			}
-		}
-
-		if ($type=='single') {
-		// search users where username or firstname or lastname begins likes $needle
-		$sql = 'SELECT course.code, course.visual_code, course.title, session_rel_course.id_session
-				FROM '.$tbl_course.' course
-				LEFT JOIN '.$tbl_session_rel_course.' session_rel_course
-					ON course.code = session_rel_course.course_code
-					AND session_rel_course.id_session = '.intval($id_session).'
-				WHERE course.visual_code LIKE "'.$needle.'%"
-				OR course.title LIKE "'.$needle.'%"';
-		} else {
-
-		$sql = 'SELECT course.code, course.visual_code, course.title
-				FROM '.$tbl_course.' course
-				WHERE course.visual_code LIKE "'.$needle.'%" '.$cond_course_code.' ORDER BY course.code ';
-		}
-
-		global $_configuration;
-		if ($_configuration['multiple_access_urls']==true) {
-			$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-			$access_url_id = api_get_current_access_url_id();
-			if ($access_url_id != -1){
-
-				if ($type=='single') {
-					$sql = 'SELECT course.code, course.visual_code, course.title, session_rel_course.id_session
-							FROM '.$tbl_course.' course
-							LEFT JOIN '.$tbl_session_rel_course.' session_rel_course
-								ON course.code = session_rel_course.course_code
-								AND session_rel_course.id_session = '.intval($id_session).'
-							INNER JOIN '.$tbl_course_rel_access_url.' url_course ON (url_course.course_code=course.code)
-							WHERE access_url_id = '.$access_url_id.' AND (course.visual_code LIKE "'.$needle.'%"
-							OR course.title LIKE "'.$needle.'%" )';
-				} else {
-					$sql = 'SELECT course.code, course.visual_code, course.title
-							FROM '.$tbl_course.' course, '.$tbl_course_rel_access_url.' url_course
-							WHERE url_course.course_code=course.code AND access_url_id = '.$access_url_id.'
-							AND course.visual_code LIKE "'.$needle.'%" '.$cond_course_code.' ORDER BY course.code ';
-				}
-			}
-		}
-
-		$rs = Database::query($sql, __FILE__, __LINE__);
-		$course_list = array();
-		if ($type=='single') {
-
-			while($course = Database :: fetch_array($rs)) {
-				$course_list[] = $course['code'];
-				$course_title=str_replace("'","\'",$course_title);
-				$return .= '<a href="javascript: void(0);" onclick="javascript: add_course_to_session(\''.$course['code'].'\',\''.$course_title.' ('.$course['visual_code'].')'.'\')">'.$course['title'].' ('.$course['visual_code'].')</a><br />';
-			}
-
-			$xajax_response -> addAssign('ajax_list_courses_single','innerHTML',api_utf8_encode($return));
-
-		} else {
-
-			$return .= '<select id="origin" name="NoSessionCoursesList[]" multiple="multiple" size="20" style="width:340px;">';
-			while($course = Database :: fetch_array($rs)) {
-				$course_list[] = $course['code'];
-				$course_title=str_replace("'","\'",$course_title);
-				$return .= '<option value="'.$course['code'].'" title="'.htmlspecialchars($course['title'].' ('.$course['visual_code'].')',ENT_QUOTES).'">'.$course['title'].' ('.$course['visual_code'].')</option>';
-			}
-			$return .= '</select>';
-
-			$xajax_response -> addAssign('ajax_list_courses_multiple','innerHTML',api_utf8_encode($return));
-		}
-	}
-	$_SESSION['course_list'] = $course_list;
-	return $xajax_response;
-}
-$xajax -> processRequests();
-
-$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
-$htmlHeadXtra[] = '
-<script type="text/javascript">
-function add_course_to_session (code, content) {
-
-	document.getElementById("course_to_add").value = "";
-	document.getElementById("ajax_list_courses_single").innerHTML = "";
-
-	destination = document.getElementById("destination");
-
-	for (i=0;i<destination.length;i++) {
-		if(destination.options[i].text == content) {
-				return false;
-		}
-	}
-
-	destination.options[destination.length] = new Option(content,code);
-
-	destination.selectedIndex = -1;
-	sortOptions(destination.options);
-}
-function remove_item(origin)
-{
-	for(var i = 0 ; i<origin.options.length ; i++) {
-		if(origin.options[i].selected) {
-			origin.options[i]=null;
-			i = i-1;
-		}
-	}
-}
-</script>';
-
-
-$formSent=0;
-$errorMsg=$firstLetterCourse=$firstLetterSession='';
-$CourseList=$SessionList=array();
-$courses=$sessions=array();
-$noPHP_SELF=true;
-
-if ($_POST['formSent']) {
-
-	$formSent=$_POST['formSent'];
-	$firstLetterCourse=$_POST['firstLetterCourse'];
-	$firstLetterSession=$_POST['firstLetterSession'];
-	$CourseList=$_POST['SessionCoursesList'];
-	if (!is_array($CourseList)) {
-		$CourseList=array();
-	}
-	$nbr_courses=0;
-
-	$id_coach = Database::query("SELECT id_coach FROM $tbl_session WHERE id=$id_session");
-	$id_coach = Database::fetch_array($id_coach);
-	$id_coach = $id_coach[0];
-
-	$rs = Database::query("SELECT course_code FROM $tbl_session_rel_course WHERE id_session=$id_session");
-	$existingCourses = Database::store_result($rs);
-
-	$sql="SELECT id_user
-		FROM $tbl_session_rel_user
-		WHERE id_session = $id_session";
-	$result=Database::query($sql,__FILE__,__LINE__);
-	$UserList=Database::store_result($result);
-
-
-	foreach($CourseList as $enreg_course) {
-		$enreg_course = Database::escape_string($enreg_course);
-		$exists = false;
-		foreach($existingCourses as $existingCourse) {
-			if($enreg_course == $existingCourse['course_code']) {
-				$exists=true;
-			}
-		}
-		if(!$exists) {
-			$sql_insert_rel_course= "INSERT INTO $tbl_session_rel_course(id_session,course_code, id_coach) VALUES('$id_session','$enreg_course','$id_coach')";
-			Database::query($sql_insert_rel_course ,__FILE__,__LINE__);
-			//We add in the existing courses table the current course, to not try to add another time the current course
-			$existingCourses[]=array('course_code'=>$enreg_course);
-			$nbr_users=0;
-			foreach ($UserList as $enreg_user) {
-				$enreg_user = Database::escape_string($enreg_user['id_user']);
-				$sql_insert = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user) VALUES('$id_session','$enreg_course','$enreg_user')";
-				Database::query($sql_insert,__FILE__,__LINE__);
-				if(Database::affected_rows()) {
-					$nbr_users++;
-				}
-			}
-			Database::query("UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'",__FILE__,__LINE__);
-		}
-
-	}
-
-	foreach($existingCourses as $existingCourse) {
-		if(!in_array($existingCourse['course_code'], $CourseList)){
-			Database::query("DELETE FROM $tbl_session_rel_course WHERE course_code='".$existingCourse['course_code']."' AND id_session=$id_session");
-			Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE course_code='".$existingCourse['course_code']."' AND id_session=$id_session");
-
-		}
-	}
-	$nbr_courses=count($CourseList);
-	Database::query("UPDATE $tbl_session SET nbr_courses=$nbr_courses WHERE id='$id_session'",__FILE__,__LINE__);
-
-	if(isset($_GET['add']))
-		header('Location: add_users_to_session.php?id_session='.$id_session.'&add=true');
-	else
-		header('Location: resume_session.php?id_session='.$id_session);
-		//header('Location: '.$_GET['page'].'?id_session='.$id_session);
-}
-
-// display the dokeos header
-Display::display_header($tool_name);
-
-// display the tool title
-// api_display_tool_title($tool_name);
-
-if($add_type == 'multiple') {
-	$link_add_type_unique = '<a href="'.api_get_self().'?id_session='.$id_session.'&add='.Security::remove_XSS($_GET['add']).'&add_type=unique">'.Display::return_icon('single.gif').get_lang('SessionAddTypeUnique').'</a>';
-	$link_add_type_multiple = Display::return_icon('multiple.gif').get_lang('SessionAddTypeMultiple').' ';
-} else {
-	$link_add_type_unique = Display::return_icon('single.gif').get_lang('SessionAddTypeUnique').'&nbsp;&nbsp;&nbsp;';
-	$link_add_type_multiple = '<a href="'.api_get_self().'?id_session='.$id_session.'&add='.Security::remove_XSS($_GET['add']).'&add_type=multiple">'.Display::return_icon('multiple.gif').get_lang('SessionAddTypeMultiple').'</a>';
-}
-
-
-// the form header
-$session_info = SessionManager::fetch($id_session);
-echo '<div class="actions">';
-echo $link_add_type_unique.$link_add_type_multiple;
-echo '</div>';
-
-echo '<div class="row"><div class="form_header">'.$tool_name.' ('.$session_info['name'].')</div></div><br />';
-
-
-
-/*$sql = 'SELECT COUNT(1) FROM '.$tbl_course;
-$rs = Database::query($sql, __FILE__, __LINE__);
-$count_courses = mysql_result($rs, 0, 0);*/
-
-$ajax_search = $add_type == 'unique' ? true : false;
-$nosessionCourses = $sessionCourses = array();
-if ($ajax_search) {
-
-	$sql="SELECT code, title, visual_code, id_session
-			FROM $tbl_course course
-			INNER JOIN $tbl_session_rel_course session_rel_course
-				ON course.code = session_rel_course.course_code
-				AND session_rel_course.id_session = ".intval($id_session)."
-			ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title";
-
-	global $_configuration;
-	if ($_configuration['multiple_access_urls']==true) {
-		$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-		$access_url_id = api_get_current_access_url_id();
-		if ($access_url_id != -1){
-			$sql="SELECT code, title, visual_code, id_session
-			FROM $tbl_course course
-			INNER JOIN $tbl_session_rel_course session_rel_course
-				ON course.code = session_rel_course.course_code
-				AND session_rel_course.id_session = ".intval($id_session)."
-				INNER JOIN $tbl_course_rel_access_url url_course ON (url_course.course_code=course.code)
-				WHERE access_url_id = $access_url_id
-			ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title";
-
-		}
-	}
-
-	$result=Database::query($sql,__FILE__,__LINE__);
-	$Courses=Database::store_result($result);
-
-	foreach($Courses as $course) {
-		$sessionCourses[$course['code']] = $course ;
-	}
-} else {
-	$sql="SELECT code, title, visual_code, id_session
-			FROM $tbl_course course
-			LEFT JOIN $tbl_session_rel_course session_rel_course
-				ON course.code = session_rel_course.course_code
-				AND session_rel_course.id_session = ".intval($id_session)."
-			ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title";
-
-	global $_configuration;
-	if ($_configuration['multiple_access_urls']==true) {
-		$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-		$access_url_id = api_get_current_access_url_id();
-		if ($access_url_id != -1){
-			$sql="SELECT code, title, visual_code, id_session
-				FROM $tbl_course course
-				LEFT JOIN $tbl_session_rel_course session_rel_course
-					ON course.code = session_rel_course.course_code
-					AND session_rel_course.id_session = ".intval($id_session)."
-				INNER JOIN $tbl_course_rel_access_url url_course ON (url_course.course_code=course.code)
-				WHERE access_url_id = $access_url_id
-				ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title";
-		}
-	}
-
-	$result=Database::query($sql,__FILE__,__LINE__);
-	$Courses=Database::store_result($result);
-	foreach($Courses as $course) {
-		if ($course['id_session'] == $id_session) {
-			$sessionCourses[$course['code']] = $course ;
-		} else {
-			$nosessionCourses[$course['code']] = $course ;
-		}
-	}
-}
-
-unset($Courses);
-
-
-
-?>
-
-
-
-<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>?page=<?php echo Security::remove_XSS($_GET['page']) ?>&id_session=<?php echo $id_session; ?><?php if(!empty($_GET['add'])) echo '&add=true' ; ?>" style="margin:0px;" <?php if($ajax_search){echo ' onsubmit="valide();"';}?>>
-<input type="hidden" name="formSent" value="1" />
-
-<?php
-if(!empty($errorMsg))
-{
-	Display::display_normal_message($errorMsg); //main API
-}
-?>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%" align="center">
-<tr>
-  <td width="45%" align="center"><b><?php echo get_lang('CourseListInPlatform') ?> :</b></td>
-
-  <td width="10%">&nbsp;</td>
-  <td align="center" width="45%"><b><?php echo get_lang('CourseListInSession') ?> :</b></td>
-</tr>
-
-<?php if($add_type == 'multiple') { ?>
-<tr><td width="45%" align="center">
- <?php echo get_lang('FirstLetterCourse'); ?> :
-     <select name="firstLetterCourse" onchange = "xajax_search_courses(this.value,'multiple')">
-      <option value="%">--</option>
-      <?php
-      echo Display :: get_alphabet_options();
-      echo Display :: get_numeric_options(0,9,'');
-      ?>
-     </select>
-</td>
-<td>&nbsp;</td></tr>
-<?php } ?>
-
-<tr>
-  <td width="45%" align="center">
-
-<?php
-if(!($add_type == 'multiple')){
-	?>
-	<input type="text" id="course_to_add" onkeyup="xajax_search_courses(this.value,'single')" />
-	<div id="ajax_list_courses_single"></div>
-	<?php
-}
-else
-{
-	?>
-	<div id="ajax_list_courses_multiple">
-	<select id="origin" name="NoSessionCoursesList[]" multiple="multiple" size="20" style="width:320px;"> <?php
-	foreach($nosessionCourses as $enreg)
-	{
-		?>
-		<option value="<?php echo $enreg['code']; ?>" <?php echo 'title="'.htmlspecialchars($enreg['title'].' ('.$enreg['visual_code'].')',ENT_QUOTES).'"'; if(in_array($enreg['code'],$CourseList)) echo 'selected="selected"'; ?>><?php echo $enreg['title'].' ('.$enreg['visual_code'].')'; ?></option>
-		<?php
-	}
-	?>  </select></div> <?php
-}
-unset($nosessionCourses);
-?>
-
-  </select></td>
-  <td width="10%" valign="middle" align="center">
-  <?php
-  if ($ajax_search) {
-  ?>
-  	<button class="arrowl" type="button" onclick="remove_item(document.getElementById('destination'))"></button>
-  <?php
-  }
-  else
-  {
-  ?>
-  	<button class="arrowr" type="button" onclick="moveItem(document.getElementById('origin'), document.getElementById('destination'))" onclick="moveItem(document.getElementById('origin'), document.getElementById('destination'))"></button>
-	<br /><br />
-	<button class="arrowl" type="button" onclick="moveItem(document.getElementById('destination'), document.getElementById('origin'))" onclick="moveItem(document.getElementById('destination'), document.getElementById('origin'))"></button>
-  <?php
-  }
-  ?>
-	<br /><br /><br /><br /><br /><br />
-	<?php
-	if(isset($_GET['add']))
-	{
-		echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('NextStep').'</button>';
-	}
-	else
-	{
-		echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('SubscribeCoursesToSession').'</button>';
-	}
-	?>
-  </td>
-  <td width="45%" align="center"><select id='destination' name="SessionCoursesList[]" multiple="multiple" size="20" style="width:320px;">
-
-<?php
-foreach($sessionCourses as $enreg)
-{
-?>
-	<option value="<?php echo $enreg['code']; ?>" title="<?php echo htmlspecialchars($enreg['title'].' ('.$enreg['visual_code'].')',ENT_QUOTES); ?>"><?php echo $enreg['title'].' ('.$enreg['visual_code'].')'; ?></option>
-
-<?php
-}
-unset($sessionCourses);
-?>
-
-  </select></td>
-</tr>
-</table>
-
-</form>
-<script type="text/javascript">
-<!--
-function moveItem(origin , destination){
-
-	for(var i = 0 ; i<origin.options.length ; i++) {
-		if(origin.options[i].selected) {
-			destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
-			origin.options[i]=null;
-			i = i-1;
-		}
-	}
-	destination.selectedIndex = -1;
-	sortOptions(destination.options);
-
-
-}
-
-function sortOptions(options) {
-
-	newOptions = new Array();
-
-	for (i = 0 ; i<options.length ; i++) {
-		newOptions[i] = options[i];
-	}
-
-	newOptions = newOptions.sort(mysort);
-	options.length = 0;
-
-	for(i = 0 ; i < newOptions.length ; i++){
-		options[i] = newOptions[i];
-	}
-
-}
-
-function mysort(a, b){
-	if(a.text.toLowerCase() > b.text.toLowerCase()){
-		return 1;
-	}
-	if(a.text.toLowerCase() < b.text.toLowerCase()){
-		return -1;
-	}
-	return 0;
-}
-
-function valide(){
-	var options = document.getElementById('destination').options;
-	for (i = 0 ; i<options.length ; i++)
-		options[i].selected = true;
-
-	document.forms.formulaire.submit();
-}
--->
-
-</script>
-<?php
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display::display_footer();
-?>
+<?php //$id: $
+/* For licensing terms, see /dokeos_license.txt */
+/**
+==============================================================================
+*	@package dokeos.admin
+* 	@todo use formvalidator
+==============================================================================
+*/
+
+// name of the language file that needs to be included
+$language_file='admin';
+
+// resetting the course id
+$cidReset=true;
+
+// including some necessary dokeos files
+require '../inc/global.inc.php';
+
+// including additonal libraries
+require_once '../inc/lib/xajax/xajax.inc.php';
+require_once api_get_path(LIBRARY_PATH).'sessionmanager.lib.php';
+$xajax = new xajax();
+//$xajax->debugOn();
+$xajax -> registerFunction ('search_courses');
+
+// setting the section (for the tabs)
+$this_section = SECTION_PLATFORM_ADMIN;
+
+// Access restrictions
+api_protect_admin_script(true);
+
+// setting breadcrumbs
+$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array('url' => 'session_list.php','name' => get_lang('SessionList'));
+
+// Database Table Definitions
+$tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+$tbl_session						= Database::get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_rel_user				= Database::get_main_table(TABLE_MAIN_SESSION_USER);
+$tbl_session_rel_course				= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+$tbl_course							= Database::get_main_table(TABLE_MAIN_COURSE);
+
+// setting the name of the tool
+$tool_name= get_lang('SubscribeCoursesToSession');
+$id_session=intval($_GET['id_session']);
+
+$add_type = 'multiple';
+if(isset($_GET['add_type']) && $_GET['add_type']!=''){
+	$add_type = Security::remove_XSS($_REQUEST['add_type']);
+}
+
+if (!api_is_platform_admin()) {
+	$sql = 'SELECT session_admin_id FROM '.Database :: get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$id_session;
+	$rs = Database::query($sql,__FILE__,__LINE__);
+	if (Database::result($rs,0,0)!=$_user['user_id']) {
+		api_not_allowed(true);
+	}
+}
+
+function search_courses($needle,$type)
+{
+	global $tbl_course, $tbl_session_rel_course, $id_session;
+
+	$xajax_response = new XajaxResponse();
+	$return = '';
+	if(!empty($needle) && !empty($type)) {
+		// xajax send utf8 datas... datas in db can be non-utf8 datas
+		$charset = api_get_setting('platform_charset');
+		$needle = api_convert_encoding($needle, $charset, 'utf-8');
+
+		$cond_course_code = '';
+		if (!empty($id_session)) {
+		$id_session = Database::escape_string($id_session);
+			// check course_code from session_rel_course table
+			$sql = 'SELECT course_code FROM '.$tbl_session_rel_course.' WHERE id_session ="'.(int)$id_session.'"';
+			$res = Database::query($sql,__FILE__,__LINE__);
+			$course_codes = '';
+			if (Database::num_rows($res) > 0) {
+				while ($row = Database::fetch_row($res)) {
+					$course_codes .= '\''.$row[0].'\',';
+				}
+				$course_codes = substr($course_codes,0,(strlen($course_codes)-1));
+
+				$cond_course_code = ' AND course.code NOT IN('.$course_codes.') ';
+			}
+		}
+
+		if ($type=='single') {
+		// search users where username or firstname or lastname begins likes $needle
+		$sql = 'SELECT course.code, course.visual_code, course.title, session_rel_course.id_session
+				FROM '.$tbl_course.' course
+				LEFT JOIN '.$tbl_session_rel_course.' session_rel_course
+					ON course.code = session_rel_course.course_code
+					AND session_rel_course.id_session = '.intval($id_session).'
+				WHERE course.visual_code LIKE "'.$needle.'%"
+				OR course.title LIKE "'.$needle.'%"';
+		} else {
+
+		$sql = 'SELECT course.code, course.visual_code, course.title
+				FROM '.$tbl_course.' course
+				WHERE course.visual_code LIKE "'.$needle.'%" '.$cond_course_code.' ORDER BY course.code ';
+		}
+
+		global $_configuration;
+		if ($_configuration['multiple_access_urls']==true) {
+			$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+			$access_url_id = api_get_current_access_url_id();
+			if ($access_url_id != -1){
+
+				if ($type=='single') {
+					$sql = 'SELECT course.code, course.visual_code, course.title, session_rel_course.id_session
+							FROM '.$tbl_course.' course
+							LEFT JOIN '.$tbl_session_rel_course.' session_rel_course
+								ON course.code = session_rel_course.course_code
+								AND session_rel_course.id_session = '.intval($id_session).'
+							INNER JOIN '.$tbl_course_rel_access_url.' url_course ON (url_course.course_code=course.code)
+							WHERE access_url_id = '.$access_url_id.' AND (course.visual_code LIKE "'.$needle.'%"
+							OR course.title LIKE "'.$needle.'%" )';
+				} else {
+					$sql = 'SELECT course.code, course.visual_code, course.title
+							FROM '.$tbl_course.' course, '.$tbl_course_rel_access_url.' url_course
+							WHERE url_course.course_code=course.code AND access_url_id = '.$access_url_id.'
+							AND course.visual_code LIKE "'.$needle.'%" '.$cond_course_code.' ORDER BY course.code ';
+				}
+			}
+		}
+
+		$rs = Database::query($sql, __FILE__, __LINE__);
+		$course_list = array();
+		if ($type=='single') {
+
+			while($course = Database :: fetch_array($rs)) {
+				$course_list[] = $course['code'];
+				$course_title=str_replace("'","\'",$course_title);
+				$return .= '<a href="javascript: void(0);" onclick="javascript: add_course_to_session(\''.$course['code'].'\',\''.$course_title.' ('.$course['visual_code'].')'.'\')">'.$course['title'].' ('.$course['visual_code'].')</a><br />';
+			}
+
+			$xajax_response -> addAssign('ajax_list_courses_single','innerHTML',api_utf8_encode($return));
+
+		} else {
+
+			$return .= '<select id="origin" name="NoSessionCoursesList[]" multiple="multiple" size="20" style="width:340px;">';
+			while($course = Database :: fetch_array($rs)) {
+				$course_list[] = $course['code'];
+				$course_title=str_replace("'","\'",$course_title);
+				$return .= '<option value="'.$course['code'].'" title="'.htmlspecialchars($course['title'].' ('.$course['visual_code'].')',ENT_QUOTES).'">'.$course['title'].' ('.$course['visual_code'].')</option>';
+			}
+			$return .= '</select>';
+
+			$xajax_response -> addAssign('ajax_list_courses_multiple','innerHTML',api_utf8_encode($return));
+		}
+	}
+	$_SESSION['course_list'] = $course_list;
+	return $xajax_response;
+}
+$xajax -> processRequests();
+
+$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
+$htmlHeadXtra[] = '
+<script type="text/javascript">
+function add_course_to_session (code, content) {
+
+	document.getElementById("course_to_add").value = "";
+	document.getElementById("ajax_list_courses_single").innerHTML = "";
+
+	destination = document.getElementById("destination");
+
+	for (i=0;i<destination.length;i++) {
+		if(destination.options[i].text == content) {
+				return false;
+		}
+	}
+
+	destination.options[destination.length] = new Option(content,code);
+
+	destination.selectedIndex = -1;
+	sortOptions(destination.options);
+}
+function remove_item(origin)
+{
+	for(var i = 0 ; i<origin.options.length ; i++) {
+		if(origin.options[i].selected) {
+			origin.options[i]=null;
+			i = i-1;
+		}
+	}
+}
+</script>';
+
+
+$formSent=0;
+$errorMsg=$firstLetterCourse=$firstLetterSession='';
+$CourseList=$SessionList=array();
+$courses=$sessions=array();
+$noPHP_SELF=true;
+
+if ($_POST['formSent']) {
+
+	$formSent=$_POST['formSent'];
+	$firstLetterCourse=$_POST['firstLetterCourse'];
+	$firstLetterSession=$_POST['firstLetterSession'];
+	$CourseList=$_POST['SessionCoursesList'];
+	if (!is_array($CourseList)) {
+		$CourseList=array();
+	}
+	$nbr_courses=0;
+
+	$id_coach = Database::query("SELECT id_coach FROM $tbl_session WHERE id=$id_session");
+	$id_coach = Database::fetch_array($id_coach);
+	$id_coach = $id_coach[0];
+
+	$rs = Database::query("SELECT course_code FROM $tbl_session_rel_course WHERE id_session=$id_session");
+	$existingCourses = Database::store_result($rs);
+
+	$sql="SELECT id_user
+		FROM $tbl_session_rel_user
+		WHERE id_session = $id_session";
+	$result=Database::query($sql,__FILE__,__LINE__);
+	$UserList=Database::store_result($result);
+
+
+	foreach($CourseList as $enreg_course) {
+		$enreg_course = Database::escape_string($enreg_course);
+		$exists = false;
+		foreach($existingCourses as $existingCourse) {
+			if($enreg_course == $existingCourse['course_code']) {
+				$exists=true;
+			}
+		}
+		if(!$exists) {
+			$sql_insert_rel_course= "INSERT INTO $tbl_session_rel_course(id_session,course_code, id_coach) VALUES('$id_session','$enreg_course','$id_coach')";
+			Database::query($sql_insert_rel_course ,__FILE__,__LINE__);
+			//We add in the existing courses table the current course, to not try to add another time the current course
+			$existingCourses[]=array('course_code'=>$enreg_course);
+			$nbr_users=0;
+			foreach ($UserList as $enreg_user) {
+				$enreg_user = Database::escape_string($enreg_user['id_user']);
+				$sql_insert = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user) VALUES('$id_session','$enreg_course','$enreg_user')";
+				Database::query($sql_insert,__FILE__,__LINE__);
+				if(Database::affected_rows()) {
+					$nbr_users++;
+				}
+			}
+			Database::query("UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'",__FILE__,__LINE__);
+		}
+
+	}
+
+	foreach($existingCourses as $existingCourse) {
+		if(!in_array($existingCourse['course_code'], $CourseList)){
+			Database::query("DELETE FROM $tbl_session_rel_course WHERE course_code='".$existingCourse['course_code']."' AND id_session=$id_session");
+			Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE course_code='".$existingCourse['course_code']."' AND id_session=$id_session");
+
+		}
+	}
+	$nbr_courses=count($CourseList);
+	Database::query("UPDATE $tbl_session SET nbr_courses=$nbr_courses WHERE id='$id_session'",__FILE__,__LINE__);
+
+	if(isset($_GET['add']))
+		header('Location: add_users_to_session.php?id_session='.$id_session.'&add=true');
+	else
+		header('Location: resume_session.php?id_session='.$id_session);
+		//header('Location: '.$_GET['page'].'?id_session='.$id_session);
+}
+
+// display the dokeos header
+Display::display_header($tool_name);
+
+// display the tool title
+// api_display_tool_title($tool_name);
+
+if($add_type == 'multiple') {
+	$link_add_type_unique = '<a href="'.api_get_self().'?id_session='.$id_session.'&add='.Security::remove_XSS($_GET['add']).'&add_type=unique">'.Display::return_icon('single.gif').get_lang('SessionAddTypeUnique').'</a>';
+	$link_add_type_multiple = Display::return_icon('multiple.gif').get_lang('SessionAddTypeMultiple').' ';
+} else {
+	$link_add_type_unique = Display::return_icon('single.gif').get_lang('SessionAddTypeUnique').'&nbsp;&nbsp;&nbsp;';
+	$link_add_type_multiple = '<a href="'.api_get_self().'?id_session='.$id_session.'&add='.Security::remove_XSS($_GET['add']).'&add_type=multiple">'.Display::return_icon('multiple.gif').get_lang('SessionAddTypeMultiple').'</a>';
+}
+
+
+// the form header
+$session_info = SessionManager::fetch($id_session);
+echo '<div class="actions">';
+echo $link_add_type_unique.$link_add_type_multiple;
+echo '</div>';
+
+echo '<div class="row"><div class="form_header">'.$tool_name.' ('.$session_info['name'].')</div></div><br />';
+
+
+
+/*$sql = 'SELECT COUNT(1) FROM '.$tbl_course;
+$rs = Database::query($sql, __FILE__, __LINE__);
+$count_courses = mysql_result($rs, 0, 0);*/
+
+$ajax_search = $add_type == 'unique' ? true : false;
+$nosessionCourses = $sessionCourses = array();
+if ($ajax_search) {
+
+	$sql="SELECT code, title, visual_code, id_session
+			FROM $tbl_course course
+			INNER JOIN $tbl_session_rel_course session_rel_course
+				ON course.code = session_rel_course.course_code
+				AND session_rel_course.id_session = ".intval($id_session)."
+			ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title";
+
+	global $_configuration;
+	if ($_configuration['multiple_access_urls']==true) {
+		$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+		$access_url_id = api_get_current_access_url_id();
+		if ($access_url_id != -1){
+			$sql="SELECT code, title, visual_code, id_session
+			FROM $tbl_course course
+			INNER JOIN $tbl_session_rel_course session_rel_course
+				ON course.code = session_rel_course.course_code
+				AND session_rel_course.id_session = ".intval($id_session)."
+				INNER JOIN $tbl_course_rel_access_url url_course ON (url_course.course_code=course.code)
+				WHERE access_url_id = $access_url_id
+			ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title";
+
+		}
+	}
+
+	$result=Database::query($sql,__FILE__,__LINE__);
+	$Courses=Database::store_result($result);
+
+	foreach($Courses as $course) {
+		$sessionCourses[$course['code']] = $course ;
+	}
+} else {
+	$sql="SELECT code, title, visual_code, id_session
+			FROM $tbl_course course
+			LEFT JOIN $tbl_session_rel_course session_rel_course
+				ON course.code = session_rel_course.course_code
+				AND session_rel_course.id_session = ".intval($id_session)."
+			ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title";
+
+	global $_configuration;
+	if ($_configuration['multiple_access_urls']==true) {
+		$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+		$access_url_id = api_get_current_access_url_id();
+		if ($access_url_id != -1){
+			$sql="SELECT code, title, visual_code, id_session
+				FROM $tbl_course course
+				LEFT JOIN $tbl_session_rel_course session_rel_course
+					ON course.code = session_rel_course.course_code
+					AND session_rel_course.id_session = ".intval($id_session)."
+				INNER JOIN $tbl_course_rel_access_url url_course ON (url_course.course_code=course.code)
+				WHERE access_url_id = $access_url_id
+				ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title";
+		}
+	}
+
+	$result=Database::query($sql,__FILE__,__LINE__);
+	$Courses=Database::store_result($result);
+	foreach($Courses as $course) {
+		if ($course['id_session'] == $id_session) {
+			$sessionCourses[$course['code']] = $course ;
+		} else {
+			$nosessionCourses[$course['code']] = $course ;
+		}
+	}
+}
+
+unset($Courses);
+
+
+
+?>
+
+
+
+<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>?page=<?php echo Security::remove_XSS($_GET['page']) ?>&id_session=<?php echo $id_session; ?><?php if(!empty($_GET['add'])) echo '&add=true' ; ?>" style="margin:0px;" <?php if($ajax_search){echo ' onsubmit="valide();"';}?>>
+<input type="hidden" name="formSent" value="1" />
+
+<?php
+if(!empty($errorMsg))
+{
+	Display::display_normal_message($errorMsg); //main API
+}
+?>
+
+<table border="0" cellpadding="5" cellspacing="0" width="100%" align="center">
+<tr>
+  <td width="45%" align="center"><b><?php echo get_lang('CourseListInPlatform') ?> :</b></td>
+
+  <td width="10%">&nbsp;</td>
+  <td align="center" width="45%"><b><?php echo get_lang('CourseListInSession') ?> :</b></td>
+</tr>
+
+<?php if($add_type == 'multiple') { ?>
+<tr><td width="45%" align="center">
+ <?php echo get_lang('FirstLetterCourse'); ?> :
+     <select name="firstLetterCourse" onchange = "xajax_search_courses(this.value,'multiple')">
+      <option value="%">--</option>
+      <?php
+      echo Display :: get_alphabet_options();
+      echo Display :: get_numeric_options(0,9,'');
+      ?>
+     </select>
+</td>
+<td>&nbsp;</td></tr>
+<?php } ?>
+
+<tr>
+  <td width="45%" align="center">
+
+<?php
+if(!($add_type == 'multiple')){
+	?>
+	<input type="text" id="course_to_add" onkeyup="xajax_search_courses(this.value,'single')" />
+	<div id="ajax_list_courses_single"></div>
+	<?php
+}
+else
+{
+	?>
+	<div id="ajax_list_courses_multiple">
+	<select id="origin" name="NoSessionCoursesList[]" multiple="multiple" size="20" style="width:320px;"> <?php
+	foreach($nosessionCourses as $enreg)
+	{
+		?>
+		<option value="<?php echo $enreg['code']; ?>" <?php echo 'title="'.htmlspecialchars($enreg['title'].' ('.$enreg['visual_code'].')',ENT_QUOTES).'"'; if(in_array($enreg['code'],$CourseList)) echo 'selected="selected"'; ?>><?php echo $enreg['title'].' ('.$enreg['visual_code'].')'; ?></option>
+		<?php
+	}
+	?>  </select></div> <?php
+}
+unset($nosessionCourses);
+?>
+
+  </select></td>
+  <td width="10%" valign="middle" align="center">
+  <?php
+  if ($ajax_search) {
+  ?>
+  	<button class="arrowl" type="button" onclick="remove_item(document.getElementById('destination'))"></button>
+  <?php
+  }
+  else
+  {
+  ?>
+  	<button class="arrowr" type="button" onclick="moveItem(document.getElementById('origin'), document.getElementById('destination'))" onclick="moveItem(document.getElementById('origin'), document.getElementById('destination'))"></button>
+	<br /><br />
+	<button class="arrowl" type="button" onclick="moveItem(document.getElementById('destination'), document.getElementById('origin'))" onclick="moveItem(document.getElementById('destination'), document.getElementById('origin'))"></button>
+  <?php
+  }
+  ?>
+	<br /><br /><br /><br /><br /><br />
+	<?php
+	if(isset($_GET['add']))
+	{
+		echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('NextStep').'</button>';
+	}
+	else
+	{
+		echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('SubscribeCoursesToSession').'</button>';
+	}
+	?>
+  </td>
+  <td width="45%" align="center"><select id='destination' name="SessionCoursesList[]" multiple="multiple" size="20" style="width:320px;">
+
+<?php
+foreach($sessionCourses as $enreg)
+{
+?>
+	<option value="<?php echo $enreg['code']; ?>" title="<?php echo htmlspecialchars($enreg['title'].' ('.$enreg['visual_code'].')',ENT_QUOTES); ?>"><?php echo $enreg['title'].' ('.$enreg['visual_code'].')'; ?></option>
+
+<?php
+}
+unset($sessionCourses);
+?>
+
+  </select></td>
+</tr>
+</table>
+
+</form>
+<script type="text/javascript">
+<!--
+function moveItem(origin , destination){
+
+	for(var i = 0 ; i<origin.options.length ; i++) {
+		if(origin.options[i].selected) {
+			destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
+			origin.options[i]=null;
+			i = i-1;
+		}
+	}
+	destination.selectedIndex = -1;
+	sortOptions(destination.options);
+
+
+}
+
+function sortOptions(options) {
+
+	newOptions = new Array();
+
+	for (i = 0 ; i<options.length ; i++) {
+		newOptions[i] = options[i];
+	}
+
+	newOptions = newOptions.sort(mysort);
+	options.length = 0;
+
+	for(i = 0 ; i < newOptions.length ; i++){
+		options[i] = newOptions[i];
+	}
+
+}
+
+function mysort(a, b){
+	if(a.text.toLowerCase() > b.text.toLowerCase()){
+		return 1;
+	}
+	if(a.text.toLowerCase() < b.text.toLowerCase()){
+		return -1;
+	}
+	return 0;
+}
+
+function valide(){
+	var options = document.getElementById('destination').options;
+	for (i = 0 ; i<options.length ; i++)
+		options[i].selected = true;
+
+	document.forms.formulaire.submit();
+}
+-->
+
+</script>
+<?php
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display::display_footer();
+?>

+ 26 - 26
main/admin/add_users_to_session.php

@@ -87,7 +87,7 @@ function search_users($needle,$type)
 		$needle = api_convert_encoding($needle, $charset, 'utf-8');
 		$user_anonymous=api_get_anonymous_id();
 
-		$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
+		$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
 		$cond_user_id = '';
 		if (!empty($id_session)) {
 		$id_session = Database::escape_string($id_session);
@@ -110,13 +110,13 @@ function search_users($needle,$type)
 			$sql = 'SELECT user_id, username, lastname, firstname FROM '.$tbl_user.' user
 					WHERE (username LIKE "'.$needle.'%"
 					OR firstname LIKE "'.$needle.'%"
-				OR lastname LIKE "'.$needle.'%") AND user_id<>"'.$user_anonymous.'"'.
-				$order_clause.
-				' LIMIT 11';
+				OR lastname LIKE "'.$needle.'%") AND user_id<>"'.$user_anonymous.'"'.
+				$order_clause.
+				' LIMIT 11';
 		} else {
 			$sql = 'SELECT user_id, username, lastname, firstname FROM '.$tbl_user.' user
-					WHERE '.(api_sort_by_first_name() ? 'firstname' : 'lastname').' LIKE "'.$needle.'%" AND user_id<>"'.$user_anonymous.'"'.$cond_user_id.
-					$order_clause;
+					WHERE '.(api_sort_by_first_name() ? 'firstname' : 'lastname').' LIKE "'.$needle.'%" AND user_id<>"'.$user_anonymous.'"'.$cond_user_id.
+					$order_clause;
 		}
 
 		global $_configuration;
@@ -129,15 +129,15 @@ function search_users($needle,$type)
 					INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id)
 					WHERE access_url_id = '.$access_url_id.'  AND (username LIKE "'.$needle.'%"
 					OR firstname LIKE "'.$needle.'%"
-					OR lastname LIKE "'.$needle.'%") AND user.user_id<>"'.$user_anonymous.'"'.
-					$order_clause.
-					' LIMIT 11';
+					OR lastname LIKE "'.$needle.'%") AND user.user_id<>"'.$user_anonymous.'"'.
+					$order_clause.
+					' LIMIT 11';
 				} else {
 					$sql = 'SELECT user.user_id, username, lastname, firstname FROM '.$tbl_user.' user
 					INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id)
 					WHERE access_url_id = '.$access_url_id.'
-					AND '.(api_sort_by_first_name() ? 'firstname' : 'lastname').' LIKE "'.$needle.'%" AND user.user_id<>"'.$user_anonymous.'"'.$cond_user_id.
-					$order_clause;
+					AND '.(api_sort_by_first_name() ? 'firstname' : 'lastname').' LIKE "'.$needle.'%" AND user.user_id<>"'.$user_anonymous.'"'.$cond_user_id.
+					$order_clause;
 				}
 
 			}
@@ -149,8 +149,8 @@ function search_users($needle,$type)
 			while ($user = Database :: fetch_array($rs)) {
 	            $i++;
 	            if ($i<=10) {
-            		$person_name = api_get_person_name($user['firstname'], $user['lastname']);
-					$return .= '<a href="javascript: void(0);" onclick="javascript: add_user_to_session(\''.$user['user_id'].'\',\''.$person_name.' ('.$user['username'].')'.'\')">'.$person_name.' ('.$user['username'].')</a><br />';
+            		$person_name = api_get_person_name($user['firstname'], $user['lastname']);
+					$return .= '<a href="javascript: void(0);" onclick="javascript: add_user_to_session(\''.$user['user_id'].'\',\''.$person_name.' ('.$user['username'].')'.'\')">'.$person_name.' ('.$user['username'].')</a><br />';
 	            } else {
 	            	$return .= '...<br />';
 	            }
@@ -162,8 +162,8 @@ function search_users($needle,$type)
 			global $nosessionUsersList;
 			$return .= '<select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:360px;">';
 			while ($user = Database :: fetch_array($rs)) {
-				$person_name = api_get_person_name($user['firstname'], $user['lastname']);
-	            $return .= '<option value="'.$user['user_id'].'">'.$person_name.' ('.$user['username'].')</option>';
+				$person_name = api_get_person_name($user['firstname'], $user['lastname']);
+	            $return .= '<option value="'.$user['user_id'].'">'.$person_name.' ('.$user['username'].')</option>';
 			}
 			$return .= '</select>';
 			$xajax_response -> addAssign('ajax_list_users_multiple','innerHTML',api_utf8_encode($return));
@@ -269,14 +269,14 @@ $count_courses = Database::result($rs, 0, 0);*/
 $ajax_search = $add_type == 'unique' ? true : false;
 global $_configuration;
 
-$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
+$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
 if ($ajax_search) {
 	$sql="SELECT user_id, lastname, firstname, username, id_session
 			FROM $tbl_user
 			INNER JOIN $tbl_session_rel_user
 				ON $tbl_session_rel_user.id_user = $tbl_user.user_id
-				AND $tbl_session_rel_user.id_session = ".intval($id_session).
-			$order_clause;
+				AND $tbl_session_rel_user.id_session = ".intval($id_session).
+			$order_clause;
 
 	if ($_configuration['multiple_access_urls']==true) {
 		$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
@@ -289,7 +289,7 @@ if ($ajax_search) {
 				AND $tbl_session_rel_user.id_session = ".intval($id_session)."
 				INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id)
 				WHERE access_url_id = $access_url_id
-				$order_clause";
+				$order_clause";
 		}
 	}
 	$result=Database::query($sql,__FILE__,__LINE__);
@@ -351,14 +351,14 @@ if ($ajax_search) {
 				LEFT JOIN $tbl_session_rel_user
 				ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$id_session'
 				$where_filter
-			$order_clause";
+			$order_clause";
 
 		} else {
 			$sql="SELECT  user_id, lastname, firstname, username, id_session
 				FROM $tbl_user u
 				LEFT JOIN $tbl_session_rel_user
 				ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$id_session'
-			$order_clause";
+			$order_clause";
 		}
 		if ($_configuration['multiple_access_urls']==true) {
 			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
@@ -370,7 +370,7 @@ if ($ajax_search) {
 					ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$id_session'
 				INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id)
 				WHERE access_url_id = $access_url_id  $where_filter
-			$order_clause";
+			$order_clause";
 			}
 		}
 
@@ -392,7 +392,7 @@ if ($ajax_search) {
 			FROM $tbl_user u
 			LEFT JOIN $tbl_session_rel_user
 			ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$id_session'
-			$order_clause";
+			$order_clause";
 
 		if ($_configuration['multiple_access_urls']==true) {
 			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
@@ -404,7 +404,7 @@ if ($ajax_search) {
 					ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$id_session'
 				INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id)
 				WHERE access_url_id = $access_url_id
-				$order_clause";
+				$order_clause";
 			}
 		}
 	$result=Database::query($sql,__FILE__,__LINE__);
@@ -525,7 +525,7 @@ if(!empty($errorMsg)) {
 		<?php
 		foreach($nosessionUsersList as $enreg) {
 		?>
-			<option value="<?php echo $enreg['user_id']; ?>" <?php if(in_array($enreg['user_id'],$UserList)) echo 'selected="selected"'; ?>><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
+			<option value="<?php echo $enreg['user_id']; ?>" <?php if(in_array($enreg['user_id'],$UserList)) echo 'selected="selected"'; ?>><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
 		<?php
 		}
 		?>
@@ -559,7 +559,7 @@ if(!empty($errorMsg)) {
 <?php
 foreach($sessionUsersList as $enreg) {
 ?>
-	<option value="<?php echo $enreg['user_id']; ?>"><?php echo $enreg['firstname'].' '.$enreg['lastname'].' ('.$enreg['username'].')'; ?></option>
+	<option value="<?php echo $enreg['user_id']; ?>"><?php echo $enreg['firstname'].' '.$enreg['lastname'].' ('.$enreg['username'].')'; ?></option>
 
 <?php
 }

+ 3116 - 3116
main/admin/calendar.lib.php

@@ -1,3116 +1,3116 @@
-<?php // $id: $
-/* For licensing terms, see /dokeos_license.txt */
-/**
-==============================================================================
-*	@package dokeos.admin
-*	@author Carlos Vargas
-*	This file is the calendar/agenda.inc.php
-==============================================================================
-*/
-
-/*
------------------------------------------------------------
-	Constants and variables
------------------------------------------------------------
-*/
-// the variables for the days and the months
-// Defining the shorts for the days
-$DaysShort = api_get_week_days_short();
-// Defining the days of the week to allow translation of the days
-$DaysLong = api_get_week_days_long();
-// Defining the months of the year to allow translation of the months
-$MonthsLong = api_get_months_long();
-
-/*
-==============================================================================
-		FUNCTIONS
-==============================================================================
-*/
-
-/**
-* Retrieves all the agenda items from the table
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @author Yannick Warnier <yannick.warnier@dokeos.com> - cleanup
-* @param integer $month: the integer value of the month we are viewing
-* @param integer $year: the 4-digit year indication e.g. 2005
-* @return array
-*/
-
-/**
-* show the mini calender of the given month
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @param array an array containing all the agenda items for the given month
-* @param integer $month: the integer value of the month we are viewing
-* @param integer $year: the 4-digit year indication e.g. 2005
-* @param string $monthName: the language variable for the mont name
-* @return html code
-* @todo refactor this so that $monthName is no longer needed as a parameter
-*/
-function display_minimonthcalendar($agendaitems, $month, $year, $monthName)
-{
-	global $DaysShort;
-	//Handle leap year
-	$numberofdays = array (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
-	if (($year % 400 == 0) or ($year % 4 == 0 and $year % 100 <> 0))
-		$numberofdays[2] = 29;
-	//Get the first day of the month
-	$dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
-	//Start the week on monday
-	$startdayofweek = $dayone['wday'] <> 0 ? ($dayone['wday'] - 1) : 6;
-	$backwardsURL = api_get_self()."?".api_get_cidreq()."&amp;coursePath=".(empty($_GET['coursePath'])?'':$_GET['coursePath'])."&amp;courseCode=".(empty($_GET['courseCode'])?'':$_GET['courseCode'])."&amp;month=". ($month == 1 ? 12 : $month -1)."&amp;year=". ($month == 1 ? $year -1 : $year);
-	$forewardsURL = api_get_self()."?".api_get_cidreq()."&amp;coursePath=".(empty($_GET['coursePath'])?'':$_GET['coursePath'])."&amp;courseCode=".(empty($_GET['courseCode'])?'':$_GET['courseCode'])."&amp;month=". ($month == 12 ? 1 : $month +1)."&amp;year=". ($month == 12 ? $year +1 : $year);
-
-	echo 	"<table class=\"data_table\">\n",
-			"<tr>\n",
-			"<th width=\"10%\"><a href=\"", $backwardsURL, "\"> &laquo; </a></th>\n",
-			"<th width=\"80%\" colspan=\"5\">", $monthName, " ", $year, "</th>\n",
-			"<th  width=\"10%\"><a href=\"", $forewardsURL, "\"> &raquo; </a></th>\n", "</tr>\n";
-	echo "<tr>\n";
-	for ($ii = 1; $ii < 8; $ii ++)
-	{
-		echo "<td class=\"weekdays\">", $DaysShort[$ii % 7], "</td>\n";
-	}
-	echo "</tr>\n";
-	$curday = -1;
-	$today = getdate();
-	while ($curday <= $numberofdays[$month])
-	{
-		echo "<tr>\n";
-		for ($ii = 0; $ii < 7; $ii ++)
-		{
-			if (($curday == -1) && ($ii == $startdayofweek))
-			{
-				$curday = 1;
-			}
-			if (($curday > 0) && ($curday <= $numberofdays[$month]))
-			{
-				$bgcolor = $ii < 5 ? $class="class=\"days_week\"" : $class="class=\"days_weekend\"";
-				$dayheader = "$curday";
-				if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon']))
-				{
-					$dayheader = "$curday";
-					$class = "class=\"days_today\"";
-				}
-				echo "\t<td ".$class.">";
-				if (!empty($agendaitems[$curday]))
-				{
-					echo "<a href=\"".api_get_self()."?".api_get_cidreq()."&amp;action=view&amp;view=day&amp;day=".$curday."&amp;month=".$month."&amp;year=".$year."\">".$dayheader."</a>";
-				}
-				else
-				{
-					echo $dayheader;
-				}
-				// "a".$dayheader." <span class=\"agendaitem\">".$agendaitems[$curday]."</span>\n";
-				echo "</td>\n";
-				$curday ++;
-			}
-			else
-			{
-				echo "<td>&nbsp;</td>\n";
-			}
-		}
-		echo "</tr>\n";
-	}
-	echo "</table>\n";
-}
-/**
-* show the calender of the given month
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @param integer $month: the integer value of the month we are viewing
-* @param integer $year: the 4-digit year indication e.g. 2005
-* @return html code
-*/
-/**
-* returns all the javascript that is required for easily selecting the target people/groups this goes into the $htmlHeadXtra[] array
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @return javascript code
-*/
-function to_javascript()
-{
-$Send2All=get_lang("Send2All");
-return "<script type=\"text/javascript\" language=\"JavaScript\">
-<!-- Begin javascript menu swapper
-
-function move(fbox,	tbox)
-{
-	var	arrFbox	= new Array();
-	var	arrTbox	= new Array();
-	var	arrLookup =	new	Array();
-
-	var	i;
-	for	(i = 0;	i <	tbox.options.length; i++)
-	{
-		arrLookup[tbox.options[i].text]	= tbox.options[i].value;
-		arrTbox[i] = tbox.options[i].text;
-	}
-
-	var	fLength	= 0;
-	var	tLength	= arrTbox.length;
-
-	for(i =	0; i < fbox.options.length;	i++)
-	{
-		arrLookup[fbox.options[i].text]	= fbox.options[i].value;
-
-		if (fbox.options[i].selected &&	fbox.options[i].value != \"\")
-		{
-			arrTbox[tLength] = fbox.options[i].text;
-			tLength++;
-		}
-		else
-		{
-			arrFbox[fLength] = fbox.options[i].text;
-			fLength++;
-		}
-	}
-
-	arrFbox.sort();
-	arrTbox.sort();
-	fbox.length	= 0;
-	tbox.length	= 0;
-
-	var	c;
-	for(c =	0; c < arrFbox.length; c++)
-	{
-		var	no = new Option();
-		no.value = arrLookup[arrFbox[c]];
-		no.text	= arrFbox[c];
-		fbox[c]	= no;
-	}
-	for(c =	0; c < arrTbox.length; c++)
-	{
-		var	no = new Option();
-		no.value = arrLookup[arrTbox[c]];
-		no.text	= arrTbox[c];
-		tbox[c]	= no;
-	}
-}
-
-function checkDate(month, day, year)
-{
-  var monthLength =
-    new Array(31,28,31,30,31,30,31,31,30,31,30,31);
-
-  if (!day || !month || !year)
-    return false;
-
-  // check for bisestile year
-  if (year/4 == parseInt(year/4))
-    monthLength[1] = 29;
-
-  if (month < 1 || month > 12)
-    return false;
-
-  if (day > monthLength[month-1])
-    return false;
-
-  return true;
-}
-
-function mktime()
-{
-    var no, ma = 0, mb = 0, i = 0, d = new Date(), argv = arguments, argc = argv.length;
-    d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1972);
-    var dateManip = {
-        0: function(tt){ return d.setHours(tt); },
-        1: function(tt){ return d.setMinutes(tt); },
-        2: function(tt){ set = d.setSeconds(tt); mb = d.getDate() - 1; return set; },
-        3: function(tt){ set = d.setMonth(parseInt(tt)-1); ma = d.getFullYear() - 1972; return set; },
-        4: function(tt){ return d.setDate(tt+mb); },
-        5: function(tt){ return d.setYear(tt+ma); }
-    };
-    for( i = 0; i < argc; i++ ){
-        no = parseInt(argv[i]*1);
-        if (isNaN(no)) {
-            return false;
-        } else {
-            // arg is number, lets manipulate date object
-            if(!dateManip[i](no)){
-                // failed
-                return false;
-            }
-        }
-    }
-    return Math.floor(d.getTime()/1000);
-}
-
-function validate()
-{
-	var	f =	document.new_calendar_item;
-	f.submit();
-	return true;
-}
-
-function validate_date()
-{
-		var start_day = document.new_calendar_item.fday.value;
-		var start_month = document.new_calendar_item.fmonth.value;
-		var start_year = document.new_calendar_item.fyear.value;
-		var start_hour = document.new_calendar_item.fhour.value;
-		var start_minute = document.new_calendar_item.fminute.value;
-		var start_date = mktime(start_hour,start_minute,0,start_month,start_day,start_year)
-
-		var ends_day = document.new_calendar_item.end_fday.value;
-		var ends_month = document.new_calendar_item.end_fmonth.value;
-		var ends_year = document.new_calendar_item.end_fyear.value;
-		var ends_hour = document.new_calendar_item.end_fhour.value;
-		var ends_minute = document.new_calendar_item.end_fminute.value;
-		var ends_date = mktime(ends_hour,ends_minute,0,ends_month,ends_day,ends_year)
-
-		msg_err1 = document.getElementById(\"err_date\");
-		msg_err2 = document.getElementById(\"err_start_date\");
-		msg_err3 = document.getElementById(\"err_end_date\");
-		msg_err4 = document.getElementById(\"err_title\");
-
-		if (start_date > ends_date) {
-			msg_err1.style.display =\"block\";
-			msg_err1.innerHTML=\"".get_lang('EndDateCannotBeBeforeTheStartDate')."\";
-			msg_err2.innerHTML=\"\";msg_err3.innerHTML=\"\";
-		} else if (checkDate(start_month,start_day,start_year) == false) {
-			msg_err2.style.display =\"block\";
-			msg_err2.innerHTML=\"".get_lang('InvalidDate')."\";
-			msg_err1.innerHTML=\"\";msg_err3.innerHTML=\"\";
-		} else if (checkDate(ends_month,ends_day,ends_year) == false) {
-			msg_err3.style.display =\"block\";
-			msg_err3.innerHTML=\"".get_lang('InvalidDate')."\";
-			msg_err1.innerHTML=\"\";msg_err2.innerHTML=\"\";
-		} else if (document.new_calendar_item.title.value == '') {
-			msg_err4.style.display =\"block\";
-			msg_err4.innerHTML=\"".get_lang('FieldRequired')."\";
-			msg_err1.innerHTML=\"\";msg_err2.innerHTML=\"\";msg_err3.innerHTML=\"\";
-		}  else {
-			document.new_calendar_item.submit();
-		}
-
-}
-//	End	-->
-</script>";
-}
-
-
-
-/**
-* returns the javascript for setting a filter. This is a jump menu
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @return javascript code
-*/
-function user_group_filter_javascript()
-{
-return "<script language=\"JavaScript\" type=\"text/JavaScript\">
-<!--
-function MM_jumpMenu(targ,selObj,restore){
-  eval(targ+\".location='\"+selObj.options[selObj.selectedIndex].value+\"'\");
-  if (restore) selObj.selectedIndex=0;
-}
-//-->
-</script>
-";
-}
-
-function display_monthcalendar($month, $year)
-{
-	global $MonthsLong;
-	global $DaysShort;
-	global $origin;
-
-	// grabbing all the calendar items for this year and storing it in a array
-	$data=get_calendar_items($month,$year);
-
-
-	//Handle leap year
-	$numberofdays = array(0,31,28,31,30,31,30,31,31,30,31,30,31);
-	if (($year%400 == 0) or ($year%4==0 and $year%100<>0)) $numberofdays[2] = 29;
-
-	//Get the first day of the month
-	$dayone = getdate(mktime(0,0,0,$month,1,$year));
-  	//Start the week on monday
-	$startdayofweek = $dayone['wday']<>0 ? ($dayone['wday']-1) : 6;
-
-	$backwardsURL = api_get_self()."?".api_get_cidreq()."&amp;origin=$origin&amp;month=".($month==1 ? 12 : $month-1)."&amp;year=".($month==1 ? $year-1 : $year);
-	$forewardsURL = api_get_self()."?".api_get_cidreq()."&amp;origin=$origin&amp;month=".($month==12 ? 1 : $month+1)."&amp;year=".($month==12 ? $year+1 : $year);
-
-	   $maand_array_maandnummer=$month-1;
-
-	echo "<table class=\"data_table\">\n",
-		"<tr>\n",
-		"<th width=\"10%\"><a href=\"",$backwardsURL,"\"> &laquo; </a></th>\n",
-		"<th width=\"80%\" colspan=\"5\">",$MonthsLong[$maand_array_maandnummer]," ",$year,"</th>\n",
-		"<th width=\"10%\"><a href=\"",$forewardsURL,"\"> &raquo; </a></th>\n",
-		"</tr>\n";
-
-	echo "<tr>\n";
-
-	for ($ii=1;$ii<8; $ii++)
-	{
-	echo "<td class=\"weekdays\" width=\"14%\">",$DaysShort[$ii%7],"</td>\n";
-  }
-
-	echo "</tr>\n";
-	$curday = -1;
-	$today = getdate();
-	while ($curday <=$numberofdays[$month])
-  	{
-	echo "<tr>\n";
-    	for ($ii=0; $ii<7; $ii++)
-	  	{
-	  		if (($curday == -1)&&($ii==$startdayofweek))
-			{
-	    		$curday = 1;
-			}
-			if (($curday>0)&&($curday<=$numberofdays[$month]))
-			{
-				$bgcolor = $ii<5 ? "class=\"row_odd\"" : "class=\"row_even\"";
-
-				$dayheader = "$curday";
-				if (key_exists($curday,$data))
-				{
-					$dayheader="<a href='".api_get_self()."?".api_get_cidreq()."&amp;view=list&amp;origin=$origin&amp;month=$month&amp;year=$year&amp;day=$curday#$curday'>".$curday."</a>";
-					foreach ($data[$curday] as $key=>$agenda_item)
-					{
-						foreach ($agenda_item as $key=>$value)
-						{
-							$dayheader .= '<br /><b>'.substr($value['start_date'],11,8).'</b>';
-							$dayheader .= ' - ';
-							$dayheader .= $value['title'];
-						}
-					}
-				}
-
-				if (($curday==$today['mday'])&&($year ==$today['year'])&&($month == $today['mon']))
-				{
-			echo "<td id=\"today\" ",$bgcolor,"\">".$dayheader." \n";
-      }
-				else
-				{
-			echo "<td id=\"days\" ",$bgcolor,"\">".$dayheader." \n";
-				}
-			echo "</td>\n";
-
-	      		$curday++;
-	    }
-	  		else
-	    {
-	echo "<td>&nbsp;</td>";
-
-	    }
-		}
-	echo "</tr>";
-    }
-echo "</table>";
-}
-/**
-* this function shows the form with the user that were not selected
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @return html code
-*/
-/**
-* This function stores the Agenda Item in the table calendar_event and updates the item_property table also
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @return integer the id of the last added agenda item
-*/
-function store_new_agenda_item()
-{
-	global $_user /*, $_course*/;
-	$TABLEAGENDA = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-    //$t_agenda_repeat = Database::get_course_Table(TABLE_AGENDA_REPEAT);
-
-	// some filtering of the input data
-	$title=strip_tags(trim($_POST['title'])); // no html allowed in the title
-	$content=trim($_POST['content']);
-	$start_date=(int)$_POST['fyear']."-".(int)$_POST['fmonth']."-".(int)$_POST['fday']." ".(int)$_POST['fhour'].":".(int)$_POST['fminute'].":00";
-    $end_date=(int)$_POST['end_fyear']."-".(int)$_POST['end_fmonth']."-".(int)$_POST['end_fday']." ".(int)$_POST['end_fhour'].":".(int)$_POST['end_fminute'].":00";
-
-	// store in the table calendar_event
-	 $sql = "INSERT INTO ".$TABLEAGENDA."
-					        (title,content, start_date, end_date)
-					        VALUES
-					        ('".$title."','".$content."', '".$start_date."','".$end_date."')";
-
-	$result = Database::query($sql,__FILE__,__LINE__) or die (Database::error());
-	$last_id=Database::insert_id();
-
-	// store in last_tooledit (first the groups, then the users
-	$to=$_POST['selectedform'];
-	/*	if ((!is_null($to))or (!empty($_SESSION['toolgroup']))) // !is_null($to): when no user is selected we send it to everyone
-	{
-		$send_to=separate_users_groups($to);
-		// storing the selected groups
-		if (is_array($send_to['groups']))
-		{
-			foreach ($send_to['groups'] as $group)
-			{
-				api_item_property_update($_course, TOOL_CALENDAR_EVENT, $last_id,"AgendaAdded", $_user['user_id'], $group,'',$start_date, $end_date);
-			}
-		}
-		// storing the selected users
-		if (is_array($send_to['users']))
-		{
-			foreach ($send_to['users'] as $user)
-			{
-				api_item_property_update($_course, TOOL_CALENDAR_EVENT, $last_id,"AgendaAdded", $_user['user_id'],'',$user, $start_date,$end_date);
-			}
-		}
-	}
-	else // the message is sent to everyone, so we set the group to 0
-	{
-		api_item_property_update($_course, TOOL_CALENDAR_EVENT, $last_id,"AgendaAdded", $_user['user_id'], '','',$start_date,$end_date);
-	}*/
-
-// storing the resources
-	//store_resources($_SESSION['source_type'],$last_id);
-
-    //if repetitive, insert element into agenda_repeat table
-/*    if(!empty($_POST['repeat']) && !empty($_POST['repeat_type']))
-    {
-    	if(!empty($_POST['repeat_end_year']) && !empty($_POST['repeat_end_month']) && !empty($_POST['repeat_end_day']))
-        {
-        	$end_y = intval($_POST['repeat_end_year']);
-            $end_m = intval($_POST['repeat_end_month']);
-            $end_d = intval($_POST['repeat_end_day']);
-            $end = mktime((int)$_POST['fhour'],(int)$_POST['fminute'],0,$end_m,$end_d,$end_y);
-            $now = time();
-            $type = Database::escape_string($_POST['repeat_type']);
-
-        	if($end > $now
-                && in_array($type,array('daily','weekly','monthlyByDate','monthlyByDay','monthlyByDayR','yearly')))
-            {
-        	   $sql = "INSERT INTO $t_agenda_repeat (cal_id, cal_type, cal_end)" .
-                    " VALUES ($last_id,'$type',$end)";
-               $res = Database::query($sql,__FILE__,__LINE__);
-            }
-        }
-    }
-	return $last_id;*/
-}
-
-/**
-* The links that allows the student AND course administrator to show all agenda items and sort up/down
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-function display_courseadmin_links() {
-	echo "<a href='".api_get_self()."?".api_get_cidreq()."&action=add&amp;origin=".Security::remove_XSS($_GET['origin'])."'>".Display::return_icon('calendar_personal_add.gif', get_lang('AgendaAdd'))." ".get_lang('AgendaAdd')."</a>";
-
-}
-function display_student_links()
-{
-	global $show;
-	if ($_SESSION['sort'] == 'DESC')
-	{
-		echo "<a href='".api_get_self()."?sort=asc&amp;origin=".$_GET['origin']."'>".Display::return_icon('calendar_up.gif',get_lang('AgendaSortChronologicallyUp')).' '.get_lang("AgendaSortChronologicallyUp")."</a>";
-	}
-	else
-	{
-		echo "<a href='".api_get_self()."?sort=desc&amp;origin=".$_GET['origin']."'>".Display::return_icon('calendar_down.gif',get_lang('AgendaSortChronologicallyDown')).' '.get_lang("AgendaSortChronologicallyDown")."</a>";
-	}
-	if ($_SESSION['view'] <> 'month')
-	{
-		echo "\t<a href=\"".api_get_self()."?action=view&amp;view=month\"><img src=\"../img/calendar_month.gif\" border=\"0\" alt=\"".get_lang('MonthView')."\" /> ".get_lang('MonthView')."</a>\n";
-	}
-	else
-	{
-		echo "\t<a href=\"".api_get_self()."?action=view&amp;view=list\"><img src=\"../img/calendar_select.gif\" border=\"0\" alt=\"".get_lang('ListView')."\" /> ".get_lang('ListView')."</a>\n";
-	}
-}
-/**
-* get all the information of the agenda_item from the database
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @param integer the id of the agenda item we are getting all the information of
-* @return an associative array that contains all the information of the agenda item. The keys are the database fields
-*/
-function get_agenda_item($id)
-{
-	$TABLEAGENDA = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-    //$t_agenda_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT);
-    $item = array();
-	if(empty($id))
-    {
-        $id=(int)addslashes($_GET['id']);
-    }
-    else
-    {
-    	$id = (int) $id;
-    }
-    if(empty($id)){return $item;}
-	$sql 					= "SELECT * FROM ".$TABLEAGENDA." WHERE id='".$id."'";
-	$result					= Database::query($sql,__FILE__,__LINE__);
-	$entry_to_edit 			= Database::fetch_array($result);
-	$item['title']			= $entry_to_edit["title"];
-	$item['content']		= $entry_to_edit["content"];
-	$item['start_date']		= $entry_to_edit["start_date"];
-	$item['end_date']		= $entry_to_edit["end_date"];
-	$item['to']				== "everyone";
-	// if the item has been sent to everybody then we show the compact to form
-	if ($item['to']=="everyone")
-	{
-		$_SESSION['allow_individual_calendar']="hide";
-	}
-	else
-	{
-		$_SESSION['allow_individual_calendar']="show";
-	}
-
-	return $item;
-}
-/**
-* This is the function that updates an agenda item. It does 3 things
-* 1. storethe start_date, end_date, title and message in the calendar_event table
-* 2. store the groups/users who this message is meant for in the item_property table
-* 3. modify the attachments (if needed)
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-function store_edited_agenda_item()
-{
-
-	// STEP 1: editing the calendar_event table
-	// 1.a.  some filtering of the input data
-	$id=(int)$_POST['id'];
-	$title=strip_tags(trim($_POST['title'])); // no html allowed in the title
-	$content=trim($_POST['content']);
-	$start_date=(int)$_POST['fyear']."-".(int)$_POST['fmonth']."-".(int)$_POST['fday']." ".(int)$_POST['fhour'].":".(int)$_POST['fminute'].":00";
-	$end_date=(int)$_POST['end_fyear']."-".(int)$_POST['end_fmonth']."-".(int)$_POST['end_fday']." ".(int)$_POST['end_fhour'].":".(int)$_POST['end_fminute'].":00";
-	$to=$_POST['selectedform'];
-	// 1.b. the actual saving in calendar_event table
-	$edit_result=save_edit_agenda_item($id,$title,$content,$start_date,$end_date);
-
-	echo '<br />';
-	Display::display_normal_message(get_lang("EditSuccess"));
-
-}
-
-/**
-* This function stores the Agenda Item in the table calendar_event and updates the item_property table also (after an edit)
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-function save_edit_agenda_item($id,$title,$content,$start_date,$end_date)
-{
-	$TABLEAGENDA = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-		$id=Database::escape_string($id);
-		$title=Database::escape_string($title);
-		$content=Database::escape_string($content);
-		$start_date=Database::escape_string($start_date);
-		$end_date=Database::escape_string($end_date);
-
-
-	// store the modifications in the table calendar_event
-	$sql = "UPDATE ".$TABLEAGENDA."
-								SET title='".$title."',
-									content='".$content."',
-									start_date='".$start_date."',
-									end_date='".$end_date."'
-								WHERE id='".$id."'";
-	$result = Database::query($sql,__FILE__,__LINE__) or die (Database::error());
-	return true;
-}
-
-/**
-* This is the function that deletes an agenda item.
-* The agenda item is no longer fycically deleted but the visibility in the item_property table is set to 2
-* which means that it is invisible for the student AND course admin. Only the platform administrator can see it.
-* This will in a later stage allow the platform administrator to recover resources that were mistakenly deleted
-* by the course administrator
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @param integer the id of the agenda item wa are deleting
-*/
-function delete_agenda_item($id)
-{
-	global $_course;
-	$id=Database::escape_string($id);
-	if (is_allowed_to_edit()  && !api_is_anonymous())
-	{
-		if (!empty($_GET['id']) && isset($_GET['action']) && $_GET['action']=="delete")
-		{
-		    $t_agenda     = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-            $id=(int)addslashes($_GET['id']);
-            $sql = "SELECT * FROM $t_agenda WHERE id = $id";
-            $res = Database::query($sql,__FILE__,__LINE__);
-            if(Database::num_rows($res)>0)
-            {
-                $sql = "DELETE FROM ".$t_agenda." WHERE id='$id'";
-                $result = Database::query($sql,__FILE__,__LINE__) or die (Database::error());
-            }
-			api_item_property_update($_course,TOOL_CALENDAR_EVENT,$id,'delete',api_get_user_id());
-			$id=null;
-			echo '<br />';
-			Display::display_normal_message(get_lang("AgendaDeleteSuccess"));
-		}
-	}
-
-}
-/**
-* Makes an agenda item visible or invisible for a student
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @param integer id the id of the agenda item we are changing the visibility of
-*/
-function showhide_agenda_item($id)
-{
-	global $nameTools;
-	/*==================================================
-				SHOW / HIDE A CALENDAR ITEM
-	  ==================================================*/
-	//  and $_GET['isStudentView']<>"false" is added to prevent that the visibility is changed after you do the following:
-	// change visibility -> studentview -> course manager view
-	if ((is_allowed_to_edit() && !api_is_anonymous()) and $_GET['isStudentView']<>"false")
-	{
-		if (isset($_GET['id'])&&$_GET['id']&&isset($_GET['action'])&&$_GET['action']=="showhide")
-		{
-			$id=(int)addslashes($_GET['id']);
-			change_visibility($nameTools,$id);
-			Display::display_normal_message(get_lang("VisibilityChanged"));
-		}
-	}
-}
-/**
-* Displays all the agenda items
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @author Yannick Warnier <yannick.warnier@dokeos.com> - cleanup
-*/
-function display_agenda_items()
-{
-	$TABLEAGENDA = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-	global $select_month, $select_year;
-	global $DaysShort, $DaysLong, $MonthsLong;
-	global $is_courseAdmin;
-	global $dateFormatLong, $timeNoSecFormat,$charset, $_user, $_course;
-
-	// getting the group memberships
-	//$group_memberships=GroupManager::get_group_ids($_course['dbName'],$_user['user_id']);
-
-	// getting the name of the groups
-	//$group_names=get_course_groups();
-
-	/*--------------------------------------------------
-			CONSTRUCT THE SQL STATEMENT
-	  --------------------------------------------------*/
-
-    $start = 0;
-    $stop = 0;
-	// this is to make a difference between showing everything (all months) or only the current month)
-	// $show_all_current is a part of the sql statement
-	if ($_SESSION['show']!=="showall")
-	{
-		$show_all_current=" AND MONTH(start_date)=$select_month AND year(start_date)=$select_year";
-        $start = mktime(0,0,0,$select_month,1,$select_year);
-        $stop = 0;
-        if(empty($select_year)){$select_year = date('Y');}
-        if(empty($select_month)){$select_month = date('m');}
-        if($select_month==12)
-        {
-            $stop = mktime(0,0,0,1,1,$select_year+1)-1;
-        }
-        else
-        {
-            $stop = mktime(0,0,0,$select_month+1,1,$select_year)-1;
-        }
-	}
-	else
-	{
-		$show_all_current="";
-        $start = time();
-        $stop = mktime(0,0,0,1,1,2038);//by default, set year to maximum for mktime()
-	}
-
-	// by default we use the id of the current user. The course administrator can see the agenda of other users by using the user / group filter
-
-    $repeats = array(); //placeholder for repeated events
-
-	if (is_allowed_to_edit() && !api_is_anonymous()) {
-		$sql="SELECT * FROM ".$TABLEAGENDA.' ORDER BY start_date '.$_SESSION['sort'];
-		//echo "<pre>".$sql."</pre>";
-		$result=Database::query($sql,__FILE__,__LINE__) or die(Database::error());
-		$number_items=Database::num_rows($result);
-	} else {
-		$number_items = 0;
-	}
-
-
-	/*--------------------------------------------------
-			DISPLAY: NO ITEMS
-	  --------------------------------------------------*/
-	if ($number_items==0)
-	{
-        echo "<table class=\"data_table\" ><tr><td>".get_lang("NoAgendaItems")."</td></tr></table>";
-	}
-
-	/*--------------------------------------------------
-			DISPLAY: THE ITEMS
-	  --------------------------------------------------*/
-
-    $month_bar="";
-    $event_list="";
-    $counter=0;
-    $export_icon = 'export.png';
-    $export_icon_low = 'export_low_fade.png';
-    $export_icon_high = 'export_high_fade.png';
-
-    while($myrow=Database::fetch_array($result))
-    {
-    	$is_repeated = !empty($myrow['parent_event_id']);
-	    echo '<table class="data_table">',"\n";
-        /*--------------------------------------------------
-        		display: the month bar
-         --------------------------------------------------*/
-        // Make the month bar appear only once.
-        if ($month_bar != date("m",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"])))
-		{
-            $month_bar = date("m",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"]));
-			echo "\t<tr>\n\t\t<td class=\"agenda_month_divider\" colspan=\"3\" valign=\"top\">".
-			api_ucfirst(format_locale_date("%B %Y",strtotime($myrow["start_date"]))).
-			"</td>\n\t</tr>\n";
-		}
-
-        /*--------------------------------------------------
-         display: the icon, title, destinees of the item
-         -------------------------------------------------*/
-    	echo '<tr>';
-
-    	// highlight: if a date in the small calendar is clicked we highlight the relevant items
-    	$db_date=(int)date("d",strtotime($myrow["start_date"])).date("n",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"]));
-    	if ($_GET["day"].$_GET["month"].$_GET["year"] <>$db_date)
-    	{
-    		if ($myrow['visibility']=='0')
-    		{
-    			$style="data_hidden";
-    			$stylenotbold="datanotbold_hidden";
-    			$text_style="text_hidden";
-    		}
-    		else
-    		{
-    			$style="data";
-    			$stylenotbold="datanotbold";
-    			$text_style="text";
-    		}
-
-    	}
-    	else
-    	{
-    		$style="datanow";
-    		$stylenotbold="datanotboldnow";
-    		$text_style="textnow";
-    	}
-
-    	echo "\t\t<th>\n";
-    	// adding an internal anchor
-    	echo "\t\t\t<a name=\"".(int)date("d",strtotime($myrow["start_date"]))."\"></a>";
-    	// the icons. If the message is sent to one or more specific users/groups
-    	// we add the groups icon
-    	// 2do: if it is sent to groups we display the group icon, if it is sent to a user we show the user icon
-    	Display::display_icon('agenda.gif', get_lang('Agenda'));
-    	if ($myrow['to_group_id']!=='0')
-    	{
-    		echo Display::return_icon('group.gif', get_lang('Group'));
-    	}
-    	echo " ".$myrow['title']."\n";
-    	echo "\t\t</th>\n";
-
-    	// the message has been sent to
-    	echo "\t\t<th>".get_lang("SentTo").": ".get_lang('AllUsersOfThePlatform');
-    	//$sent_to=sent_to(TOOL_CALENDAR_EVENT, $myrow["ref"]);
-    	//$sent_to_form=sent_to_form($sent_to);
-    //	echo $sent_to_form;
-    	echo "</th>";
-
-    	if (!$is_repeated && (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous())))
-    	{
-    		if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $myrow['id'] ) ) )
-			{ // a coach can only delete an element belonging to his session
-	    		echo '<th>'.get_lang('Modify');
-	    		echo '</th></tr>';
-			}
-    	}
-
-        /*--------------------------------------------------
-     			display: the title
-         --------------------------------------------------*/
-    	echo "<tr class='row_odd'>";
-    	echo "\t\t<td>".get_lang("StartTimeWindow").": ";
-    	echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["start_date"])))."&nbsp;&nbsp;&nbsp;";
-    	echo ucfirst(strftime($timeNoSecFormat,strtotime($myrow["start_date"])))."";
-    	echo "</td>\n";
-    	echo "\t\t<td>";
-    	if ($myrow["end_date"]<>"0000-00-00 00:00:00")
-    	{
-    		echo get_lang("EndTimeWindow").": ";
-    		echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["end_date"])))."&nbsp;&nbsp;&nbsp;";
-    		echo ucfirst(strftime($timeNoSecFormat,strtotime($myrow["end_date"])))."";
-    	}
-    	echo "</td>\n";
-
-    	// attachment list
-	    	//$attachment_list=get_attachment($myrow['id']);
-
-        /*--------------------------------------------------
-    	 display: edit delete button (course admin only)
-         --------------------------------------------------*/
-
-
-    	if (!$is_repeated && (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous())))
-    	{
-    		if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $myrow['id'] ) ) )
-			{ // a coach can only delete an element belonging to his session
-				$mylink = api_get_self().'?'.api_get_cidreq().'&amp;origin='.Security::remove_XSS($_GET['origin']).'&amp;id='.$myrow['id'];
-	    		echo '<td align="center">';
-	    		// edit
-    			echo '<a href="'.$mylink.'&amp;action=edit&amp;title="'.get_lang("ModifyCalendarItem").'">';
-	    		echo Display::return_icon('edit.gif', get_lang('ModifyCalendarItem'))."</a>";
-
-    			echo "<a href=\"".$mylink."&amp;action=delete\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."')) return false;\"  title=\"".get_lang("Delete")."\"> ";
-	    		echo Display::return_icon('delete.gif', get_lang('Delete'))."</a>";
-			}
-
-    	if (!$is_repeated && (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous())))
-    	{
-    		if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $myrow['id'] ) ) )
-			{ // a coach can only delete an element belonging to his session
-    			$td_colspan= '<td colspan="3">';
-			}
-			else
-			{
-				$td_colspan= '<td colspan="2">';
-			}
-    	}
-    	else
-    	{
-    		$td_colspan= '<td colspan="2">';
-    	}
-    	$mylink = 'calendar_ical_export.php?'.api_get_cidreq().'&amp;type=course&amp;id='.$myrow['id'];
-		echo '<a class="ical_export" href="'.$mylink.'&amp;class=confidential" title="'.get_lang('ExportiCalConfidential').'">'.Display::return_icon($export_icon_high, get_lang('ExportiCalConfidential')).'</a> ';
-    	echo '<a class="ical_export" href="'.$mylink.'&amp;class=private" title="'.get_lang('ExportiCalPrivate').'">'.Display::return_icon($export_icon_low, get_lang('ExportiCalPrivate')).'</a> ';
-    	echo '<a class="ical_export" href="'.$mylink.'&amp;class=public" title="'.get_lang('ExportiCalPublic').'">'.Display::return_icon($export_icon, get_lang('ExportiCalPublic')).'</a> ';
-	    echo '<a href="#" onclick="javascript:win_print=window.open(\'calendar_view_print.php?id='.$myrow['id'].'\',\'popup\',\'left=100,top=100,width=700,height=500,scrollbars=1,resizable=0\'); win_print.focus(); return false;">'.Display::return_icon('print.gif', get_lang('Print')).'</a>&nbsp;';
-    	echo '</td>';
-    	echo '</tr>';
-}
-
-        /*--------------------------------------------------
-     			display: the content
-         --------------------------------------------------*/
-    	$content = $myrow['content'];
-    	$content = make_clickable($content);
-    	$content = text_filter($content);
-    	echo "<tr class='row_even'>";
-    	echo "<td colspan='3'>";
-
-    	echo $content;
-    	// show attachment list
-			if (!empty($attachment_list)) {
-
-				$realname=$attachment_list['path'];
-				$user_filename=$attachment_list['filename'];
-				$full_file_name = 'download.php?file='.$realname;
-				echo Display::return_icon('attachment.gif',get_lang('Attachment'));
-				echo '<a href="'.$full_file_name.'';
-				echo ' "> '.$user_filename.' </a>';
-				echo '<span class="forum_attach_comment" >'.$attachment_list['comment'].'</span>';
-				if (api_is_allowed_to_edit()) {
-					echo '&nbsp;&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;origin='.Security::remove_XSS($_GET['origin']).'&amp;action=delete_attach&amp;id_attach='.$attachment_list['id'].'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset)).'\')) return false;">'.Display::return_icon('delete.gif',get_lang('Delete')).'</a><br />';
-				}
-
-			}
-
-	    echo '</td></tr>';
-
-
-        /*--------------------------------------------------
-     			display: the added resources
-         --------------------------------------------------
-    	if (check_added_resources("Agenda", $myrow["id"]))
-    	{
-
-    		echo '<tr>';
-    		echo '<td colspan="3">';
-    		echo "<i>".get_lang("AddedResources")."</i><br/>";
-    		if ($myrow['visibility']==0)
-    		{
-    			$addedresource_style="invisible";
-    		}
-    		display_added_resources("Agenda", $myrow["id"], $addedresource_style);
-    		echo "</td></tr>";
-    	}*/
-
-
-    	$event_list.=$myrow['id'].',';
-
-    	$counter++;
-        /*--------------------------------------------------
-    	 display: jump-to-top icon
-         --------------------------------------------------*/
-    	echo '<tr>';
-        echo '<td colspan="3">';
-        if($is_repeated){echo get_lang('RepeatedEvent'),'<a href="',api_get_self(),'?',api_get_cidreq,'&amp;agenda_id=',$myrow['parent_event_id'],'" alt="',get_lang('RepeatedEventViewOriginalEvent'),'">',get_lang('RepeatedEventViewOriginalEvent'),'</a>';}
-    	echo "<a href=\"#top\">".Display::return_icon('top.gif', get_lang('Top'))."</a></td></tr>";
-    	echo "</table><br /><br />";
-    } // end while ($myrow=Database::fetch_array($result))
-
-    if(!empty($event_list))
-    {
-    	$event_list=substr($event_list,0,-1);
-    }
-    else
-    {
-    	$event_list='0';
-    }
-
-    echo "<form name=\"event_list_form\"><input type=\"hidden\" name=\"event_list\" value=\"$event_list\" /></form>";
-
-    // closing the layout table
-    echo "</td>",
-    	"</tr>",
-    	"</table>";
-}
-
-/**
-* Displays only 1 agenda item. This is used when an agenda item is added to the learning path.
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-function display_one_agenda_item($agenda_id)
-{
-	$TABLEAGENDA = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-	global $TABLE_ITEM_PROPERTY;
-	global $select_month, $select_year;
-	global $DaysShort, $DaysLong, $MonthsLong;
-	global $is_courseAdmin;
-	global $dateFormatLong, $timeNoSecFormat, $charset;
-	global $_user;
-	$agenda_id=Database::escape_string($agenda_id);
-	//echo "displaying agenda items";
-
-	// getting the name of the groups
-	//$group_names=get_course_groups();
-
-	/*--------------------------------------------------
-			CONSTRUCT THE SQL STATEMENT
-	  --------------------------------------------------*/
-
-	$sql="SELECT *	FROM ".$TABLEAGENDA;
-	$result=Database::query($sql,__FILE__,__LINE__) or die(Database::error());
-	$number_items=Database::num_rows($result);
-	$myrow=Database::fetch_array($result); // there should be only one item so no need for a while loop
-
-    $sql_rep = "SELECT * FROM $TABLEAGENDA WHERE id = $agenda_id";
-    $res_rep = Database::query($sql_rep,__FILE__,__LINE__);
-    $repeat = false;
-    $repeat_id = 0;
-    if(Database::num_rows($res_rep)>0)
-    {
-        $repeat=true;
-        $row_rep = Database::fetch_array($res_rep);
-        //$repeat_id = $row_rep['parent_event_id'];
-    }
-
-	/*--------------------------------------------------
-			DISPLAY: NO ITEMS
-	  --------------------------------------------------*/
-	if ($number_items==0)
-	{
-		echo "<table id=\"data_table\" ><tr><td>".get_lang("NoAgendaItems")."</td></tr></table>";
-	}
-
-	/*--------------------------------------------------
-			DISPLAY: THE ITEMS
-	  --------------------------------------------------*/
-	echo "<table id=\"data_table\">\n";
-
-	/*--------------------------------------------------
-	 DISPLAY : the icon, title, destinees of the item
-	  --------------------------------------------------*/
-	echo "\t<tr>\n";
-
-	// highlight: if a date in the small calendar is clicked we highlight the relevant items
-	$db_date=(int)date("d",strtotime($myrow["start_date"])).date("n",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"]));
-	if ($_GET["day"].$_GET["month"].$_GET["year"] <>$db_date)
-	{
-		if ($myrow['visibility']=='0')
-		{
-			$style="data_hidden";
-			$stylenotbold="datanotbold_hidden";
-			$text_style="text_hidden";
-		}
-		else
-		{
-			$style="data";
-			$stylenotbold="datanotbold";
-			$text_style="text";
-		}
-	}
-	else
-	{
-		$style="datanow";
-		$stylenotbold="datanotboldnow";
-		$text_style="textnow";
-	}
-
-
-	echo "\t\t<td class=\"".$style."\">\n";
-
-	// adding an internal anchor
-	echo "\t\t\t<a name=\"".(int)date("d",strtotime($myrow["start_date"]))."\"></a>";
-
-	// the icons. If the message is sent to one or more specific users/groups
-	// we add the groups icon
-	// 2do: if it is sent to groups we display the group icon, if it is sent to a user we show the user icon
-	echo Display::return_icon('agenda.gif');
-	if ($myrow['to_group_id']!=='0')
-	{
-		echo Display::return_icon('group.gif');
-	}
-	echo " ".$myrow['title']."\n";
-	echo "\t\t</td>\n";
-
-	// the message has been sent to
-	echo "\t\t<td class=\"".$stylenotbold."\">".get_lang("SentTo").": ".get_lang('AllUsersOfThePlatform');
-	$sent_to=sent_to(TOOL_CALENDAR_EVENT, $myrow["ref"]);
-	$sent_to_form=sent_to_form($sent_to);
-	echo $sent_to_form;
-	echo "</td>\n\t</tr>\n";
-
-	/*--------------------------------------------------
-	 			DISPLAY: the title
-	  --------------------------------------------------*/
-	echo "\t<tr class=\"".$stylenotbold."\">\n";
-	echo "\t\t<td>".get_lang("StartTime").": ";
-	echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["start_date"])))."&nbsp;&nbsp;&nbsp;";
-	echo ucfirst(strftime($timeNoSecFormat,strtotime($myrow["start_date"])))."";
-	echo "</td>\n";
-	echo "\t\t<td>".get_lang("EndTime").": ";
-	echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["end_date"])))."&nbsp;&nbsp;&nbsp;";
-	echo ucfirst(strftime($timeNoSecFormat,strtotime($myrow["end_date"])))."";
-	echo "</td>\n";
-	echo "\n\t</tr>\n";
-
-	/*--------------------------------------------------
-	 			DISPLAY: the content
-	  --------------------------------------------------*/
-    $export_icon = '../img/export.png';
-    $export_icon_low = '../img/export_low_fade.png';
-    $export_icon_high = '../img/export_high_fade.png';
-
-	$content = $myrow['content'];
-	$content = make_clickable($content);
-	$content = text_filter($content);
-	//echo "\t<tr>\n\t\t<td class=\"".$text_style."\" colspan='2'>";
-	//echo $content;
-	//echo "</td></tr>";
-    echo "<tr class='row_even'>";
-    echo '<td colspan="2">';
-    echo $content;
-    echo '</td></tr>';
-
-	/*--------------------------------------------------
-	 			DISPLAY: the added resources
-	  --------------------------------------------------*/
-	if (check_added_resources("Agenda", $myrow["id"]))
-		{
-		echo "<tr><td colspan='2'>";
-		echo "<i>".get_lang("AddedResources")."</i><br/>";
-		if ($myrow['visibility']==0)
-		{
-			$addedresource_style="invisible";
-		}
-		display_added_resources("Agenda", $myrow["id"], $addedresource_style);
-		echo "</td></tr>";
-		}
-
-	/*--------------------------------------------------
-		DISPLAY: edit delete button (course admin only)
-	  --------------------------------------------------*/
-	echo '<tr><td colspan="2">';
-	if (!$repeat && api_is_allowed_to_edit(false,true))	{
-		// edit
-		$mylink = api_get_self()."?".api_get_cidreq()."&amp;origin=".Security::remove_XSS($_GET['origin'])."&amp;id=".$myrow['id'];
-		echo 	"<a href=\"".$mylink."&amp;action=edit\">",
-				Display::return_icon('edit.gif', get_lang('ModifyCalendarItem')), "</a>",
-				"<a href=\"".$mylink."&amp;action=delete\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."')) return false;\">",
-				Display::return_icon('delete.gif', get_lang('Delete')),"</a>";
-		if ($myrow['visibility']==1) {
-			$image_visibility="visible";
-		} else {
-			$image_visibility="invisible";
-		}
-		echo 	'<a href="'.$mylink.'&amp;action=showhide">',Display::return_icon($image_visibility, get_lang('Visible')),'</a><br /><br />';
-	}
-   	$mylink = 'calendar_ical_export.php?'.api_get_cidreq().'&amp;type=course&amp;id='.$myrow['id'];
-    echo '<a class="ical_export" href="'.$mylink.'&amp;class=confidential" title="'.get_lang('ExportiCalConfidential').'">'.Display::return_icon($export_icon_high, get_lang('ExportiCalConfidential')).'</a> ';
-    	echo '<a class="ical_export" href="'.$mylink.'&amp;class=private" title="'.get_lang('ExportiCalPrivate').'">'.Display::return_icon($export_icon_low, get_lang('ExportiCalPrivate')).'</a> ';
-    	echo '<a class="ical_export" href="'.$mylink.'&amp;class=public" title="'.get_lang('ExportiCalPublic').'">'.Display::return_icon($export_icon, get_lang('ExportiCalPublic')).'</a> ';
-    echo '<a href="#" onclick="javascript:win_print=window.open(\'calendar_view_print.php?id='.$myrow['id'].'\',\'popup\',\'left=100,top=100,width=700,height=500,scrollbars=1,resizable=0\'); win_print.focus(); return false;">'.Display::return_icon('print.gif', get_lang('Print')).'</a>&nbsp;';
-	echo "</td>";
-    if($repeat) {
-    	echo '<tr>';
-    	echo '<td colspan="2">',get_lang('RepeatedEvent'),'<a href="',api_get_self(),'?',api_get_cidreq(),'&amp;agenda_id=',$repeat_id,'" alt="',get_lang('RepeatedEventViewOriginalEvent'),'">',get_lang('RepeatedEventViewOriginalEvent'),'</a></td>';
-        echo '</tr>';
-    }
-	echo "</table>";
-
-	// closing the layout table
-	echo "</td>",
-		"</tr>",
-		"</table>";
-}
-/**
-* Show the form for adding a new agenda item. This is the same function that is used whenever we are editing an
-* agenda item. When the id parameter is empty (default behaviour), then we show an empty form, else we are editing and
-* we have to retrieve the information that is in the database and use this information in the forms.
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @param integer id, the id of the agenda item we are editing. By default this is empty which means that we are adding an
-*		 agenda item.
-*/
-function show_group_filter_form()
-{
-$group_list=get_course_groups();
-
-echo "<select name=\"select\" onchange=\"MM_jumpMenu('parent',this,0)\">";
-echo "<option value=\"agenda.php?group=none\">show all groups</option>";
-/*foreach($group_list as $this_group)
-	{
-	// echo "<option value=\"agenda.php?isStudentView=true&amp;group=".$this_group['id']."\">".$this_group['name']."</option>";
-	echo "<option value=\"agenda.php?group=".$this_group['id']."\" ";
-	echo ($this_group['id']==$_SESSION['group'])? " selected":"" ;
-	echo ">".$this_group['name']."</option>";
-	}*/
-echo "</select>";
-}
-
-function show_user_filter_form()
-{
-$user_list=get_course_users();
-
-//echo "<select name=\"select\" onchange=\"MM_jumpMenu('parent',this,0)\">";
-//echo "<option value=\"agenda.php?user=none\">show all users</option>";
-/*foreach($user_list as $this_user)
-	{
-	// echo "<option value=\"agenda.php?isStudentView=true&amp;user=".$this_user['uid']."\">".$this_user['lastName']." ".$this_user['firstName']."</option>";
-	echo "<option value=\"agenda.php?user=".$this_user['uid']."\" ";
-	echo ($this_user['uid']==$_SESSION['user'])? " selected":"" ;
-	echo ">".$this_user['lastName']." ".$this_user['firstName']."</option>";
-	}*/
-echo "</select>";
-}
-
-function show_user_group_filter_form()
-{
-	echo "\n<select name=\"select\" onchange=\"MM_jumpMenu('parent',this,0)\">";
-	echo "\n\t<option value=\"agenda.php?user=none\">".get_lang("ShowAll")."</option>";
-
-	// Groups
-	echo "\n\t<optgroup label=\"".get_lang("Groups")."\">";
-	$group_list=get_course_groups();
-/*	foreach($group_list as $this_group)
-	{
-		// echo "<option value=\"agenda.php?isStudentView=true&amp;group=".$this_group['id']."\">".$this_group['name']."</option>";
-		echo "\n\t\t<option value=\"agenda.php?group=".$this_group['id']."\" ";
-		echo ($this_group['id']==$_SESSION['group'])? " selected":"" ;
-		echo ">".$this_group['name']."</option>";
-	}*/
-	echo "\n\t</optgroup>";
-
-	// Users
-	echo "\n\t<optgroup label=\"".get_lang("Users")."\">";
-	$user_list=get_course_users();
-/*	foreach($user_list as $this_user)
-		{
-		// echo "<option value=\"agenda.php?isStudentView=true&amp;user=".$this_user['uid']."\">".$this_user['lastName']." ".$this_user['firstName']."</option>";
-		echo "\n\t\t<option value=\"agenda.php?user=".$this_user['uid']."\" ";
-		echo ($this_user['uid']==$_SESSION['user'])? " selected":"" ;
-		echo ">".$this_user['lastName']." ".$this_user['firstName']."</option>";
-		}*/
-	echo "\n\t</optgroup>";
-	echo "</select>";
-}
-
-function show_add_form($id = '')
-{
-
-	global $MonthsLong;
-	$htmlHeadXtra[] = to_javascript();
-	// the default values for the forms
-	if ($_GET['originalresource'] !== 'no')
-	{
-		$day	= date('d');
-		$month	= date('m');
-		$year	= date('Y');
-		$hours	= 9;
-		$minutes= '00';
-
-		$end_day	= date('d');
-		$end_month	= date('m');
-		$end_year	= date('Y');
-		$end_hours	= 17;
-		$end_minutes= '00';
-        $repeat = false;
-	}
-	else
-	{
-
-		// we are coming from the resource linker so there might already have been some information in the form.
-		// When we clicked on the button to add resources we stored every form information into a session and now we
-		// are doing the opposite thing: getting the information out of the session and putting it into variables to
-		// display it in the forms.
-		$form_elements=$_SESSION['formelements'];
-		$day=$form_elements['day'];
-		$month=$form_elements['month'];
-		$year=$form_elements['year'];
-		$hours=$form_elements['hour'];
-		$minutes=$form_elements['minutes'];
-		$end_day=$form_elements['end_day'];
-		$end_month=$form_elements['end_month'];
-		$end_year=$form_elements['end_year'];
-		$end_hours=$form_elements['end_hours'];
-		$end_minutes=$form_elements['end_minutes'];
-		$title=$form_elements['title'];
-		$content=$form_elements['content'];
-		$id=$form_elements['id'];
-		$to=$form_elements['to'];
-        $repeat = $form_elements['repeat'];
-	}
-
-
-	//	switching the send to all/send to groups/send to users
-	if ($_POST['To'])
-	{
-			$day			= $_POST['fday'];
-			$month			= $_POST['fmonth'];
-			$year			= $_POST['fyear'];
-			$hours			= $_POST['fhour'];
-			$minutes		= $_POST['fminute'];
-			$end_day		= $_POST['end_fday'];
-			$end_month		= $_POST['end_fmonth'];
-			$end_year		= $_POST['end_fyear'];
-			$end_hours		= $_POST['end_fhour'];
-			$end_minutes	= $_POST['end_fminute'];
-			$title 			= $_POST['title'];
-			$content		= $_POST['content'];
-			// the invisible fields
-			$action			= $_POST['action'];
-			$id				= $_POST['id'];
-            $repeat         = !empty($_POST['repeat'])?true:false;
-		}
-
-
-	// if the id is set then we are editing an agenda item
-	if (is_int($id))
-	{
-		//echo "before get_agenda_item".$_SESSION['allow_individual_calendar'];
-		$item_2_edit=get_agenda_item($id);
-		$title	= $item_2_edit['title'];
-		$content= $item_2_edit['content'];
-		// start date
-		list($datepart, $timepart) = split(" ", $item_2_edit['start_date']);
-		list($year, $month, $day) = explode("-", $datepart);
-		list($hours, $minutes, $seconds) = explode(":", $timepart);
-		// end date
-		list($datepart, $timepart) = split(" ", $item_2_edit['end_date']);
-		list($end_year, $end_month, $end_day) = explode("-", $datepart);
-		list($end_hours, $end_minutes, $end_seconds) = explode(":", $timepart);
-		// attachments
-		//edit_added_resources("Agenda", $id);
-		$to=$item_2_edit['to'];
-		//echo "<br />after get_agenda_item".$_SESSION['allow_individual_calendar'];
-	}
-	$content=stripslashes($content);
-	$title=stripslashes($title);
-	// we start a completely new item, we do not come from the resource linker
-	if ($_GET['originalresource']!=="no" and $_GET['action']=="add")
-	{
-
-		$_SESSION["formelements"]=null;
-		//unset_session_resources();//--------------------------------------------------------------------------------------
-	}
-?>
-
-<!-- START OF THE FORM  -->
-<form enctype="multipart/form-data"  action="<?php echo api_get_self().'?origin='.$_GET['origin'].'&amp;action='.$_GET['action']; ?>" method="post" name="new_calendar_item">
-<input type="hidden" name="id" value="<?php if (isset($id)) echo $id; ?>" />
-<input type="hidden" name="action" value="<?php if (isset($_GET['action'])) echo $_GET['action']; ?>" />
-<input type="hidden" name="sort" value="asc" />
-<input type="hidden" name="submit_event" value="ok" />
-<?php
-	echo '<div class="row"><div class="form_header">';
-	echo (isset($id) AND $id<>'')?get_lang('ModifyCalendarItem'):get_lang("AddCalendarItem");
-	echo '</div></div>';
-	?>
-<table border="0" cellpadding="5" cellspacing="0" width="80%" id="newedit_form">
-	<!-- START date and time -->
-<tr>
-<div>
-<table border="0" width="80%">
-				<tr><td colspan="4">
-					<div id="err_date" style="display:none;color:red"></div>
-					<div id="err_start_date" style="display:none;color:red"></div>
-				</td></tr>
-				<td width="10%">
-					<!-- date: 1 -> 31 -->
-					<nobr><?php echo get_lang('StartDate').": \n"; ?></nobr>
-				</td>
-				<td width="35%">
-					<select name="fday" onchange="javascript:document.new_calendar_item.end_fday.value=this.value;">
-							<?php
-							// small loop for filling all the dates
-							// 2do: the available dates should be those of the selected month => february is from 1 to 28 (or 29) and not to 31
-							echo "\n";
-							foreach (range(1, 31) as $i)
-											{
-											// values have to have double digits
-											$value = ($i <= 9 ? '0'.$i : $i );
-											// the current day is indicated with [] around the date
-											if ($value==$day)
-											{
-												echo "\t\t\t\t <option value=\"".$value."\" selected> ".$i." </option>\n";
-											}
-											else
-											{
-												echo "\t\t\t\t<option value=\"$value\">$i</option>\n";
-											}
-										}
-										 ?>
-					</select>
-					<!-- month: january -> december -->
-					<select name="fmonth" onchange="javascript:document.new_calendar_item.end_fmonth.value=this.value;">
-					<?php
-											echo "\n";
-											for ($i=1; $i<=12; $i++)
-											{
-												// values have to have double digits
-												if ($i<=9)
-												{
-													$value="0".$i;
-												}
-												else
-												{
-													$value=$i;
-												}
-												if ($value==$month)
-												{
-													echo "\t\t\t\t <option value=\"".$value."\" selected>".$MonthsLong[$i-1]."</option>\n";
-												}
-												else
-												{
-													echo "\t\t\t\t <option value=\"".$value."\">".$MonthsLong[$i-1]."</option>\n";
-												}
-											} ?>
-					</select>
-					<select name="fyear" onchange="javascript:document.new_calendar_item.end_fyear.value=this.value;">
-										<option value="<?php echo ($year-1); ?>"><?php echo ($year-1); ?></option>
-											<option value="<?php echo $year; ?>" selected="selected"><?php echo $year; ?></option>
-											<?php
-												echo "\n";
-												for ($i=1; $i<=5; $i++)
-												{
-													$value=$year+$i;
-													echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
-												} ?>
-					</select>
-					<a href="javascript:openCalendar('new_calendar_item','f')"><?php Display::display_icon('calendar_select.gif', get_lang('Select'), array ('style' => 'vertical-align: middle;')); ?></a>
-					</td>
-					<td width="10%">
-						<nobr><?php echo get_lang('StartTime').": \n"; ?></nobr>
-					</td>
-					<td>
-						<select name="fhour" onchange="javascript:document.new_calendar_item.end_fhour.value=this.value;">
-							<!-- <option value="--">--</option> -->
-							<?php
-								echo "\n";
-								foreach (range(0, 23) as $i)
-								{
-									// values have to have double digits
-									$value = ($i <= 9 ? '0'.$i : $i );
-									// the current hour is indicated with [] around the hour
-									if ($hours==$value)
-									{
-										echo "\t\t\t\t<option value=\"".$value."\" selected> ".$value." </option>\n";
-									}
-									else
-									{
-										echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
-									}
-								} ?>
-						</select>
-
-						<select name="fminute" onchange="javascript:document.new_calendar_item.end_fminute.value=this.value;">
-							<!-- <option value="<?php echo $minutes ?>"><?php echo $minutes; ?></option> -->
-							<!-- <option value="--">--</option> -->
-							<?php
-								foreach (range(0, 59) as $i)
-								{
-									// values have to have double digits
-									$value = ($i <= 9 ? '0'.$i : $i );
-									echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
-								} ?>
-						</select>
-					</td>
-
-</div>
-</tr>
-			<!-- END date and time -->
-<tr>
-<div>
-					<tr><td colspan="4"><div id="err_end_date" style="display:none;color:red"></div></td></tr>
-					<td >
-							<!-- date: 1 -> 31 -->
-							<nobr><?php echo get_lang('EndDate').": "; ?></nobr>
-					</td>
-					<td  >
-						<select name="end_fday">
-							<?php
-								// small loop for filling all the dates
-								// 2do: the available dates should be those of the selected month => february is from 1 to 28 (or 29) and not to 31
-								echo "\n";
-								foreach (range(1, 31) as $i)
-								{
-									// values have to have double digits
-									$value = ($i <= 9 ? '0'.$i : $i );
-									// the current day is indicated with [] around the date
-									if ($value==$end_day)
-										{ echo "\t\t\t\t <option value=\"".$value."\" selected> ".$i." </option>\n";}
-									else
-										{ echo "\t\t\t\t <option value=\"".$value."\">".$i."</option>\n"; }
-									}?>
-						</select>
-							<!-- month: january -> december -->
-						<select name="end_fmonth">
-								<?php
-								echo "\n";
-								foreach (range(1, 12) as $i)
-								{
-									// values have to have double digits
-									$value = ($i <= 9 ? '0'.$i : $i );
-									if ($value==$end_month)
-										{ echo "\t\t\t\t <option value=\"".$value."\" selected>".$MonthsLong[$i-1]."</option>\n"; }
-									else
-										{ echo "\t\t\t\t <option value=\"".$value."\">".$MonthsLong[$i-1]."</option>\n"; }
-									}?>
-						</select>
-						<select name="end_fyear">
-								<option value="<?php echo ($end_year-1) ?>"><?php echo ($end_year-1) ?></option>
-								<option value="<?php echo $end_year ?>" selected> <?php echo $end_year ?> </option>
-								<?php
-								echo "\n";
-								for ($i=1; $i<=5; $i++)
-								{
-									$value=$end_year+$i;
-									echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
-								} ?>
-						</select>
-						<a href="javascript:openCalendar('new_calendar_item', 'end_f')"><?php Display::display_icon('calendar_select.gif',get_lang('Select'), array ('style' => 'vertical-align: middle;')); ?></a>
-					</td>
-					<td >
-						<nobr><?php echo get_lang('EndTime').": \n"; ?></nobr>
-					</td>
-					<td >
-						<select name="end_fhour">
-							<!-- <option value="--">--</option> -->
-							<?php
-								echo "\n";
-								foreach (range(0, 23) as $i)
-								{
-									// values have to have double digits
-									$value = ($i <= 9 ? '0'.$i : $i );
-									// the current hour is indicated with [] around the hour
-									if ($end_hours==$value)
-										{ echo "\t\t\t\t<option value=\"".$value."\" selected> ".$value." </option>\n"; }
-									else
-										{ echo "\t\t\t\t<option value=\"".$value."\"> ".$value." </option>\n"; }
-								} ?>
-						</select>
-
-						<select name="end_fminute">
-							<!-- <option value="<?php echo $end_minutes; ?>"><?php echo $end_minutes; ?></option> -->
-							<!-- <option value="--">--</option> -->
-							<?php
-								foreach (range(0, 59) as $i)
-								{
-									// values have to have double digits
-									$value = ($i <= 9 ? '0'.$i : $i );
-									echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
-								} ?>
-						</select>
-						<br>
-				</td>
-</div>
-</tr>
-<tr><td colspan="4">
-<hr noshade="noshade" color="#cccccc" />
-	<div id="err_title" style="display:none;color:red"></div>
-</td></tr>
-<tr class="subtitle">
-		<td colspan="4" valign="top"><?php echo get_lang('ItemTitle'); ?> :
-			<!--<div style='margin-left: 80px'><textarea name="title" cols="50" rows="2" wrap="virtual" style="vertical-align:top; width:75%; height:50px;"><?php  if (isset($title)) echo $title; ?></textarea></div>-->
-			<input type="text" size="60" name="title" value="<?php  if (isset($title)) echo $title; ?>" />
-		</td>
-	</tr>
-
-	<tr>
-		<td colspan="4">
-
-			<?php
-			require_once(api_get_path(LIBRARY_PATH) . "/fckeditor/fckeditor.php");
-
-			$oFCKeditor = new FCKeditor('content') ;
-
-			$oFCKeditor->ToolbarSet = 'GlobalAgenda';
-			$oFCKeditor->Width		= '100%';
-			$oFCKeditor->Height		= '175';
-			$oFCKeditor->Value		= $content;
-
-			$return =	$oFCKeditor->CreateHtml();
-
-			echo $return;
-
- ?>
-		</td>
-	</tr>
-	<!--<?php /* ADDED BY UGENT, Patrick Cool, march 2004 */ ?>
-	<tr>
-		<td colspan="4">
-	    <?php
-			//onclick="selectAll(this.form.elements[6],true)"
-
-//				show_addresource_button('onclick="selectAll(this.form.elements[6],true)"');
-
-		?>
-		</td>
-	</tr>-->
-	<?php
-	   //if ($_SESSION['addedresource'])
-	   echo "\t<tr>\n";
-	   echo "\t\t<td colspan=\"4\">\n";
-	   //echo display_resources(0);//--------------------------------------------------------
-	   $test=$_SESSION['addedresource'];
-	   echo "\t\t</td>\n\t</tr>\n";
-	   /* END ADDED BY UGENT, Patrick Cool, march 2004 */
-    if(empty($id)) //only show repeat fields when adding the first time
-    {
-	?>
-
-    <tr>
-      <td colspan="4" />
-    </tr>
-    <?php
-    }//only show repeat fields if adding, not if editing
-    ?>
-	<tr>
-		<td colspan="4">
-		<?php
-		if ($_GET['action']=='edit'){
-			$class='save';
-			$text=get_lang('ModifyEvent');
-
-		}else{
-			$class='add';
-			$text=get_lang('AddEvent');
-		}
-		?>
-		<button type="button" class="add" value="<?php echo get_lang('Ok'); ?>" onclick="validate_date()" ><?php echo $text;  ?></button>
-
-		</td>
-	</tr>
-</table>
-</form>
-<?php
-}
-
-function get_agendaitems($month, $year)
-{
-	global $_user;
-	global $_configuration;
-	$month=Database::escape_string($month);
-	$year=Database::escape_string($year);
-
-	$items = array ();
-
-	//databases of the courses
-	$TABLEAGENDA = Database :: get_course_table(TABLE_MAIN_SYSTEM_CALENDAR);
-	//$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-
-	//$group_memberships = GroupManager :: get_group_ids(Database::get_current_course_database(), $_user['user_id']);
-	// if the user is administrator of that course we show all the agenda items
-	//if (api_is_allowed_to_edit())
-	//{
-		//echo "course admin";
-		$sqlquery = "SELECT
-						DISTINCT *
-						FROM ".$TABLEAGENDA."
-						WHERE
-						MONTH(start_date)='".$month."'
-						AND YEAR(start_date)='".$year."'
-						GROUP BY id
-						ORDER BY start_date ";
-	//}
-	// if the user is not an administrator of that course
-/*	else
-	{
-		//echo "GEEN course admin";
-		if (is_array($group_memberships) && count($group_memberships)>0)
-		{
-			$sqlquery = "SELECT
-							agenda.*
-							FROM ".$TABLEAGENDA."
-							WHERE
-							MONTH(agenda.start_date)='".$month."'
-							AND YEAR(agenda.start_date)='".$year."'
-							ORDER BY start_date ";
-		}
-		else
-		{
-			$sqlquery = "SELECT
-							agenda.*, item_property.*
-							FROM ".$TABLEAGENDA."
-							WHERE
-							MONTH(agenda.start_date)='".$month."'
-							AND YEAR(agenda.start_date)='".$year."'
-							ORDER BY start_date ";
-		}
-	}*/
-
-	//$mycourse = api_get_course_info();
-	$portal_url = $_configuration['root_web'];
-	if ($_configuration['multiple_access_urls']==true) {
-		$access_url_id = api_get_current_access_url_id();
-		if ($access_url_id != -1 ){
-			$url = api_get_access_url($access_url_id);
-			$portal_url = $url['url'];
-		}
-	}
-
-    $result = Database::query($sqlquery, __FILE__, __LINE__);
-	while ($item = Database::fetch_array($result))
-	{
-		$agendaday = date('j',strtotime($item['start_date']));
-		$time= date('H:i',strtotime($item['start_date']));
-		$URL = $portal_url.'main/admin/agenda.php?day='.$agendaday."&amp;month=".$month."&amp;year=".$year; // RH  //Patrick Cool: to highlight the relevant agenda item
-		$items[$agendaday][$item['start_time']] .= '<i>'.$time.'</i> <a href="'.$URL.'" title="'.$item['title'].'<br />';
-	}
-
-	// sorting by hour for every day
-	$agendaitems = array ();
-	while (list ($agendaday, $tmpitems) = each($items))
-	{
-		sort($tmpitems);
-		while (list ($key, $val) = each($tmpitems))
-		{
-			$agendaitems[$agendaday] .= $val;
-		}
-	}
-	return $agendaitems;
-}
-
-function display_upcoming_events()
-{
-	echo '<b>'.get_lang('UpcomingEvent').'</b><br />';
-	$number_of_items_to_show = (int)api_get_setting('number_of_upcoming_events');
-
-	//databases of the courses
-	$TABLEAGENDA = Database :: get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-	//$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-    //$mycourse = api_get_course_info();
-    //$myuser = api_get_user_info();
-
-	//$group_memberships = GroupManager :: get_group_ids($mycourse['dbName'], $myuser['user_id']);
-	// if the user is administrator of that course we show all the agenda items
-	/*if (api_is_allowed_to_edit())
-	{*/
-		//echo "course admin";
-		$sqlquery = "SELECT
-						DISTINCT *
-						FROM ".$TABLEAGENDA."
-						ORDER BY start_date ";
-	//}
-	// if the user is not an administrator of that course
-	$result = Database::query($sqlquery, __FILE__, __LINE__);
-	$counter = 0;
-	while ($item = Database::fetch_array($result,'ASSOC'))
-	{
-		if ($counter < $number_of_items_to_show)
-		{
-			echo $item['start_date'],' - ',$item['title'],'<br />';
-			$counter++;
-		}
-	}
-}
-/**
- * This function calculates the startdate of the week (monday)
- * and the enddate of the week (sunday)
- * and returns it as an array
- */
-function calculate_start_end_of_week($week_number, $year)
-{
-	// determine the start and end date
-	// step 1: we calculate a timestamp for a day in this week
-	$random_day_in_week = mktime(0, 0, 0, 1, 1, $year) + ($week_number-1) * (7 * 24 * 60 * 60); // we calculate a random day in this week
-	// step 2: we which day this is (0=sunday, 1=monday, ...)
-	$number_day_in_week = date('w', $random_day_in_week);
-	// step 3: we calculate the timestamp of the monday of the week we are in
-	$start_timestamp = $random_day_in_week - (($number_day_in_week -1) * 24 * 60 * 60);
-	// step 4: we calculate the timestamp of the sunday of the week we are in
-	$end_timestamp = $random_day_in_week + ((7 - $number_day_in_week +1) * 24 * 60 * 60) - 3600;
-	// step 5: calculating the start_day, end_day, start_month, end_month, start_year, end_year
-	$start_day = date('j', $start_timestamp);
-	$start_month = date('n', $start_timestamp);
-	$start_year = date('Y', $start_timestamp);
-	$end_day = date('j', $end_timestamp);
-	$end_month = date('n', $end_timestamp);
-	$end_year = date('Y', $end_timestamp);
-	$start_end_array['start']['day'] = $start_day;
-	$start_end_array['start']['month'] = $start_month;
-	$start_end_array['start']['year'] = $start_year;
-	$start_end_array['end']['day'] = $end_day;
-	$start_end_array['end']['month'] = $end_month;
-	$start_end_array['end']['year'] = $end_year;
-	return $start_end_array;
-}
-/**
- * Show the mini calendar of the given month
- */
-function display_daycalendar($agendaitems, $day, $month, $year, $weekdaynames, $monthName)
-{
-	global $DaysShort, $DaysLong, $course_path;
-	global $MonthsLong;
-	global $query;
-
-	// timestamp of today
-	$today = mktime();
-	$nextday = $today + (24 * 60 * 60);
-	$previousday = $today - (24 * 60 * 60);
-	// the week number of the year
-	$week_number = date("W", $today);
-	// if we moved to the next / previous day we have to recalculate the $today variable
-	if ($_GET['day'])
-	{
-		$today = mktime(0, 0, 0, $month, $day, $year);
-		$nextday = $today + (24 * 60 * 60);
-		$previousday = $today - (24 * 60 * 60);
-		$week_number = date("W", $today);
-	}
-	// calculating the start date of the week
-	// the date of the monday of this week is the timestamp of today minus
-	// number of days that have already passed this week * 24 hours * 60 minutes * 60 seconds
-	$current_day = date("j", $today); // Day of the month without leading zeros (1 to 31) of today
-	$day_of_the_week = date("w", $today); // Numeric representation of the day of the week	0 (for Sunday) through 6 (for Saturday) of today
-	//$timestamp_first_date_of_week=$today-(($day_of_the_week-1)*24*60*60); // timestamp of the monday of this week
-	//$timestamp_last_date_of_week=$today+((7-$day_of_the_week)*24*60*60); // timestamp of the sunday of this week
-	// we are loading all the calendar items of all the courses for today
-	echo "<table class=\"data_table\">\n";
-	// the forward and backwards url
-	$backwardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=day&amp;day=".date("j", $previousday)."&amp;month=".date("n", $previousday)."&amp;year=".date("Y", $previousday);
-	$forewardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=day&amp;day=".date("j", $nextday)."&amp;month=".date("n", $nextday)."&amp;year=".date("Y", $nextday);
-	// The title row containing the day
-	echo "<tr>\n", "<th width=\"10%\"><a href=\"", $backwardsURL, "\">&#171;</a></th>\n", "<th>";
-	echo $DaysLong[$day_of_the_week]." ".date("j", $today)." ".$MonthsLong[date("n", $today) - 1]." ".date("Y", $today);
-	echo "</th>";
-	echo "<th width=\"10%\"><a href=\"", $forewardsURL, "\">&#187;</a></th>\n";
-	echo "</tr>\n";
-	// the rows for each half an hour
-	for ($i = 10; $i < 48; $i ++)
-	{
-		if ($i % 2 == 0)
-		{
-			$class = "class=\"row_even\"";
-		}
-		else
-		{
-			$class = "class=\"row_odd\"";
-		}
-		echo "<tr $class>\n";
-		echo "\t";
-		if ($i % 2 == 0)
-		{
-			echo ("<td valign=\"top\" width=\"75\">". (($i) / 2)." ".get_lang("HourShort")." 00</td>\n");
-		}
-		else
-		{
-			echo ("<td valign=\"top\" width=\"75\">". ((($i) / 2) - (1 / 2))." ".get_lang("HourShort")." 30</td>\n");
-		}
-		echo "\t<td $class valign=\"top\" colspan=\"2\">\n";
-		if (is_array($agendaitems[$i]))
-		{
-			foreach ($agendaitems[$i] as $key => $value)
-			{
-				echo $value;
-			}
-		}
-		else
-		{
-			echo $agendaitems[$i];
-		}
-		echo "\t</td>\n";
-		echo "</tr>\n";
-	}
-	echo "</table>\n";
-}
-/**
- *	Display the weekly view of the calendar
- */
-function display_weekcalendar($agendaitems, $month, $year, $weekdaynames, $monthName)
-{
-	global $DaysShort,$course_path;
-	global $MonthsLong;
-	// timestamp of today
-	$today = time();
-	$day_of_the_week = date("w", $today);
-	$thisday_of_the_week = date("w", $today);
-	// the week number of the year
-	$week_number = date("W", $today);
-	$thisweek_number = $week_number;
-	// if we moved to the next / previous week we have to recalculate the $today variable
-	if ($_GET['week'])
-	{
-		$today = mktime(0, 0, 0, 1, 1, $year);
-		$today = $today + (((int)$_GET['week']-1) * (7 * 24 * 60 * 60));
-		$week_number = date("W", $today);
-	}
-	// calculating the start date of the week
-	// the date of the monday of this week is the timestamp of today minus
-	// number of days that have already passed this week * 24 hours * 60 minutes * 60 seconds
-	$current_day = date("j", $today); // Day of the month without leading zeros (1 to 31) of today
-	$day_of_the_week = date("w", $today); // Numeric representation of the day of the week	0 (for Sunday) through 6 (for Saturday) of today
-	$timestamp_first_date_of_week = $today - (($day_of_the_week -1) * 24 * 60 * 60); // timestamp of the monday of this week
-	$timestamp_last_date_of_week = $today + ((7 - $day_of_the_week) * 24 * 60 * 60); // timestamp of the sunday of this week
-	$backwardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=week&amp;week=". ($week_number -1);
-	$forewardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=week&amp;week=". ($week_number +1);
-	echo "<table id=\"agenda_list\">\n";
-	// The title row containing the the week information (week of the year (startdate of week - enddate of week)
-	echo "<tr class=\"title\">\n";
-	echo "<td width=\"10%\"><a href=\"", $backwardsURL, "\">&#171;</a></td>\n";
-	echo "<td colspan=\"5\">".get_lang("Week")." ".$week_number;
-	echo " (".$DaysShort['1']." ".date("j", $timestamp_first_date_of_week)." ".$MonthsLong[date("n", $timestamp_first_date_of_week) - 1]." ".date("Y", $timestamp_first_date_of_week)." - ".$DaysShort['0']." ".date("j", $timestamp_last_date_of_week)." ".$MonthsLong[date("n", $timestamp_last_date_of_week) - 1]." ".date("Y", $timestamp_last_date_of_week).')';
-	echo "</td>";
-	echo "<td width=\"10%\"><a href=\"", $forewardsURL, "\">&#187;</a></td>\n", "</tr>\n";
-	// The second row containing the short names of the days of the week
-	echo "<tr>\n";
-	// this is the Day of the month without leading zeros (1 to 31) of the monday of this week
-	$tmp_timestamp = $timestamp_first_date_of_week;
-	for ($ii = 1; $ii < 8; $ii ++)
-	{
-		$is_today = ($ii == $thisday_of_the_week AND (!isset($_GET['week']) OR $_GET['week']==$thisweek_number));
-		echo "\t<td class=\"weekdays\">";
-		if ($is_today)
-		{
-			echo "<font color=#CC3300>";
-		}
-		echo $DaysShort[$ii % 7]." ".date("j", $tmp_timestamp)." ".$MonthsLong[date("n", $tmp_timestamp) - 1];
-		if ($is_today)
-		{
-			echo "</font>";
-		}
-		echo "</td>\n";
-		// we 24 hours * 60 minutes * 60 seconds to the $tmp_timestamp
-		$array_tmp_timestamp[] = $tmp_timestamp;
-		$tmp_timestamp = $tmp_timestamp + (24 * 60 * 60);
-	}
-	echo "</tr>\n";
-	// the table cells containing all the entries for that day
-	echo "<tr>\n";
-	$counter = 0;
-	foreach ($array_tmp_timestamp as $key => $value)
-	{
-		if ($counter < 5)
-		{
-			$class = "class=\"days_week\"";
-		}
-		else
-		{
-			$class = "class=\"days_weekend\"";
-		}
-		if ($counter == $thisday_of_the_week -1 AND (!isset($_GET['week']) OR $_GET['week']==$thisweek_number))
-		{
-			$class = "class=\"days_today\"";
-		}
-
-		echo "\t<td ".$class.">";
-		echo "<span class=\"agendaitem\">".$agendaitems[date('j', $value)]."&nbsp;</span> ";
-		echo "</td>\n";
-		$counter ++;
-	}
-	echo "</tr>\n";
-	echo "</table>\n";
-}
-/**
- * Show the monthcalender of the given month
- */
-function get_day_agendaitems($courses_dbs, $month, $year, $day)
-{
-	global $_user;
-	global $_configuration;
-	global $setting_agenda_link;
-
-	$items = array ();
-
-	// get agenda-items for every course
-	//$query=Database::query($sql_select_courses);
-	foreach ($courses_dbs as $key => $array_course_info)
-	{
-		//databases of the courses
-		$TABLEAGENDA = Database :: get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-		//$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $array_course_info['db']);
-
-		// getting all the groups of the user for the current course
-		//$group_memberships = GroupManager :: get_group_ids($array_course_info['db'], $_user['user_id']);
-		// if the user is administrator of that course we show all the agenda items
-		if ($array_course_info['status'] == '1')
-		{
-			//echo "course admin";
-			$sqlquery = "SELECT DISTINCT *
-										FROM ".$TABLEAGENDA."
-										WHERE
-										DAYOFMONTH(start_date)='".$day."' AND MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
-										GROUP BY agenda.id
-										ORDER BY start_date ";
-		}
-		// if the user is not an administrator of that course
-		/*else
-		{
-			//echo "GEEN course admin";
-			if (is_array($group_memberships) && count($group_memberships)>0)
-			{
-				$sqlquery = "SELECT
-													agenda.*
-													FROM ".$TABLEAGENDA."
-													WHERE
-													DAYOFMONTH(start_date)='".$day."' AND MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
-													ORDER BY start_date ";
-			}
-			else
-			{
-				$sqlquery = "SELECT
-													agenda.*
-													FROM ".$TABLEAGENDA."
-													WHERE
-													DAYOFMONTH(start_date)='".$day."' AND MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
-													ORDER BY start_date ";
-			}
-		}*/
-		//$sqlquery = "SELECT * FROM $agendadb WHERE DAYOFMONTH(day)='$day' AND month(day)='$month' AND year(day)='$year'";
-		//echo "abc";
-		//echo $sqlquery;
-		$result = Database::query($sqlquery, __FILE__, __LINE__);
-		$portal_url = $_configuration['root_web'];
-		if ($_configuration['multiple_access_urls']==true) {
-			$access_url_id = api_get_current_access_url_id();
-			if ($access_url_id != -1 ){
-				$url = api_get_access_url($access_url_id);
-				$portal_url = $url['url'];
-			}
-		}
-
-		//echo Database::num_rows($result);
-		while ($item = Database::fetch_array($result))
-		{
-			// in the display_daycalendar function we use $i (ranging from 0 to 47) for each halfhour
-			// we want to know for each agenda item for this day to wich halfhour it must be assigned
-			list ($datepart, $timepart) = split(" ", $item['start_date']);
-			list ($year, $month, $day) = explode("-", $datepart);
-			list ($hours, $minutes, $seconds) = explode(":", $timepart);
-
-			$halfhour = 2 * $hours;
-			if ($minutes >= '30')
-			{
-				$halfhour = $halfhour +1;
-			}
-
-			if ($setting_agenda_link == 'coursecode')
-			{
-				$title=$array_course_info['title'];
-				$agenda_link = api_substr($title, 0, 14);
-			}
-			else
-			{
-				$agenda_link = Display::return_icon('course_home.gif');
-			}
-
-			//$URL = $_configuration['root_web'].$mycours["dir"]."/";
-			$URL = $portal_url.'main/admin/agenda.php?cidReq='."&amp;day=$day&amp;month=$month&amp;year=$year#$day"; // RH  //Patrick Cool: to highlight the relevant agenda item
-			$items[$halfhour][] .= "<i>".$hours.":".$minutes."</i> <a href=\"$URL\" title=\"".$array_course_info['name']."\">".$agenda_link."</a>  ".$item['title']."<br />";
-		}
-	}
-	// sorting by hour for every day
-	$agendaitems = array();
-	while (list($agendaday, $tmpitems) = each($items))
-	{
-		sort($tmpitems);
-		while (list($key,$val) = each($tmpitems))
-		{
-			$agendaitems[$agendaday].=$val;
-		}
-	}
-	$agendaitems = $items;
-	//print_r($agendaitems);
-	return $agendaitems;
-}
-
-/**
- * Return agenda items of the week
- */
-function get_week_agendaitems($courses_dbs, $month, $year, $week = '')
-{
-	$TABLEAGENDA = Database :: get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-	global $_user;
-	global $_configuration;
-	global $setting_agenda_link;
-
-	$items = array ();
-	// The default value of the week
-	if ($week == '')
-	{
-		$week_number = date("W", time());
-	}
-	else
-	{
-		$week_number = $week;
-	}
-	$start_end = calculate_start_end_of_week($week_number, $year);
-	$start_filter = $start_end['start']['year']."-".$start_end['start']['month']."-".$start_end['start']['day'];
-	$end_filter = $start_end['end']['year']."-".$start_end['end']['month']."-".$start_end['end']['day'];
-	// get agenda-items for every course
-	foreach ($courses_dbs as $key => $array_course_info)
-	{
-		//databases of the courses
-		$TABLEAGENDA = Database :: get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-		//$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $array_course_info["db"]);
-
-		// getting all the groups of the user for the current course
-	//	$group_memberships = GroupManager :: get_group_ids($array_course_info["db"], $_user['user_id']);
-
-		// if the user is administrator of that course we show all the agenda items
-		//if ($array_course_info['status'] == '1')
-		//{
-			//echo "course admin";
-			$sqlquery = "SELECT DISTINCT * FROM ".$TABLEAGENDA." ORDER BY start_date";
-		//}
-		// if the user is not an administrator of that course
-		//else
-		//{
-			//echo "GEEN course admin";
-/*			if (is_array($group_memberships) && count($group_memberships)>0)
-			{
-				$sqlquery = "SELECT *  FROM ".$TABLEAGENDA." ORDER BY a.start_date";
-			}
-			else*/
-			//{
-			//	$sqlquery = "SELECT * FROM ".$TABLEAGENDA." ORDER BY a.start_date";
-			//}
-		//}
-		//echo "<pre>".$sqlquery."</pre>";
-		// $sqlquery = "SELECT * FROM $agendadb WHERE (DAYOFMONTH(day)>='$start_day' AND DAYOFMONTH(day)<='$end_day')
-		//				AND (MONTH(day)>='$start_month' AND MONTH(day)<='$end_month')
-		//				AND (YEAR(day)>='$start_year' AND YEAR(day)<='$end_year')";
-		$result = Database::query($sqlquery, __FILE__, __LINE__);
-
-		$portal_url = $_configuration['root_web'];
-		if ($_configuration['multiple_access_urls']==true) {
-			$access_url_id = api_get_current_access_url_id();
-			if ($access_url_id != -1 ){
-				$url = api_get_access_url($access_url_id);
-				$portal_url = $url['url'];
-			}
-		}
-
-		while ($item = Database::fetch_array($result))
-		{
-			$agendaday = date("j",strtotime($item['start_date']));
-			$time= date("H:i",strtotime($item['start_date']));
-
-			if ($setting_agenda_link == 'coursecode')
-			{
-				$title=$array_course_info['title'];
-				$agenda_link = api_substr($title, 0, 14);
-			}
-			else
-			{
-				$agenda_link = Display::return_icon('course_home.gif');
-			}
-
-			$URL = $portal_url."main/admin/agenda.php?cidReq=".urlencode($array_course_info["code"])."&amp;day=$agendaday&amp;month=$month&amp;year=$year#$agendaday"; // RH  //Patrick Cool: to highlight the relevant agenda item
-			$items[$agendaday][$item['start_time']] .= "<i>$time</i> <a href=\"$URL\" title=\"".$array_course_info["name"]."\">".$agenda_link."</a>  ".$item['title']."<br />";
-		}
-	}
-	// sorting by hour for every day
-	$agendaitems = array ();
-	while (list ($agendaday, $tmpitems) = each($items))
-	{
-		sort($tmpitems);
-		while (list ($key, $val) = each($tmpitems))
-		{
-			$agendaitems[$agendaday] .= $val;
-		}
-	}
-	//print_r($agendaitems);
-	return $agendaitems;
-}
-/**
- * Get repeated events of a course between two dates (timespan of a day).
- * Returns an array containing the events
- * @param   string  Course info array (as returned by api_get_course_info())
- * @param	int		UNIX timestamp of span start. Defaults 0, later transformed into today's start
- * @param	int		UNIX timestamp. Defaults to 0, later transformed into today's end
- * @param   array   A set of parameters to alter the SQL query
- * @return	array	[int] => [course_id,parent_event_id,start_date,end_date,title,description]
- */
-function get_repeated_events_day_view($course_info,$start=0,$end=0,$params)
-{
-	$events = array();
-	//initialise all values
-	$y=0;
-	$m=0;
-	$d=0;
-    //block $end if higher than 2038 -- PHP doesn't go past that
-    if($end>2145934800){$end = 2145934800;}
-	if($start == 0 or $end == 0)
-	{
-		$y=date('Y');
-		$m=date('m');
-		$d=date('j');
-	}
-	if($start==0)
-	{
-		$start = mktime(0,0,0,$m,$d,$y);
-	}
-	$db_start = date('Y-m-d H:i:s',$start);
-	if($end==0)
-	{
-		$end = mktime(23,59,59,$m,$d,$y);
-	}
-	//$db_end = date('Y-m-d H:i:s',$end);
-
-	$t_cal = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR,$course_info['dbName']);
-	//$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
-    $t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
-	$sql = "SELECT c.id, c.title, c.content, " .
-			" UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
-			" cr.cal_type, cr.cal_end " .
-			" FROM $t_cal c, $t_cal_repeat cr, $t_ip as item_property " .
-			" WHERE cr.cal_end >= $start " .
-			" AND cr.cal_id = c.id " .
-            " AND item_property.ref = c.id ".
-            " AND item_property.tool = '".TOOL_CALENDAR_EVENT."' ".
-			" AND c.start_date <= '$db_start' "
-            .(!empty($params['conditions'])?$params['conditions']:'')
-            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
-            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
-	$res = Database::query($sql,__FILE__,__LINE__);
-	if(Database::num_rows($res)>0)
-	{
-		while($row = Database::fetch_array($res))
-		{
-			$orig_start = $row['orig_start'];
-			$orig_end = $row['orig_end'];
-			$repeat_type = $row['cal_type'];
-			switch($repeat_type)
-			{
-				case 'daily':
-					//we are in the daily view, so if this element is repeated daily and
-					//the repetition is still active today (which is a condition of the SQL query)
-					//then the event happens today. Just build today's timestamp for start and end
-					$time_orig_h = date('H',$orig_start);
-					$time_orig_m = date('i',$orig_start);
-					$time_orig_s = date('s',$orig_start);
-					$int_time = (($time_orig_h*60)+$time_orig_m)*60+$time_orig_s; //time in seconds since 00:00:00
-					$span = $orig_end - $orig_start; //total seconds between start and stop of original event
-					$current_start =$start + $int_time; //unixtimestamp start of today's event
-					$current_stop = $start+$int_time+$span; //unixtimestamp stop of today's event
-					$events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
-					break;
-				case 'weekly':
-					$time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/W/j/N/G/i/s',$end);
-					list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig))) && ($dw_orig == $dw_now))
-					{ //if the event is after the original (at least one week) and the day of the week is the same
-					  $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				case 'monthlyByDate':
-					$time_orig = date('Y/n/j/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/j/G/i/s',$end);
-					list($y_now,$m_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig))) && ($d_orig == $d_now))
-					{
-					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				case 'monthlyByDayR':
-					//not implemented yet
-					break;
-				case 'monthlyByDay':
-					//not implemented yet
-					break;
-				case 'yearly':
-					$time_orig = date('Y/n/j/z/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/j/z/G/i/s',$end);
-					list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					if(($y_now>$y_orig) && ($dy_orig == $dy_now))
-					{
-					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				default:
-					break;
-			}
-		}
-	}
-	return $events;
-}
-/**
- * Get repeated events of a course between two dates (timespan of a week).
- * Returns an array containing the events
- * @param	string	Course info array (as returned by api_get_course_info())
- * @param	int		UNIX timestamp of span start. Defaults 0, later transformed into today's start
- * @param	int		UNIX timestamp. Defaults to 0, later transformed into today's end
- * @param   array   A set of parameters to alter the SQL query
- * @return	array	[int] => [course_id,parent_event_id,start_date,end_date,title,description]
- */
-function get_repeated_events_week_view($course_info,$start=0,$end=0,$params)
-{
-	$events = array();
-    //block $end if higher than 2038 -- PHP doesn't go past that
-    if($end>2145934800){$end = 2145934800;}
-	//initialise all values
-	$y=0;
-	$m=0;
-	$d=0;
-	if($start == 0 or $end == 0)
-	{
-		$time = time();
-		$dw = date('w',$time);
-		$week_start = $time - (($dw-1)*86400);
-		$y = date('Y',$week_start);
-		$m = date('m',$week_start);
-		$d = date('j',$week_start);
-		$w = date('W',$week_start);
-	}
-	if($start==0)
-	{
-		$start = mktime(0,0,0,$m,$d,$y);
-	}
-	$db_start = date('Y-m-d H:i:s',$start);
-	if($end==0)
-	{
-		$end = $start+(86400*7)-1; //start of week, more 7 days, minus 1 second to get back to the previoyus day
-	}
-	//$db_end = date('Y-m-d H:i:s',$end);
-
-	$t_cal = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-	//$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
-    //$t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
-    $sql = "SELECT c.id, c.title, c.content " .
-            " UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
-            " FROM". $t_cal ."
-             WHERE c.start_date <= '$db_start' "
-            .(!empty($params['conditions'])?$params['conditions']:'')
-            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
-            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
-	$res = Database::query($sql,__FILE__,__LINE__);
-	if(Database::num_rows($res)>0)
-	{
-		while($row = Database::fetch_array($res))
-		{
-			$orig_start = $row['orig_start'];
-			$orig_end = $row['orig_end'];
-			$repeat_type = $row['cal_type'];
-			switch($repeat_type)
-			{
-				case 'daily':
-					$time_orig_h = date('H',$orig_start);
-					$time_orig_m = date('i',$orig_start);
-					$time_orig_s = date('s',$orig_start);
-					$int_time = (($time_orig_h*60)+$time_orig_m)*60+$time_orig_s; //time in seconds since 00:00:00
-					$span = $orig_end - $orig_start; //total seconds between start and stop of original event
-					for($i=0;$i<7;$i++)
-					{
-						$current_start = $start + ($i*86400) + $int_time; //unixtimestamp start of today's event
-						$current_stop = $start + ($i*86400) + $int_time + $span; //unixtimestamp stop of today's event
-						$events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
-					}
-					break;
-				case 'weekly':
-					$time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/W/j/N/G/i/s',$end);
-					list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig))))
-					{ //if the event is after the original (at least one week) and the day of the week is the same
-					  $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				case 'monthlyByDate':
-					$time_orig = date('Y/n/W/j/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$w_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/W/j/G/i/s',$end);
-					list($y_now,$m_now,$w_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
-					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig))) && ($start<$event_repetition_time && $event_repetition_time<$end))
-					{ //if the event is after the original (at least one month) and the original event's day is between the first day of the week and the last day of the week
-					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				case 'monthlyByDayR':
-					//not implemented yet
-					break;
-				case 'monthlyByDay':
-					//not implemented yet
-					break;
-				case 'yearly':
-					$time_orig = date('Y/n/j/z/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/j/z/G/i/s',$end);
-					list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
-					if((($y_now>$y_orig) && ($start<$event_repetition_time && $event_repetition_time<$end)))
-					{
-					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				default:
-					break;
-			}
-		}
-	}
-	return $events;
-}
-/**
- * Get repeated events of a course between two dates (timespan of a month).
- * Returns an array containing the events
- * @param   string  Course info array (as returned by api_get_course_info())
- * @param	int		UNIX timestamp of span start. Defaults 0, later transformed into today's start
- * @param	int		UNIX timestamp. Defaults to 0, later transformed into today's end
- * @param   array   A set of parameters to alter the SQL query
- * @return	array	[int] => [course_id,parent_event_id,start_date,end_date,title,description]
- */
-function get_repeated_events_month_view($course_info,$start=0,$end=0,$params)
-{
-	$events = array();
-    //block $end if higher than 2038 -- PHP doesn't go past that
-    if($end>2145934800){$end = 2145934800;}
-	//initialise all values
-	$y=0;
-	$m=0;
-	$d=0;
-	if($start == 0 or $end == 0)
-	{
-		$time = time();
-		$y = date('Y');
-		$m = date('m');
-	}
-	if($start==0)
-	{
-		$start = mktime(0,0,0,$m,1,$y);
-	}
-	$db_start = date('Y-m-d H:i:s',$start);
-	if($end==0)
-	{
-		if($m==12)
-		{
-			$end = mktime(0,0,0,1,1,$y+1)-1; //start of next month, minus 1 second to get back to the previoyus day
-		}
-		else
-		{
-			$end = mktime(0,0,0,$m+1,1,$y)-1;
-		}
-	}
-	//$db_end = date('Y-m-d H:i:s',$end);
-
-	$t_cal = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-	//$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
-    //$t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
-    $sql = "SELECT c.id, c.title, c.content, " .
-            " UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
-            " cr.cal_type, cr.cal_end " .
-            " FROM $t_cal c, $t_cal_repeat cr, $t_ip as item_property " .
-            " WHERE cr.cal_end >= $start " .
-            " AND cr.cal_id = c.id " .
-            " AND item_property.ref = c.id ".
-            " AND item_property.tool = '".TOOL_CALENDAR_EVENT."' ".
-            " AND c.start_date <= '$db_start' "
-            .(!empty($params['conditions'])?$params['conditions']:'')
-            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
-            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
-	$res = Database::query($sql,__FILE__,__LINE__);
-	if(Database::num_rows($res)>0)
-	{
-		while($row = Database::fetch_array($res))
-		{
-			$orig_start = $row['orig_start'];
-			$orig_end = $row['orig_end'];
-			$repeat_type = $row['cal_type'];
-			switch($repeat_type)
-			{
-				case 'daily':
-					$time_orig_h = date('H',$orig_start);
-					$time_orig_m = date('i',$orig_start);
-					$time_orig_s = date('s',$orig_start);
-					$month_last_day = date('d',$end);
-					$int_time = (($time_orig_h*60)+$time_orig_m)*60+$time_orig_s; //time in seconds since 00:00:00
-					$span = $orig_end - $orig_start; //total seconds between start and stop of original event
-					for($i=0;$i<$month_last_day;$i++)
-					{
-						$current_start = $start + ($i*86400) + $int_time; //unixtimestamp start of today's event
-						$current_stop = $start + ($i*86400) + $int_time + $span; //unixtimestamp stop of today's event
-						$events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
-					}
-					break;
-				case 'weekly':
-					//A weekly repeated event is very difficult to catch in a month view,
-					//because weeks start before or at the same time as the first day of the month
-					//The same can be said for the end of the month.
-					// The idea is thus to get all possible events by enlarging the scope of
-					// the month to get complete weeks covering the complete month, and then take out
-					// the events that start before the 1st ($start) or after the last day of the month ($end)
-					$time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-                    $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
-                    list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-
-					$time_now = date('Y/n/W/j/N/G/i/s',$end);
-					list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-
-					$month_first_week = date('W',$start);
-					$month_last_week = date('W',$end);
-
-					if(($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig)))
-					{ //if the event is after the original (at least one week) and the day of the week is the same
-						for($i=$month_first_week;$i<=$month_last_week;$i++)
-						{
-						  //the "day of the week" of repetition is the same as the $dw_orig,
-                          //so to get the "day of the month" from the "day of the week", we have
-                          //to get the first "day of the week" for this week and add the number
-                          //of days (in seconds) to reach the $dw_orig
-                          //example: the first week spans between the 28th of April (Monday) to the
-                          // 4th of May (Sunday). The event occurs on the 2nd day of each week.
-                          // This means the event occurs on 29/4, 6/5, 13/5, 20/5 and 27/5.
-                          // We want to get all of these, and then reject 29/4 because it is out
-                          // of the month itself.
-
-                          //First, to get the start time of the first day of the month view (even if
-                          // the day is from the past month), we get the month start date (1/5) and
-                          // see which day of the week it is, and subtract the number of days necessary
-                          // to get back to the first day of the week.
-                          $month_first_day_weekday = date('N',$start);
-                          $first_week_start = $start - (($month_first_day_weekday-1)*86400);
-
-                          //Second, we add the week day of the original event, so that we have an
-                          // absolute time that represents the first repetition of the event in
-                          // our 4- or 5-weeks timespan
-                          $first_event_repeat_start = $first_week_start + (($dw_orig-1)*86400) + ($h_orig*3600) + ($n_orig*60) + $s_orig;
-
-                          //Third, we start looping through the repetitions and see if they are between
-                          // $start and $end
-					      for($i = $first_event_repeat_start; $i<=$end; $i+=604800)
-                          {
-                          	if($start<$i && $i<$end)
-                            {
-                               list($y_repeat,$m_repeat,$d_repeat,$h_repeat,$n_repeat,$s_repeat) = split('/',date('Y/m/j/H/i/s',$i));
-                               $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-                            }
-                          }
-						}
-					}
-					break;
-				case 'monthlyByDate':
-					$time_orig = date('Y/n/W/j/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$w_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/W/j/G/i/s',$end);
-					list($y_now,$m_now,$w_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
-					if(($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig)))
-					{ //if the event is after the original (at least one month) and the original event's day is between the first day of the week and the last day of the week
-					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				case 'monthlyByDayR':
-					//not implemented yet
-					break;
-				case 'monthlyByDay':
-					//not implemented yet
-					break;
-				case 'yearly':
-					$time_orig = date('Y/n/j/z/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/j/z/G/i/s',$end);
-					list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
-					if((($y_now>$y_orig) && ($start<$event_repetition_time && $event_repetition_time<$end)))
-					{
-					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				default:
-					break;
-			}
-		}
-	}
-	return $events;
-}
-/**
- * Get repeated events of a course between two dates (1 year timespan). Used for the list display.
- * This is virtually unlimited but by default it shortens to 100 years from now (even a birthday shouldn't be useful more than this time - except for turtles)
- * Returns an array containing the events
- * @param   string  Course info array (as returned by api_get_course_info())
- * @param   int     UNIX timestamp of span start. Defaults 0, later transformed into today's start
- * @param   int     UNIX timestamp. Defaults to 0, later transformed into today's end
- * @param   array   A set of parameters to alter the SQL query
- * @return  array   [int] => [course_id,parent_event_id,start_date,end_date,title,description]
- */
-function get_repeated_events_list_view($course_info,$start=0,$end=0,$params)
-{
-    $events = array();
-    //block $end if higher than 2038 -- PHP doesn't go past that
-    if($end>2145934800){$end = 2145934800;}
-    //initialise all values
-    $y=0;
-    $m=0;
-    $d=0;
-    if(empty($start) or empty($end))
-    {
-        $time = time();
-        $y = date('Y');
-        $m = date('m');
-    }
-    if(empty($start))
-    {
-        $start = mktime(0, 0, 0, $m, 1, $y);
-    }
-    $db_start = date('Y-m-d H:i:s', $start);
-    if(empty($end))
-    {
-        $end = mktime(0, 0, 0, 1, 1, 2037);
-    }
-    //$db_end = date('Y-m-d H:i:s',$end);
-
-    $t_cal = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR,$course_info['dbName']);
-    //$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
-    //$t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
-    $sql = "SELECT c.id, c.title, c.content, " .
-            " UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
-            " cr.cal_type, cr.cal_end " .
-            " FROM $t_cal c, $t_cal_repeat cr, $t_ip as item_property " .
-            " WHERE cr.cal_end >= $start " .
-            " AND cr.cal_id = c.id " .
-            " AND item_property.ref = c.id ".
-            " AND item_property.tool = '".TOOL_CALENDAR_EVENT."' ".
-            " AND c.start_date <= '$db_start' "
-            .(!empty($params['conditions'])?$params['conditions']:'')
-            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
-            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
-    $res = Database::query($sql,__FILE__,__LINE__);
-    if(Database::num_rows($res)>0)
-    {
-        while($row = Database::fetch_array($res))
-        {
-            $orig_start = $row['orig_start'];
-            $orig_end = $row['orig_end'];
-            $repeat_type = $row['cal_type'];
-            $repeat_end = $row['cal_end'];
-            switch($repeat_type)
-            {
-                case 'daily':
-                    $time_orig_h = date('H',$orig_start);
-                    $time_orig_m = date('i',$orig_start);
-                    $time_orig_s = date('s',$orig_start);
-                    $span = $orig_end - $orig_start; //total seconds between start and stop of original event
-                    for($i=$orig_start+86400;($i<$end && $i<=$repeat_end);$i+=86400)
-                    {
-                        $current_start = $i; //unixtimestamp start of today's event
-                        $current_stop = $i + $span; //unixtimestamp stop of today's event
-                        $events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
-                    }
-                    break;
-                case 'weekly':
-                    //A weekly repeated event is very difficult to catch in a month view,
-                    // because weeks start before or at the same time as the first day of the month
-                    //The same can be said for the end of the month.
-                    // The idea is thus to get all possible events by enlarging the scope of
-                    // the month to get complete weeks covering the complete month, and then take out
-                    // the events that start before the 1st ($start) or after the last day of the month ($end)
-                    $time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
-                    list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-                    $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
-                    list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-
-                    $time_now = date('Y/n/W/j/N/G/i/s',$end);
-                    list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-                    if($w_now==52)
-                    {
-                        ++$y_now;
-                        $w_now=1;
-                    }
-                    else
-                    {
-                        ++$w_now;
-                    }
-                    $month_first_week = date('W',$start);
-                    $total_weeks = ((date('Y',$end)-$y_orig)-1)*52;
-                    $month_last_week = $month_first_week + $total_weeks;
-
-                    if(($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig)))
-                    { //if the event is after the original (at least one week) and the day of the week is the same
-                        //for($i=$month_first_week;($i<=$month_last_week && $i<1000);$i++)
-                        //{
-
-
-                          /*
-                           The "day of the week" of repetition is the same as the $dw_orig,
-                           so to get the "day of the month" from the "day of the week", we have
-                           to get the first "day of the week" for this week and add the number
-                           of days (in seconds) to reach the $dw_orig
-                          example: the first week spans between the 28th of April (Monday) to the
-                           4th of May (Sunday). The event occurs on the 2nd day of each week.
-                           This means the event occurs on 29/4, 6/5, 13/5, 20/5 and 27/5.
-                           We want to get all of these, and then reject 29/4 because it is out
-                           of the month itself.
-                          First, to get the start time of the first day of the month view (even if
-                           the day is from the past month), we get the month start date (1/5) and
-                           see which day of the week it is, and subtract the number of days necessary
-                           to get back to the first day of the week.
-                          */
-                          $month_first_day_weekday = date('N',$start);
-                          $first_week_start = $start - (($month_first_day_weekday-1)*86400);
-
-                          //Second, we add the week day of the original event, so that we have an
-                          // absolute time that represents the first repetition of the event in
-                          // our 4- or 5-weeks timespan
-                          $first_event_repeat_start = $first_week_start + (($dw_orig-1)*86400) + ($h_orig*3600) + ($n_orig*60) + $s_orig;
-
-                          //Third, we start looping through the repetitions and see if they are between
-                          // $start and $end
-                          for($i = $first_event_repeat_start; ($i<=$end && $i<=$repeat_end); $i+=604800)
-                          {
-                            if($start<$i && $i<=$end && $i<=$repeat_end)
-                            {
-                               list($y_repeat,$m_repeat,$d_repeat,$h_repeat,$n_repeat,$s_repeat) = split('/',date('Y/m/j/H/i/s',$i));
-                               $new_start_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
-                               $new_stop_time = mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now);
-                               $events[] = array($course_info['id'], $row['id'], $new_start_time, $new_stop_time, $row['title'], $row['content']);
-                            }
-                            $time_now = date('Y/n/W/j/N/G/i/s',$i+604800);
-                            list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-                          }
-                        //}
-                    }
-                    break;
-                case 'monthlyByDate':
-                    $time_orig = date('Y/n/W/j/G/i/s',$orig_start);
-                    list($y_orig,$m_orig,$w_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-
-                    $time_now = date('Y/n/W/j/G/i/s',$start);
-                    list($y_now,$m_now,$w_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-                    //make sure we are one month ahead (to avoid being the same month as the original event)
-                    if($m_now==12)
-                    {
-                        ++$y_now;
-                        $m_now = 1;
-                    }
-                    else
-                    {
-                        ++$m_now;
-                    }
-
-                    $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-                    list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-
-                    $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
-                    $diff = $orig_end - $orig_start;
-                    while((($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig))) && ($event_repetition_time < $end) && ($event_repetition_time < $repeat_end))
-                    { //if the event is after the original (at least one month) and the original event's day is between the first day of the week and the last day of the week
-                      $new_start_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
-                      $new_stop_time = mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now);
-                      $events[] = array($course_info['id'],$row['id'],$new_start_time,$new_stop_time,$row['title'],$row['content']);
-                      if($m_now==12)
-                      {
-                      	++$y_now;
-                        $m_now = 1;
-                      }
-                      else
-                      {
-                        ++$m_now;
-                      }
-                      $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
-                    }
-                    break;
-                case 'monthlyByDayR':
-                    //not implemented yet
-                    break;
-                case 'monthlyByDay':
-                    //not implemented yet
-                    break;
-                case 'yearly':
-                    $time_orig = date('Y/n/j/z/G/i/s',$orig_start);
-                    list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-                    $time_now = date('Y/n/j/z/G/i/s',$end);
-                    list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-                    $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
-                    while((($y_now>$y_orig) && ($start<$event_repetition_time && $event_repetition_time<$end && $event_repetition_time<$repeat_end)))
-                    {
-                      $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-                      list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-                      $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-                      ++$y_now;
-                      $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
-                    }
-                    break;
-                default:
-                    break;
-            }
-        }
-    }
-    return $events;
-}
-/**
- * Tells if an agenda item is repeated
- * @param   string  Course database
- * @param   int     The agenda item
- * @return  boolean True if repeated, false otherwise
- */
-function is_repeated_event($id,$course=null)
-{
-	if(empty($course))
-    {
-    	$course_info = api_get_course_info();
-        $course = $course_info['dbName'];
-    }
-    $id = (int) $id;
-	//$t_agenda_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course);
-    $sql = "SELECT * FROM $t_agenda_repeat WHERE cal_id = $id";
-    $res = Database::query($sql,__FILE__,__LINE__);
-    if(Database::num_rows($res)>0)
-    {
-    	return true;
-    }
-    return false;
-}
-/**
- * Adds x weeks to a UNIX timestamp
- * @param   int     The timestamp
- * @param   int     The number of weeks to add
- * @return  int     The new timestamp
- */
-function add_week($timestamp,$num=1)
-{
-    return $timestamp + $num*604800;
-}
-/**
- * Adds x months to a UNIX timestamp
- * @param   int     The timestamp
- * @param   int     The number of years to add
- * @return  int     The new timestamp
- */
-function add_month($timestamp,$num=1)
-{
-	list($y, $m, $d, $h, $n, $s) = split('/',date('Y/m/d/h/i/s',$timestamp));
-    if($m+$num>12)
-    {
-    	$y += floor($num/12);
-        $m += $num%12;
-    }
-    else
-    {
-        $m += $num;
-    }
-    return mktime($h, $n, $s, $m, $d, $y);
-}
-/**
- * Adds x years to a UNIX timestamp
- * @param   int     The timestamp
- * @param   int     The number of years to add
- * @return  int     The new timestamp
- */
-function add_year($timestamp,$num=1)
-{
-    list($y, $m, $d, $h, $n, $s) = split('/',date('Y/m/d/h/i/s',$timestamp));
-    return mktime($h, $n, $s, $m, $d, $y+$num);
-}
-/**
- * Adds an agenda item in the database. Similar to store_new_agenda_item() except it takes parameters
- * @param   array   Course info
- * @param   string  Event title
- * @param   string  Event content/description
- * @param   string  Start date
- * @param   string  End date
- * @param   array   List of groups to which this event is added
- * @param   int     Parent id (optional)
- * @return  int     The new item's DB ID
- */
-function agenda_add_item($course_info, $title, $content, $db_start_date, $db_end_date, $to=array(), $parent_id=null)
-{
-  global $_course;
-    $user_id    = api_get_user_id();
-    $t_agenda   = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-
-    // some filtering of the input data
-    $title      = Database::escape_string($title); // no html allowed in the title
-    $content    = Database::escape_string($content);
-    $start_date = Database::escape_string($db_start_date);
-    $end_date   = Database::escape_string($db_end_date);
-
-     isset($_SESSION['id_session'])?$id_session=intval($_SESSION['id_session']):$id_session=null;
-    // store in the table calendar_event
-
-    // check if exists in calendar_event table
-    $sql = "SELECT * FROM $t_agenda WHERE title='$title' AND content = '$content' AND start_date = '$start_date'
-    		AND end_date = '$end_date' ".(!empty($parent_id)? "AND parent_event_id = '$parent_id'":"");
-    $result = Database::query($sql,__FILE__,__LINE__);
-    $count = Database::num_rows($result);
-    if ($count > 0) {
-    	return false;
-    }
-
-    $sql = "INSERT INTO ".$t_agenda."
-                            (title,content, start_date, end_date)
-                            VALUES
-                            ('".$title."','".$content."', '".$start_date."','".$end_date."')";
-
-    $result = Database::query($sql,__FILE__,__LINE__) or die (Database::error());
-    $last_id=Database::insert_id();
-
-    // add a attachment file in agenda
-
-   // add_agenda_attachment_file($file_comment,$last_id);
-
-    // store in last_tooledit (first the groups, then the users
-    $done = false;
-    if ((!is_null($to))or (!empty($_SESSION['toolgroup']))) // !is_null($to): when no user is selected we send it to everyone
-    {
-        $send_to=separate_users_groups($to);
-        // storing the selected groups
-        if (is_array($send_to['groups']))
-        {
-            foreach ($send_to['groups'] as $group)
-            {
-                api_item_property_update($course_info, TOOL_CALENDAR_EVENT, $last_id, "AgendaAdded", $user_id, $group,'',$start_date, $end_date);
-                $done = true;
-            }
-        }
-        // storing the selected users
-        if (is_array($send_to['users']))
-        {
-            foreach ($send_to['users'] as $user)
-            {
-                api_item_property_update($course_info, TOOL_CALENDAR_EVENT, $last_id, "AgendaAdded", $user_id,'',$user, $start_date,$end_date);
-                $done = true;
-            }
-        }
-    }
-
-    if(!$done) // the message is sent to everyone, so we set the group to 0
-    {
-        api_item_property_update($course_info, TOOL_CALENDAR_EVENT, $last_id, "AgendaAdded", $user_id, $start_date,$end_date);
-    }
-    // storing the resources
-    if (!empty($_SESSION['source_type']) && !empty($last_id)) {
-    //store_resources($_SESSION['source_type'],$last_id);
-    }
-    return $last_id;
-}
-/**
- * Adds a repetitive item to the database
- * @param   array   Course info
- * @param   int     The original event's id
- * @param   string  Type of repetition
- * @param   int     Timestamp of end of repetition (repeating until that date)
- * @param   array   Original event's destination
- * @return  boolean False if error, True otherwise
- */
- function get_calendar_items($month, $year)
-{
-	global $_user, $_course;
-	global $is_allowed_to_edit;
-
-	$month=Database::escape_string($month);
-	$year=Database::escape_string($year);
-
-	// database variables
-	$TABLEAGENDA = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-	//$TABLE_ITEM_PROPERTY=Database::get_course_table(TABLE_ITEM_PROPERTY);
-
-    $month_first_day = mktime(0,0,0,$month,1,$year);
-    $month_last_day  = mktime(0,0,0,$month+1,1,$year)-1;
-    if ($month==12) {
-        $month_last_day = mktime(0,0,0,1,1,$year+1)-1;
-    }
-    $repeats = array();
-    $data=array();
-	if (is_allowed_to_edit()) {
-		$sql="SELECT
-			DISTINCT *
-			FROM ".$TABLEAGENDA." agenda
-			WHERE MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
-			GROUP BY id ".
-			"ORDER BY  start_date ";
-		$result=Database::query($sql,__FILE__,__LINE__);
-
-		while ($row=Database::fetch_array($result)) {
-			$datum_item=(int)substr($row["start_date"],8,2);
-			$data[$datum_item][intval($datum_item)][] = $row;
-		}
-	}
-	return $data;
-}
-
-function agenda_add_repeat_item($course_info,$orig_id,$type,$end,$orig_dest)
-{/*
-	$t_agenda   = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR,$course_info['dbName']);
-   // $t_agenda_r = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
-    //$sql = "SELECT title, content, UNIX_TIMESTAMP(start_date) as sd, UNIX_TIMESTAMP(end_date) as ed FROM $t_agenda WHERE id = $orig_id";
-    $sql = "SELECT title, content, start_date as sd, end_date as ed FROM $t_agenda WHERE id = $orig_id";
-    $res = Database::query($sql,__FILE__,__LINE__);
-    if(Database::num_rows($res)!==1){return false;}
-    $row = Database::fetch_array($res);
-    //$orig_start = $row['sd'];
-    $orig_start = mktime(substr($row['sd'],11,2),substr($row['sd'],14,2),substr($row['sd'],17,2),substr($row['sd'],5,2),substr($row['sd'],8,2),substr($row['sd'],0,4));
-    //$orig_end   = $row['ed'];
-    $orig_end   = mktime(substr($row['ed'],11,2),substr($row['ed'],14,2),substr($row['ed'],17,2),substr($row['ed'],5,2),substr($row['ed'],8,2),substr($row['ed'],0,4));
-    $diff = $orig_end - $orig_start;
-    $orig_title = $row['title'];
-    $orig_content = $row['content'];
-    $now = time();
-    $type = Database::escape_string($type);
-    $end = (int) $end;
-    if(1<=$end && $end<=500)
-    {
-    	//we assume that, with this type of value, the user actually gives a count of repetitions
-        //and that he wants us to calculate the end date with that (particularly in case of imports from ical)
-        switch($type)
-        {
-            case 'daily':
-                $end = $orig_start + (86400*$end);
-                break;
-            case 'weekly':
-                $end = add_week($orig_start,$end);
-                break;
-            case 'monthlyByDate':
-                $end = add_month($orig_start,$end);
-                break;
-            case 'monthlyByDay':
-                //TODO
-                break;
-            case 'monthlyByDayR':
-                //TODO
-                break;
-            case 'yearly':
-                $end = add_year($orig_start,$end);
-                break;
-        }
-    }
-    if($end > $now
-        && in_array($type,array('daily','weekly','monthlyByDate','monthlyByDay','monthlyByDayR','yearly')))
-    {
-       $sql = "INSERT INTO $t_agenda_r (cal_id, cal_type, cal_end)" .
-            " VALUES ($orig_id,'$type',$end)";
-       $res = Database::query($sql,__FILE__,__LINE__);
-        switch($type)
-        {
-            case 'daily':
-                for($i = $orig_start + 86400; ($i <= $end); $i += 86400)
-                {
-                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $i), date('Y-m-d H:i:s', $i+$diff), $orig_dest, $orig_id);
-                }
-                break;
-            case 'weekly':
-                for($i = $orig_start + 604800; ($i <= $end); $i += 604800)
-                {
-                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $i), date('Y-m-d H:i:s', $i+$diff), $orig_dest, $orig_id);
-                }
-                break;
-            case 'monthlyByDate':
-                $next_start = add_month($orig_start);
-                while($next_start <= $end)
-                {
-                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $next_start), date('Y-m-d H:i:s', $next_start+$diff), $orig_dest, $orig_id);
-                    $next_start = add_month($next_start);
-                }
-                break;
-            case 'monthlyByDay':
-                //not yet implemented
-                break;
-            case 'monthlyByDayR':
-                //not yet implemented
-                break;
-            case 'yearly':
-                $next_start = add_year($orig_start);
-                while($next_start <= $end)
-                {
-                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $next_start), date('Y-m-d H:i:s', $next_start+$diff), $orig_dest, $orig_id);
-                    $next_start = add_year($next_start);
-                }
-                break;
-        }
-    }
-	return true;*/
-}
-/**
- * Import an iCal file into the database
- * @param   array   Course info
- * @return  boolean True on success, false otherwise
- */
-
-function agenda_import_ical($course_info,$file)
-{
-	require_once(api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
-    $charset = api_get_setting('platform_charset');
-    $filepath = api_get_path(SYS_ARCHIVE_PATH).$file['name'];
-    if(!@move_uploaded_file($file['tmp_name'],$filepath))
-    {
-    	error_log('Problem moving uploaded file: '.$file['error'].' in '.__FILE__.' line '.__LINE__);
-    	return false;
-    }
-    require_once (api_get_path(LIBRARY_PATH).'icalcreator/iCalcreator.class.php');
-    $ical = new vcalendar();
-    $ical->setConfig( 'directory', dirname($filepath) );
-    $ical->setConfig( 'filename', basename($filepath) );
-    $ical->parse();
-    //we need to recover: summary, description, dtstart, dtend, organizer, attendee, location (=course name),
-    // rrule
-    $ve = $ical->getComponent(0);
-    //print_r($ve);
-    $ttitle = $ve->getProperty('summary');
-    //print_r($ttitle);
-    $title = api_convert_encoding($ttitle,$charset,'UTF-8');
-    $tdesc = $ve->getProperty('description');
-    $desc = api_convert_encoding($tdesc,$charset,'UTF-8');
-    $ts = $ve->getProperty('dtstart');
-    $start_date = $ts['year'].'-'.$ts['month'].'-'.$ts['day'].' '.$ts['hour'].':'.$ts['min'].':'.$ts['sec'];
-    $ts = $ve->getProperty('dtend');
-    $end_date = $ts['year'].'-'.$ts['month'].'-'.$ts['day'].' '.$ts['hour'].':'.$ts['min'].':'.$ts['sec'];
-    //echo $start_date.' - '.$end_date;
-    $organizer = $ve->getProperty('organizer');
-    $attendee = $ve->getProperty('attendee');
-    $course_name = $ve->getProperty('location');
-    //insert the event in our database
-    $id = agenda_add_item($course_info,$title,$desc,$start_date,$end_date,$_POST['selectedform']);
-
-    $repeat = $ve->getProperty('rrule');
-    if(is_array($repeat) && !empty($repeat['FREQ']))
-    {
-    	$trans = array('DAILY'=>'daily','WEEKLY'=>'weekly','MONTHLY'=>'monthlyByDate','YEARLY'=>'yearly');
-        $freq = $trans[$repeat['FREQ']];
-        $interval = $repeat['INTERVAL'];
-        if(isset($repeat['UNTIL']) && is_array($repeat['UNTIL']))
-        {
-            $until = mktime(23,59,59,$repeat['UNTIL']['month'],$repeat['UNTIL']['day'],$repeat['UNTIL']['year']);
-            $res = agenda_add_repeat_item($course_info,$id,$freq,$until,$_POST['selectedform']);
-        }
-        //TODO: deal with count
-        if(!empty($repeat['COUNT']))
-        {
-            $count = $repeat['COUNT'];
-            $res = agenda_add_repeat_item($course_info,$id,$freq,$count,$_POST['selectedform']);
-        }
-    }
-    return true;
-}
-?>
+<?php // $id: $
+/* For licensing terms, see /dokeos_license.txt */
+/**
+==============================================================================
+*	@package dokeos.admin
+*	@author Carlos Vargas
+*	This file is the calendar/agenda.inc.php
+==============================================================================
+*/
+
+/*
+-----------------------------------------------------------
+	Constants and variables
+-----------------------------------------------------------
+*/
+// the variables for the days and the months
+// Defining the shorts for the days
+$DaysShort = api_get_week_days_short();
+// Defining the days of the week to allow translation of the days
+$DaysLong = api_get_week_days_long();
+// Defining the months of the year to allow translation of the months
+$MonthsLong = api_get_months_long();
+
+/*
+==============================================================================
+		FUNCTIONS
+==============================================================================
+*/
+
+/**
+* Retrieves all the agenda items from the table
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @author Yannick Warnier <yannick.warnier@dokeos.com> - cleanup
+* @param integer $month: the integer value of the month we are viewing
+* @param integer $year: the 4-digit year indication e.g. 2005
+* @return array
+*/
+
+/**
+* show the mini calender of the given month
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @param array an array containing all the agenda items for the given month
+* @param integer $month: the integer value of the month we are viewing
+* @param integer $year: the 4-digit year indication e.g. 2005
+* @param string $monthName: the language variable for the mont name
+* @return html code
+* @todo refactor this so that $monthName is no longer needed as a parameter
+*/
+function display_minimonthcalendar($agendaitems, $month, $year, $monthName)
+{
+	global $DaysShort;
+	//Handle leap year
+	$numberofdays = array (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
+	if (($year % 400 == 0) or ($year % 4 == 0 and $year % 100 <> 0))
+		$numberofdays[2] = 29;
+	//Get the first day of the month
+	$dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
+	//Start the week on monday
+	$startdayofweek = $dayone['wday'] <> 0 ? ($dayone['wday'] - 1) : 6;
+	$backwardsURL = api_get_self()."?".api_get_cidreq()."&amp;coursePath=".(empty($_GET['coursePath'])?'':$_GET['coursePath'])."&amp;courseCode=".(empty($_GET['courseCode'])?'':$_GET['courseCode'])."&amp;month=". ($month == 1 ? 12 : $month -1)."&amp;year=". ($month == 1 ? $year -1 : $year);
+	$forewardsURL = api_get_self()."?".api_get_cidreq()."&amp;coursePath=".(empty($_GET['coursePath'])?'':$_GET['coursePath'])."&amp;courseCode=".(empty($_GET['courseCode'])?'':$_GET['courseCode'])."&amp;month=". ($month == 12 ? 1 : $month +1)."&amp;year=". ($month == 12 ? $year +1 : $year);
+
+	echo 	"<table class=\"data_table\">\n",
+			"<tr>\n",
+			"<th width=\"10%\"><a href=\"", $backwardsURL, "\"> &laquo; </a></th>\n",
+			"<th width=\"80%\" colspan=\"5\">", $monthName, " ", $year, "</th>\n",
+			"<th  width=\"10%\"><a href=\"", $forewardsURL, "\"> &raquo; </a></th>\n", "</tr>\n";
+	echo "<tr>\n";
+	for ($ii = 1; $ii < 8; $ii ++)
+	{
+		echo "<td class=\"weekdays\">", $DaysShort[$ii % 7], "</td>\n";
+	}
+	echo "</tr>\n";
+	$curday = -1;
+	$today = getdate();
+	while ($curday <= $numberofdays[$month])
+	{
+		echo "<tr>\n";
+		for ($ii = 0; $ii < 7; $ii ++)
+		{
+			if (($curday == -1) && ($ii == $startdayofweek))
+			{
+				$curday = 1;
+			}
+			if (($curday > 0) && ($curday <= $numberofdays[$month]))
+			{
+				$bgcolor = $ii < 5 ? $class="class=\"days_week\"" : $class="class=\"days_weekend\"";
+				$dayheader = "$curday";
+				if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon']))
+				{
+					$dayheader = "$curday";
+					$class = "class=\"days_today\"";
+				}
+				echo "\t<td ".$class.">";
+				if (!empty($agendaitems[$curday]))
+				{
+					echo "<a href=\"".api_get_self()."?".api_get_cidreq()."&amp;action=view&amp;view=day&amp;day=".$curday."&amp;month=".$month."&amp;year=".$year."\">".$dayheader."</a>";
+				}
+				else
+				{
+					echo $dayheader;
+				}
+				// "a".$dayheader." <span class=\"agendaitem\">".$agendaitems[$curday]."</span>\n";
+				echo "</td>\n";
+				$curday ++;
+			}
+			else
+			{
+				echo "<td>&nbsp;</td>\n";
+			}
+		}
+		echo "</tr>\n";
+	}
+	echo "</table>\n";
+}
+/**
+* show the calender of the given month
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @param integer $month: the integer value of the month we are viewing
+* @param integer $year: the 4-digit year indication e.g. 2005
+* @return html code
+*/
+/**
+* returns all the javascript that is required for easily selecting the target people/groups this goes into the $htmlHeadXtra[] array
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @return javascript code
+*/
+function to_javascript()
+{
+$Send2All=get_lang("Send2All");
+return "<script type=\"text/javascript\" language=\"JavaScript\">
+<!-- Begin javascript menu swapper
+
+function move(fbox,	tbox)
+{
+	var	arrFbox	= new Array();
+	var	arrTbox	= new Array();
+	var	arrLookup =	new	Array();
+
+	var	i;
+	for	(i = 0;	i <	tbox.options.length; i++)
+	{
+		arrLookup[tbox.options[i].text]	= tbox.options[i].value;
+		arrTbox[i] = tbox.options[i].text;
+	}
+
+	var	fLength	= 0;
+	var	tLength	= arrTbox.length;
+
+	for(i =	0; i < fbox.options.length;	i++)
+	{
+		arrLookup[fbox.options[i].text]	= fbox.options[i].value;
+
+		if (fbox.options[i].selected &&	fbox.options[i].value != \"\")
+		{
+			arrTbox[tLength] = fbox.options[i].text;
+			tLength++;
+		}
+		else
+		{
+			arrFbox[fLength] = fbox.options[i].text;
+			fLength++;
+		}
+	}
+
+	arrFbox.sort();
+	arrTbox.sort();
+	fbox.length	= 0;
+	tbox.length	= 0;
+
+	var	c;
+	for(c =	0; c < arrFbox.length; c++)
+	{
+		var	no = new Option();
+		no.value = arrLookup[arrFbox[c]];
+		no.text	= arrFbox[c];
+		fbox[c]	= no;
+	}
+	for(c =	0; c < arrTbox.length; c++)
+	{
+		var	no = new Option();
+		no.value = arrLookup[arrTbox[c]];
+		no.text	= arrTbox[c];
+		tbox[c]	= no;
+	}
+}
+
+function checkDate(month, day, year)
+{
+  var monthLength =
+    new Array(31,28,31,30,31,30,31,31,30,31,30,31);
+
+  if (!day || !month || !year)
+    return false;
+
+  // check for bisestile year
+  if (year/4 == parseInt(year/4))
+    monthLength[1] = 29;
+
+  if (month < 1 || month > 12)
+    return false;
+
+  if (day > monthLength[month-1])
+    return false;
+
+  return true;
+}
+
+function mktime()
+{
+    var no, ma = 0, mb = 0, i = 0, d = new Date(), argv = arguments, argc = argv.length;
+    d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1972);
+    var dateManip = {
+        0: function(tt){ return d.setHours(tt); },
+        1: function(tt){ return d.setMinutes(tt); },
+        2: function(tt){ set = d.setSeconds(tt); mb = d.getDate() - 1; return set; },
+        3: function(tt){ set = d.setMonth(parseInt(tt)-1); ma = d.getFullYear() - 1972; return set; },
+        4: function(tt){ return d.setDate(tt+mb); },
+        5: function(tt){ return d.setYear(tt+ma); }
+    };
+    for( i = 0; i < argc; i++ ){
+        no = parseInt(argv[i]*1);
+        if (isNaN(no)) {
+            return false;
+        } else {
+            // arg is number, lets manipulate date object
+            if(!dateManip[i](no)){
+                // failed
+                return false;
+            }
+        }
+    }
+    return Math.floor(d.getTime()/1000);
+}
+
+function validate()
+{
+	var	f =	document.new_calendar_item;
+	f.submit();
+	return true;
+}
+
+function validate_date()
+{
+		var start_day = document.new_calendar_item.fday.value;
+		var start_month = document.new_calendar_item.fmonth.value;
+		var start_year = document.new_calendar_item.fyear.value;
+		var start_hour = document.new_calendar_item.fhour.value;
+		var start_minute = document.new_calendar_item.fminute.value;
+		var start_date = mktime(start_hour,start_minute,0,start_month,start_day,start_year)
+
+		var ends_day = document.new_calendar_item.end_fday.value;
+		var ends_month = document.new_calendar_item.end_fmonth.value;
+		var ends_year = document.new_calendar_item.end_fyear.value;
+		var ends_hour = document.new_calendar_item.end_fhour.value;
+		var ends_minute = document.new_calendar_item.end_fminute.value;
+		var ends_date = mktime(ends_hour,ends_minute,0,ends_month,ends_day,ends_year)
+
+		msg_err1 = document.getElementById(\"err_date\");
+		msg_err2 = document.getElementById(\"err_start_date\");
+		msg_err3 = document.getElementById(\"err_end_date\");
+		msg_err4 = document.getElementById(\"err_title\");
+
+		if (start_date > ends_date) {
+			msg_err1.style.display =\"block\";
+			msg_err1.innerHTML=\"".get_lang('EndDateCannotBeBeforeTheStartDate')."\";
+			msg_err2.innerHTML=\"\";msg_err3.innerHTML=\"\";
+		} else if (checkDate(start_month,start_day,start_year) == false) {
+			msg_err2.style.display =\"block\";
+			msg_err2.innerHTML=\"".get_lang('InvalidDate')."\";
+			msg_err1.innerHTML=\"\";msg_err3.innerHTML=\"\";
+		} else if (checkDate(ends_month,ends_day,ends_year) == false) {
+			msg_err3.style.display =\"block\";
+			msg_err3.innerHTML=\"".get_lang('InvalidDate')."\";
+			msg_err1.innerHTML=\"\";msg_err2.innerHTML=\"\";
+		} else if (document.new_calendar_item.title.value == '') {
+			msg_err4.style.display =\"block\";
+			msg_err4.innerHTML=\"".get_lang('FieldRequired')."\";
+			msg_err1.innerHTML=\"\";msg_err2.innerHTML=\"\";msg_err3.innerHTML=\"\";
+		}  else {
+			document.new_calendar_item.submit();
+		}
+
+}
+//	End	-->
+</script>";
+}
+
+
+
+/**
+* returns the javascript for setting a filter. This is a jump menu
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @return javascript code
+*/
+function user_group_filter_javascript()
+{
+return "<script language=\"JavaScript\" type=\"text/JavaScript\">
+<!--
+function MM_jumpMenu(targ,selObj,restore){
+  eval(targ+\".location='\"+selObj.options[selObj.selectedIndex].value+\"'\");
+  if (restore) selObj.selectedIndex=0;
+}
+//-->
+</script>
+";
+}
+
+function display_monthcalendar($month, $year)
+{
+	global $MonthsLong;
+	global $DaysShort;
+	global $origin;
+
+	// grabbing all the calendar items for this year and storing it in a array
+	$data=get_calendar_items($month,$year);
+
+
+	//Handle leap year
+	$numberofdays = array(0,31,28,31,30,31,30,31,31,30,31,30,31);
+	if (($year%400 == 0) or ($year%4==0 and $year%100<>0)) $numberofdays[2] = 29;
+
+	//Get the first day of the month
+	$dayone = getdate(mktime(0,0,0,$month,1,$year));
+  	//Start the week on monday
+	$startdayofweek = $dayone['wday']<>0 ? ($dayone['wday']-1) : 6;
+
+	$backwardsURL = api_get_self()."?".api_get_cidreq()."&amp;origin=$origin&amp;month=".($month==1 ? 12 : $month-1)."&amp;year=".($month==1 ? $year-1 : $year);
+	$forewardsURL = api_get_self()."?".api_get_cidreq()."&amp;origin=$origin&amp;month=".($month==12 ? 1 : $month+1)."&amp;year=".($month==12 ? $year+1 : $year);
+
+	   $maand_array_maandnummer=$month-1;
+
+	echo "<table class=\"data_table\">\n",
+		"<tr>\n",
+		"<th width=\"10%\"><a href=\"",$backwardsURL,"\"> &laquo; </a></th>\n",
+		"<th width=\"80%\" colspan=\"5\">",$MonthsLong[$maand_array_maandnummer]," ",$year,"</th>\n",
+		"<th width=\"10%\"><a href=\"",$forewardsURL,"\"> &raquo; </a></th>\n",
+		"</tr>\n";
+
+	echo "<tr>\n";
+
+	for ($ii=1;$ii<8; $ii++)
+	{
+	echo "<td class=\"weekdays\" width=\"14%\">",$DaysShort[$ii%7],"</td>\n";
+  }
+
+	echo "</tr>\n";
+	$curday = -1;
+	$today = getdate();
+	while ($curday <=$numberofdays[$month])
+  	{
+	echo "<tr>\n";
+    	for ($ii=0; $ii<7; $ii++)
+	  	{
+	  		if (($curday == -1)&&($ii==$startdayofweek))
+			{
+	    		$curday = 1;
+			}
+			if (($curday>0)&&($curday<=$numberofdays[$month]))
+			{
+				$bgcolor = $ii<5 ? "class=\"row_odd\"" : "class=\"row_even\"";
+
+				$dayheader = "$curday";
+				if (key_exists($curday,$data))
+				{
+					$dayheader="<a href='".api_get_self()."?".api_get_cidreq()."&amp;view=list&amp;origin=$origin&amp;month=$month&amp;year=$year&amp;day=$curday#$curday'>".$curday."</a>";
+					foreach ($data[$curday] as $key=>$agenda_item)
+					{
+						foreach ($agenda_item as $key=>$value)
+						{
+							$dayheader .= '<br /><b>'.substr($value['start_date'],11,8).'</b>';
+							$dayheader .= ' - ';
+							$dayheader .= $value['title'];
+						}
+					}
+				}
+
+				if (($curday==$today['mday'])&&($year ==$today['year'])&&($month == $today['mon']))
+				{
+			echo "<td id=\"today\" ",$bgcolor,"\">".$dayheader." \n";
+      }
+				else
+				{
+			echo "<td id=\"days\" ",$bgcolor,"\">".$dayheader." \n";
+				}
+			echo "</td>\n";
+
+	      		$curday++;
+	    }
+	  		else
+	    {
+	echo "<td>&nbsp;</td>";
+
+	    }
+		}
+	echo "</tr>";
+    }
+echo "</table>";
+}
+/**
+* this function shows the form with the user that were not selected
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @return html code
+*/
+/**
+* This function stores the Agenda Item in the table calendar_event and updates the item_property table also
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @return integer the id of the last added agenda item
+*/
+function store_new_agenda_item()
+{
+	global $_user /*, $_course*/;
+	$TABLEAGENDA = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+    //$t_agenda_repeat = Database::get_course_Table(TABLE_AGENDA_REPEAT);
+
+	// some filtering of the input data
+	$title=strip_tags(trim($_POST['title'])); // no html allowed in the title
+	$content=trim($_POST['content']);
+	$start_date=(int)$_POST['fyear']."-".(int)$_POST['fmonth']."-".(int)$_POST['fday']." ".(int)$_POST['fhour'].":".(int)$_POST['fminute'].":00";
+    $end_date=(int)$_POST['end_fyear']."-".(int)$_POST['end_fmonth']."-".(int)$_POST['end_fday']." ".(int)$_POST['end_fhour'].":".(int)$_POST['end_fminute'].":00";
+
+	// store in the table calendar_event
+	 $sql = "INSERT INTO ".$TABLEAGENDA."
+					        (title,content, start_date, end_date)
+					        VALUES
+					        ('".$title."','".$content."', '".$start_date."','".$end_date."')";
+
+	$result = Database::query($sql,__FILE__,__LINE__) or die (Database::error());
+	$last_id=Database::insert_id();
+
+	// store in last_tooledit (first the groups, then the users
+	$to=$_POST['selectedform'];
+	/*	if ((!is_null($to))or (!empty($_SESSION['toolgroup']))) // !is_null($to): when no user is selected we send it to everyone
+	{
+		$send_to=separate_users_groups($to);
+		// storing the selected groups
+		if (is_array($send_to['groups']))
+		{
+			foreach ($send_to['groups'] as $group)
+			{
+				api_item_property_update($_course, TOOL_CALENDAR_EVENT, $last_id,"AgendaAdded", $_user['user_id'], $group,'',$start_date, $end_date);
+			}
+		}
+		// storing the selected users
+		if (is_array($send_to['users']))
+		{
+			foreach ($send_to['users'] as $user)
+			{
+				api_item_property_update($_course, TOOL_CALENDAR_EVENT, $last_id,"AgendaAdded", $_user['user_id'],'',$user, $start_date,$end_date);
+			}
+		}
+	}
+	else // the message is sent to everyone, so we set the group to 0
+	{
+		api_item_property_update($_course, TOOL_CALENDAR_EVENT, $last_id,"AgendaAdded", $_user['user_id'], '','',$start_date,$end_date);
+	}*/
+
+// storing the resources
+	//store_resources($_SESSION['source_type'],$last_id);
+
+    //if repetitive, insert element into agenda_repeat table
+/*    if(!empty($_POST['repeat']) && !empty($_POST['repeat_type']))
+    {
+    	if(!empty($_POST['repeat_end_year']) && !empty($_POST['repeat_end_month']) && !empty($_POST['repeat_end_day']))
+        {
+        	$end_y = intval($_POST['repeat_end_year']);
+            $end_m = intval($_POST['repeat_end_month']);
+            $end_d = intval($_POST['repeat_end_day']);
+            $end = mktime((int)$_POST['fhour'],(int)$_POST['fminute'],0,$end_m,$end_d,$end_y);
+            $now = time();
+            $type = Database::escape_string($_POST['repeat_type']);
+
+        	if($end > $now
+                && in_array($type,array('daily','weekly','monthlyByDate','monthlyByDay','monthlyByDayR','yearly')))
+            {
+        	   $sql = "INSERT INTO $t_agenda_repeat (cal_id, cal_type, cal_end)" .
+                    " VALUES ($last_id,'$type',$end)";
+               $res = Database::query($sql,__FILE__,__LINE__);
+            }
+        }
+    }
+	return $last_id;*/
+}
+
+/**
+* The links that allows the student AND course administrator to show all agenda items and sort up/down
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+function display_courseadmin_links() {
+	echo "<a href='".api_get_self()."?".api_get_cidreq()."&action=add&amp;origin=".Security::remove_XSS($_GET['origin'])."'>".Display::return_icon('calendar_personal_add.gif', get_lang('AgendaAdd'))." ".get_lang('AgendaAdd')."</a>";
+
+}
+function display_student_links()
+{
+	global $show;
+	if ($_SESSION['sort'] == 'DESC')
+	{
+		echo "<a href='".api_get_self()."?sort=asc&amp;origin=".$_GET['origin']."'>".Display::return_icon('calendar_up.gif',get_lang('AgendaSortChronologicallyUp')).' '.get_lang("AgendaSortChronologicallyUp")."</a>";
+	}
+	else
+	{
+		echo "<a href='".api_get_self()."?sort=desc&amp;origin=".$_GET['origin']."'>".Display::return_icon('calendar_down.gif',get_lang('AgendaSortChronologicallyDown')).' '.get_lang("AgendaSortChronologicallyDown")."</a>";
+	}
+	if ($_SESSION['view'] <> 'month')
+	{
+		echo "\t<a href=\"".api_get_self()."?action=view&amp;view=month\"><img src=\"../img/calendar_month.gif\" border=\"0\" alt=\"".get_lang('MonthView')."\" /> ".get_lang('MonthView')."</a>\n";
+	}
+	else
+	{
+		echo "\t<a href=\"".api_get_self()."?action=view&amp;view=list\"><img src=\"../img/calendar_select.gif\" border=\"0\" alt=\"".get_lang('ListView')."\" /> ".get_lang('ListView')."</a>\n";
+	}
+}
+/**
+* get all the information of the agenda_item from the database
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @param integer the id of the agenda item we are getting all the information of
+* @return an associative array that contains all the information of the agenda item. The keys are the database fields
+*/
+function get_agenda_item($id)
+{
+	$TABLEAGENDA = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+    //$t_agenda_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT);
+    $item = array();
+	if(empty($id))
+    {
+        $id=(int)addslashes($_GET['id']);
+    }
+    else
+    {
+    	$id = (int) $id;
+    }
+    if(empty($id)){return $item;}
+	$sql 					= "SELECT * FROM ".$TABLEAGENDA." WHERE id='".$id."'";
+	$result					= Database::query($sql,__FILE__,__LINE__);
+	$entry_to_edit 			= Database::fetch_array($result);
+	$item['title']			= $entry_to_edit["title"];
+	$item['content']		= $entry_to_edit["content"];
+	$item['start_date']		= $entry_to_edit["start_date"];
+	$item['end_date']		= $entry_to_edit["end_date"];
+	$item['to']				== "everyone";
+	// if the item has been sent to everybody then we show the compact to form
+	if ($item['to']=="everyone")
+	{
+		$_SESSION['allow_individual_calendar']="hide";
+	}
+	else
+	{
+		$_SESSION['allow_individual_calendar']="show";
+	}
+
+	return $item;
+}
+/**
+* This is the function that updates an agenda item. It does 3 things
+* 1. storethe start_date, end_date, title and message in the calendar_event table
+* 2. store the groups/users who this message is meant for in the item_property table
+* 3. modify the attachments (if needed)
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+function store_edited_agenda_item()
+{
+
+	// STEP 1: editing the calendar_event table
+	// 1.a.  some filtering of the input data
+	$id=(int)$_POST['id'];
+	$title=strip_tags(trim($_POST['title'])); // no html allowed in the title
+	$content=trim($_POST['content']);
+	$start_date=(int)$_POST['fyear']."-".(int)$_POST['fmonth']."-".(int)$_POST['fday']." ".(int)$_POST['fhour'].":".(int)$_POST['fminute'].":00";
+	$end_date=(int)$_POST['end_fyear']."-".(int)$_POST['end_fmonth']."-".(int)$_POST['end_fday']." ".(int)$_POST['end_fhour'].":".(int)$_POST['end_fminute'].":00";
+	$to=$_POST['selectedform'];
+	// 1.b. the actual saving in calendar_event table
+	$edit_result=save_edit_agenda_item($id,$title,$content,$start_date,$end_date);
+
+	echo '<br />';
+	Display::display_normal_message(get_lang("EditSuccess"));
+
+}
+
+/**
+* This function stores the Agenda Item in the table calendar_event and updates the item_property table also (after an edit)
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+function save_edit_agenda_item($id,$title,$content,$start_date,$end_date)
+{
+	$TABLEAGENDA = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+		$id=Database::escape_string($id);
+		$title=Database::escape_string($title);
+		$content=Database::escape_string($content);
+		$start_date=Database::escape_string($start_date);
+		$end_date=Database::escape_string($end_date);
+
+
+	// store the modifications in the table calendar_event
+	$sql = "UPDATE ".$TABLEAGENDA."
+								SET title='".$title."',
+									content='".$content."',
+									start_date='".$start_date."',
+									end_date='".$end_date."'
+								WHERE id='".$id."'";
+	$result = Database::query($sql,__FILE__,__LINE__) or die (Database::error());
+	return true;
+}
+
+/**
+* This is the function that deletes an agenda item.
+* The agenda item is no longer fycically deleted but the visibility in the item_property table is set to 2
+* which means that it is invisible for the student AND course admin. Only the platform administrator can see it.
+* This will in a later stage allow the platform administrator to recover resources that were mistakenly deleted
+* by the course administrator
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @param integer the id of the agenda item wa are deleting
+*/
+function delete_agenda_item($id)
+{
+	global $_course;
+	$id=Database::escape_string($id);
+	if (is_allowed_to_edit()  && !api_is_anonymous())
+	{
+		if (!empty($_GET['id']) && isset($_GET['action']) && $_GET['action']=="delete")
+		{
+		    $t_agenda     = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+            $id=(int)addslashes($_GET['id']);
+            $sql = "SELECT * FROM $t_agenda WHERE id = $id";
+            $res = Database::query($sql,__FILE__,__LINE__);
+            if(Database::num_rows($res)>0)
+            {
+                $sql = "DELETE FROM ".$t_agenda." WHERE id='$id'";
+                $result = Database::query($sql,__FILE__,__LINE__) or die (Database::error());
+            }
+			api_item_property_update($_course,TOOL_CALENDAR_EVENT,$id,'delete',api_get_user_id());
+			$id=null;
+			echo '<br />';
+			Display::display_normal_message(get_lang("AgendaDeleteSuccess"));
+		}
+	}
+
+}
+/**
+* Makes an agenda item visible or invisible for a student
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @param integer id the id of the agenda item we are changing the visibility of
+*/
+function showhide_agenda_item($id)
+{
+	global $nameTools;
+	/*==================================================
+				SHOW / HIDE A CALENDAR ITEM
+	  ==================================================*/
+	//  and $_GET['isStudentView']<>"false" is added to prevent that the visibility is changed after you do the following:
+	// change visibility -> studentview -> course manager view
+	if ((is_allowed_to_edit() && !api_is_anonymous()) and $_GET['isStudentView']<>"false")
+	{
+		if (isset($_GET['id'])&&$_GET['id']&&isset($_GET['action'])&&$_GET['action']=="showhide")
+		{
+			$id=(int)addslashes($_GET['id']);
+			change_visibility($nameTools,$id);
+			Display::display_normal_message(get_lang("VisibilityChanged"));
+		}
+	}
+}
+/**
+* Displays all the agenda items
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @author Yannick Warnier <yannick.warnier@dokeos.com> - cleanup
+*/
+function display_agenda_items()
+{
+	$TABLEAGENDA = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+	global $select_month, $select_year;
+	global $DaysShort, $DaysLong, $MonthsLong;
+	global $is_courseAdmin;
+	global $dateFormatLong, $timeNoSecFormat,$charset, $_user, $_course;
+
+	// getting the group memberships
+	//$group_memberships=GroupManager::get_group_ids($_course['dbName'],$_user['user_id']);
+
+	// getting the name of the groups
+	//$group_names=get_course_groups();
+
+	/*--------------------------------------------------
+			CONSTRUCT THE SQL STATEMENT
+	  --------------------------------------------------*/
+
+    $start = 0;
+    $stop = 0;
+	// this is to make a difference between showing everything (all months) or only the current month)
+	// $show_all_current is a part of the sql statement
+	if ($_SESSION['show']!=="showall")
+	{
+		$show_all_current=" AND MONTH(start_date)=$select_month AND year(start_date)=$select_year";
+        $start = mktime(0,0,0,$select_month,1,$select_year);
+        $stop = 0;
+        if(empty($select_year)){$select_year = date('Y');}
+        if(empty($select_month)){$select_month = date('m');}
+        if($select_month==12)
+        {
+            $stop = mktime(0,0,0,1,1,$select_year+1)-1;
+        }
+        else
+        {
+            $stop = mktime(0,0,0,$select_month+1,1,$select_year)-1;
+        }
+	}
+	else
+	{
+		$show_all_current="";
+        $start = time();
+        $stop = mktime(0,0,0,1,1,2038);//by default, set year to maximum for mktime()
+	}
+
+	// by default we use the id of the current user. The course administrator can see the agenda of other users by using the user / group filter
+
+    $repeats = array(); //placeholder for repeated events
+
+	if (is_allowed_to_edit() && !api_is_anonymous()) {
+		$sql="SELECT * FROM ".$TABLEAGENDA.' ORDER BY start_date '.$_SESSION['sort'];
+		//echo "<pre>".$sql."</pre>";
+		$result=Database::query($sql,__FILE__,__LINE__) or die(Database::error());
+		$number_items=Database::num_rows($result);
+	} else {
+		$number_items = 0;
+	}
+
+
+	/*--------------------------------------------------
+			DISPLAY: NO ITEMS
+	  --------------------------------------------------*/
+	if ($number_items==0)
+	{
+        echo "<table class=\"data_table\" ><tr><td>".get_lang("NoAgendaItems")."</td></tr></table>";
+	}
+
+	/*--------------------------------------------------
+			DISPLAY: THE ITEMS
+	  --------------------------------------------------*/
+
+    $month_bar="";
+    $event_list="";
+    $counter=0;
+    $export_icon = 'export.png';
+    $export_icon_low = 'export_low_fade.png';
+    $export_icon_high = 'export_high_fade.png';
+
+    while($myrow=Database::fetch_array($result))
+    {
+    	$is_repeated = !empty($myrow['parent_event_id']);
+	    echo '<table class="data_table">',"\n";
+        /*--------------------------------------------------
+        		display: the month bar
+         --------------------------------------------------*/
+        // Make the month bar appear only once.
+        if ($month_bar != date("m",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"])))
+		{
+            $month_bar = date("m",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"]));
+			echo "\t<tr>\n\t\t<td class=\"agenda_month_divider\" colspan=\"3\" valign=\"top\">".
+			api_ucfirst(format_locale_date("%B %Y",strtotime($myrow["start_date"]))).
+			"</td>\n\t</tr>\n";
+		}
+
+        /*--------------------------------------------------
+         display: the icon, title, destinees of the item
+         -------------------------------------------------*/
+    	echo '<tr>';
+
+    	// highlight: if a date in the small calendar is clicked we highlight the relevant items
+    	$db_date=(int)date("d",strtotime($myrow["start_date"])).date("n",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"]));
+    	if ($_GET["day"].$_GET["month"].$_GET["year"] <>$db_date)
+    	{
+    		if ($myrow['visibility']=='0')
+    		{
+    			$style="data_hidden";
+    			$stylenotbold="datanotbold_hidden";
+    			$text_style="text_hidden";
+    		}
+    		else
+    		{
+    			$style="data";
+    			$stylenotbold="datanotbold";
+    			$text_style="text";
+    		}
+
+    	}
+    	else
+    	{
+    		$style="datanow";
+    		$stylenotbold="datanotboldnow";
+    		$text_style="textnow";
+    	}
+
+    	echo "\t\t<th>\n";
+    	// adding an internal anchor
+    	echo "\t\t\t<a name=\"".(int)date("d",strtotime($myrow["start_date"]))."\"></a>";
+    	// the icons. If the message is sent to one or more specific users/groups
+    	// we add the groups icon
+    	// 2do: if it is sent to groups we display the group icon, if it is sent to a user we show the user icon
+    	Display::display_icon('agenda.gif', get_lang('Agenda'));
+    	if ($myrow['to_group_id']!=='0')
+    	{
+    		echo Display::return_icon('group.gif', get_lang('Group'));
+    	}
+    	echo " ".$myrow['title']."\n";
+    	echo "\t\t</th>\n";
+
+    	// the message has been sent to
+    	echo "\t\t<th>".get_lang("SentTo").": ".get_lang('AllUsersOfThePlatform');
+    	//$sent_to=sent_to(TOOL_CALENDAR_EVENT, $myrow["ref"]);
+    	//$sent_to_form=sent_to_form($sent_to);
+    //	echo $sent_to_form;
+    	echo "</th>";
+
+    	if (!$is_repeated && (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous())))
+    	{
+    		if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $myrow['id'] ) ) )
+			{ // a coach can only delete an element belonging to his session
+	    		echo '<th>'.get_lang('Modify');
+	    		echo '</th></tr>';
+			}
+    	}
+
+        /*--------------------------------------------------
+     			display: the title
+         --------------------------------------------------*/
+    	echo "<tr class='row_odd'>";
+    	echo "\t\t<td>".get_lang("StartTimeWindow").": ";
+    	echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["start_date"])))."&nbsp;&nbsp;&nbsp;";
+    	echo ucfirst(strftime($timeNoSecFormat,strtotime($myrow["start_date"])))."";
+    	echo "</td>\n";
+    	echo "\t\t<td>";
+    	if ($myrow["end_date"]<>"0000-00-00 00:00:00")
+    	{
+    		echo get_lang("EndTimeWindow").": ";
+    		echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["end_date"])))."&nbsp;&nbsp;&nbsp;";
+    		echo ucfirst(strftime($timeNoSecFormat,strtotime($myrow["end_date"])))."";
+    	}
+    	echo "</td>\n";
+
+    	// attachment list
+	    	//$attachment_list=get_attachment($myrow['id']);
+
+        /*--------------------------------------------------
+    	 display: edit delete button (course admin only)
+         --------------------------------------------------*/
+
+
+    	if (!$is_repeated && (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous())))
+    	{
+    		if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $myrow['id'] ) ) )
+			{ // a coach can only delete an element belonging to his session
+				$mylink = api_get_self().'?'.api_get_cidreq().'&amp;origin='.Security::remove_XSS($_GET['origin']).'&amp;id='.$myrow['id'];
+	    		echo '<td align="center">';
+	    		// edit
+    			echo '<a href="'.$mylink.'&amp;action=edit&amp;title="'.get_lang("ModifyCalendarItem").'">';
+	    		echo Display::return_icon('edit.gif', get_lang('ModifyCalendarItem'))."</a>";
+
+    			echo "<a href=\"".$mylink."&amp;action=delete\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."')) return false;\"  title=\"".get_lang("Delete")."\"> ";
+	    		echo Display::return_icon('delete.gif', get_lang('Delete'))."</a>";
+			}
+
+    	if (!$is_repeated && (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous())))
+    	{
+    		if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $myrow['id'] ) ) )
+			{ // a coach can only delete an element belonging to his session
+    			$td_colspan= '<td colspan="3">';
+			}
+			else
+			{
+				$td_colspan= '<td colspan="2">';
+			}
+    	}
+    	else
+    	{
+    		$td_colspan= '<td colspan="2">';
+    	}
+    	$mylink = 'calendar_ical_export.php?'.api_get_cidreq().'&amp;type=course&amp;id='.$myrow['id'];
+		echo '<a class="ical_export" href="'.$mylink.'&amp;class=confidential" title="'.get_lang('ExportiCalConfidential').'">'.Display::return_icon($export_icon_high, get_lang('ExportiCalConfidential')).'</a> ';
+    	echo '<a class="ical_export" href="'.$mylink.'&amp;class=private" title="'.get_lang('ExportiCalPrivate').'">'.Display::return_icon($export_icon_low, get_lang('ExportiCalPrivate')).'</a> ';
+    	echo '<a class="ical_export" href="'.$mylink.'&amp;class=public" title="'.get_lang('ExportiCalPublic').'">'.Display::return_icon($export_icon, get_lang('ExportiCalPublic')).'</a> ';
+	    echo '<a href="#" onclick="javascript:win_print=window.open(\'calendar_view_print.php?id='.$myrow['id'].'\',\'popup\',\'left=100,top=100,width=700,height=500,scrollbars=1,resizable=0\'); win_print.focus(); return false;">'.Display::return_icon('print.gif', get_lang('Print')).'</a>&nbsp;';
+    	echo '</td>';
+    	echo '</tr>';
+}
+
+        /*--------------------------------------------------
+     			display: the content
+         --------------------------------------------------*/
+    	$content = $myrow['content'];
+    	$content = make_clickable($content);
+    	$content = text_filter($content);
+    	echo "<tr class='row_even'>";
+    	echo "<td colspan='3'>";
+
+    	echo $content;
+    	// show attachment list
+			if (!empty($attachment_list)) {
+
+				$realname=$attachment_list['path'];
+				$user_filename=$attachment_list['filename'];
+				$full_file_name = 'download.php?file='.$realname;
+				echo Display::return_icon('attachment.gif',get_lang('Attachment'));
+				echo '<a href="'.$full_file_name.'';
+				echo ' "> '.$user_filename.' </a>';
+				echo '<span class="forum_attach_comment" >'.$attachment_list['comment'].'</span>';
+				if (api_is_allowed_to_edit()) {
+					echo '&nbsp;&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;origin='.Security::remove_XSS($_GET['origin']).'&amp;action=delete_attach&amp;id_attach='.$attachment_list['id'].'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset)).'\')) return false;">'.Display::return_icon('delete.gif',get_lang('Delete')).'</a><br />';
+				}
+
+			}
+
+	    echo '</td></tr>';
+
+
+        /*--------------------------------------------------
+     			display: the added resources
+         --------------------------------------------------
+    	if (check_added_resources("Agenda", $myrow["id"]))
+    	{
+
+    		echo '<tr>';
+    		echo '<td colspan="3">';
+    		echo "<i>".get_lang("AddedResources")."</i><br/>";
+    		if ($myrow['visibility']==0)
+    		{
+    			$addedresource_style="invisible";
+    		}
+    		display_added_resources("Agenda", $myrow["id"], $addedresource_style);
+    		echo "</td></tr>";
+    	}*/
+
+
+    	$event_list.=$myrow['id'].',';
+
+    	$counter++;
+        /*--------------------------------------------------
+    	 display: jump-to-top icon
+         --------------------------------------------------*/
+    	echo '<tr>';
+        echo '<td colspan="3">';
+        if($is_repeated){echo get_lang('RepeatedEvent'),'<a href="',api_get_self(),'?',api_get_cidreq,'&amp;agenda_id=',$myrow['parent_event_id'],'" alt="',get_lang('RepeatedEventViewOriginalEvent'),'">',get_lang('RepeatedEventViewOriginalEvent'),'</a>';}
+    	echo "<a href=\"#top\">".Display::return_icon('top.gif', get_lang('Top'))."</a></td></tr>";
+    	echo "</table><br /><br />";
+    } // end while ($myrow=Database::fetch_array($result))
+
+    if(!empty($event_list))
+    {
+    	$event_list=substr($event_list,0,-1);
+    }
+    else
+    {
+    	$event_list='0';
+    }
+
+    echo "<form name=\"event_list_form\"><input type=\"hidden\" name=\"event_list\" value=\"$event_list\" /></form>";
+
+    // closing the layout table
+    echo "</td>",
+    	"</tr>",
+    	"</table>";
+}
+
+/**
+* Displays only 1 agenda item. This is used when an agenda item is added to the learning path.
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+function display_one_agenda_item($agenda_id)
+{
+	$TABLEAGENDA = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+	global $TABLE_ITEM_PROPERTY;
+	global $select_month, $select_year;
+	global $DaysShort, $DaysLong, $MonthsLong;
+	global $is_courseAdmin;
+	global $dateFormatLong, $timeNoSecFormat, $charset;
+	global $_user;
+	$agenda_id=Database::escape_string($agenda_id);
+	//echo "displaying agenda items";
+
+	// getting the name of the groups
+	//$group_names=get_course_groups();
+
+	/*--------------------------------------------------
+			CONSTRUCT THE SQL STATEMENT
+	  --------------------------------------------------*/
+
+	$sql="SELECT *	FROM ".$TABLEAGENDA;
+	$result=Database::query($sql,__FILE__,__LINE__) or die(Database::error());
+	$number_items=Database::num_rows($result);
+	$myrow=Database::fetch_array($result); // there should be only one item so no need for a while loop
+
+    $sql_rep = "SELECT * FROM $TABLEAGENDA WHERE id = $agenda_id";
+    $res_rep = Database::query($sql_rep,__FILE__,__LINE__);
+    $repeat = false;
+    $repeat_id = 0;
+    if(Database::num_rows($res_rep)>0)
+    {
+        $repeat=true;
+        $row_rep = Database::fetch_array($res_rep);
+        //$repeat_id = $row_rep['parent_event_id'];
+    }
+
+	/*--------------------------------------------------
+			DISPLAY: NO ITEMS
+	  --------------------------------------------------*/
+	if ($number_items==0)
+	{
+		echo "<table id=\"data_table\" ><tr><td>".get_lang("NoAgendaItems")."</td></tr></table>";
+	}
+
+	/*--------------------------------------------------
+			DISPLAY: THE ITEMS
+	  --------------------------------------------------*/
+	echo "<table id=\"data_table\">\n";
+
+	/*--------------------------------------------------
+	 DISPLAY : the icon, title, destinees of the item
+	  --------------------------------------------------*/
+	echo "\t<tr>\n";
+
+	// highlight: if a date in the small calendar is clicked we highlight the relevant items
+	$db_date=(int)date("d",strtotime($myrow["start_date"])).date("n",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"]));
+	if ($_GET["day"].$_GET["month"].$_GET["year"] <>$db_date)
+	{
+		if ($myrow['visibility']=='0')
+		{
+			$style="data_hidden";
+			$stylenotbold="datanotbold_hidden";
+			$text_style="text_hidden";
+		}
+		else
+		{
+			$style="data";
+			$stylenotbold="datanotbold";
+			$text_style="text";
+		}
+	}
+	else
+	{
+		$style="datanow";
+		$stylenotbold="datanotboldnow";
+		$text_style="textnow";
+	}
+
+
+	echo "\t\t<td class=\"".$style."\">\n";
+
+	// adding an internal anchor
+	echo "\t\t\t<a name=\"".(int)date("d",strtotime($myrow["start_date"]))."\"></a>";
+
+	// the icons. If the message is sent to one or more specific users/groups
+	// we add the groups icon
+	// 2do: if it is sent to groups we display the group icon, if it is sent to a user we show the user icon
+	echo Display::return_icon('agenda.gif');
+	if ($myrow['to_group_id']!=='0')
+	{
+		echo Display::return_icon('group.gif');
+	}
+	echo " ".$myrow['title']."\n";
+	echo "\t\t</td>\n";
+
+	// the message has been sent to
+	echo "\t\t<td class=\"".$stylenotbold."\">".get_lang("SentTo").": ".get_lang('AllUsersOfThePlatform');
+	$sent_to=sent_to(TOOL_CALENDAR_EVENT, $myrow["ref"]);
+	$sent_to_form=sent_to_form($sent_to);
+	echo $sent_to_form;
+	echo "</td>\n\t</tr>\n";
+
+	/*--------------------------------------------------
+	 			DISPLAY: the title
+	  --------------------------------------------------*/
+	echo "\t<tr class=\"".$stylenotbold."\">\n";
+	echo "\t\t<td>".get_lang("StartTime").": ";
+	echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["start_date"])))."&nbsp;&nbsp;&nbsp;";
+	echo ucfirst(strftime($timeNoSecFormat,strtotime($myrow["start_date"])))."";
+	echo "</td>\n";
+	echo "\t\t<td>".get_lang("EndTime").": ";
+	echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["end_date"])))."&nbsp;&nbsp;&nbsp;";
+	echo ucfirst(strftime($timeNoSecFormat,strtotime($myrow["end_date"])))."";
+	echo "</td>\n";
+	echo "\n\t</tr>\n";
+
+	/*--------------------------------------------------
+	 			DISPLAY: the content
+	  --------------------------------------------------*/
+    $export_icon = '../img/export.png';
+    $export_icon_low = '../img/export_low_fade.png';
+    $export_icon_high = '../img/export_high_fade.png';
+
+	$content = $myrow['content'];
+	$content = make_clickable($content);
+	$content = text_filter($content);
+	//echo "\t<tr>\n\t\t<td class=\"".$text_style."\" colspan='2'>";
+	//echo $content;
+	//echo "</td></tr>";
+    echo "<tr class='row_even'>";
+    echo '<td colspan="2">';
+    echo $content;
+    echo '</td></tr>';
+
+	/*--------------------------------------------------
+	 			DISPLAY: the added resources
+	  --------------------------------------------------*/
+	if (check_added_resources("Agenda", $myrow["id"]))
+		{
+		echo "<tr><td colspan='2'>";
+		echo "<i>".get_lang("AddedResources")."</i><br/>";
+		if ($myrow['visibility']==0)
+		{
+			$addedresource_style="invisible";
+		}
+		display_added_resources("Agenda", $myrow["id"], $addedresource_style);
+		echo "</td></tr>";
+		}
+
+	/*--------------------------------------------------
+		DISPLAY: edit delete button (course admin only)
+	  --------------------------------------------------*/
+	echo '<tr><td colspan="2">';
+	if (!$repeat && api_is_allowed_to_edit(false,true))	{
+		// edit
+		$mylink = api_get_self()."?".api_get_cidreq()."&amp;origin=".Security::remove_XSS($_GET['origin'])."&amp;id=".$myrow['id'];
+		echo 	"<a href=\"".$mylink."&amp;action=edit\">",
+				Display::return_icon('edit.gif', get_lang('ModifyCalendarItem')), "</a>",
+				"<a href=\"".$mylink."&amp;action=delete\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."')) return false;\">",
+				Display::return_icon('delete.gif', get_lang('Delete')),"</a>";
+		if ($myrow['visibility']==1) {
+			$image_visibility="visible";
+		} else {
+			$image_visibility="invisible";
+		}
+		echo 	'<a href="'.$mylink.'&amp;action=showhide">',Display::return_icon($image_visibility, get_lang('Visible')),'</a><br /><br />';
+	}
+   	$mylink = 'calendar_ical_export.php?'.api_get_cidreq().'&amp;type=course&amp;id='.$myrow['id'];
+    echo '<a class="ical_export" href="'.$mylink.'&amp;class=confidential" title="'.get_lang('ExportiCalConfidential').'">'.Display::return_icon($export_icon_high, get_lang('ExportiCalConfidential')).'</a> ';
+    	echo '<a class="ical_export" href="'.$mylink.'&amp;class=private" title="'.get_lang('ExportiCalPrivate').'">'.Display::return_icon($export_icon_low, get_lang('ExportiCalPrivate')).'</a> ';
+    	echo '<a class="ical_export" href="'.$mylink.'&amp;class=public" title="'.get_lang('ExportiCalPublic').'">'.Display::return_icon($export_icon, get_lang('ExportiCalPublic')).'</a> ';
+    echo '<a href="#" onclick="javascript:win_print=window.open(\'calendar_view_print.php?id='.$myrow['id'].'\',\'popup\',\'left=100,top=100,width=700,height=500,scrollbars=1,resizable=0\'); win_print.focus(); return false;">'.Display::return_icon('print.gif', get_lang('Print')).'</a>&nbsp;';
+	echo "</td>";
+    if($repeat) {
+    	echo '<tr>';
+    	echo '<td colspan="2">',get_lang('RepeatedEvent'),'<a href="',api_get_self(),'?',api_get_cidreq(),'&amp;agenda_id=',$repeat_id,'" alt="',get_lang('RepeatedEventViewOriginalEvent'),'">',get_lang('RepeatedEventViewOriginalEvent'),'</a></td>';
+        echo '</tr>';
+    }
+	echo "</table>";
+
+	// closing the layout table
+	echo "</td>",
+		"</tr>",
+		"</table>";
+}
+/**
+* Show the form for adding a new agenda item. This is the same function that is used whenever we are editing an
+* agenda item. When the id parameter is empty (default behaviour), then we show an empty form, else we are editing and
+* we have to retrieve the information that is in the database and use this information in the forms.
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @param integer id, the id of the agenda item we are editing. By default this is empty which means that we are adding an
+*		 agenda item.
+*/
+function show_group_filter_form()
+{
+$group_list=get_course_groups();
+
+echo "<select name=\"select\" onchange=\"MM_jumpMenu('parent',this,0)\">";
+echo "<option value=\"agenda.php?group=none\">show all groups</option>";
+/*foreach($group_list as $this_group)
+	{
+	// echo "<option value=\"agenda.php?isStudentView=true&amp;group=".$this_group['id']."\">".$this_group['name']."</option>";
+	echo "<option value=\"agenda.php?group=".$this_group['id']."\" ";
+	echo ($this_group['id']==$_SESSION['group'])? " selected":"" ;
+	echo ">".$this_group['name']."</option>";
+	}*/
+echo "</select>";
+}
+
+function show_user_filter_form()
+{
+$user_list=get_course_users();
+
+//echo "<select name=\"select\" onchange=\"MM_jumpMenu('parent',this,0)\">";
+//echo "<option value=\"agenda.php?user=none\">show all users</option>";
+/*foreach($user_list as $this_user)
+	{
+	// echo "<option value=\"agenda.php?isStudentView=true&amp;user=".$this_user['uid']."\">".$this_user['lastName']." ".$this_user['firstName']."</option>";
+	echo "<option value=\"agenda.php?user=".$this_user['uid']."\" ";
+	echo ($this_user['uid']==$_SESSION['user'])? " selected":"" ;
+	echo ">".$this_user['lastName']." ".$this_user['firstName']."</option>";
+	}*/
+echo "</select>";
+}
+
+function show_user_group_filter_form()
+{
+	echo "\n<select name=\"select\" onchange=\"MM_jumpMenu('parent',this,0)\">";
+	echo "\n\t<option value=\"agenda.php?user=none\">".get_lang("ShowAll")."</option>";
+
+	// Groups
+	echo "\n\t<optgroup label=\"".get_lang("Groups")."\">";
+	$group_list=get_course_groups();
+/*	foreach($group_list as $this_group)
+	{
+		// echo "<option value=\"agenda.php?isStudentView=true&amp;group=".$this_group['id']."\">".$this_group['name']."</option>";
+		echo "\n\t\t<option value=\"agenda.php?group=".$this_group['id']."\" ";
+		echo ($this_group['id']==$_SESSION['group'])? " selected":"" ;
+		echo ">".$this_group['name']."</option>";
+	}*/
+	echo "\n\t</optgroup>";
+
+	// Users
+	echo "\n\t<optgroup label=\"".get_lang("Users")."\">";
+	$user_list=get_course_users();
+/*	foreach($user_list as $this_user)
+		{
+		// echo "<option value=\"agenda.php?isStudentView=true&amp;user=".$this_user['uid']."\">".$this_user['lastName']." ".$this_user['firstName']."</option>";
+		echo "\n\t\t<option value=\"agenda.php?user=".$this_user['uid']."\" ";
+		echo ($this_user['uid']==$_SESSION['user'])? " selected":"" ;
+		echo ">".$this_user['lastName']." ".$this_user['firstName']."</option>";
+		}*/
+	echo "\n\t</optgroup>";
+	echo "</select>";
+}
+
+function show_add_form($id = '')
+{
+
+	global $MonthsLong;
+	$htmlHeadXtra[] = to_javascript();
+	// the default values for the forms
+	if ($_GET['originalresource'] !== 'no')
+	{
+		$day	= date('d');
+		$month	= date('m');
+		$year	= date('Y');
+		$hours	= 9;
+		$minutes= '00';
+
+		$end_day	= date('d');
+		$end_month	= date('m');
+		$end_year	= date('Y');
+		$end_hours	= 17;
+		$end_minutes= '00';
+        $repeat = false;
+	}
+	else
+	{
+
+		// we are coming from the resource linker so there might already have been some information in the form.
+		// When we clicked on the button to add resources we stored every form information into a session and now we
+		// are doing the opposite thing: getting the information out of the session and putting it into variables to
+		// display it in the forms.
+		$form_elements=$_SESSION['formelements'];
+		$day=$form_elements['day'];
+		$month=$form_elements['month'];
+		$year=$form_elements['year'];
+		$hours=$form_elements['hour'];
+		$minutes=$form_elements['minutes'];
+		$end_day=$form_elements['end_day'];
+		$end_month=$form_elements['end_month'];
+		$end_year=$form_elements['end_year'];
+		$end_hours=$form_elements['end_hours'];
+		$end_minutes=$form_elements['end_minutes'];
+		$title=$form_elements['title'];
+		$content=$form_elements['content'];
+		$id=$form_elements['id'];
+		$to=$form_elements['to'];
+        $repeat = $form_elements['repeat'];
+	}
+
+
+	//	switching the send to all/send to groups/send to users
+	if ($_POST['To'])
+	{
+			$day			= $_POST['fday'];
+			$month			= $_POST['fmonth'];
+			$year			= $_POST['fyear'];
+			$hours			= $_POST['fhour'];
+			$minutes		= $_POST['fminute'];
+			$end_day		= $_POST['end_fday'];
+			$end_month		= $_POST['end_fmonth'];
+			$end_year		= $_POST['end_fyear'];
+			$end_hours		= $_POST['end_fhour'];
+			$end_minutes	= $_POST['end_fminute'];
+			$title 			= $_POST['title'];
+			$content		= $_POST['content'];
+			// the invisible fields
+			$action			= $_POST['action'];
+			$id				= $_POST['id'];
+            $repeat         = !empty($_POST['repeat'])?true:false;
+		}
+
+
+	// if the id is set then we are editing an agenda item
+	if (is_int($id))
+	{
+		//echo "before get_agenda_item".$_SESSION['allow_individual_calendar'];
+		$item_2_edit=get_agenda_item($id);
+		$title	= $item_2_edit['title'];
+		$content= $item_2_edit['content'];
+		// start date
+		list($datepart, $timepart) = split(" ", $item_2_edit['start_date']);
+		list($year, $month, $day) = explode("-", $datepart);
+		list($hours, $minutes, $seconds) = explode(":", $timepart);
+		// end date
+		list($datepart, $timepart) = split(" ", $item_2_edit['end_date']);
+		list($end_year, $end_month, $end_day) = explode("-", $datepart);
+		list($end_hours, $end_minutes, $end_seconds) = explode(":", $timepart);
+		// attachments
+		//edit_added_resources("Agenda", $id);
+		$to=$item_2_edit['to'];
+		//echo "<br />after get_agenda_item".$_SESSION['allow_individual_calendar'];
+	}
+	$content=stripslashes($content);
+	$title=stripslashes($title);
+	// we start a completely new item, we do not come from the resource linker
+	if ($_GET['originalresource']!=="no" and $_GET['action']=="add")
+	{
+
+		$_SESSION["formelements"]=null;
+		//unset_session_resources();//--------------------------------------------------------------------------------------
+	}
+?>
+
+<!-- START OF THE FORM  -->
+<form enctype="multipart/form-data"  action="<?php echo api_get_self().'?origin='.$_GET['origin'].'&amp;action='.$_GET['action']; ?>" method="post" name="new_calendar_item">
+<input type="hidden" name="id" value="<?php if (isset($id)) echo $id; ?>" />
+<input type="hidden" name="action" value="<?php if (isset($_GET['action'])) echo $_GET['action']; ?>" />
+<input type="hidden" name="sort" value="asc" />
+<input type="hidden" name="submit_event" value="ok" />
+<?php
+	echo '<div class="row"><div class="form_header">';
+	echo (isset($id) AND $id<>'')?get_lang('ModifyCalendarItem'):get_lang("AddCalendarItem");
+	echo '</div></div>';
+	?>
+<table border="0" cellpadding="5" cellspacing="0" width="80%" id="newedit_form">
+	<!-- START date and time -->
+<tr>
+<div>
+<table border="0" width="80%">
+				<tr><td colspan="4">
+					<div id="err_date" style="display:none;color:red"></div>
+					<div id="err_start_date" style="display:none;color:red"></div>
+				</td></tr>
+				<td width="10%">
+					<!-- date: 1 -> 31 -->
+					<nobr><?php echo get_lang('StartDate').": \n"; ?></nobr>
+				</td>
+				<td width="35%">
+					<select name="fday" onchange="javascript:document.new_calendar_item.end_fday.value=this.value;">
+							<?php
+							// small loop for filling all the dates
+							// 2do: the available dates should be those of the selected month => february is from 1 to 28 (or 29) and not to 31
+							echo "\n";
+							foreach (range(1, 31) as $i)
+											{
+											// values have to have double digits
+											$value = ($i <= 9 ? '0'.$i : $i );
+											// the current day is indicated with [] around the date
+											if ($value==$day)
+											{
+												echo "\t\t\t\t <option value=\"".$value."\" selected> ".$i." </option>\n";
+											}
+											else
+											{
+												echo "\t\t\t\t<option value=\"$value\">$i</option>\n";
+											}
+										}
+										 ?>
+					</select>
+					<!-- month: january -> december -->
+					<select name="fmonth" onchange="javascript:document.new_calendar_item.end_fmonth.value=this.value;">
+					<?php
+											echo "\n";
+											for ($i=1; $i<=12; $i++)
+											{
+												// values have to have double digits
+												if ($i<=9)
+												{
+													$value="0".$i;
+												}
+												else
+												{
+													$value=$i;
+												}
+												if ($value==$month)
+												{
+													echo "\t\t\t\t <option value=\"".$value."\" selected>".$MonthsLong[$i-1]."</option>\n";
+												}
+												else
+												{
+													echo "\t\t\t\t <option value=\"".$value."\">".$MonthsLong[$i-1]."</option>\n";
+												}
+											} ?>
+					</select>
+					<select name="fyear" onchange="javascript:document.new_calendar_item.end_fyear.value=this.value;">
+										<option value="<?php echo ($year-1); ?>"><?php echo ($year-1); ?></option>
+											<option value="<?php echo $year; ?>" selected="selected"><?php echo $year; ?></option>
+											<?php
+												echo "\n";
+												for ($i=1; $i<=5; $i++)
+												{
+													$value=$year+$i;
+													echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
+												} ?>
+					</select>
+					<a href="javascript:openCalendar('new_calendar_item','f')"><?php Display::display_icon('calendar_select.gif', get_lang('Select'), array ('style' => 'vertical-align: middle;')); ?></a>
+					</td>
+					<td width="10%">
+						<nobr><?php echo get_lang('StartTime').": \n"; ?></nobr>
+					</td>
+					<td>
+						<select name="fhour" onchange="javascript:document.new_calendar_item.end_fhour.value=this.value;">
+							<!-- <option value="--">--</option> -->
+							<?php
+								echo "\n";
+								foreach (range(0, 23) as $i)
+								{
+									// values have to have double digits
+									$value = ($i <= 9 ? '0'.$i : $i );
+									// the current hour is indicated with [] around the hour
+									if ($hours==$value)
+									{
+										echo "\t\t\t\t<option value=\"".$value."\" selected> ".$value." </option>\n";
+									}
+									else
+									{
+										echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
+									}
+								} ?>
+						</select>
+
+						<select name="fminute" onchange="javascript:document.new_calendar_item.end_fminute.value=this.value;">
+							<!-- <option value="<?php echo $minutes ?>"><?php echo $minutes; ?></option> -->
+							<!-- <option value="--">--</option> -->
+							<?php
+								foreach (range(0, 59) as $i)
+								{
+									// values have to have double digits
+									$value = ($i <= 9 ? '0'.$i : $i );
+									echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
+								} ?>
+						</select>
+					</td>
+
+</div>
+</tr>
+			<!-- END date and time -->
+<tr>
+<div>
+					<tr><td colspan="4"><div id="err_end_date" style="display:none;color:red"></div></td></tr>
+					<td >
+							<!-- date: 1 -> 31 -->
+							<nobr><?php echo get_lang('EndDate').": "; ?></nobr>
+					</td>
+					<td  >
+						<select name="end_fday">
+							<?php
+								// small loop for filling all the dates
+								// 2do: the available dates should be those of the selected month => february is from 1 to 28 (or 29) and not to 31
+								echo "\n";
+								foreach (range(1, 31) as $i)
+								{
+									// values have to have double digits
+									$value = ($i <= 9 ? '0'.$i : $i );
+									// the current day is indicated with [] around the date
+									if ($value==$end_day)
+										{ echo "\t\t\t\t <option value=\"".$value."\" selected> ".$i." </option>\n";}
+									else
+										{ echo "\t\t\t\t <option value=\"".$value."\">".$i."</option>\n"; }
+									}?>
+						</select>
+							<!-- month: january -> december -->
+						<select name="end_fmonth">
+								<?php
+								echo "\n";
+								foreach (range(1, 12) as $i)
+								{
+									// values have to have double digits
+									$value = ($i <= 9 ? '0'.$i : $i );
+									if ($value==$end_month)
+										{ echo "\t\t\t\t <option value=\"".$value."\" selected>".$MonthsLong[$i-1]."</option>\n"; }
+									else
+										{ echo "\t\t\t\t <option value=\"".$value."\">".$MonthsLong[$i-1]."</option>\n"; }
+									}?>
+						</select>
+						<select name="end_fyear">
+								<option value="<?php echo ($end_year-1) ?>"><?php echo ($end_year-1) ?></option>
+								<option value="<?php echo $end_year ?>" selected> <?php echo $end_year ?> </option>
+								<?php
+								echo "\n";
+								for ($i=1; $i<=5; $i++)
+								{
+									$value=$end_year+$i;
+									echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
+								} ?>
+						</select>
+						<a href="javascript:openCalendar('new_calendar_item', 'end_f')"><?php Display::display_icon('calendar_select.gif',get_lang('Select'), array ('style' => 'vertical-align: middle;')); ?></a>
+					</td>
+					<td >
+						<nobr><?php echo get_lang('EndTime').": \n"; ?></nobr>
+					</td>
+					<td >
+						<select name="end_fhour">
+							<!-- <option value="--">--</option> -->
+							<?php
+								echo "\n";
+								foreach (range(0, 23) as $i)
+								{
+									// values have to have double digits
+									$value = ($i <= 9 ? '0'.$i : $i );
+									// the current hour is indicated with [] around the hour
+									if ($end_hours==$value)
+										{ echo "\t\t\t\t<option value=\"".$value."\" selected> ".$value." </option>\n"; }
+									else
+										{ echo "\t\t\t\t<option value=\"".$value."\"> ".$value." </option>\n"; }
+								} ?>
+						</select>
+
+						<select name="end_fminute">
+							<!-- <option value="<?php echo $end_minutes; ?>"><?php echo $end_minutes; ?></option> -->
+							<!-- <option value="--">--</option> -->
+							<?php
+								foreach (range(0, 59) as $i)
+								{
+									// values have to have double digits
+									$value = ($i <= 9 ? '0'.$i : $i );
+									echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
+								} ?>
+						</select>
+						<br>
+				</td>
+</div>
+</tr>
+<tr><td colspan="4">
+<hr noshade="noshade" color="#cccccc" />
+	<div id="err_title" style="display:none;color:red"></div>
+</td></tr>
+<tr class="subtitle">
+		<td colspan="4" valign="top"><?php echo get_lang('ItemTitle'); ?> :
+			<!--<div style='margin-left: 80px'><textarea name="title" cols="50" rows="2" wrap="virtual" style="vertical-align:top; width:75%; height:50px;"><?php  if (isset($title)) echo $title; ?></textarea></div>-->
+			<input type="text" size="60" name="title" value="<?php  if (isset($title)) echo $title; ?>" />
+		</td>
+	</tr>
+
+	<tr>
+		<td colspan="4">
+
+			<?php
+			require_once(api_get_path(LIBRARY_PATH) . "/fckeditor/fckeditor.php");
+
+			$oFCKeditor = new FCKeditor('content') ;
+
+			$oFCKeditor->ToolbarSet = 'GlobalAgenda';
+			$oFCKeditor->Width		= '100%';
+			$oFCKeditor->Height		= '175';
+			$oFCKeditor->Value		= $content;
+
+			$return =	$oFCKeditor->CreateHtml();
+
+			echo $return;
+
+ ?>
+		</td>
+	</tr>
+	<!--<?php /* ADDED BY UGENT, Patrick Cool, march 2004 */ ?>
+	<tr>
+		<td colspan="4">
+	    <?php
+			//onclick="selectAll(this.form.elements[6],true)"
+
+//				show_addresource_button('onclick="selectAll(this.form.elements[6],true)"');
+
+		?>
+		</td>
+	</tr>-->
+	<?php
+	   //if ($_SESSION['addedresource'])
+	   echo "\t<tr>\n";
+	   echo "\t\t<td colspan=\"4\">\n";
+	   //echo display_resources(0);//--------------------------------------------------------
+	   $test=$_SESSION['addedresource'];
+	   echo "\t\t</td>\n\t</tr>\n";
+	   /* END ADDED BY UGENT, Patrick Cool, march 2004 */
+    if(empty($id)) //only show repeat fields when adding the first time
+    {
+	?>
+
+    <tr>
+      <td colspan="4" />
+    </tr>
+    <?php
+    }//only show repeat fields if adding, not if editing
+    ?>
+	<tr>
+		<td colspan="4">
+		<?php
+		if ($_GET['action']=='edit'){
+			$class='save';
+			$text=get_lang('ModifyEvent');
+
+		}else{
+			$class='add';
+			$text=get_lang('AddEvent');
+		}
+		?>
+		<button type="button" class="add" value="<?php echo get_lang('Ok'); ?>" onclick="validate_date()" ><?php echo $text;  ?></button>
+
+		</td>
+	</tr>
+</table>
+</form>
+<?php
+}
+
+function get_agendaitems($month, $year)
+{
+	global $_user;
+	global $_configuration;
+	$month=Database::escape_string($month);
+	$year=Database::escape_string($year);
+
+	$items = array ();
+
+	//databases of the courses
+	$TABLEAGENDA = Database :: get_course_table(TABLE_MAIN_SYSTEM_CALENDAR);
+	//$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
+
+	//$group_memberships = GroupManager :: get_group_ids(Database::get_current_course_database(), $_user['user_id']);
+	// if the user is administrator of that course we show all the agenda items
+	//if (api_is_allowed_to_edit())
+	//{
+		//echo "course admin";
+		$sqlquery = "SELECT
+						DISTINCT *
+						FROM ".$TABLEAGENDA."
+						WHERE
+						MONTH(start_date)='".$month."'
+						AND YEAR(start_date)='".$year."'
+						GROUP BY id
+						ORDER BY start_date ";
+	//}
+	// if the user is not an administrator of that course
+/*	else
+	{
+		//echo "GEEN course admin";
+		if (is_array($group_memberships) && count($group_memberships)>0)
+		{
+			$sqlquery = "SELECT
+							agenda.*
+							FROM ".$TABLEAGENDA."
+							WHERE
+							MONTH(agenda.start_date)='".$month."'
+							AND YEAR(agenda.start_date)='".$year."'
+							ORDER BY start_date ";
+		}
+		else
+		{
+			$sqlquery = "SELECT
+							agenda.*, item_property.*
+							FROM ".$TABLEAGENDA."
+							WHERE
+							MONTH(agenda.start_date)='".$month."'
+							AND YEAR(agenda.start_date)='".$year."'
+							ORDER BY start_date ";
+		}
+	}*/
+
+	//$mycourse = api_get_course_info();
+	$portal_url = $_configuration['root_web'];
+	if ($_configuration['multiple_access_urls']==true) {
+		$access_url_id = api_get_current_access_url_id();
+		if ($access_url_id != -1 ){
+			$url = api_get_access_url($access_url_id);
+			$portal_url = $url['url'];
+		}
+	}
+
+    $result = Database::query($sqlquery, __FILE__, __LINE__);
+	while ($item = Database::fetch_array($result))
+	{
+		$agendaday = date('j',strtotime($item['start_date']));
+		$time= date('H:i',strtotime($item['start_date']));
+		$URL = $portal_url.'main/admin/agenda.php?day='.$agendaday."&amp;month=".$month."&amp;year=".$year; // RH  //Patrick Cool: to highlight the relevant agenda item
+		$items[$agendaday][$item['start_time']] .= '<i>'.$time.'</i> <a href="'.$URL.'" title="'.$item['title'].'<br />';
+	}
+
+	// sorting by hour for every day
+	$agendaitems = array ();
+	while (list ($agendaday, $tmpitems) = each($items))
+	{
+		sort($tmpitems);
+		while (list ($key, $val) = each($tmpitems))
+		{
+			$agendaitems[$agendaday] .= $val;
+		}
+	}
+	return $agendaitems;
+}
+
+function display_upcoming_events()
+{
+	echo '<b>'.get_lang('UpcomingEvent').'</b><br />';
+	$number_of_items_to_show = (int)api_get_setting('number_of_upcoming_events');
+
+	//databases of the courses
+	$TABLEAGENDA = Database :: get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+	//$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
+    //$mycourse = api_get_course_info();
+    //$myuser = api_get_user_info();
+
+	//$group_memberships = GroupManager :: get_group_ids($mycourse['dbName'], $myuser['user_id']);
+	// if the user is administrator of that course we show all the agenda items
+	/*if (api_is_allowed_to_edit())
+	{*/
+		//echo "course admin";
+		$sqlquery = "SELECT
+						DISTINCT *
+						FROM ".$TABLEAGENDA."
+						ORDER BY start_date ";
+	//}
+	// if the user is not an administrator of that course
+	$result = Database::query($sqlquery, __FILE__, __LINE__);
+	$counter = 0;
+	while ($item = Database::fetch_array($result,'ASSOC'))
+	{
+		if ($counter < $number_of_items_to_show)
+		{
+			echo $item['start_date'],' - ',$item['title'],'<br />';
+			$counter++;
+		}
+	}
+}
+/**
+ * This function calculates the startdate of the week (monday)
+ * and the enddate of the week (sunday)
+ * and returns it as an array
+ */
+function calculate_start_end_of_week($week_number, $year)
+{
+	// determine the start and end date
+	// step 1: we calculate a timestamp for a day in this week
+	$random_day_in_week = mktime(0, 0, 0, 1, 1, $year) + ($week_number-1) * (7 * 24 * 60 * 60); // we calculate a random day in this week
+	// step 2: we which day this is (0=sunday, 1=monday, ...)
+	$number_day_in_week = date('w', $random_day_in_week);
+	// step 3: we calculate the timestamp of the monday of the week we are in
+	$start_timestamp = $random_day_in_week - (($number_day_in_week -1) * 24 * 60 * 60);
+	// step 4: we calculate the timestamp of the sunday of the week we are in
+	$end_timestamp = $random_day_in_week + ((7 - $number_day_in_week +1) * 24 * 60 * 60) - 3600;
+	// step 5: calculating the start_day, end_day, start_month, end_month, start_year, end_year
+	$start_day = date('j', $start_timestamp);
+	$start_month = date('n', $start_timestamp);
+	$start_year = date('Y', $start_timestamp);
+	$end_day = date('j', $end_timestamp);
+	$end_month = date('n', $end_timestamp);
+	$end_year = date('Y', $end_timestamp);
+	$start_end_array['start']['day'] = $start_day;
+	$start_end_array['start']['month'] = $start_month;
+	$start_end_array['start']['year'] = $start_year;
+	$start_end_array['end']['day'] = $end_day;
+	$start_end_array['end']['month'] = $end_month;
+	$start_end_array['end']['year'] = $end_year;
+	return $start_end_array;
+}
+/**
+ * Show the mini calendar of the given month
+ */
+function display_daycalendar($agendaitems, $day, $month, $year, $weekdaynames, $monthName)
+{
+	global $DaysShort, $DaysLong, $course_path;
+	global $MonthsLong;
+	global $query;
+
+	// timestamp of today
+	$today = mktime();
+	$nextday = $today + (24 * 60 * 60);
+	$previousday = $today - (24 * 60 * 60);
+	// the week number of the year
+	$week_number = date("W", $today);
+	// if we moved to the next / previous day we have to recalculate the $today variable
+	if ($_GET['day'])
+	{
+		$today = mktime(0, 0, 0, $month, $day, $year);
+		$nextday = $today + (24 * 60 * 60);
+		$previousday = $today - (24 * 60 * 60);
+		$week_number = date("W", $today);
+	}
+	// calculating the start date of the week
+	// the date of the monday of this week is the timestamp of today minus
+	// number of days that have already passed this week * 24 hours * 60 minutes * 60 seconds
+	$current_day = date("j", $today); // Day of the month without leading zeros (1 to 31) of today
+	$day_of_the_week = date("w", $today); // Numeric representation of the day of the week	0 (for Sunday) through 6 (for Saturday) of today
+	//$timestamp_first_date_of_week=$today-(($day_of_the_week-1)*24*60*60); // timestamp of the monday of this week
+	//$timestamp_last_date_of_week=$today+((7-$day_of_the_week)*24*60*60); // timestamp of the sunday of this week
+	// we are loading all the calendar items of all the courses for today
+	echo "<table class=\"data_table\">\n";
+	// the forward and backwards url
+	$backwardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=day&amp;day=".date("j", $previousday)."&amp;month=".date("n", $previousday)."&amp;year=".date("Y", $previousday);
+	$forewardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=day&amp;day=".date("j", $nextday)."&amp;month=".date("n", $nextday)."&amp;year=".date("Y", $nextday);
+	// The title row containing the day
+	echo "<tr>\n", "<th width=\"10%\"><a href=\"", $backwardsURL, "\">&#171;</a></th>\n", "<th>";
+	echo $DaysLong[$day_of_the_week]." ".date("j", $today)." ".$MonthsLong[date("n", $today) - 1]." ".date("Y", $today);
+	echo "</th>";
+	echo "<th width=\"10%\"><a href=\"", $forewardsURL, "\">&#187;</a></th>\n";
+	echo "</tr>\n";
+	// the rows for each half an hour
+	for ($i = 10; $i < 48; $i ++)
+	{
+		if ($i % 2 == 0)
+		{
+			$class = "class=\"row_even\"";
+		}
+		else
+		{
+			$class = "class=\"row_odd\"";
+		}
+		echo "<tr $class>\n";
+		echo "\t";
+		if ($i % 2 == 0)
+		{
+			echo ("<td valign=\"top\" width=\"75\">". (($i) / 2)." ".get_lang("HourShort")." 00</td>\n");
+		}
+		else
+		{
+			echo ("<td valign=\"top\" width=\"75\">". ((($i) / 2) - (1 / 2))." ".get_lang("HourShort")." 30</td>\n");
+		}
+		echo "\t<td $class valign=\"top\" colspan=\"2\">\n";
+		if (is_array($agendaitems[$i]))
+		{
+			foreach ($agendaitems[$i] as $key => $value)
+			{
+				echo $value;
+			}
+		}
+		else
+		{
+			echo $agendaitems[$i];
+		}
+		echo "\t</td>\n";
+		echo "</tr>\n";
+	}
+	echo "</table>\n";
+}
+/**
+ *	Display the weekly view of the calendar
+ */
+function display_weekcalendar($agendaitems, $month, $year, $weekdaynames, $monthName)
+{
+	global $DaysShort,$course_path;
+	global $MonthsLong;
+	// timestamp of today
+	$today = time();
+	$day_of_the_week = date("w", $today);
+	$thisday_of_the_week = date("w", $today);
+	// the week number of the year
+	$week_number = date("W", $today);
+	$thisweek_number = $week_number;
+	// if we moved to the next / previous week we have to recalculate the $today variable
+	if ($_GET['week'])
+	{
+		$today = mktime(0, 0, 0, 1, 1, $year);
+		$today = $today + (((int)$_GET['week']-1) * (7 * 24 * 60 * 60));
+		$week_number = date("W", $today);
+	}
+	// calculating the start date of the week
+	// the date of the monday of this week is the timestamp of today minus
+	// number of days that have already passed this week * 24 hours * 60 minutes * 60 seconds
+	$current_day = date("j", $today); // Day of the month without leading zeros (1 to 31) of today
+	$day_of_the_week = date("w", $today); // Numeric representation of the day of the week	0 (for Sunday) through 6 (for Saturday) of today
+	$timestamp_first_date_of_week = $today - (($day_of_the_week -1) * 24 * 60 * 60); // timestamp of the monday of this week
+	$timestamp_last_date_of_week = $today + ((7 - $day_of_the_week) * 24 * 60 * 60); // timestamp of the sunday of this week
+	$backwardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=week&amp;week=". ($week_number -1);
+	$forewardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=week&amp;week=". ($week_number +1);
+	echo "<table id=\"agenda_list\">\n";
+	// The title row containing the the week information (week of the year (startdate of week - enddate of week)
+	echo "<tr class=\"title\">\n";
+	echo "<td width=\"10%\"><a href=\"", $backwardsURL, "\">&#171;</a></td>\n";
+	echo "<td colspan=\"5\">".get_lang("Week")." ".$week_number;
+	echo " (".$DaysShort['1']." ".date("j", $timestamp_first_date_of_week)." ".$MonthsLong[date("n", $timestamp_first_date_of_week) - 1]." ".date("Y", $timestamp_first_date_of_week)." - ".$DaysShort['0']." ".date("j", $timestamp_last_date_of_week)." ".$MonthsLong[date("n", $timestamp_last_date_of_week) - 1]." ".date("Y", $timestamp_last_date_of_week).')';
+	echo "</td>";
+	echo "<td width=\"10%\"><a href=\"", $forewardsURL, "\">&#187;</a></td>\n", "</tr>\n";
+	// The second row containing the short names of the days of the week
+	echo "<tr>\n";
+	// this is the Day of the month without leading zeros (1 to 31) of the monday of this week
+	$tmp_timestamp = $timestamp_first_date_of_week;
+	for ($ii = 1; $ii < 8; $ii ++)
+	{
+		$is_today = ($ii == $thisday_of_the_week AND (!isset($_GET['week']) OR $_GET['week']==$thisweek_number));
+		echo "\t<td class=\"weekdays\">";
+		if ($is_today)
+		{
+			echo "<font color=#CC3300>";
+		}
+		echo $DaysShort[$ii % 7]." ".date("j", $tmp_timestamp)." ".$MonthsLong[date("n", $tmp_timestamp) - 1];
+		if ($is_today)
+		{
+			echo "</font>";
+		}
+		echo "</td>\n";
+		// we 24 hours * 60 minutes * 60 seconds to the $tmp_timestamp
+		$array_tmp_timestamp[] = $tmp_timestamp;
+		$tmp_timestamp = $tmp_timestamp + (24 * 60 * 60);
+	}
+	echo "</tr>\n";
+	// the table cells containing all the entries for that day
+	echo "<tr>\n";
+	$counter = 0;
+	foreach ($array_tmp_timestamp as $key => $value)
+	{
+		if ($counter < 5)
+		{
+			$class = "class=\"days_week\"";
+		}
+		else
+		{
+			$class = "class=\"days_weekend\"";
+		}
+		if ($counter == $thisday_of_the_week -1 AND (!isset($_GET['week']) OR $_GET['week']==$thisweek_number))
+		{
+			$class = "class=\"days_today\"";
+		}
+
+		echo "\t<td ".$class.">";
+		echo "<span class=\"agendaitem\">".$agendaitems[date('j', $value)]."&nbsp;</span> ";
+		echo "</td>\n";
+		$counter ++;
+	}
+	echo "</tr>\n";
+	echo "</table>\n";
+}
+/**
+ * Show the monthcalender of the given month
+ */
+function get_day_agendaitems($courses_dbs, $month, $year, $day)
+{
+	global $_user;
+	global $_configuration;
+	global $setting_agenda_link;
+
+	$items = array ();
+
+	// get agenda-items for every course
+	//$query=Database::query($sql_select_courses);
+	foreach ($courses_dbs as $key => $array_course_info)
+	{
+		//databases of the courses
+		$TABLEAGENDA = Database :: get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+		//$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $array_course_info['db']);
+
+		// getting all the groups of the user for the current course
+		//$group_memberships = GroupManager :: get_group_ids($array_course_info['db'], $_user['user_id']);
+		// if the user is administrator of that course we show all the agenda items
+		if ($array_course_info['status'] == '1')
+		{
+			//echo "course admin";
+			$sqlquery = "SELECT DISTINCT *
+										FROM ".$TABLEAGENDA."
+										WHERE
+										DAYOFMONTH(start_date)='".$day."' AND MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
+										GROUP BY agenda.id
+										ORDER BY start_date ";
+		}
+		// if the user is not an administrator of that course
+		/*else
+		{
+			//echo "GEEN course admin";
+			if (is_array($group_memberships) && count($group_memberships)>0)
+			{
+				$sqlquery = "SELECT
+													agenda.*
+													FROM ".$TABLEAGENDA."
+													WHERE
+													DAYOFMONTH(start_date)='".$day."' AND MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
+													ORDER BY start_date ";
+			}
+			else
+			{
+				$sqlquery = "SELECT
+													agenda.*
+													FROM ".$TABLEAGENDA."
+													WHERE
+													DAYOFMONTH(start_date)='".$day."' AND MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
+													ORDER BY start_date ";
+			}
+		}*/
+		//$sqlquery = "SELECT * FROM $agendadb WHERE DAYOFMONTH(day)='$day' AND month(day)='$month' AND year(day)='$year'";
+		//echo "abc";
+		//echo $sqlquery;
+		$result = Database::query($sqlquery, __FILE__, __LINE__);
+		$portal_url = $_configuration['root_web'];
+		if ($_configuration['multiple_access_urls']==true) {
+			$access_url_id = api_get_current_access_url_id();
+			if ($access_url_id != -1 ){
+				$url = api_get_access_url($access_url_id);
+				$portal_url = $url['url'];
+			}
+		}
+
+		//echo Database::num_rows($result);
+		while ($item = Database::fetch_array($result))
+		{
+			// in the display_daycalendar function we use $i (ranging from 0 to 47) for each halfhour
+			// we want to know for each agenda item for this day to wich halfhour it must be assigned
+			list ($datepart, $timepart) = split(" ", $item['start_date']);
+			list ($year, $month, $day) = explode("-", $datepart);
+			list ($hours, $minutes, $seconds) = explode(":", $timepart);
+
+			$halfhour = 2 * $hours;
+			if ($minutes >= '30')
+			{
+				$halfhour = $halfhour +1;
+			}
+
+			if ($setting_agenda_link == 'coursecode')
+			{
+				$title=$array_course_info['title'];
+				$agenda_link = api_substr($title, 0, 14);
+			}
+			else
+			{
+				$agenda_link = Display::return_icon('course_home.gif');
+			}
+
+			//$URL = $_configuration['root_web'].$mycours["dir"]."/";
+			$URL = $portal_url.'main/admin/agenda.php?cidReq='."&amp;day=$day&amp;month=$month&amp;year=$year#$day"; // RH  //Patrick Cool: to highlight the relevant agenda item
+			$items[$halfhour][] .= "<i>".$hours.":".$minutes."</i> <a href=\"$URL\" title=\"".$array_course_info['name']."\">".$agenda_link."</a>  ".$item['title']."<br />";
+		}
+	}
+	// sorting by hour for every day
+	$agendaitems = array();
+	while (list($agendaday, $tmpitems) = each($items))
+	{
+		sort($tmpitems);
+		while (list($key,$val) = each($tmpitems))
+		{
+			$agendaitems[$agendaday].=$val;
+		}
+	}
+	$agendaitems = $items;
+	//print_r($agendaitems);
+	return $agendaitems;
+}
+
+/**
+ * Return agenda items of the week
+ */
+function get_week_agendaitems($courses_dbs, $month, $year, $week = '')
+{
+	$TABLEAGENDA = Database :: get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+	global $_user;
+	global $_configuration;
+	global $setting_agenda_link;
+
+	$items = array ();
+	// The default value of the week
+	if ($week == '')
+	{
+		$week_number = date("W", time());
+	}
+	else
+	{
+		$week_number = $week;
+	}
+	$start_end = calculate_start_end_of_week($week_number, $year);
+	$start_filter = $start_end['start']['year']."-".$start_end['start']['month']."-".$start_end['start']['day'];
+	$end_filter = $start_end['end']['year']."-".$start_end['end']['month']."-".$start_end['end']['day'];
+	// get agenda-items for every course
+	foreach ($courses_dbs as $key => $array_course_info)
+	{
+		//databases of the courses
+		$TABLEAGENDA = Database :: get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+		//$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $array_course_info["db"]);
+
+		// getting all the groups of the user for the current course
+	//	$group_memberships = GroupManager :: get_group_ids($array_course_info["db"], $_user['user_id']);
+
+		// if the user is administrator of that course we show all the agenda items
+		//if ($array_course_info['status'] == '1')
+		//{
+			//echo "course admin";
+			$sqlquery = "SELECT DISTINCT * FROM ".$TABLEAGENDA." ORDER BY start_date";
+		//}
+		// if the user is not an administrator of that course
+		//else
+		//{
+			//echo "GEEN course admin";
+/*			if (is_array($group_memberships) && count($group_memberships)>0)
+			{
+				$sqlquery = "SELECT *  FROM ".$TABLEAGENDA." ORDER BY a.start_date";
+			}
+			else*/
+			//{
+			//	$sqlquery = "SELECT * FROM ".$TABLEAGENDA." ORDER BY a.start_date";
+			//}
+		//}
+		//echo "<pre>".$sqlquery."</pre>";
+		// $sqlquery = "SELECT * FROM $agendadb WHERE (DAYOFMONTH(day)>='$start_day' AND DAYOFMONTH(day)<='$end_day')
+		//				AND (MONTH(day)>='$start_month' AND MONTH(day)<='$end_month')
+		//				AND (YEAR(day)>='$start_year' AND YEAR(day)<='$end_year')";
+		$result = Database::query($sqlquery, __FILE__, __LINE__);
+
+		$portal_url = $_configuration['root_web'];
+		if ($_configuration['multiple_access_urls']==true) {
+			$access_url_id = api_get_current_access_url_id();
+			if ($access_url_id != -1 ){
+				$url = api_get_access_url($access_url_id);
+				$portal_url = $url['url'];
+			}
+		}
+
+		while ($item = Database::fetch_array($result))
+		{
+			$agendaday = date("j",strtotime($item['start_date']));
+			$time= date("H:i",strtotime($item['start_date']));
+
+			if ($setting_agenda_link == 'coursecode')
+			{
+				$title=$array_course_info['title'];
+				$agenda_link = api_substr($title, 0, 14);
+			}
+			else
+			{
+				$agenda_link = Display::return_icon('course_home.gif');
+			}
+
+			$URL = $portal_url."main/admin/agenda.php?cidReq=".urlencode($array_course_info["code"])."&amp;day=$agendaday&amp;month=$month&amp;year=$year#$agendaday"; // RH  //Patrick Cool: to highlight the relevant agenda item
+			$items[$agendaday][$item['start_time']] .= "<i>$time</i> <a href=\"$URL\" title=\"".$array_course_info["name"]."\">".$agenda_link."</a>  ".$item['title']."<br />";
+		}
+	}
+	// sorting by hour for every day
+	$agendaitems = array ();
+	while (list ($agendaday, $tmpitems) = each($items))
+	{
+		sort($tmpitems);
+		while (list ($key, $val) = each($tmpitems))
+		{
+			$agendaitems[$agendaday] .= $val;
+		}
+	}
+	//print_r($agendaitems);
+	return $agendaitems;
+}
+/**
+ * Get repeated events of a course between two dates (timespan of a day).
+ * Returns an array containing the events
+ * @param   string  Course info array (as returned by api_get_course_info())
+ * @param	int		UNIX timestamp of span start. Defaults 0, later transformed into today's start
+ * @param	int		UNIX timestamp. Defaults to 0, later transformed into today's end
+ * @param   array   A set of parameters to alter the SQL query
+ * @return	array	[int] => [course_id,parent_event_id,start_date,end_date,title,description]
+ */
+function get_repeated_events_day_view($course_info,$start=0,$end=0,$params)
+{
+	$events = array();
+	//initialise all values
+	$y=0;
+	$m=0;
+	$d=0;
+    //block $end if higher than 2038 -- PHP doesn't go past that
+    if($end>2145934800){$end = 2145934800;}
+	if($start == 0 or $end == 0)
+	{
+		$y=date('Y');
+		$m=date('m');
+		$d=date('j');
+	}
+	if($start==0)
+	{
+		$start = mktime(0,0,0,$m,$d,$y);
+	}
+	$db_start = date('Y-m-d H:i:s',$start);
+	if($end==0)
+	{
+		$end = mktime(23,59,59,$m,$d,$y);
+	}
+	//$db_end = date('Y-m-d H:i:s',$end);
+
+	$t_cal = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR,$course_info['dbName']);
+	//$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
+    $t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
+	$sql = "SELECT c.id, c.title, c.content, " .
+			" UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
+			" cr.cal_type, cr.cal_end " .
+			" FROM $t_cal c, $t_cal_repeat cr, $t_ip as item_property " .
+			" WHERE cr.cal_end >= $start " .
+			" AND cr.cal_id = c.id " .
+            " AND item_property.ref = c.id ".
+            " AND item_property.tool = '".TOOL_CALENDAR_EVENT."' ".
+			" AND c.start_date <= '$db_start' "
+            .(!empty($params['conditions'])?$params['conditions']:'')
+            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
+            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
+	$res = Database::query($sql,__FILE__,__LINE__);
+	if(Database::num_rows($res)>0)
+	{
+		while($row = Database::fetch_array($res))
+		{
+			$orig_start = $row['orig_start'];
+			$orig_end = $row['orig_end'];
+			$repeat_type = $row['cal_type'];
+			switch($repeat_type)
+			{
+				case 'daily':
+					//we are in the daily view, so if this element is repeated daily and
+					//the repetition is still active today (which is a condition of the SQL query)
+					//then the event happens today. Just build today's timestamp for start and end
+					$time_orig_h = date('H',$orig_start);
+					$time_orig_m = date('i',$orig_start);
+					$time_orig_s = date('s',$orig_start);
+					$int_time = (($time_orig_h*60)+$time_orig_m)*60+$time_orig_s; //time in seconds since 00:00:00
+					$span = $orig_end - $orig_start; //total seconds between start and stop of original event
+					$current_start =$start + $int_time; //unixtimestamp start of today's event
+					$current_stop = $start+$int_time+$span; //unixtimestamp stop of today's event
+					$events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
+					break;
+				case 'weekly':
+					$time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/W/j/N/G/i/s',$end);
+					list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig))) && ($dw_orig == $dw_now))
+					{ //if the event is after the original (at least one week) and the day of the week is the same
+					  $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				case 'monthlyByDate':
+					$time_orig = date('Y/n/j/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/j/G/i/s',$end);
+					list($y_now,$m_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig))) && ($d_orig == $d_now))
+					{
+					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				case 'monthlyByDayR':
+					//not implemented yet
+					break;
+				case 'monthlyByDay':
+					//not implemented yet
+					break;
+				case 'yearly':
+					$time_orig = date('Y/n/j/z/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/j/z/G/i/s',$end);
+					list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					if(($y_now>$y_orig) && ($dy_orig == $dy_now))
+					{
+					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				default:
+					break;
+			}
+		}
+	}
+	return $events;
+}
+/**
+ * Get repeated events of a course between two dates (timespan of a week).
+ * Returns an array containing the events
+ * @param	string	Course info array (as returned by api_get_course_info())
+ * @param	int		UNIX timestamp of span start. Defaults 0, later transformed into today's start
+ * @param	int		UNIX timestamp. Defaults to 0, later transformed into today's end
+ * @param   array   A set of parameters to alter the SQL query
+ * @return	array	[int] => [course_id,parent_event_id,start_date,end_date,title,description]
+ */
+function get_repeated_events_week_view($course_info,$start=0,$end=0,$params)
+{
+	$events = array();
+    //block $end if higher than 2038 -- PHP doesn't go past that
+    if($end>2145934800){$end = 2145934800;}
+	//initialise all values
+	$y=0;
+	$m=0;
+	$d=0;
+	if($start == 0 or $end == 0)
+	{
+		$time = time();
+		$dw = date('w',$time);
+		$week_start = $time - (($dw-1)*86400);
+		$y = date('Y',$week_start);
+		$m = date('m',$week_start);
+		$d = date('j',$week_start);
+		$w = date('W',$week_start);
+	}
+	if($start==0)
+	{
+		$start = mktime(0,0,0,$m,$d,$y);
+	}
+	$db_start = date('Y-m-d H:i:s',$start);
+	if($end==0)
+	{
+		$end = $start+(86400*7)-1; //start of week, more 7 days, minus 1 second to get back to the previoyus day
+	}
+	//$db_end = date('Y-m-d H:i:s',$end);
+
+	$t_cal = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+	//$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
+    //$t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
+    $sql = "SELECT c.id, c.title, c.content " .
+            " UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
+            " FROM". $t_cal ."
+             WHERE c.start_date <= '$db_start' "
+            .(!empty($params['conditions'])?$params['conditions']:'')
+            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
+            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
+	$res = Database::query($sql,__FILE__,__LINE__);
+	if(Database::num_rows($res)>0)
+	{
+		while($row = Database::fetch_array($res))
+		{
+			$orig_start = $row['orig_start'];
+			$orig_end = $row['orig_end'];
+			$repeat_type = $row['cal_type'];
+			switch($repeat_type)
+			{
+				case 'daily':
+					$time_orig_h = date('H',$orig_start);
+					$time_orig_m = date('i',$orig_start);
+					$time_orig_s = date('s',$orig_start);
+					$int_time = (($time_orig_h*60)+$time_orig_m)*60+$time_orig_s; //time in seconds since 00:00:00
+					$span = $orig_end - $orig_start; //total seconds between start and stop of original event
+					for($i=0;$i<7;$i++)
+					{
+						$current_start = $start + ($i*86400) + $int_time; //unixtimestamp start of today's event
+						$current_stop = $start + ($i*86400) + $int_time + $span; //unixtimestamp stop of today's event
+						$events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
+					}
+					break;
+				case 'weekly':
+					$time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/W/j/N/G/i/s',$end);
+					list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig))))
+					{ //if the event is after the original (at least one week) and the day of the week is the same
+					  $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				case 'monthlyByDate':
+					$time_orig = date('Y/n/W/j/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$w_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/W/j/G/i/s',$end);
+					list($y_now,$m_now,$w_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
+					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig))) && ($start<$event_repetition_time && $event_repetition_time<$end))
+					{ //if the event is after the original (at least one month) and the original event's day is between the first day of the week and the last day of the week
+					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				case 'monthlyByDayR':
+					//not implemented yet
+					break;
+				case 'monthlyByDay':
+					//not implemented yet
+					break;
+				case 'yearly':
+					$time_orig = date('Y/n/j/z/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/j/z/G/i/s',$end);
+					list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
+					if((($y_now>$y_orig) && ($start<$event_repetition_time && $event_repetition_time<$end)))
+					{
+					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				default:
+					break;
+			}
+		}
+	}
+	return $events;
+}
+/**
+ * Get repeated events of a course between two dates (timespan of a month).
+ * Returns an array containing the events
+ * @param   string  Course info array (as returned by api_get_course_info())
+ * @param	int		UNIX timestamp of span start. Defaults 0, later transformed into today's start
+ * @param	int		UNIX timestamp. Defaults to 0, later transformed into today's end
+ * @param   array   A set of parameters to alter the SQL query
+ * @return	array	[int] => [course_id,parent_event_id,start_date,end_date,title,description]
+ */
+function get_repeated_events_month_view($course_info,$start=0,$end=0,$params)
+{
+	$events = array();
+    //block $end if higher than 2038 -- PHP doesn't go past that
+    if($end>2145934800){$end = 2145934800;}
+	//initialise all values
+	$y=0;
+	$m=0;
+	$d=0;
+	if($start == 0 or $end == 0)
+	{
+		$time = time();
+		$y = date('Y');
+		$m = date('m');
+	}
+	if($start==0)
+	{
+		$start = mktime(0,0,0,$m,1,$y);
+	}
+	$db_start = date('Y-m-d H:i:s',$start);
+	if($end==0)
+	{
+		if($m==12)
+		{
+			$end = mktime(0,0,0,1,1,$y+1)-1; //start of next month, minus 1 second to get back to the previoyus day
+		}
+		else
+		{
+			$end = mktime(0,0,0,$m+1,1,$y)-1;
+		}
+	}
+	//$db_end = date('Y-m-d H:i:s',$end);
+
+	$t_cal = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+	//$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
+    //$t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
+    $sql = "SELECT c.id, c.title, c.content, " .
+            " UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
+            " cr.cal_type, cr.cal_end " .
+            " FROM $t_cal c, $t_cal_repeat cr, $t_ip as item_property " .
+            " WHERE cr.cal_end >= $start " .
+            " AND cr.cal_id = c.id " .
+            " AND item_property.ref = c.id ".
+            " AND item_property.tool = '".TOOL_CALENDAR_EVENT."' ".
+            " AND c.start_date <= '$db_start' "
+            .(!empty($params['conditions'])?$params['conditions']:'')
+            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
+            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
+	$res = Database::query($sql,__FILE__,__LINE__);
+	if(Database::num_rows($res)>0)
+	{
+		while($row = Database::fetch_array($res))
+		{
+			$orig_start = $row['orig_start'];
+			$orig_end = $row['orig_end'];
+			$repeat_type = $row['cal_type'];
+			switch($repeat_type)
+			{
+				case 'daily':
+					$time_orig_h = date('H',$orig_start);
+					$time_orig_m = date('i',$orig_start);
+					$time_orig_s = date('s',$orig_start);
+					$month_last_day = date('d',$end);
+					$int_time = (($time_orig_h*60)+$time_orig_m)*60+$time_orig_s; //time in seconds since 00:00:00
+					$span = $orig_end - $orig_start; //total seconds between start and stop of original event
+					for($i=0;$i<$month_last_day;$i++)
+					{
+						$current_start = $start + ($i*86400) + $int_time; //unixtimestamp start of today's event
+						$current_stop = $start + ($i*86400) + $int_time + $span; //unixtimestamp stop of today's event
+						$events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
+					}
+					break;
+				case 'weekly':
+					//A weekly repeated event is very difficult to catch in a month view,
+					//because weeks start before or at the same time as the first day of the month
+					//The same can be said for the end of the month.
+					// The idea is thus to get all possible events by enlarging the scope of
+					// the month to get complete weeks covering the complete month, and then take out
+					// the events that start before the 1st ($start) or after the last day of the month ($end)
+					$time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+                    $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
+                    list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+
+					$time_now = date('Y/n/W/j/N/G/i/s',$end);
+					list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+
+					$month_first_week = date('W',$start);
+					$month_last_week = date('W',$end);
+
+					if(($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig)))
+					{ //if the event is after the original (at least one week) and the day of the week is the same
+						for($i=$month_first_week;$i<=$month_last_week;$i++)
+						{
+						  //the "day of the week" of repetition is the same as the $dw_orig,
+                          //so to get the "day of the month" from the "day of the week", we have
+                          //to get the first "day of the week" for this week and add the number
+                          //of days (in seconds) to reach the $dw_orig
+                          //example: the first week spans between the 28th of April (Monday) to the
+                          // 4th of May (Sunday). The event occurs on the 2nd day of each week.
+                          // This means the event occurs on 29/4, 6/5, 13/5, 20/5 and 27/5.
+                          // We want to get all of these, and then reject 29/4 because it is out
+                          // of the month itself.
+
+                          //First, to get the start time of the first day of the month view (even if
+                          // the day is from the past month), we get the month start date (1/5) and
+                          // see which day of the week it is, and subtract the number of days necessary
+                          // to get back to the first day of the week.
+                          $month_first_day_weekday = date('N',$start);
+                          $first_week_start = $start - (($month_first_day_weekday-1)*86400);
+
+                          //Second, we add the week day of the original event, so that we have an
+                          // absolute time that represents the first repetition of the event in
+                          // our 4- or 5-weeks timespan
+                          $first_event_repeat_start = $first_week_start + (($dw_orig-1)*86400) + ($h_orig*3600) + ($n_orig*60) + $s_orig;
+
+                          //Third, we start looping through the repetitions and see if they are between
+                          // $start and $end
+					      for($i = $first_event_repeat_start; $i<=$end; $i+=604800)
+                          {
+                          	if($start<$i && $i<$end)
+                            {
+                               list($y_repeat,$m_repeat,$d_repeat,$h_repeat,$n_repeat,$s_repeat) = split('/',date('Y/m/j/H/i/s',$i));
+                               $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+                            }
+                          }
+						}
+					}
+					break;
+				case 'monthlyByDate':
+					$time_orig = date('Y/n/W/j/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$w_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/W/j/G/i/s',$end);
+					list($y_now,$m_now,$w_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
+					if(($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig)))
+					{ //if the event is after the original (at least one month) and the original event's day is between the first day of the week and the last day of the week
+					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				case 'monthlyByDayR':
+					//not implemented yet
+					break;
+				case 'monthlyByDay':
+					//not implemented yet
+					break;
+				case 'yearly':
+					$time_orig = date('Y/n/j/z/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/j/z/G/i/s',$end);
+					list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
+					if((($y_now>$y_orig) && ($start<$event_repetition_time && $event_repetition_time<$end)))
+					{
+					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				default:
+					break;
+			}
+		}
+	}
+	return $events;
+}
+/**
+ * Get repeated events of a course between two dates (1 year timespan). Used for the list display.
+ * This is virtually unlimited but by default it shortens to 100 years from now (even a birthday shouldn't be useful more than this time - except for turtles)
+ * Returns an array containing the events
+ * @param   string  Course info array (as returned by api_get_course_info())
+ * @param   int     UNIX timestamp of span start. Defaults 0, later transformed into today's start
+ * @param   int     UNIX timestamp. Defaults to 0, later transformed into today's end
+ * @param   array   A set of parameters to alter the SQL query
+ * @return  array   [int] => [course_id,parent_event_id,start_date,end_date,title,description]
+ */
+function get_repeated_events_list_view($course_info,$start=0,$end=0,$params)
+{
+    $events = array();
+    //block $end if higher than 2038 -- PHP doesn't go past that
+    if($end>2145934800){$end = 2145934800;}
+    //initialise all values
+    $y=0;
+    $m=0;
+    $d=0;
+    if(empty($start) or empty($end))
+    {
+        $time = time();
+        $y = date('Y');
+        $m = date('m');
+    }
+    if(empty($start))
+    {
+        $start = mktime(0, 0, 0, $m, 1, $y);
+    }
+    $db_start = date('Y-m-d H:i:s', $start);
+    if(empty($end))
+    {
+        $end = mktime(0, 0, 0, 1, 1, 2037);
+    }
+    //$db_end = date('Y-m-d H:i:s',$end);
+
+    $t_cal = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR,$course_info['dbName']);
+    //$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
+    //$t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
+    $sql = "SELECT c.id, c.title, c.content, " .
+            " UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
+            " cr.cal_type, cr.cal_end " .
+            " FROM $t_cal c, $t_cal_repeat cr, $t_ip as item_property " .
+            " WHERE cr.cal_end >= $start " .
+            " AND cr.cal_id = c.id " .
+            " AND item_property.ref = c.id ".
+            " AND item_property.tool = '".TOOL_CALENDAR_EVENT."' ".
+            " AND c.start_date <= '$db_start' "
+            .(!empty($params['conditions'])?$params['conditions']:'')
+            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
+            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
+    $res = Database::query($sql,__FILE__,__LINE__);
+    if(Database::num_rows($res)>0)
+    {
+        while($row = Database::fetch_array($res))
+        {
+            $orig_start = $row['orig_start'];
+            $orig_end = $row['orig_end'];
+            $repeat_type = $row['cal_type'];
+            $repeat_end = $row['cal_end'];
+            switch($repeat_type)
+            {
+                case 'daily':
+                    $time_orig_h = date('H',$orig_start);
+                    $time_orig_m = date('i',$orig_start);
+                    $time_orig_s = date('s',$orig_start);
+                    $span = $orig_end - $orig_start; //total seconds between start and stop of original event
+                    for($i=$orig_start+86400;($i<$end && $i<=$repeat_end);$i+=86400)
+                    {
+                        $current_start = $i; //unixtimestamp start of today's event
+                        $current_stop = $i + $span; //unixtimestamp stop of today's event
+                        $events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
+                    }
+                    break;
+                case 'weekly':
+                    //A weekly repeated event is very difficult to catch in a month view,
+                    // because weeks start before or at the same time as the first day of the month
+                    //The same can be said for the end of the month.
+                    // The idea is thus to get all possible events by enlarging the scope of
+                    // the month to get complete weeks covering the complete month, and then take out
+                    // the events that start before the 1st ($start) or after the last day of the month ($end)
+                    $time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
+                    list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+                    $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
+                    list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+
+                    $time_now = date('Y/n/W/j/N/G/i/s',$end);
+                    list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+                    if($w_now==52)
+                    {
+                        ++$y_now;
+                        $w_now=1;
+                    }
+                    else
+                    {
+                        ++$w_now;
+                    }
+                    $month_first_week = date('W',$start);
+                    $total_weeks = ((date('Y',$end)-$y_orig)-1)*52;
+                    $month_last_week = $month_first_week + $total_weeks;
+
+                    if(($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig)))
+                    { //if the event is after the original (at least one week) and the day of the week is the same
+                        //for($i=$month_first_week;($i<=$month_last_week && $i<1000);$i++)
+                        //{
+
+
+                          /*
+                           The "day of the week" of repetition is the same as the $dw_orig,
+                           so to get the "day of the month" from the "day of the week", we have
+                           to get the first "day of the week" for this week and add the number
+                           of days (in seconds) to reach the $dw_orig
+                          example: the first week spans between the 28th of April (Monday) to the
+                           4th of May (Sunday). The event occurs on the 2nd day of each week.
+                           This means the event occurs on 29/4, 6/5, 13/5, 20/5 and 27/5.
+                           We want to get all of these, and then reject 29/4 because it is out
+                           of the month itself.
+                          First, to get the start time of the first day of the month view (even if
+                           the day is from the past month), we get the month start date (1/5) and
+                           see which day of the week it is, and subtract the number of days necessary
+                           to get back to the first day of the week.
+                          */
+                          $month_first_day_weekday = date('N',$start);
+                          $first_week_start = $start - (($month_first_day_weekday-1)*86400);
+
+                          //Second, we add the week day of the original event, so that we have an
+                          // absolute time that represents the first repetition of the event in
+                          // our 4- or 5-weeks timespan
+                          $first_event_repeat_start = $first_week_start + (($dw_orig-1)*86400) + ($h_orig*3600) + ($n_orig*60) + $s_orig;
+
+                          //Third, we start looping through the repetitions and see if they are between
+                          // $start and $end
+                          for($i = $first_event_repeat_start; ($i<=$end && $i<=$repeat_end); $i+=604800)
+                          {
+                            if($start<$i && $i<=$end && $i<=$repeat_end)
+                            {
+                               list($y_repeat,$m_repeat,$d_repeat,$h_repeat,$n_repeat,$s_repeat) = split('/',date('Y/m/j/H/i/s',$i));
+                               $new_start_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
+                               $new_stop_time = mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now);
+                               $events[] = array($course_info['id'], $row['id'], $new_start_time, $new_stop_time, $row['title'], $row['content']);
+                            }
+                            $time_now = date('Y/n/W/j/N/G/i/s',$i+604800);
+                            list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+                          }
+                        //}
+                    }
+                    break;
+                case 'monthlyByDate':
+                    $time_orig = date('Y/n/W/j/G/i/s',$orig_start);
+                    list($y_orig,$m_orig,$w_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+
+                    $time_now = date('Y/n/W/j/G/i/s',$start);
+                    list($y_now,$m_now,$w_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+                    //make sure we are one month ahead (to avoid being the same month as the original event)
+                    if($m_now==12)
+                    {
+                        ++$y_now;
+                        $m_now = 1;
+                    }
+                    else
+                    {
+                        ++$m_now;
+                    }
+
+                    $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+                    list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+
+                    $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
+                    $diff = $orig_end - $orig_start;
+                    while((($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig))) && ($event_repetition_time < $end) && ($event_repetition_time < $repeat_end))
+                    { //if the event is after the original (at least one month) and the original event's day is between the first day of the week and the last day of the week
+                      $new_start_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
+                      $new_stop_time = mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now);
+                      $events[] = array($course_info['id'],$row['id'],$new_start_time,$new_stop_time,$row['title'],$row['content']);
+                      if($m_now==12)
+                      {
+                      	++$y_now;
+                        $m_now = 1;
+                      }
+                      else
+                      {
+                        ++$m_now;
+                      }
+                      $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
+                    }
+                    break;
+                case 'monthlyByDayR':
+                    //not implemented yet
+                    break;
+                case 'monthlyByDay':
+                    //not implemented yet
+                    break;
+                case 'yearly':
+                    $time_orig = date('Y/n/j/z/G/i/s',$orig_start);
+                    list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+                    $time_now = date('Y/n/j/z/G/i/s',$end);
+                    list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+                    $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
+                    while((($y_now>$y_orig) && ($start<$event_repetition_time && $event_repetition_time<$end && $event_repetition_time<$repeat_end)))
+                    {
+                      $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+                      list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+                      $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+                      ++$y_now;
+                      $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
+                    }
+                    break;
+                default:
+                    break;
+            }
+        }
+    }
+    return $events;
+}
+/**
+ * Tells if an agenda item is repeated
+ * @param   string  Course database
+ * @param   int     The agenda item
+ * @return  boolean True if repeated, false otherwise
+ */
+function is_repeated_event($id,$course=null)
+{
+	if(empty($course))
+    {
+    	$course_info = api_get_course_info();
+        $course = $course_info['dbName'];
+    }
+    $id = (int) $id;
+	//$t_agenda_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course);
+    $sql = "SELECT * FROM $t_agenda_repeat WHERE cal_id = $id";
+    $res = Database::query($sql,__FILE__,__LINE__);
+    if(Database::num_rows($res)>0)
+    {
+    	return true;
+    }
+    return false;
+}
+/**
+ * Adds x weeks to a UNIX timestamp
+ * @param   int     The timestamp
+ * @param   int     The number of weeks to add
+ * @return  int     The new timestamp
+ */
+function add_week($timestamp,$num=1)
+{
+    return $timestamp + $num*604800;
+}
+/**
+ * Adds x months to a UNIX timestamp
+ * @param   int     The timestamp
+ * @param   int     The number of years to add
+ * @return  int     The new timestamp
+ */
+function add_month($timestamp,$num=1)
+{
+	list($y, $m, $d, $h, $n, $s) = split('/',date('Y/m/d/h/i/s',$timestamp));
+    if($m+$num>12)
+    {
+    	$y += floor($num/12);
+        $m += $num%12;
+    }
+    else
+    {
+        $m += $num;
+    }
+    return mktime($h, $n, $s, $m, $d, $y);
+}
+/**
+ * Adds x years to a UNIX timestamp
+ * @param   int     The timestamp
+ * @param   int     The number of years to add
+ * @return  int     The new timestamp
+ */
+function add_year($timestamp,$num=1)
+{
+    list($y, $m, $d, $h, $n, $s) = split('/',date('Y/m/d/h/i/s',$timestamp));
+    return mktime($h, $n, $s, $m, $d, $y+$num);
+}
+/**
+ * Adds an agenda item in the database. Similar to store_new_agenda_item() except it takes parameters
+ * @param   array   Course info
+ * @param   string  Event title
+ * @param   string  Event content/description
+ * @param   string  Start date
+ * @param   string  End date
+ * @param   array   List of groups to which this event is added
+ * @param   int     Parent id (optional)
+ * @return  int     The new item's DB ID
+ */
+function agenda_add_item($course_info, $title, $content, $db_start_date, $db_end_date, $to=array(), $parent_id=null)
+{
+  global $_course;
+    $user_id    = api_get_user_id();
+    $t_agenda   = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+
+    // some filtering of the input data
+    $title      = Database::escape_string($title); // no html allowed in the title
+    $content    = Database::escape_string($content);
+    $start_date = Database::escape_string($db_start_date);
+    $end_date   = Database::escape_string($db_end_date);
+
+     isset($_SESSION['id_session'])?$id_session=intval($_SESSION['id_session']):$id_session=null;
+    // store in the table calendar_event
+
+    // check if exists in calendar_event table
+    $sql = "SELECT * FROM $t_agenda WHERE title='$title' AND content = '$content' AND start_date = '$start_date'
+    		AND end_date = '$end_date' ".(!empty($parent_id)? "AND parent_event_id = '$parent_id'":"");
+    $result = Database::query($sql,__FILE__,__LINE__);
+    $count = Database::num_rows($result);
+    if ($count > 0) {
+    	return false;
+    }
+
+    $sql = "INSERT INTO ".$t_agenda."
+                            (title,content, start_date, end_date)
+                            VALUES
+                            ('".$title."','".$content."', '".$start_date."','".$end_date."')";
+
+    $result = Database::query($sql,__FILE__,__LINE__) or die (Database::error());
+    $last_id=Database::insert_id();
+
+    // add a attachment file in agenda
+
+   // add_agenda_attachment_file($file_comment,$last_id);
+
+    // store in last_tooledit (first the groups, then the users
+    $done = false;
+    if ((!is_null($to))or (!empty($_SESSION['toolgroup']))) // !is_null($to): when no user is selected we send it to everyone
+    {
+        $send_to=separate_users_groups($to);
+        // storing the selected groups
+        if (is_array($send_to['groups']))
+        {
+            foreach ($send_to['groups'] as $group)
+            {
+                api_item_property_update($course_info, TOOL_CALENDAR_EVENT, $last_id, "AgendaAdded", $user_id, $group,'',$start_date, $end_date);
+                $done = true;
+            }
+        }
+        // storing the selected users
+        if (is_array($send_to['users']))
+        {
+            foreach ($send_to['users'] as $user)
+            {
+                api_item_property_update($course_info, TOOL_CALENDAR_EVENT, $last_id, "AgendaAdded", $user_id,'',$user, $start_date,$end_date);
+                $done = true;
+            }
+        }
+    }
+
+    if(!$done) // the message is sent to everyone, so we set the group to 0
+    {
+        api_item_property_update($course_info, TOOL_CALENDAR_EVENT, $last_id, "AgendaAdded", $user_id, $start_date,$end_date);
+    }
+    // storing the resources
+    if (!empty($_SESSION['source_type']) && !empty($last_id)) {
+    //store_resources($_SESSION['source_type'],$last_id);
+    }
+    return $last_id;
+}
+/**
+ * Adds a repetitive item to the database
+ * @param   array   Course info
+ * @param   int     The original event's id
+ * @param   string  Type of repetition
+ * @param   int     Timestamp of end of repetition (repeating until that date)
+ * @param   array   Original event's destination
+ * @return  boolean False if error, True otherwise
+ */
+ function get_calendar_items($month, $year)
+{
+	global $_user, $_course;
+	global $is_allowed_to_edit;
+
+	$month=Database::escape_string($month);
+	$year=Database::escape_string($year);
+
+	// database variables
+	$TABLEAGENDA = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+	//$TABLE_ITEM_PROPERTY=Database::get_course_table(TABLE_ITEM_PROPERTY);
+
+    $month_first_day = mktime(0,0,0,$month,1,$year);
+    $month_last_day  = mktime(0,0,0,$month+1,1,$year)-1;
+    if ($month==12) {
+        $month_last_day = mktime(0,0,0,1,1,$year+1)-1;
+    }
+    $repeats = array();
+    $data=array();
+	if (is_allowed_to_edit()) {
+		$sql="SELECT
+			DISTINCT *
+			FROM ".$TABLEAGENDA." agenda
+			WHERE MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
+			GROUP BY id ".
+			"ORDER BY  start_date ";
+		$result=Database::query($sql,__FILE__,__LINE__);
+
+		while ($row=Database::fetch_array($result)) {
+			$datum_item=(int)substr($row["start_date"],8,2);
+			$data[$datum_item][intval($datum_item)][] = $row;
+		}
+	}
+	return $data;
+}
+
+function agenda_add_repeat_item($course_info,$orig_id,$type,$end,$orig_dest)
+{/*
+	$t_agenda   = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR,$course_info['dbName']);
+   // $t_agenda_r = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
+    //$sql = "SELECT title, content, UNIX_TIMESTAMP(start_date) as sd, UNIX_TIMESTAMP(end_date) as ed FROM $t_agenda WHERE id = $orig_id";
+    $sql = "SELECT title, content, start_date as sd, end_date as ed FROM $t_agenda WHERE id = $orig_id";
+    $res = Database::query($sql,__FILE__,__LINE__);
+    if(Database::num_rows($res)!==1){return false;}
+    $row = Database::fetch_array($res);
+    //$orig_start = $row['sd'];
+    $orig_start = mktime(substr($row['sd'],11,2),substr($row['sd'],14,2),substr($row['sd'],17,2),substr($row['sd'],5,2),substr($row['sd'],8,2),substr($row['sd'],0,4));
+    //$orig_end   = $row['ed'];
+    $orig_end   = mktime(substr($row['ed'],11,2),substr($row['ed'],14,2),substr($row['ed'],17,2),substr($row['ed'],5,2),substr($row['ed'],8,2),substr($row['ed'],0,4));
+    $diff = $orig_end - $orig_start;
+    $orig_title = $row['title'];
+    $orig_content = $row['content'];
+    $now = time();
+    $type = Database::escape_string($type);
+    $end = (int) $end;
+    if(1<=$end && $end<=500)
+    {
+    	//we assume that, with this type of value, the user actually gives a count of repetitions
+        //and that he wants us to calculate the end date with that (particularly in case of imports from ical)
+        switch($type)
+        {
+            case 'daily':
+                $end = $orig_start + (86400*$end);
+                break;
+            case 'weekly':
+                $end = add_week($orig_start,$end);
+                break;
+            case 'monthlyByDate':
+                $end = add_month($orig_start,$end);
+                break;
+            case 'monthlyByDay':
+                //TODO
+                break;
+            case 'monthlyByDayR':
+                //TODO
+                break;
+            case 'yearly':
+                $end = add_year($orig_start,$end);
+                break;
+        }
+    }
+    if($end > $now
+        && in_array($type,array('daily','weekly','monthlyByDate','monthlyByDay','monthlyByDayR','yearly')))
+    {
+       $sql = "INSERT INTO $t_agenda_r (cal_id, cal_type, cal_end)" .
+            " VALUES ($orig_id,'$type',$end)";
+       $res = Database::query($sql,__FILE__,__LINE__);
+        switch($type)
+        {
+            case 'daily':
+                for($i = $orig_start + 86400; ($i <= $end); $i += 86400)
+                {
+                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $i), date('Y-m-d H:i:s', $i+$diff), $orig_dest, $orig_id);
+                }
+                break;
+            case 'weekly':
+                for($i = $orig_start + 604800; ($i <= $end); $i += 604800)
+                {
+                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $i), date('Y-m-d H:i:s', $i+$diff), $orig_dest, $orig_id);
+                }
+                break;
+            case 'monthlyByDate':
+                $next_start = add_month($orig_start);
+                while($next_start <= $end)
+                {
+                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $next_start), date('Y-m-d H:i:s', $next_start+$diff), $orig_dest, $orig_id);
+                    $next_start = add_month($next_start);
+                }
+                break;
+            case 'monthlyByDay':
+                //not yet implemented
+                break;
+            case 'monthlyByDayR':
+                //not yet implemented
+                break;
+            case 'yearly':
+                $next_start = add_year($orig_start);
+                while($next_start <= $end)
+                {
+                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $next_start), date('Y-m-d H:i:s', $next_start+$diff), $orig_dest, $orig_id);
+                    $next_start = add_year($next_start);
+                }
+                break;
+        }
+    }
+	return true;*/
+}
+/**
+ * Import an iCal file into the database
+ * @param   array   Course info
+ * @return  boolean True on success, false otherwise
+ */
+
+function agenda_import_ical($course_info,$file)
+{
+	require_once(api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
+    $charset = api_get_setting('platform_charset');
+    $filepath = api_get_path(SYS_ARCHIVE_PATH).$file['name'];
+    if(!@move_uploaded_file($file['tmp_name'],$filepath))
+    {
+    	error_log('Problem moving uploaded file: '.$file['error'].' in '.__FILE__.' line '.__LINE__);
+    	return false;
+    }
+    require_once (api_get_path(LIBRARY_PATH).'icalcreator/iCalcreator.class.php');
+    $ical = new vcalendar();
+    $ical->setConfig( 'directory', dirname($filepath) );
+    $ical->setConfig( 'filename', basename($filepath) );
+    $ical->parse();
+    //we need to recover: summary, description, dtstart, dtend, organizer, attendee, location (=course name),
+    // rrule
+    $ve = $ical->getComponent(0);
+    //print_r($ve);
+    $ttitle = $ve->getProperty('summary');
+    //print_r($ttitle);
+    $title = api_convert_encoding($ttitle,$charset,'UTF-8');
+    $tdesc = $ve->getProperty('description');
+    $desc = api_convert_encoding($tdesc,$charset,'UTF-8');
+    $ts = $ve->getProperty('dtstart');
+    $start_date = $ts['year'].'-'.$ts['month'].'-'.$ts['day'].' '.$ts['hour'].':'.$ts['min'].':'.$ts['sec'];
+    $ts = $ve->getProperty('dtend');
+    $end_date = $ts['year'].'-'.$ts['month'].'-'.$ts['day'].' '.$ts['hour'].':'.$ts['min'].':'.$ts['sec'];
+    //echo $start_date.' - '.$end_date;
+    $organizer = $ve->getProperty('organizer');
+    $attendee = $ve->getProperty('attendee');
+    $course_name = $ve->getProperty('location');
+    //insert the event in our database
+    $id = agenda_add_item($course_info,$title,$desc,$start_date,$end_date,$_POST['selectedform']);
+
+    $repeat = $ve->getProperty('rrule');
+    if(is_array($repeat) && !empty($repeat['FREQ']))
+    {
+    	$trans = array('DAILY'=>'daily','WEEKLY'=>'weekly','MONTHLY'=>'monthlyByDate','YEARLY'=>'yearly');
+        $freq = $trans[$repeat['FREQ']];
+        $interval = $repeat['INTERVAL'];
+        if(isset($repeat['UNTIL']) && is_array($repeat['UNTIL']))
+        {
+            $until = mktime(23,59,59,$repeat['UNTIL']['month'],$repeat['UNTIL']['day'],$repeat['UNTIL']['year']);
+            $res = agenda_add_repeat_item($course_info,$id,$freq,$until,$_POST['selectedform']);
+        }
+        //TODO: deal with count
+        if(!empty($repeat['COUNT']))
+        {
+            $count = $repeat['COUNT'];
+            $res = agenda_add_repeat_item($course_info,$id,$freq,$count,$_POST['selectedform']);
+        }
+    }
+    return true;
+}
+?>

+ 409 - 409
main/admin/calendar.php

@@ -1,410 +1,410 @@
-<?php // $id: $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2008 Dokeos S.A.
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	@package dokeos.admin
-*	@author Carlos Vargas
-*	This file is the calendar/agenda.php
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file[] = 'admin';
-$language_file[] = 'agenda';
-
-// resetting the course id
-$cidReset=true;
-// including some necessary dokeos files
-require('../inc/global.inc.php');
-
-$this_section = SECTION_PLATFORM_ADMIN;
-$_SESSION['this_section']=$this_section;
-
-// Access restrictions
-api_protect_admin_script(true);
-
-// setting breadcrumbs
-$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-//$interbreadcrumb[] = array('url' => 'session_list.php','name' => get_lang('SessionList'));
-
-// Database Table Definitions
-//	$tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-//	$tbl_session						= Database::get_main_table(TABLE_MAIN_SESSION);
-//	$tbl_session_rel_user				= Database::get_main_table(TABLE_MAIN_SESSION_USER);
-//	$tbl_session_rel_course				= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-//	$tbl_course							= Database::get_main_table(TABLE_MAIN_COURSE);
-
-// setting the name of the tool
-$tool_name= get_lang('SubscribeCoursesToSession');
-
-$id_session=intval($_GET['id_session']);
-
-if(!api_is_platform_admin())
-{
-	$sql = 'SELECT session_admin_id FROM '.Database :: get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$id_session;
-	$rs = Database::query($sql,__FILE__,__LINE__);
-	if(mysql_result($rs,0,0)!=$_user['user_id'])
-	{
-		api_not_allowed(true);
-	}
-}
-/*
------------------------------------------------------------
-	Libraries
------------------------------------------------------------
-*/
-// containing the functions for the agenda tool
-include "calendar.lib.php";
-// some debug functions
-include($includePath."/lib/debug.lib.inc.php");
-
-
-/*==============================================================================
-  			TREATING THE PARAMETERS
-			1. viewing month only or everything
-			2. sort ascending or descending
-			3. showing or hiding the send-to-specific-groups-or-users form
-			4. filter user or group
-  ============================================================================== */
-// 1. show all or show current month?
-if (!$_SESSION['show'])
-{
-	$_SESSION['show']="showall";
-}
-if (!empty($_GET['action']) and $_GET['action']=="showcurrent")
-{
-	$_SESSION['show']="showcurrent";
-}
-if (!empty($_GET['action']) and $_GET['action']=="showall")
-{
-	$_SESSION['show']="showall";
-}
-//echo $_SESSION['show'];
-
-// 2. sorting order (ASC or DESC)
-if (empty($_GET['sort']) and empty($_SESSION['sort']))
-{
-	$_SESSION['sort']="DESC";
-}
-if (!empty($_GET['sort']) and $_GET['sort']=="asc")
-{
-	$_SESSION['sort']="ASC";
-}
-if (!empty($_GET['sort']) and $_GET['sort']=="desc")
-{
-	$_SESSION['sort']="DESC";
-}
-if (!empty($_GET['view']))
-{
-	$_SESSION['view'] = $_GET['view'];
-}
-
-// 3. showing or hiding the send-to-specific-groups-or-users form
-$setting_allow_individual_calendar=true;
-if (empty($_POST['To']) and empty($_SESSION['allow_individual_calendar']))
-{
-	$_SESSION['allow_individual_calendar']="hide";
-}
-$allow_individual_calendar_status=$_SESSION['allow_individual_calendar'];
-if (!empty($_POST['To']) and ($allow_individual_calendar_status=="hide"))
-{
-	$_SESSION['allow_individual_calendar']="show";
-}
-if (!empty($_GET['sort']) and ($allow_individual_calendar_status=="show"))
-{
-	$_SESSION['allow_individual_calendar']="hide";
-}
-
-$htmlHeadXtra[] = to_javascript();
-
-// this loads the javascript that is needed for the date popup selection
-$htmlHeadXtra[] = "<script src=\"calendar_tbl_change.js\" type=\"text/javascript\" language=\"javascript\"></script>";
-
-// setting the name of the tool
-$nameTools = get_lang('GlobalAgenda'); // language variable in trad4all.inc.php
-
-// showing the header if we are not in the learning path, if we are in
-// the learning path, we do not include the banner so we have to explicitly
-// include the stylesheet, which is normally done in the header
-/*if (empty($_GET['origin']) or $_GET['origin'] != 'learnpath')
-{*/
-Display::display_header($nameTools,'Agenda');
-/*}
-else
-{
-	echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"".$clarolineRepositoryWeb."css/default.css\"/>";
-}*/
-
-/* ==============================================================================
-  			SETTING SOME VARIABLES
-============================================================================== */
-// Variable definitions
-$dateNow 			= format_locale_date($dateTimeFormatLong);
-// Defining the shorts for the days. We use camelcase because these are arrays of language variables
-$DaysShort = api_get_week_days_short();
-// Defining the days of the week to allow translation of the days. We use camelcase because these are arrays of language variables
-$DaysLong = api_get_week_days_long();
-// Defining the months of the year to allow translation of the months. We use camelcase because these are arrays of language variables
-$MonthsLong = api_get_months_long();
-
-// Database table definitions
-$TABLEAGENDA 			= Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-$TABLE_ITEM_PROPERTY 	= Database::get_course_table(TABLE_ITEM_PROPERTY);
-$tbl_user       		= Database::get_main_table(TABLE_MAIN_USER);
-$tbl_courseUser 		= Database::get_main_table(TABLE_MAIN_COURSE_USER);
-$tbl_group      		= Database::get_course_table(TABLE_GROUP);
-$tbl_groupUser  		= Database::get_course_table(TABLE_GROUP_USER);
-$tbl_session_course_user= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
-
-
-/* ==============================================================================
-  			ACCESS RIGHTS
-============================================================================== */
-// permission stuff - also used by loading from global in agenda.inc.php
-$is_allowed_to_edit = is_allowed_to_edit() OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous());
-
-// Displaying the title of the tool
-// api_display_tool_title($nameTools);
-
-// tool introduction
-//Display::display_introduction_section(TOOL_CALENDAR_EVENT);
-
-// insert an anchor (top) so one can jump back to the top of the page
-echo "<a name=\"top\"></a>";
-
-/*
-==============================================================================
-		MAIN SECTION
-==============================================================================
-*/
-
-//setting the default year and month
-$select_year = '';
-$select_month = '';
-if(!empty($_GET['year']))
-{
-	$select_year = (int)$_GET['year'];
-}
-if(!empty($_GET['month']))
-{
-	$select_month = (int)$_GET['month'];
-}
-if (empty($select_year) && empty($select_month))
-{
-	$today = getdate();
-	$select_year = $today['year'];
-	$select_month = $today['mon'];
-}
-
-echo '<div class="actions">';
-if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()))
-{
-	display_student_links();
-	display_courseadmin_links();
-}
-
-echo '</div><br /><br />';
-
-
-echo '<table width="100%" border="0" cellspacing="0" cellpadding="0">'
-		. '<tr>';
-
-
-// THE LEFT PART
-if (empty($_GET['origin']) or $_GET['origin']!='learnpath')
-{
-	echo '<td width="220" height="19" valign="top">';
-	// the small calendar
-	$MonthName = $MonthsLong[$select_month -1];
-	$agenda_items=get_calendar_items($select_month,$select_year);
-	if (api_get_setting('display_mini_month_calendar') == 'true')
-	{
-		display_minimonthcalendar($agenda_items, $select_month,$select_year, $MonthName);
-	}
-	/*if (api_get_setting('display_upcoming_events') == 'true') {
-		display_upcoming_events();
-	}*/
-	echo '</td>';
-	echo '<td width="20" background="../img/verticalruler.gif">&nbsp;</td>';
-}
-
-
-// THE RIGHT PART
-echo '<td valign="top">';
-echo '<div class="sort" style="float:right">';
-
-echo '</div>';
-if (api_is_allowed_to_edit(false,true))
-{
-	switch ($_GET['action'])
-	{
-		case "add":
-            if(!empty($_POST['ical_submit'])) {
-                $course_info = api_get_course_info();
-                agenda_import_ical($course_info,$_FILES['ical_import']);
-                if (api_get_setting('display_upcoming_events') == 'true') {
-					display_upcoming_events();
-				}
-                display_agenda_items();
-            } elseif ($_POST['submit_event']) {
-
-		     $course_info = api_get_course_info();
-			    $event_start    = (int) $_POST['fyear'].'-'.(int) $_POST['fmonth'].'-'.(int) $_POST['fday'].' '.(int) $_POST['fhour'].':'.(int) $_POST['fminute'].':00';
-                $event_stop     = (int) $_POST['end_fyear'].'-'.(int) $_POST['end_fmonth'].'-'.(int) $_POST['end_fday'].' '.(int) $_POST['end_fhour'].':'.(int) $_POST['end_fminute'].':00';
-
-				$id = agenda_add_item($course_info,$_POST['title'],$_POST['content'],$event_start,$event_stop,$_POST['selectedform'],false,$_POST['file_comment']);
-
-                if(!empty($_POST['repeat'])) {
-                	$end_y = intval($_POST['repeat_end_year']);
-                    $end_m = intval($_POST['repeat_end_month']);
-                    $end_d = intval($_POST['repeat_end_day']);
-                    $end   = mktime(23, 59, 59, $end_m, $end_d, $end_y);
-                    $res = agenda_add_repeat_item($course_info,$id,$_POST['repeat_type'],$end,null,$_POST['file_comment']);
-                }
-                if (api_get_setting('display_upcoming_events') == 'true') {
-					display_upcoming_events();
-				}
-				display_agenda_items();
-			} else {
-				show_add_form();
-			}
-			break;
-
-		case "edit":
-			if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, intval($_REQUEST['id']) ) ) )
-			{ // a coach can only delete an element belonging to his session
-				if ($_POST['submit_event'])
-				{		$my_id_attach = (int)$_REQUEST['id_attach'];
-						$my_file_comment = Database::escape_string($_REQUEST['file_comment']);
-						store_edited_agenda_item($my_id_attach,$my_file_comment);
-						if (api_get_setting('display_upcoming_events') == 'true') {
-							display_upcoming_events();
-						}
-						display_agenda_items();
-				}
-				else
-				{
-						$id=(int)$_GET['id'];
-						show_add_form($id);
-				}
-			}
-			else
-			{
-				if (api_get_setting('display_upcoming_events') == 'true') {
-					display_upcoming_events();
-				}
-				display_agenda_items();
-			}
-			break;
-
-		case "delete":
-			$id=(int)$_GET['id'];
-			if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $id ) ) )
-			{ // a coach can only delete an element belonging to his session
-				delete_agenda_item($id);
-			}
-				if (api_get_setting('display_upcoming_events') == 'true') {
-					display_upcoming_events();
-				}
-				display_agenda_items();
-			break;
-
-		case "showhide":
-			$id=(int)$_GET['id'];
-			if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $id ) ) )
-			{ // a coach can only delete an element belonging to his session
-				showhide_agenda_item($id);
-			}
-			if (api_get_setting('display_upcoming_events') == 'true') {
-					display_upcoming_events();
-			}
-			display_agenda_items();
-			break;
-		case "announce": //copying the agenda item into an announcement
-			$id=(int)$_GET['id'];
-			if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $id ) ) )
-			{ // a coach can only delete an element belonging to his session
-				$ann_id = store_agenda_item_as_announcement($id);
-				$tool_group_link = (isset($_SESSION['toolgroup'])?'&toolgroup='.$_SESSION['toolgroup']:'');
-				echo '<br />';
-				Display::display_normal_message(get_lang('CopiedAsAnnouncement').'<a href="../announcements/announcements.php?id='.$ann_id.$tool_group_link.'">'.get_lang('NewAnnouncement').'</a>', false);
-			}
-			if (api_get_setting('display_upcoming_events') == 'true') {
-					display_upcoming_events();
-			}
-			display_agenda_items();
-			break;
-		case "delete_attach": //delete attachment file
-			$id_attach = (int)$_GET['id_attach'];
-			if (!empty($id_attach)) {
-				delete_attachment_file($id_attach);
-			}
-			if (api_get_setting('display_upcoming_events') == 'true') {
-					display_upcoming_events();
-			}
-			display_agenda_items();
-			break;
-
-	}
-}
-
-// this is for students and whenever the courseaministrator has not chosen any action. It is in fact the default behaviour
-if (!$_GET['action'] OR $_GET['action']=="showall"  OR $_GET['action']=="showcurrent" OR $_GET['action']=="view")
-{
-	if ($_GET['origin'] != 'learnpath')
-	{
-		if (!$_SESSION['view'] OR $_SESSION['view'] <> 'month')
-		{
-            if(!empty($_GET['agenda_id']))
-            {
-                 display_one_agenda_item((int)$_GET['agenda_id']);
-            }
-            else
-            {
-			     display_agenda_items();
-            }
-		}
-        else
-        {
-			display_monthcalendar($select_month, $select_year);
-		}
-	}
-	else
-	{
-		display_one_agenda_item((int)$_GET['agenda_id']);
-	}
-}
-echo "&nbsp;</td></tr></table>";
-
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-// The footer is displayed only if we are not in the learnpath
-if ($_GET['origin'] != 'learnpath')
-{
-
-	Display::display_footer();
-
-}
+<?php // $id: $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos S.A.
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	@package dokeos.admin
+*	@author Carlos Vargas
+*	This file is the calendar/agenda.php
+==============================================================================
+*/
+
+// name of the language file that needs to be included
+$language_file[] = 'admin';
+$language_file[] = 'agenda';
+
+// resetting the course id
+$cidReset=true;
+// including some necessary dokeos files
+require('../inc/global.inc.php');
+
+$this_section = SECTION_PLATFORM_ADMIN;
+$_SESSION['this_section']=$this_section;
+
+// Access restrictions
+api_protect_admin_script(true);
+
+// setting breadcrumbs
+$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+//$interbreadcrumb[] = array('url' => 'session_list.php','name' => get_lang('SessionList'));
+
+// Database Table Definitions
+//	$tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+//	$tbl_session						= Database::get_main_table(TABLE_MAIN_SESSION);
+//	$tbl_session_rel_user				= Database::get_main_table(TABLE_MAIN_SESSION_USER);
+//	$tbl_session_rel_course				= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+//	$tbl_course							= Database::get_main_table(TABLE_MAIN_COURSE);
+
+// setting the name of the tool
+$tool_name= get_lang('SubscribeCoursesToSession');
+
+$id_session=intval($_GET['id_session']);
+
+if(!api_is_platform_admin())
+{
+	$sql = 'SELECT session_admin_id FROM '.Database :: get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$id_session;
+	$rs = Database::query($sql,__FILE__,__LINE__);
+	if(mysql_result($rs,0,0)!=$_user['user_id'])
+	{
+		api_not_allowed(true);
+	}
+}
+/*
+-----------------------------------------------------------
+	Libraries
+-----------------------------------------------------------
+*/
+// containing the functions for the agenda tool
+include "calendar.lib.php";
+// some debug functions
+include($includePath."/lib/debug.lib.inc.php");
+
+
+/*==============================================================================
+  			TREATING THE PARAMETERS
+			1. viewing month only or everything
+			2. sort ascending or descending
+			3. showing or hiding the send-to-specific-groups-or-users form
+			4. filter user or group
+  ============================================================================== */
+// 1. show all or show current month?
+if (!$_SESSION['show'])
+{
+	$_SESSION['show']="showall";
+}
+if (!empty($_GET['action']) and $_GET['action']=="showcurrent")
+{
+	$_SESSION['show']="showcurrent";
+}
+if (!empty($_GET['action']) and $_GET['action']=="showall")
+{
+	$_SESSION['show']="showall";
+}
+//echo $_SESSION['show'];
+
+// 2. sorting order (ASC or DESC)
+if (empty($_GET['sort']) and empty($_SESSION['sort']))
+{
+	$_SESSION['sort']="DESC";
+}
+if (!empty($_GET['sort']) and $_GET['sort']=="asc")
+{
+	$_SESSION['sort']="ASC";
+}
+if (!empty($_GET['sort']) and $_GET['sort']=="desc")
+{
+	$_SESSION['sort']="DESC";
+}
+if (!empty($_GET['view']))
+{
+	$_SESSION['view'] = $_GET['view'];
+}
+
+// 3. showing or hiding the send-to-specific-groups-or-users form
+$setting_allow_individual_calendar=true;
+if (empty($_POST['To']) and empty($_SESSION['allow_individual_calendar']))
+{
+	$_SESSION['allow_individual_calendar']="hide";
+}
+$allow_individual_calendar_status=$_SESSION['allow_individual_calendar'];
+if (!empty($_POST['To']) and ($allow_individual_calendar_status=="hide"))
+{
+	$_SESSION['allow_individual_calendar']="show";
+}
+if (!empty($_GET['sort']) and ($allow_individual_calendar_status=="show"))
+{
+	$_SESSION['allow_individual_calendar']="hide";
+}
+
+$htmlHeadXtra[] = to_javascript();
+
+// this loads the javascript that is needed for the date popup selection
+$htmlHeadXtra[] = "<script src=\"calendar_tbl_change.js\" type=\"text/javascript\" language=\"javascript\"></script>";
+
+// setting the name of the tool
+$nameTools = get_lang('GlobalAgenda'); // language variable in trad4all.inc.php
+
+// showing the header if we are not in the learning path, if we are in
+// the learning path, we do not include the banner so we have to explicitly
+// include the stylesheet, which is normally done in the header
+/*if (empty($_GET['origin']) or $_GET['origin'] != 'learnpath')
+{*/
+Display::display_header($nameTools,'Agenda');
+/*}
+else
+{
+	echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"".$clarolineRepositoryWeb."css/default.css\"/>";
+}*/
+
+/* ==============================================================================
+  			SETTING SOME VARIABLES
+============================================================================== */
+// Variable definitions
+$dateNow 			= format_locale_date($dateTimeFormatLong);
+// Defining the shorts for the days. We use camelcase because these are arrays of language variables
+$DaysShort = api_get_week_days_short();
+// Defining the days of the week to allow translation of the days. We use camelcase because these are arrays of language variables
+$DaysLong = api_get_week_days_long();
+// Defining the months of the year to allow translation of the months. We use camelcase because these are arrays of language variables
+$MonthsLong = api_get_months_long();
+
+// Database table definitions
+$TABLEAGENDA 			= Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+$TABLE_ITEM_PROPERTY 	= Database::get_course_table(TABLE_ITEM_PROPERTY);
+$tbl_user       		= Database::get_main_table(TABLE_MAIN_USER);
+$tbl_courseUser 		= Database::get_main_table(TABLE_MAIN_COURSE_USER);
+$tbl_group      		= Database::get_course_table(TABLE_GROUP);
+$tbl_groupUser  		= Database::get_course_table(TABLE_GROUP_USER);
+$tbl_session_course_user= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+
+
+
+/* ==============================================================================
+  			ACCESS RIGHTS
+============================================================================== */
+// permission stuff - also used by loading from global in agenda.inc.php
+$is_allowed_to_edit = is_allowed_to_edit() OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous());
+
+// Displaying the title of the tool
+// api_display_tool_title($nameTools);
+
+// tool introduction
+//Display::display_introduction_section(TOOL_CALENDAR_EVENT);
+
+// insert an anchor (top) so one can jump back to the top of the page
+echo "<a name=\"top\"></a>";
+
+/*
+==============================================================================
+		MAIN SECTION
+==============================================================================
+*/
+
+//setting the default year and month
+$select_year = '';
+$select_month = '';
+if(!empty($_GET['year']))
+{
+	$select_year = (int)$_GET['year'];
+}
+if(!empty($_GET['month']))
+{
+	$select_month = (int)$_GET['month'];
+}
+if (empty($select_year) && empty($select_month))
+{
+	$today = getdate();
+	$select_year = $today['year'];
+	$select_month = $today['mon'];
+}
+
+echo '<div class="actions">';
+if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()))
+{
+	display_student_links();
+	display_courseadmin_links();
+}
+
+echo '</div><br /><br />';
+
+
+echo '<table width="100%" border="0" cellspacing="0" cellpadding="0">'
+		. '<tr>';
+
+
+// THE LEFT PART
+if (empty($_GET['origin']) or $_GET['origin']!='learnpath')
+{
+	echo '<td width="220" height="19" valign="top">';
+	// the small calendar
+	$MonthName = $MonthsLong[$select_month -1];
+	$agenda_items=get_calendar_items($select_month,$select_year);
+	if (api_get_setting('display_mini_month_calendar') == 'true')
+	{
+		display_minimonthcalendar($agenda_items, $select_month,$select_year, $MonthName);
+	}
+	/*if (api_get_setting('display_upcoming_events') == 'true') {
+		display_upcoming_events();
+	}*/
+	echo '</td>';
+	echo '<td width="20" background="../img/verticalruler.gif">&nbsp;</td>';
+}
+
+
+// THE RIGHT PART
+echo '<td valign="top">';
+echo '<div class="sort" style="float:right">';
+
+echo '</div>';
+if (api_is_allowed_to_edit(false,true))
+{
+	switch ($_GET['action'])
+	{
+		case "add":
+            if(!empty($_POST['ical_submit'])) {
+                $course_info = api_get_course_info();
+                agenda_import_ical($course_info,$_FILES['ical_import']);
+                if (api_get_setting('display_upcoming_events') == 'true') {
+					display_upcoming_events();
+				}
+                display_agenda_items();
+            } elseif ($_POST['submit_event']) {
+
+		     $course_info = api_get_course_info();
+			    $event_start    = (int) $_POST['fyear'].'-'.(int) $_POST['fmonth'].'-'.(int) $_POST['fday'].' '.(int) $_POST['fhour'].':'.(int) $_POST['fminute'].':00';
+                $event_stop     = (int) $_POST['end_fyear'].'-'.(int) $_POST['end_fmonth'].'-'.(int) $_POST['end_fday'].' '.(int) $_POST['end_fhour'].':'.(int) $_POST['end_fminute'].':00';
+
+				$id = agenda_add_item($course_info,$_POST['title'],$_POST['content'],$event_start,$event_stop,$_POST['selectedform'],false,$_POST['file_comment']);
+
+                if(!empty($_POST['repeat'])) {
+                	$end_y = intval($_POST['repeat_end_year']);
+                    $end_m = intval($_POST['repeat_end_month']);
+                    $end_d = intval($_POST['repeat_end_day']);
+                    $end   = mktime(23, 59, 59, $end_m, $end_d, $end_y);
+                    $res = agenda_add_repeat_item($course_info,$id,$_POST['repeat_type'],$end,null,$_POST['file_comment']);
+                }
+                if (api_get_setting('display_upcoming_events') == 'true') {
+					display_upcoming_events();
+				}
+				display_agenda_items();
+			} else {
+				show_add_form();
+			}
+			break;
+
+		case "edit":
+			if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, intval($_REQUEST['id']) ) ) )
+			{ // a coach can only delete an element belonging to his session
+				if ($_POST['submit_event'])
+				{		$my_id_attach = (int)$_REQUEST['id_attach'];
+						$my_file_comment = Database::escape_string($_REQUEST['file_comment']);
+						store_edited_agenda_item($my_id_attach,$my_file_comment);
+						if (api_get_setting('display_upcoming_events') == 'true') {
+							display_upcoming_events();
+						}
+						display_agenda_items();
+				}
+				else
+				{
+						$id=(int)$_GET['id'];
+						show_add_form($id);
+				}
+			}
+			else
+			{
+				if (api_get_setting('display_upcoming_events') == 'true') {
+					display_upcoming_events();
+				}
+				display_agenda_items();
+			}
+			break;
+
+		case "delete":
+			$id=(int)$_GET['id'];
+			if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $id ) ) )
+			{ // a coach can only delete an element belonging to his session
+				delete_agenda_item($id);
+			}
+				if (api_get_setting('display_upcoming_events') == 'true') {
+					display_upcoming_events();
+				}
+				display_agenda_items();
+			break;
+
+		case "showhide":
+			$id=(int)$_GET['id'];
+			if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $id ) ) )
+			{ // a coach can only delete an element belonging to his session
+				showhide_agenda_item($id);
+			}
+			if (api_get_setting('display_upcoming_events') == 'true') {
+					display_upcoming_events();
+			}
+			display_agenda_items();
+			break;
+		case "announce": //copying the agenda item into an announcement
+			$id=(int)$_GET['id'];
+			if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $id ) ) )
+			{ // a coach can only delete an element belonging to his session
+				$ann_id = store_agenda_item_as_announcement($id);
+				$tool_group_link = (isset($_SESSION['toolgroup'])?'&toolgroup='.$_SESSION['toolgroup']:'');
+				echo '<br />';
+				Display::display_normal_message(get_lang('CopiedAsAnnouncement').'<a href="../announcements/announcements.php?id='.$ann_id.$tool_group_link.'">'.get_lang('NewAnnouncement').'</a>', false);
+			}
+			if (api_get_setting('display_upcoming_events') == 'true') {
+					display_upcoming_events();
+			}
+			display_agenda_items();
+			break;
+		case "delete_attach": //delete attachment file
+			$id_attach = (int)$_GET['id_attach'];
+			if (!empty($id_attach)) {
+				delete_attachment_file($id_attach);
+			}
+			if (api_get_setting('display_upcoming_events') == 'true') {
+					display_upcoming_events();
+			}
+			display_agenda_items();
+			break;
+
+	}
+}
+
+// this is for students and whenever the courseaministrator has not chosen any action. It is in fact the default behaviour
+if (!$_GET['action'] OR $_GET['action']=="showall"  OR $_GET['action']=="showcurrent" OR $_GET['action']=="view")
+{
+	if ($_GET['origin'] != 'learnpath')
+	{
+		if (!$_SESSION['view'] OR $_SESSION['view'] <> 'month')
+		{
+            if(!empty($_GET['agenda_id']))
+            {
+                 display_one_agenda_item((int)$_GET['agenda_id']);
+            }
+            else
+            {
+			     display_agenda_items();
+            }
+		}
+        else
+        {
+			display_monthcalendar($select_month, $select_year);
+		}
+	}
+	else
+	{
+		display_one_agenda_item((int)$_GET['agenda_id']);
+	}
+}
+echo "&nbsp;</td></tr></table>";
+
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+// The footer is displayed only if we are not in the learnpath
+if ($_GET['origin'] != 'learnpath')
+{
+
+	Display::display_footer();
+
+}
 ?>

+ 212 - 212
main/admin/class_user_import.php

@@ -1,212 +1,212 @@
-<?php
-
-// $Id: class_user_import.php 9018 2006-06-28 15:11:16Z evie_em $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2005 Bart Mollet <bart.mollet@hogent.be>
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-* This tool allows platform admins to update class-user relations by uploading
-* a CSVfile
-* @package dokeos.admin
-==============================================================================
-*/
-
-/**
- * Validates imported data.
- */
-function validate_data($user_classes) {
-	global $purification_option_for_usernames;
-	$errors = array ();
-	$classcodes = array ();
-	foreach ($user_classes as $index => $user_class) {
-		$user_class['line'] = $index + 1;
-		// 1. Check whether mandatory fields are set.
-		$mandatory_fields = array ('UserName', 'ClassName');
-		foreach ($mandatory_fields as $key => $field) {
-			if (!isset ($user_class[$field]) || strlen($user_class[$field]) == 0) {
-				$user_class['error'] = get_lang($field.'Mandatory');
-				$errors[] = $user_class;
-			}
-		}
-		// 2. Check whether classcode exists.
-		if (isset ($user_class['ClassName']) && strlen($user_class['ClassName']) != 0) {
-			// 2.1 Check whether code has been allready used in this CVS-file.
-			if (!isset ($classcodes[$user_class['ClassName']])) {
-				// 2.1.1 Check whether code exists in DB.
-				$class_table = Database :: get_main_table(TABLE_MAIN_CLASS);
-				$sql = "SELECT * FROM $class_table WHERE name = '".Database::escape_string($user_class['ClassName'])."'";
-				$res = Database::query($sql, __FILE__, __LINE__);
-				if (Database::num_rows($res) == 0) {
-					$user_class['error'] = get_lang('CodeDoesNotExists');
-					$errors[] = $user_class;
-				} else {
-					$classcodes[$user_class['CourseCode']] = 1;
-				}
-			}
-		}
-		// 3. Check username, first, check whether it is empty.
-		if (!UserManager::is_username_empty($user_class['UserName'])) {
-			// 3.1. Check whether username is too long.
-			if (UserManager::is_username_too_long($user_class['UserName'])) {
-				$user_class['error'] = get_lang('UserNameTooLong').': '.$user_class['UserName'];
-				$errors[] = $user_class;
-			}
-			$username = UserManager::purify_username($user_class['UserName'], $purification_option_for_usernames);
-			// 3.2. Check whether username exists.
-			if (UserManager::is_username_available($username)) {
-				$user_class['error'] = get_lang('UnknownUser').': '.$username;
-				$errors[] = $user_class;
-			}
-		}
-	}
-	return $errors;
-}
-
-/**
- * Saves imported data.
- */
-function save_data($users_classes) {
-
-	global $purification_option_for_usernames;
-
-	// Table definitions.
-	$user_table 		= Database :: get_main_table(TABLE_MAIN_USER);
-	$class_user_table 	= Database :: get_main_table(TABLE_MAIN_CLASS_USER);
-	$class_table 		= Database :: get_main_table(TABLE_MAIN_CLASS);
-
-	// Data parsing: purification + conversion (UserName, ClassName) --> (user_is, class_id)
-	$csv_data = array ();
-	foreach ($users_classes as $index => $user_class) {
-		$sql1 = "SELECT user_id FROM $user_table WHERE username = '".Database::escape_string(UserManager::purify_username($user_class['UserName'], $purification_option_for_usernames))."'";
-		$res1 = Database::query($sql1, __FILE__, __LINE__);
-		$obj1 = Database::fetch_object($res1);
-		$sql2 = "SELECT id FROM $class_table WHERE name = '".Database::escape_string(trim($user_class['ClassName']))."'";
-		$res2 = Database::query($sql2, __FILE__, __LINE__);
-		$obj2 = Database::fetch_object($res2);
-		if ($obj1 && $obj2) {
-			$csv_data[$obj1->user_id][$obj2->id] = 1;
-		}
-	}
-
-	// Logic for processing the request (data + UI options).
-	$db_subscriptions = array();
-	foreach ($csv_data as $user_id => $csv_subscriptions) {
-		$sql = "SELECT class_id FROM $class_user_table cu WHERE cu.user_id = $user_id";
-		$res = Database::query($sql, __FILE__, __LINE__);
-		while ($obj = Database::fetch_object($res)) {
-			$db_subscriptions[$obj->class_id] = 1;
-		}
-		$to_subscribe = array_diff(array_keys($csv_subscriptions), array_keys($db_subscriptions));
-		$to_unsubscribe = array_diff(array_keys($db_subscriptions), array_keys($csv_subscriptions));
-		// Subscriptions for new classes.
-		if ($_POST['subscribe']) {
-			foreach ($to_subscribe as $class_id) {
-				ClassManager::add_user($user_id, $class_id);
-			}
-		}
-		// Unsubscription from previous classes.
-		if ($_POST['unsubscribe']) {
-			foreach ($to_unsubscribe as $class_id) {
-				ClassManager::unsubscribe_user($user_id, $class_id);
-			}
-		}
-	}
-}
-
-/**
- * Reads a CSV-file.
- * @param string $file Path to the CSV-file
- * @return array All course-information read from the file
- */
-function parse_csv_data($file) {
-	$courses = Import::csv_to_array($file);
-	return $courses;
-}
-
-$language_file = array('admin', 'registration');
-
-$cidReset = true;
-
-include '../inc/global.inc.php';
-
-$this_section = SECTION_PLATFORM_ADMIN;
-api_protect_admin_script(true);
-
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH).'import.lib.php';
-require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
-require_once api_get_path(LIBRARY_PATH).'classmanager.lib.php';
-require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
-
-$tool_name = get_lang('AddUsersToAClass').' CSV';
-
-$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-
-// Set this option to true to enforce strict purification for usenames.
-$purification_option_for_usernames = false;
-
-set_time_limit(0);
-
-$form = new FormValidator('class_user_import');
-$form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
-$form->addElement('checkbox', 'subscribe', get_lang('Action'), get_lang('SubscribeUserIfNotAllreadySubscribed'));
-$form->addElement('checkbox', 'unsubscribe', '', get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
-$form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
-if ($form->validate()) {
-	$users_classes = parse_csv_data($_FILES['import_file']['tmp_name']);
-	$errors = validate_data($users_classes);
-	if (count($errors) == 0) {
-		save_data($users_classes);
-		header('Location: class_list.php?action=show_message&message='.urlencode(get_lang('FileImported')));
-		exit();
-	}
-}
-
-Display :: display_header($tool_name);
-api_display_tool_title($tool_name);
-
-if (count($errors) != 0) {
-	$error_message = "\n";
-	foreach ($errors as $index => $error_class_user) {
-		$error_message .= get_lang('Line').' '.$error_class_user['line'].': '.$error_class_user['error'].'</b>: ';
-		$error_message .= "\n";
-	}
-	$error_message .= "\n";
-	Display :: display_error_message($error_message);
-}
-
-$form->display();
-?>
-<p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
-<blockquote>
-<pre>
-<b>UserName</b>;<b>ClassName</b>
-jdoe;class01
-adam;class01
-</pre>
-</blockquote>
-<?php
-
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display :: display_footer();
+<?php
+
+// $Id: class_user_import.php 9018 2006-06-28 15:11:16Z evie_em $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2005 Bart Mollet <bart.mollet@hogent.be>
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+* This tool allows platform admins to update class-user relations by uploading
+* a CSVfile
+* @package dokeos.admin
+==============================================================================
+*/
+
+/**
+ * Validates imported data.
+ */
+function validate_data($user_classes) {
+	global $purification_option_for_usernames;
+	$errors = array ();
+	$classcodes = array ();
+	foreach ($user_classes as $index => $user_class) {
+		$user_class['line'] = $index + 1;
+		// 1. Check whether mandatory fields are set.
+		$mandatory_fields = array ('UserName', 'ClassName');
+		foreach ($mandatory_fields as $key => $field) {
+			if (!isset ($user_class[$field]) || strlen($user_class[$field]) == 0) {
+				$user_class['error'] = get_lang($field.'Mandatory');
+				$errors[] = $user_class;
+			}
+		}
+		// 2. Check whether classcode exists.
+		if (isset ($user_class['ClassName']) && strlen($user_class['ClassName']) != 0) {
+			// 2.1 Check whether code has been allready used in this CVS-file.
+			if (!isset ($classcodes[$user_class['ClassName']])) {
+				// 2.1.1 Check whether code exists in DB.
+				$class_table = Database :: get_main_table(TABLE_MAIN_CLASS);
+				$sql = "SELECT * FROM $class_table WHERE name = '".Database::escape_string($user_class['ClassName'])."'";
+				$res = Database::query($sql, __FILE__, __LINE__);
+				if (Database::num_rows($res) == 0) {
+					$user_class['error'] = get_lang('CodeDoesNotExists');
+					$errors[] = $user_class;
+				} else {
+					$classcodes[$user_class['CourseCode']] = 1;
+				}
+			}
+		}
+		// 3. Check username, first, check whether it is empty.
+		if (!UserManager::is_username_empty($user_class['UserName'])) {
+			// 3.1. Check whether username is too long.
+			if (UserManager::is_username_too_long($user_class['UserName'])) {
+				$user_class['error'] = get_lang('UserNameTooLong').': '.$user_class['UserName'];
+				$errors[] = $user_class;
+			}
+			$username = UserManager::purify_username($user_class['UserName'], $purification_option_for_usernames);
+			// 3.2. Check whether username exists.
+			if (UserManager::is_username_available($username)) {
+				$user_class['error'] = get_lang('UnknownUser').': '.$username;
+				$errors[] = $user_class;
+			}
+		}
+	}
+	return $errors;
+}
+
+/**
+ * Saves imported data.
+ */
+function save_data($users_classes) {
+
+	global $purification_option_for_usernames;
+
+	// Table definitions.
+	$user_table 		= Database :: get_main_table(TABLE_MAIN_USER);
+	$class_user_table 	= Database :: get_main_table(TABLE_MAIN_CLASS_USER);
+	$class_table 		= Database :: get_main_table(TABLE_MAIN_CLASS);
+
+	// Data parsing: purification + conversion (UserName, ClassName) --> (user_is, class_id)
+	$csv_data = array ();
+	foreach ($users_classes as $index => $user_class) {
+		$sql1 = "SELECT user_id FROM $user_table WHERE username = '".Database::escape_string(UserManager::purify_username($user_class['UserName'], $purification_option_for_usernames))."'";
+		$res1 = Database::query($sql1, __FILE__, __LINE__);
+		$obj1 = Database::fetch_object($res1);
+		$sql2 = "SELECT id FROM $class_table WHERE name = '".Database::escape_string(trim($user_class['ClassName']))."'";
+		$res2 = Database::query($sql2, __FILE__, __LINE__);
+		$obj2 = Database::fetch_object($res2);
+		if ($obj1 && $obj2) {
+			$csv_data[$obj1->user_id][$obj2->id] = 1;
+		}
+	}
+
+	// Logic for processing the request (data + UI options).
+	$db_subscriptions = array();
+	foreach ($csv_data as $user_id => $csv_subscriptions) {
+		$sql = "SELECT class_id FROM $class_user_table cu WHERE cu.user_id = $user_id";
+		$res = Database::query($sql, __FILE__, __LINE__);
+		while ($obj = Database::fetch_object($res)) {
+			$db_subscriptions[$obj->class_id] = 1;
+		}
+		$to_subscribe = array_diff(array_keys($csv_subscriptions), array_keys($db_subscriptions));
+		$to_unsubscribe = array_diff(array_keys($db_subscriptions), array_keys($csv_subscriptions));
+		// Subscriptions for new classes.
+		if ($_POST['subscribe']) {
+			foreach ($to_subscribe as $class_id) {
+				ClassManager::add_user($user_id, $class_id);
+			}
+		}
+		// Unsubscription from previous classes.
+		if ($_POST['unsubscribe']) {
+			foreach ($to_unsubscribe as $class_id) {
+				ClassManager::unsubscribe_user($user_id, $class_id);
+			}
+		}
+	}
+}
+
+/**
+ * Reads a CSV-file.
+ * @param string $file Path to the CSV-file
+ * @return array All course-information read from the file
+ */
+function parse_csv_data($file) {
+	$courses = Import::csv_to_array($file);
+	return $courses;
+}
+
+$language_file = array('admin', 'registration');
+
+$cidReset = true;
+
+include '../inc/global.inc.php';
+
+$this_section = SECTION_PLATFORM_ADMIN;
+api_protect_admin_script(true);
+
+require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+require_once api_get_path(LIBRARY_PATH).'import.lib.php';
+require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'classmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+
+$tool_name = get_lang('AddUsersToAClass').' CSV';
+
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+
+// Set this option to true to enforce strict purification for usenames.
+$purification_option_for_usernames = false;
+
+set_time_limit(0);
+
+$form = new FormValidator('class_user_import');
+$form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
+$form->addElement('checkbox', 'subscribe', get_lang('Action'), get_lang('SubscribeUserIfNotAllreadySubscribed'));
+$form->addElement('checkbox', 'unsubscribe', '', get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
+$form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
+if ($form->validate()) {
+	$users_classes = parse_csv_data($_FILES['import_file']['tmp_name']);
+	$errors = validate_data($users_classes);
+	if (count($errors) == 0) {
+		save_data($users_classes);
+		header('Location: class_list.php?action=show_message&message='.urlencode(get_lang('FileImported')));
+		exit();
+	}
+}
+
+Display :: display_header($tool_name);
+api_display_tool_title($tool_name);
+
+if (count($errors) != 0) {
+	$error_message = "\n";
+	foreach ($errors as $index => $error_class_user) {
+		$error_message .= get_lang('Line').' '.$error_class_user['line'].': '.$error_class_user['error'].'</b>: ';
+		$error_message .= "\n";
+	}
+	$error_message .= "\n";
+	Display :: display_error_message($error_message);
+}
+
+$form->display();
+?>
+<p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
+<blockquote>
+<pre>
+<b>UserName</b>;<b>ClassName</b>
+jdoe;class01
+adam;class01
+</pre>
+</blockquote>
+<?php
+
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display :: display_footer();

+ 559 - 559
main/admin/configure_extensions.php

@@ -1,559 +1,559 @@
-<?php // $Id: configure_homepage.php 9246 2006-09-25 13:24:53 +0000 (lun., 25 sept. 2006) bmol $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2008 Dokeos SPRL
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file='admin';
-
-$cidReset=true;
-
-include('../inc/global.inc.php');
-
-
-$this_section=SECTION_PLATFORM_ADMIN;
-
-api_protect_admin_script();
-
-$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-
-// Database Table Definitions
-$tbl_settings_current = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
-
-$message = '';
-
-require api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
-
-
-
-if(isset($_POST['activeExtension'])){
-
-	switch ($_POST['extension_code']){
-
-		case 'visio' :
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="true"
-					WHERE variable="service_visio"
-					AND subkey="active"';
-			$rs = Database::query($sql, __FILE__, __LINE__);
-			if(Database::affected_rows()>0)
-			{
-
-				// select all the courses and insert the tool inside
-				$sql = 'SELECT db_name FROM '.Database::get_main_table(TABLE_MAIN_COURSE);
-				$rs = Database::query($sql, __FILE__, __LINE__);
-				while($row = Database::fetch_array($rs)){
-					if(!empty($_POST['visio_host']))
-					{
-						$tool_table = Database::get_course_table(TABLE_TOOL_LIST,$row['db_name']);
-						$select = "SELECT id FROM $tool_table WHERE name='".TOOL_VISIO_CONFERENCE."'";
-						$selectres = Database::query($select,__FILE__, __LINE__);
-						if(Database::num_rows($selectres)<1)
-						{
-							$sql = 'INSERT INTO '.$tool_table.' SET
-									name="'.TOOL_VISIO_CONFERENCE.'",
-									link="conference/index.php?type=conference",
-									image="visio.gif",
-									visibility="1",
-									admin="0",
-									address="squaregrey.gif",
-									target="_self",
-									category="interaction"';
-							Database::query($sql, __FILE__, __LINE__);
-						}
-						$select = "SELECT id FROM $tool_table WHERE name='".TOOL_VISIO_CLASSROOM."'";
-						$selectres = Database::query($select,__FILE__, __LINE__);
-						if(Database::num_rows($selectres)<1)
-						{
-							$sql = 'INSERT INTO '.$tool_table.' SET
-									name="'.TOOL_VISIO_CLASSROOM.'",
-									link="conference/index.php?type=classroom",
-									image="visio.gif",
-									visibility="1",
-									admin="0",
-									address="squaregrey.gif",
-									target="_self",
-									category="authoring"';
-							Database::query($sql, __FILE__, __LINE__);
-						}
-					}
-				}
-				$message = get_lang('ServiceActivated');
-
-			}
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="'.Database::escape_string($_POST['visio_host']).'"
-					WHERE variable="service_visio"
-					AND subkey="visio_host"';
-			$rs = Database::query($sql, __FILE__, __LINE__);
-
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="'.Database::escape_string($_POST['visio_port']).'"
-					WHERE variable="service_visio"
-					AND subkey="visio_port"';
-			$rs = Database::query($sql, __FILE__, __LINE__);
-
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="'.Database::escape_string($_POST['visio_pass']).'"
-					WHERE variable="service_visio"
-					AND subkey="visio_pass"';
-			$rs = Database::query($sql, __FILE__, __LINE__);
-
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="'.($_POST['visio_use_rtmpt']=='true'?'true':'false').'"
-					WHERE variable="service_visio"
-					AND subkey="visio_use_rtmpt"';
-			$rs = Database::query($sql, __FILE__, __LINE__);
-
-			if(empty($message))
-			{
-				$message = get_lang('ServiceReconfigured');
-			}
-
-
-
-
-			break;
-
-		case 'ppt2lp' :
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="true"
-					WHERE variable="service_ppt2lp"
-					AND subkey="active"';
-
-			$rs = Database::query($sql, __FILE__, __LINE__);
-
-			if(Database::affected_rows()>0){
-				$message = get_lang('ServiceActivated');
-			}
-
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="'.addslashes($_POST['host']).'"
-					WHERE variable="service_ppt2lp"
-					AND subkey="host"';
-			Database::query($sql, __FILE__, __LINE__);
-
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="'.addslashes($_POST['port']).'"
-					WHERE variable="service_ppt2lp"
-					AND subkey="port"';
-			Database::query($sql, __FILE__, __LINE__);
-
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="'.addslashes($_POST['ftp_password']).'"
-					WHERE variable="service_ppt2lp"
-					AND subkey="ftp_password"';
-			Database::query($sql, __FILE__, __LINE__);
-
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="'.addslashes($_POST['user']).'"
-					WHERE variable="service_ppt2lp"
-					AND subkey="user"';
-			Database::query($sql, __FILE__, __LINE__);
-
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="'.addslashes($_POST['path_to_lzx']).'"
-					WHERE variable="service_ppt2lp"
-					AND subkey="path_to_lzx"';
-			Database::query($sql, __FILE__, __LINE__);
-
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="'.addslashes($_POST['size']).'"
-					WHERE variable="service_ppt2lp"
-					AND subkey="size"';
-			Database::query($sql, __FILE__, __LINE__);
-
-			break;
-	}
-
-}
-
-
-$listActiveServices = array();
-
-// get the list of active services
-$sql = 'SELECT variable FROM '.$tbl_settings_current.' WHERE variable LIKE "service_%" AND subkey="active" and selected_value="true"';
-
-$rs = Database::query($sql, __FILE__, __LINE__);
-while($row = Database::fetch_array($rs)){
-	$listActiveServices[] = $row['variable'];
-}
-
-$javascript_service_displayed = '';
-if(isset($_GET['display'])){
-	$javascript_service_displayed = 'document.getElementById("extension_content_'.$_GET['display'].'").style.display = "block"';
-}
-
-// javascript to handle accordion behaviour
-$javascript_message = '';
-if(!empty($message)){
-	$javascript_message =
-	'
-	document.getElementById("message").style.display = "block";
-	var timer = setTimeout(hideMessage,5000);
-	';
-}
-$htmlHeadXtra[]= '
-<script type="text/javascript">
-var listeDiv;
-var extensionsHeader = new Array();
-var extensionsContent = new Array();
-window.onload = loadTables;
-function loadTables(){
-	'.$javascript_message.'
-	var listeDiv = document.getElementsByTagName("div");
-
-	// fill extensionsHeader and extensionsContent
-	for(var i=0 ; i < listeDiv.length ; i++){
-		if(listeDiv[i].id.indexOf(\'extension_header\')!=-1){
-			listeDiv[i].onclick = afficheContent;
-			extensionsHeader.push(listeDiv[i]);
-		}
-		if(listeDiv[i].id.indexOf("extension_content")!=-1){
-			extensionsContent.push(listeDiv[i]);
-		}
-	}
-'.$javascript_service_displayed.'
-}
-
-function hideMessage(){
-	document.getElementById("message").style.display = "none";
-}
-
-function afficheContent(event){
-	var id = this.id.replace("header","content");
-	switch(document.getElementById(id).style.display){
-		case "block" :
-			document.getElementById(id).style.display = "none";
-			break;
-		case "none" :
-			document.getElementById(id).style.display = "block";
-			for(var i=0 ; i < extensionsContent.length ; i++){
-				if(extensionsContent[i].id != id)
-					extensionsContent[i].style.display = "none";
-			}
-			break;
-	}
-}
-</script>';
-
-$nameTool = get_lang('ConfigureExtensions');
-Display::display_header($nameTool);
-
-?>
-
-
-<div id="message" style="display: none">
-	<?php
-	if(!empty($message))
-		Display::display_normal_message($message)
-	?>
-</div>
-
-<div id="content" align="center">
-
-
-
-<!-- INSTRUCTIONS TO ADD AN EXTENSION HERE
-- copy paste a "main_*" div
-- set the names of the subdiv to extension_header_yourextension and extension_content_yourextension
-- extension_content_yourextension is the hidden div where you have to put your form / activation process
-- extension_header_yourextension is the name of your extension
-- you do not need to add javascript to display / hide your divs
-- please fill free to improve the global display of the document
--->
-	<!-- VISIOCONFERENCE -->
-	<div id="main_visio">
-		<div id="extension_header_visio" class="accordion_header">
-			<a href="#"><?php echo get_lang('Visioconf') ?></a>
-		</div>
-		<div id="extension_content_visio" style="display:none" class="accordion_content">
-			<?php echo get_lang('VisioconfDescription') ?><br /><br />
-			<table width="100%">
-				<tr>
-					<td align="center">
-						<?php Display::display_icon('screenshot_conf.jpg', get_lang('Visioconf')); ?>
-					</td>
-					<!--td align="center" width="50%">
-						<?php
-						$form = new FormValidator('visio');
-						$form -> addElement('text', 'visio_host', get_lang('VisioHost'));
-						$form -> addElement('html','<br /><br />');
-						$form -> addElement('text', 'visio_port', get_lang('VisioPort'));
-						$form -> addElement('html','<br /><br />');
-						$form -> addElement('text', 'visio_pass', get_lang('VisioPassword'));
-						$form -> addElement('html','<br /><br />');
-						$group = array();
-						$group[] =& HTML_QuickForm::createElement('radio', 'visio_use_rtmpt',null,get_lang('Yes'),'true');
-						$group[] =& HTML_QuickForm::createElement('radio', 'visio_use_rtmpt',null,get_lang('No'),'false');
-						$form->addGroup($group, '', get_lang('VisioUseRtmptTitle').' ('.get_lang('VisioUseRtmptComment').')', '&nbsp;');
-						//$form -> addElement('text', 'visio_is_web_rtmp', get_lang('VisioRTMPIsWeb'));
-						//$form -> addElement('html','<br /><br />');
-						$form -> addElement('hidden', 'extension_code', 'visio');
-						$defaults = array();
-						$renderer = $form -> defaultRenderer();
-						$renderer -> setElementTemplate('<div style="text-align:left">{label}</div><div style="text-align:left">{element}</div>');
-						$form -> addElement('html','<br /><br />');
-						if(in_array('service_visio',$listActiveServices))
-						{
-							$sql = 'SELECT subkey, selected_value FROM '.$tbl_settings_current.'
-									WHERE variable = "service_visio"';
-							$rs = Database::query($sql, __FILE__, __LINE__);
-							while($row = Database::fetch_array($rs,'ASSOC'))
-							{
-								$defaults[$row['subkey']] = $row['selected_value'];
-							}
-							$form -> addElement('style_submit_button', 'activeExtension', get_lang('ReconfigureExtension'),'class="save"');
-						}
-						else {
-							$form -> addElement('style_submit_button', 'activeExtension', get_lang('ActivateExtension'),'class="save"');
-						}
-						$form -> setDefaults($defaults);
-						$form -> display();
-						?>
-					</td-->
-				</tr>
-			</table>
-		</div>
-	</div>
-
-	<!-- PPT2LP -->
-	<div id="main_ppt2lp">
-		<div id="extension_header_ppt2lp" class="accordion_header">
-			<a href="#"><?php echo get_lang('Ppt2lp') ?></a>
-		</div>
-		<div id="extension_content_ppt2lp" style="display:none" class="accordion_content">
-			<?php echo get_lang('Ppt2lpDescription').' '.get_lang('Ppt2lpVoiceRecordingNeedsRed5') ?><br /><br />
-			<table width="100%">
-				<tr>
-					<td valign="top" align="center">
-						<?php Display::display_icon('screenshot_ppt2lp.jpg', get_lang('Ppt2lp')); ?>
-					</td>
-					<!--td align="center" width="50%">
-						<form method="POST" action="<?php echo api_get_self(); ?>">
-						<?php
-
-						$form = new FormValidator('ppt2lp');
-						$form -> addElement('text', 'host', get_lang('Host'));
-						$form -> addElement('html','<br /><br />');
-						$form -> addElement('text', 'port', get_lang('Port'));
-						$form -> addElement('html','<br /><br />');
-						$form -> addElement('text', 'user', get_lang('UserOnHost'));
-						$form -> addElement('html','<br /><br />');
-						$form -> addElement('text', 'ftp_password', get_lang('FtpPassword'));
-						$form -> addElement('html','<br /><br />');
-						$form -> addElement('text', 'path_to_lzx', get_lang('PathToLzx'));
-						$form -> addElement('html','<br /><br />');
-						$options = array(
-									'540x405'=>'540x405',
-									'640x480'=>'640x480',
-									'720x540'=>'720x540',
-									'800x600'=>'800x600',
-									'1000x750'=>'1000x750'
-									);
-						$form -> addElement('select', 'size', get_lang('SlideSize'), $options);
-
-
-						$form -> addElement('hidden', 'extension_code', 'ppt2lp');
-
-						$defaults = array();
-						$renderer = $form -> defaultRenderer();
-						$renderer -> setElementTemplate('<div style="text-align:left">{label}</div><div style="text-align:left">{element}</div>');
-						$form -> addElement('html','<br /><br />');
-						if(in_array('service_ppt2lp',$listActiveServices))
-						{
-							$sql = 'SELECT subkey, selected_value FROM '.$tbl_settings_current.'
-									WHERE variable = "service_ppt2lp"
-									AND subkey <> "active"';
-							$rs = Database::query($sql, __FILE__, __LINE__);
-							while($row = Database::fetch_array($rs,'ASSOC'))
-							{
-								$defaults[$row['subkey']] = $row['selected_value'];
-							}
-							$form -> addElement('style_submit_button', 'activeExtension', get_lang('ReconfigureExtension'),'class="save"');
-						}
-						else {
-							$defaults['host'] = 'localhost';
-							$defaults['port'] = '2002';
-							$defaults['size'] = '720x540';
-							$form -> addElement('style_submit_button', 'activeExtension', get_lang('ActivateExtension'),'class="save"');
-						}
-
-						$form -> setDefaults($defaults);
-						$form -> display();
-						echo '<br />';
-						?>
-						</form>
-					</td-->
-				</tr>
-			</table>
-		</div>
-	</div>
-	<?php
-	/*
-	<!-- EPHORUS -->
-	<div id="main_ephorus">
-		<div id="extension_header_ephorus" class="accordion_header">
-			<a href="#"><?php echo get_lang('EphorusPlagiarismPrevention') ?></a>
-		</div>
-		<div id="extension_content_ephorus" style="display:none;padding:0;width:780px;" class="accordion_content">
-			<table width="100%" cellpadding="0" cellspacing="0">
-				<tr>
-					<td align="center">
-						<TABLE style="WIDTH: 750px" cellSpacing="0" cellPadding="0" align="middle" border="0">
-						<TBODY>
-							<TR>
-								<TD>
-									<TABLE style="WIDTH: 475px" cellSpacing="0" cellPadding="0" border="0">
-									<TBODY>
-										<TR>
-											<TD>
-												&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
-												<a title="http://www.ephorus.com/dokeos_activate.html" href="http://www.ephorus.com/dokeos_activate.html" target="_blank">
-												<?php Display::display_icon('ephorus.gif','Ephorus'); ?>
-												</a>
-											</TD>
-											<TD>
-												<P align=center>
-													<FONT color="#669966" size="3"><?php echo get_lang('EphorusLeadersInAntiPlagiarism') ?></FONT>
-												</P>
-											</TD>
-										</TR>
-									</TBODY>
-									</TABLE>
-								</TD>
-							</TR>
-							<TR>
-								<TD>
-									<P>
-										<TABLE style="WIDTH: 85%" cellSpacing="0" cellPadding="0" border="0">
-										<TBODY>
-											<TR>
-												<TD width="50">&nbsp;
-
-												</TD>
-												<TD>
-													<P>
-														<?php echo get_lang('EphorusDescription') ?>
-													</P>
-													<P>
-														<A title="http://www.ephorus.nl/demo_account_en.html" href="http://www.ephorus.nl/demo_account_en.html" target="_blank"><?php echo get_lang('EphorusClickHereForADemoAccount') ?></A>
-													</P>
-													<P>
-														<A title="http://www.ephorus.nl:80/dokeos_activate.html" href="http://www.ephorus.nl/dokeos_activate.html" target="_blank"><?php echo get_lang('EphorusClickHereForInformationsAndPrices') ?></A>.
-													</P>
-												</TD>
-											</TR>
-										</TBODY>
-										</TABLE>
-									</P>
-								</TD>
-							</TR>
-						</TBODY>
-						</TABLE>
-                    </td>
-				</tr>
-			</table>
-		</div>
-	</div>
-	*/
-	?>
-	<!-- SEARCH -->
-	<div id="main_search">
-		<div id="extension_header_search" class="accordion_header">
-			<a href="#"><?php echo get_lang('SearchEngine') ?></a>
-		</div>
-		<div id="extension_content_search" style="display:none" class="accordion_content">
-			<?php echo get_lang('SearchEngineDescription') ?><br /><br />
-			<table width="100%">
-				<tr>
-					<td width="50%">
-						<?php Display::display_icon('screenshot_search.jpg', get_lang('SearchEngine')); ?>
-					</td>
-					<td align="center" width="50%">
-						<form method="POST" action="<?php echo api_get_self(); ?>">
-						<input type="hidden" name="extension_code" value="search" />
-						<button type="submit" class="save" name="activeExtension" value="<?php echo get_lang('ActivateExtension') ?>" ><?php echo get_lang('ActivateExtension') ?></button>
-						</form>
-					</td>
-				</tr>
-			</table>
-		</div>
-	</div>
-
-	<!-- SERVER STATS -->
-	<div id="main_serverstats">
-		<div id="extension_header_serverstats" class="accordion_header">
-			<a href="#"><?php echo get_lang('ServerStatistics') ?></a>
-		</div>
-		<div id="extension_content_serverstats" style="display:none" class="accordion_content">
-			<?php echo get_lang('ServerStatisticsDescription') ?><br /><br />
-			<table width="100%">
-				<tr>
-					<td width="50%">
-						<?php Display::display_icon('screenshot_serverstats.jpg', get_lang('ServerStatistics')); ?>
-					</td>
-					<td align="center" width="50%">
-						<form method="POST" action="<?php echo api_get_self(); ?>">
-						<input type="hidden" name="extension_code" value="serverstats" />
-						<button type="submit" class="save" name="activeExtension" value="<?php echo get_lang('ActivateExtension') ?>" ><?php echo get_lang('ActivateExtension') ?></button>
-						</form>
-					</td>
-				</tr>
-			</table>
-		</div>
-	</div>
-
-	<!-- BANDWIDTH STATS -->
-	<div id="main_bandwidthstats">
-		<div id="extension_header_bandwidthstats" class="accordion_header">
-			<a href="#"><?php echo get_lang('BandWidthStatistics') ?></a>
-		</div>
-		<div id="extension_content_bandwidthstats" style="display:none" class="accordion_content">
-			<?php echo get_lang('BandWidthStatisticsDescription') ?><br /><br />
-			<table width="100%">
-				<tr>
-					<td width="50%">
-						<?php Display::display_icon('screenshot_bandwidth.jpg', get_lang('BandWidthStatistics')); ?>
-					</td>
-					<td align="center" width="50%">
-						<form method="POST" action="<?php echo api_get_self(); ?>">
-						<input type="hidden" name="extension_code" value="bandwidthstats" />
-						<button type="submit" class="save" name="activeExtension" value="<?php echo get_lang('ActivateExtension') ?>" ><?php echo get_lang('ActivateExtension') ?></button>
-						</form>
-
-					</td>
-				</tr>
-			</table>
-		</div>
-	</div>
-
-</div><!-- /content -->
-
-
-<?php
-
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display::display_footer();
-?>
+<?php // $Id: configure_homepage.php 9246 2006-09-25 13:24:53 +0000 (lun., 25 sept. 2006) bmol $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos SPRL
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+
+// name of the language file that needs to be included
+$language_file='admin';
+
+$cidReset=true;
+
+include('../inc/global.inc.php');
+
+
+$this_section=SECTION_PLATFORM_ADMIN;
+
+api_protect_admin_script();
+
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+
+// Database Table Definitions
+$tbl_settings_current = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
+
+$message = '';
+
+require api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+
+
+
+if(isset($_POST['activeExtension'])){
+
+	switch ($_POST['extension_code']){
+
+		case 'visio' :
+			$sql = 'UPDATE '.$tbl_settings_current.' SET
+					selected_value="true"
+					WHERE variable="service_visio"
+					AND subkey="active"';
+			$rs = Database::query($sql, __FILE__, __LINE__);
+			if(Database::affected_rows()>0)
+			{
+
+				// select all the courses and insert the tool inside
+				$sql = 'SELECT db_name FROM '.Database::get_main_table(TABLE_MAIN_COURSE);
+				$rs = Database::query($sql, __FILE__, __LINE__);
+				while($row = Database::fetch_array($rs)){
+					if(!empty($_POST['visio_host']))
+					{
+						$tool_table = Database::get_course_table(TABLE_TOOL_LIST,$row['db_name']);
+						$select = "SELECT id FROM $tool_table WHERE name='".TOOL_VISIO_CONFERENCE."'";
+						$selectres = Database::query($select,__FILE__, __LINE__);
+						if(Database::num_rows($selectres)<1)
+						{
+							$sql = 'INSERT INTO '.$tool_table.' SET
+									name="'.TOOL_VISIO_CONFERENCE.'",
+									link="conference/index.php?type=conference",
+									image="visio.gif",
+									visibility="1",
+									admin="0",
+									address="squaregrey.gif",
+									target="_self",
+									category="interaction"';
+							Database::query($sql, __FILE__, __LINE__);
+						}
+						$select = "SELECT id FROM $tool_table WHERE name='".TOOL_VISIO_CLASSROOM."'";
+						$selectres = Database::query($select,__FILE__, __LINE__);
+						if(Database::num_rows($selectres)<1)
+						{
+							$sql = 'INSERT INTO '.$tool_table.' SET
+									name="'.TOOL_VISIO_CLASSROOM.'",
+									link="conference/index.php?type=classroom",
+									image="visio.gif",
+									visibility="1",
+									admin="0",
+									address="squaregrey.gif",
+									target="_self",
+									category="authoring"';
+							Database::query($sql, __FILE__, __LINE__);
+						}
+					}
+				}
+				$message = get_lang('ServiceActivated');
+
+			}
+			$sql = 'UPDATE '.$tbl_settings_current.' SET
+					selected_value="'.Database::escape_string($_POST['visio_host']).'"
+					WHERE variable="service_visio"
+					AND subkey="visio_host"';
+			$rs = Database::query($sql, __FILE__, __LINE__);
+
+			$sql = 'UPDATE '.$tbl_settings_current.' SET
+					selected_value="'.Database::escape_string($_POST['visio_port']).'"
+					WHERE variable="service_visio"
+					AND subkey="visio_port"';
+			$rs = Database::query($sql, __FILE__, __LINE__);
+
+			$sql = 'UPDATE '.$tbl_settings_current.' SET
+					selected_value="'.Database::escape_string($_POST['visio_pass']).'"
+					WHERE variable="service_visio"
+					AND subkey="visio_pass"';
+			$rs = Database::query($sql, __FILE__, __LINE__);
+
+			$sql = 'UPDATE '.$tbl_settings_current.' SET
+					selected_value="'.($_POST['visio_use_rtmpt']=='true'?'true':'false').'"
+					WHERE variable="service_visio"
+					AND subkey="visio_use_rtmpt"';
+			$rs = Database::query($sql, __FILE__, __LINE__);
+
+			if(empty($message))
+			{
+				$message = get_lang('ServiceReconfigured');
+			}
+
+
+
+
+			break;
+
+		case 'ppt2lp' :
+			$sql = 'UPDATE '.$tbl_settings_current.' SET
+					selected_value="true"
+					WHERE variable="service_ppt2lp"
+					AND subkey="active"';
+
+			$rs = Database::query($sql, __FILE__, __LINE__);
+
+			if(Database::affected_rows()>0){
+				$message = get_lang('ServiceActivated');
+			}
+
+			$sql = 'UPDATE '.$tbl_settings_current.' SET
+					selected_value="'.addslashes($_POST['host']).'"
+					WHERE variable="service_ppt2lp"
+					AND subkey="host"';
+			Database::query($sql, __FILE__, __LINE__);
+
+			$sql = 'UPDATE '.$tbl_settings_current.' SET
+					selected_value="'.addslashes($_POST['port']).'"
+					WHERE variable="service_ppt2lp"
+					AND subkey="port"';
+			Database::query($sql, __FILE__, __LINE__);
+
+			$sql = 'UPDATE '.$tbl_settings_current.' SET
+					selected_value="'.addslashes($_POST['ftp_password']).'"
+					WHERE variable="service_ppt2lp"
+					AND subkey="ftp_password"';
+			Database::query($sql, __FILE__, __LINE__);
+
+			$sql = 'UPDATE '.$tbl_settings_current.' SET
+					selected_value="'.addslashes($_POST['user']).'"
+					WHERE variable="service_ppt2lp"
+					AND subkey="user"';
+			Database::query($sql, __FILE__, __LINE__);
+
+			$sql = 'UPDATE '.$tbl_settings_current.' SET
+					selected_value="'.addslashes($_POST['path_to_lzx']).'"
+					WHERE variable="service_ppt2lp"
+					AND subkey="path_to_lzx"';
+			Database::query($sql, __FILE__, __LINE__);
+
+			$sql = 'UPDATE '.$tbl_settings_current.' SET
+					selected_value="'.addslashes($_POST['size']).'"
+					WHERE variable="service_ppt2lp"
+					AND subkey="size"';
+			Database::query($sql, __FILE__, __LINE__);
+
+			break;
+	}
+
+}
+
+
+$listActiveServices = array();
+
+// get the list of active services
+$sql = 'SELECT variable FROM '.$tbl_settings_current.' WHERE variable LIKE "service_%" AND subkey="active" and selected_value="true"';
+
+$rs = Database::query($sql, __FILE__, __LINE__);
+while($row = Database::fetch_array($rs)){
+	$listActiveServices[] = $row['variable'];
+}
+
+$javascript_service_displayed = '';
+if(isset($_GET['display'])){
+	$javascript_service_displayed = 'document.getElementById("extension_content_'.$_GET['display'].'").style.display = "block"';
+}
+
+// javascript to handle accordion behaviour
+$javascript_message = '';
+if(!empty($message)){
+	$javascript_message =
+	'
+	document.getElementById("message").style.display = "block";
+	var timer = setTimeout(hideMessage,5000);
+	';
+}
+$htmlHeadXtra[]= '
+<script type="text/javascript">
+var listeDiv;
+var extensionsHeader = new Array();
+var extensionsContent = new Array();
+window.onload = loadTables;
+function loadTables(){
+	'.$javascript_message.'
+	var listeDiv = document.getElementsByTagName("div");
+
+	// fill extensionsHeader and extensionsContent
+	for(var i=0 ; i < listeDiv.length ; i++){
+		if(listeDiv[i].id.indexOf(\'extension_header\')!=-1){
+			listeDiv[i].onclick = afficheContent;
+			extensionsHeader.push(listeDiv[i]);
+		}
+		if(listeDiv[i].id.indexOf("extension_content")!=-1){
+			extensionsContent.push(listeDiv[i]);
+		}
+	}
+'.$javascript_service_displayed.'
+}
+
+function hideMessage(){
+	document.getElementById("message").style.display = "none";
+}
+
+function afficheContent(event){
+	var id = this.id.replace("header","content");
+	switch(document.getElementById(id).style.display){
+		case "block" :
+			document.getElementById(id).style.display = "none";
+			break;
+		case "none" :
+			document.getElementById(id).style.display = "block";
+			for(var i=0 ; i < extensionsContent.length ; i++){
+				if(extensionsContent[i].id != id)
+					extensionsContent[i].style.display = "none";
+			}
+			break;
+	}
+}
+</script>';
+
+$nameTool = get_lang('ConfigureExtensions');
+Display::display_header($nameTool);
+
+?>
+
+
+<div id="message" style="display: none">
+	<?php
+	if(!empty($message))
+		Display::display_normal_message($message)
+	?>
+</div>
+
+<div id="content" align="center">
+
+
+
+<!-- INSTRUCTIONS TO ADD AN EXTENSION HERE
+- copy paste a "main_*" div
+- set the names of the subdiv to extension_header_yourextension and extension_content_yourextension
+- extension_content_yourextension is the hidden div where you have to put your form / activation process
+- extension_header_yourextension is the name of your extension
+- you do not need to add javascript to display / hide your divs
+- please fill free to improve the global display of the document
+-->
+	<!-- VISIOCONFERENCE -->
+	<div id="main_visio">
+		<div id="extension_header_visio" class="accordion_header">
+			<a href="#"><?php echo get_lang('Visioconf') ?></a>
+		</div>
+		<div id="extension_content_visio" style="display:none" class="accordion_content">
+			<?php echo get_lang('VisioconfDescription') ?><br /><br />
+			<table width="100%">
+				<tr>
+					<td align="center">
+						<?php Display::display_icon('screenshot_conf.jpg', get_lang('Visioconf')); ?>
+					</td>
+					<!--td align="center" width="50%">
+						<?php
+						$form = new FormValidator('visio');
+						$form -> addElement('text', 'visio_host', get_lang('VisioHost'));
+						$form -> addElement('html','<br /><br />');
+						$form -> addElement('text', 'visio_port', get_lang('VisioPort'));
+						$form -> addElement('html','<br /><br />');
+						$form -> addElement('text', 'visio_pass', get_lang('VisioPassword'));
+						$form -> addElement('html','<br /><br />');
+						$group = array();
+						$group[] =& HTML_QuickForm::createElement('radio', 'visio_use_rtmpt',null,get_lang('Yes'),'true');
+						$group[] =& HTML_QuickForm::createElement('radio', 'visio_use_rtmpt',null,get_lang('No'),'false');
+						$form->addGroup($group, '', get_lang('VisioUseRtmptTitle').' ('.get_lang('VisioUseRtmptComment').')', '&nbsp;');
+						//$form -> addElement('text', 'visio_is_web_rtmp', get_lang('VisioRTMPIsWeb'));
+						//$form -> addElement('html','<br /><br />');
+						$form -> addElement('hidden', 'extension_code', 'visio');
+						$defaults = array();
+						$renderer = $form -> defaultRenderer();
+						$renderer -> setElementTemplate('<div style="text-align:left">{label}</div><div style="text-align:left">{element}</div>');
+						$form -> addElement('html','<br /><br />');
+						if(in_array('service_visio',$listActiveServices))
+						{
+							$sql = 'SELECT subkey, selected_value FROM '.$tbl_settings_current.'
+									WHERE variable = "service_visio"';
+							$rs = Database::query($sql, __FILE__, __LINE__);
+							while($row = Database::fetch_array($rs,'ASSOC'))
+							{
+								$defaults[$row['subkey']] = $row['selected_value'];
+							}
+							$form -> addElement('style_submit_button', 'activeExtension', get_lang('ReconfigureExtension'),'class="save"');
+						}
+						else {
+							$form -> addElement('style_submit_button', 'activeExtension', get_lang('ActivateExtension'),'class="save"');
+						}
+						$form -> setDefaults($defaults);
+						$form -> display();
+						?>
+					</td-->
+				</tr>
+			</table>
+		</div>
+	</div>
+
+	<!-- PPT2LP -->
+	<div id="main_ppt2lp">
+		<div id="extension_header_ppt2lp" class="accordion_header">
+			<a href="#"><?php echo get_lang('Ppt2lp') ?></a>
+		</div>
+		<div id="extension_content_ppt2lp" style="display:none" class="accordion_content">
+			<?php echo get_lang('Ppt2lpDescription').' '.get_lang('Ppt2lpVoiceRecordingNeedsRed5') ?><br /><br />
+			<table width="100%">
+				<tr>
+					<td valign="top" align="center">
+						<?php Display::display_icon('screenshot_ppt2lp.jpg', get_lang('Ppt2lp')); ?>
+					</td>
+					<!--td align="center" width="50%">
+						<form method="POST" action="<?php echo api_get_self(); ?>">
+						<?php
+
+						$form = new FormValidator('ppt2lp');
+						$form -> addElement('text', 'host', get_lang('Host'));
+						$form -> addElement('html','<br /><br />');
+						$form -> addElement('text', 'port', get_lang('Port'));
+						$form -> addElement('html','<br /><br />');
+						$form -> addElement('text', 'user', get_lang('UserOnHost'));
+						$form -> addElement('html','<br /><br />');
+						$form -> addElement('text', 'ftp_password', get_lang('FtpPassword'));
+						$form -> addElement('html','<br /><br />');
+						$form -> addElement('text', 'path_to_lzx', get_lang('PathToLzx'));
+						$form -> addElement('html','<br /><br />');
+						$options = array(
+									'540x405'=>'540x405',
+									'640x480'=>'640x480',
+									'720x540'=>'720x540',
+									'800x600'=>'800x600',
+									'1000x750'=>'1000x750'
+									);
+						$form -> addElement('select', 'size', get_lang('SlideSize'), $options);
+
+
+						$form -> addElement('hidden', 'extension_code', 'ppt2lp');
+
+						$defaults = array();
+						$renderer = $form -> defaultRenderer();
+						$renderer -> setElementTemplate('<div style="text-align:left">{label}</div><div style="text-align:left">{element}</div>');
+						$form -> addElement('html','<br /><br />');
+						if(in_array('service_ppt2lp',$listActiveServices))
+						{
+							$sql = 'SELECT subkey, selected_value FROM '.$tbl_settings_current.'
+									WHERE variable = "service_ppt2lp"
+									AND subkey <> "active"';
+							$rs = Database::query($sql, __FILE__, __LINE__);
+							while($row = Database::fetch_array($rs,'ASSOC'))
+							{
+								$defaults[$row['subkey']] = $row['selected_value'];
+							}
+							$form -> addElement('style_submit_button', 'activeExtension', get_lang('ReconfigureExtension'),'class="save"');
+						}
+						else {
+							$defaults['host'] = 'localhost';
+							$defaults['port'] = '2002';
+							$defaults['size'] = '720x540';
+							$form -> addElement('style_submit_button', 'activeExtension', get_lang('ActivateExtension'),'class="save"');
+						}
+
+						$form -> setDefaults($defaults);
+						$form -> display();
+						echo '<br />';
+						?>
+						</form>
+					</td-->
+				</tr>
+			</table>
+		</div>
+	</div>
+	<?php
+	/*
+	<!-- EPHORUS -->
+	<div id="main_ephorus">
+		<div id="extension_header_ephorus" class="accordion_header">
+			<a href="#"><?php echo get_lang('EphorusPlagiarismPrevention') ?></a>
+		</div>
+		<div id="extension_content_ephorus" style="display:none;padding:0;width:780px;" class="accordion_content">
+			<table width="100%" cellpadding="0" cellspacing="0">
+				<tr>
+					<td align="center">
+						<TABLE style="WIDTH: 750px" cellSpacing="0" cellPadding="0" align="middle" border="0">
+						<TBODY>
+							<TR>
+								<TD>
+									<TABLE style="WIDTH: 475px" cellSpacing="0" cellPadding="0" border="0">
+									<TBODY>
+										<TR>
+											<TD>
+												&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+												<a title="http://www.ephorus.com/dokeos_activate.html" href="http://www.ephorus.com/dokeos_activate.html" target="_blank">
+												<?php Display::display_icon('ephorus.gif','Ephorus'); ?>
+												</a>
+											</TD>
+											<TD>
+												<P align=center>
+													<FONT color="#669966" size="3"><?php echo get_lang('EphorusLeadersInAntiPlagiarism') ?></FONT>
+												</P>
+											</TD>
+										</TR>
+									</TBODY>
+									</TABLE>
+								</TD>
+							</TR>
+							<TR>
+								<TD>
+									<P>
+										<TABLE style="WIDTH: 85%" cellSpacing="0" cellPadding="0" border="0">
+										<TBODY>
+											<TR>
+												<TD width="50">&nbsp;
+
+												</TD>
+												<TD>
+													<P>
+														<?php echo get_lang('EphorusDescription') ?>
+													</P>
+													<P>
+														<A title="http://www.ephorus.nl/demo_account_en.html" href="http://www.ephorus.nl/demo_account_en.html" target="_blank"><?php echo get_lang('EphorusClickHereForADemoAccount') ?></A>
+													</P>
+													<P>
+														<A title="http://www.ephorus.nl:80/dokeos_activate.html" href="http://www.ephorus.nl/dokeos_activate.html" target="_blank"><?php echo get_lang('EphorusClickHereForInformationsAndPrices') ?></A>.
+													</P>
+												</TD>
+											</TR>
+										</TBODY>
+										</TABLE>
+									</P>
+								</TD>
+							</TR>
+						</TBODY>
+						</TABLE>
+                    </td>
+				</tr>
+			</table>
+		</div>
+	</div>
+	*/
+	?>
+	<!-- SEARCH -->
+	<div id="main_search">
+		<div id="extension_header_search" class="accordion_header">
+			<a href="#"><?php echo get_lang('SearchEngine') ?></a>
+		</div>
+		<div id="extension_content_search" style="display:none" class="accordion_content">
+			<?php echo get_lang('SearchEngineDescription') ?><br /><br />
+			<table width="100%">
+				<tr>
+					<td width="50%">
+						<?php Display::display_icon('screenshot_search.jpg', get_lang('SearchEngine')); ?>
+					</td>
+					<td align="center" width="50%">
+						<form method="POST" action="<?php echo api_get_self(); ?>">
+						<input type="hidden" name="extension_code" value="search" />
+						<button type="submit" class="save" name="activeExtension" value="<?php echo get_lang('ActivateExtension') ?>" ><?php echo get_lang('ActivateExtension') ?></button>
+						</form>
+					</td>
+				</tr>
+			</table>
+		</div>
+	</div>
+
+	<!-- SERVER STATS -->
+	<div id="main_serverstats">
+		<div id="extension_header_serverstats" class="accordion_header">
+			<a href="#"><?php echo get_lang('ServerStatistics') ?></a>
+		</div>
+		<div id="extension_content_serverstats" style="display:none" class="accordion_content">
+			<?php echo get_lang('ServerStatisticsDescription') ?><br /><br />
+			<table width="100%">
+				<tr>
+					<td width="50%">
+						<?php Display::display_icon('screenshot_serverstats.jpg', get_lang('ServerStatistics')); ?>
+					</td>
+					<td align="center" width="50%">
+						<form method="POST" action="<?php echo api_get_self(); ?>">
+						<input type="hidden" name="extension_code" value="serverstats" />
+						<button type="submit" class="save" name="activeExtension" value="<?php echo get_lang('ActivateExtension') ?>" ><?php echo get_lang('ActivateExtension') ?></button>
+						</form>
+					</td>
+				</tr>
+			</table>
+		</div>
+	</div>
+
+	<!-- BANDWIDTH STATS -->
+	<div id="main_bandwidthstats">
+		<div id="extension_header_bandwidthstats" class="accordion_header">
+			<a href="#"><?php echo get_lang('BandWidthStatistics') ?></a>
+		</div>
+		<div id="extension_content_bandwidthstats" style="display:none" class="accordion_content">
+			<?php echo get_lang('BandWidthStatisticsDescription') ?><br /><br />
+			<table width="100%">
+				<tr>
+					<td width="50%">
+						<?php Display::display_icon('screenshot_bandwidth.jpg', get_lang('BandWidthStatistics')); ?>
+					</td>
+					<td align="center" width="50%">
+						<form method="POST" action="<?php echo api_get_self(); ?>">
+						<input type="hidden" name="extension_code" value="bandwidthstats" />
+						<button type="submit" class="save" name="activeExtension" value="<?php echo get_lang('ActivateExtension') ?>" ><?php echo get_lang('ActivateExtension') ?></button>
+						</form>
+
+					</td>
+				</tr>
+			</table>
+		</div>
+	</div>
+
+</div><!-- /content -->
+
+
+<?php
+
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display::display_footer();
+?>

+ 174 - 174
main/admin/course_import.php

@@ -1,112 +1,112 @@
-<?php // $Id: course_import.php 8216 2006-03-15 16:33:13Z turboke $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2008 Dokeos SPRL
-	Copyright (c) 2005 Bart Mollet <bart.mollet@hogent.be>
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-* This tool allows platform admins to create courses by uploading a CSV file
-* @todo Add some langvars to DLTT
-* @package dokeos.admin
-==============================================================================
-*/
-
-/**
+<?php // $Id: course_import.php 8216 2006-03-15 16:33:13Z turboke $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos SPRL
+	Copyright (c) 2005 Bart Mollet <bart.mollet@hogent.be>
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+* This tool allows platform admins to create courses by uploading a CSV file
+* @todo Add some langvars to DLTT
+* @package dokeos.admin
+==============================================================================
+*/
+
+/**
  * Validates imported data.
- */
-function validate_data($courses) {
-	global $_configuration;
+ */
+function validate_data($courses) {
+	global $_configuration;
 	global $purification_option_for_usernames;
-	$dbnamelength = strlen($_configuration['db_prefix']);
-	//Ensure the prefix + database name do not get over 40 characters
-	$maxlength = 40 - $dbnamelength;
-
-	$errors = array ();
-	$coursecodes = array ();
-	foreach ($courses as $index => $course) {
-		$course['line'] = $index +1;
+	$dbnamelength = strlen($_configuration['db_prefix']);
+	//Ensure the prefix + database name do not get over 40 characters
+	$maxlength = 40 - $dbnamelength;
+
+	$errors = array ();
+	$coursecodes = array ();
+	foreach ($courses as $index => $course) {
+		$course['line'] = $index +1;
 		// 1. Check whether mandatory fields are set.
-		$mandatory_fields = array ('Code', 'Title', 'CourseCategory', 'Teacher');
-		foreach ($mandatory_fields as $key => $field) {
+		$mandatory_fields = array ('Code', 'Title', 'CourseCategory', 'Teacher');
+		foreach ($mandatory_fields as $key => $field) {
 			if (!isset($course[$field]) || strlen($course[$field]) == 0) {
-				$course['error'] = get_lang($field.'Mandatory');
-				$errors[] = $course;
-			}
-		}
+				$course['error'] = get_lang($field.'Mandatory');
+				$errors[] = $course;
+			}
+		}
 		// 2. Check current course code.
-		if (isset ($course['Code']) && strlen($course['Code']) != 0) {
+		if (isset ($course['Code']) && strlen($course['Code']) != 0) {
 			// 2.1 Check whether code has been allready used by this CVS-file.
-			if (isset ($coursecodes[$course['Code']])) {
-				$course['error'] = get_lang('CodeTwiceInFile');
-				$errors[] = $course;
+			if (isset ($coursecodes[$course['Code']])) {
+				$course['error'] = get_lang('CodeTwiceInFile');
+				$errors[] = $course;
 			}
 			// 2.2 Check course code length.
 			elseif (api_strlen($course['Code']) > $maxlength) {
-				$course['error'] = get_lang('Max');
-				$errors[] = $course;
-			}
+				$course['error'] = get_lang('Max');
+				$errors[] = $course;
+			}
 			// 2.3 Check whether course code has been occupied.
-			else {
-				$course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
-				$sql = "SELECT * FROM $course_table WHERE code = '".Database::escape_string($course['Code'])."'";
+			else {
+				$course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
+				$sql = "SELECT * FROM $course_table WHERE code = '".Database::escape_string($course['Code'])."'";
 				$res = Database::query($sql, __FILE__, __LINE__);
-				if (Database::num_rows($res) > 0) {
-					$course['error'] = get_lang('CodeExists');
-					$errors[] = $course;
-				}
-			}
-			$coursecodes[$course['Code']] = 1;
-		}
+				if (Database::num_rows($res) > 0) {
+					$course['error'] = get_lang('CodeExists');
+					$errors[] = $course;
+				}
+			}
+			$coursecodes[$course['Code']] = 1;
+		}
 		// 3. Check whether teacher exists.
 		if (!UserManager::is_username_empty($course['Teacher'])) {
 			$teacher = UserManager::purify_username($course['Teacher'], $purification_option_for_usernames);
 			if (UserManager::is_username_available($teacher)) {
 				$course['error'] = get_lang('UnknownTeacher').' ('.$teacher.')';
-				$errors[] = $course;
-			}
-		}
+				$errors[] = $course;
+			}
+		}
 		// 4. Check whether course category exists.
 		if (isset ($course['CourseCategory']) && strlen($course['CourseCategory']) != 0) {
-			$category_table = Database :: get_main_table(TABLE_MAIN_CATEGORY);
+			$category_table = Database :: get_main_table(TABLE_MAIN_CATEGORY);
 			$sql = "SELECT * FROM $category_table WHERE code = '".Database::escape_string($course['CourseCategory'])."'";
 			$res = Database::query($sql, __FILE__, __LINE__);
 			if (Database::num_rows($res) == 0) {
 				$course['error'] = get_lang('UnkownCategory').' ('.$course['CourseCategory'].')';
-				$errors[] = $course;
-			}
-		}
-	}
-	return $errors;
-}
-
-/**
+				$errors[] = $course;
+			}
+		}
+	}
+	return $errors;
+}
+
+/**
  * Saves imported data.
  * @param   array   List of courses
- */
+ */
 function save_data($courses) {
-	global $_configuration, $firstExpirationDelay;
+	global $_configuration, $firstExpirationDelay;
 	global $purification_option_for_usernames;
-	$msg = '';
+	$msg = '';
 	foreach ($courses as $index => $course) {
 		$course_language = api_get_valid_language($course['Language']);
 		$keys = define_course_keys($course['Code'], '', $_configuration['db_prefix']);
-		$user_table = Database::get_main_table(TABLE_MAIN_USER);
+		$user_table = Database::get_main_table(TABLE_MAIN_USER);
 		$sql = "SELECT user_id, ".(api_is_western_name_order(null, $course_language) ? "CONCAT(firstname,' ',lastname)" : "CONCAT(lastname,' ',firstname)")." AS name FROM $user_table WHERE username = '".Database::escape_string(UserManager::purify_username($course['Teacher'], $purification_option_for_usernames))."'";
 		$res = Database::query($sql,__FILE__,__LINE__);
 		$teacher = Database::fetch_object($res);
@@ -114,37 +114,37 @@ function save_data($courses) {
 		$code = $keys['currentCourseId'];
 		$db_name = $keys['currentCourseDbName'];
 		$directory = $keys['currentCourseRepository'];
-		$expiration_date = time() + $firstExpirationDelay;
-		prepare_course_repository($directory, $code);
-		update_Db_course($db_name);
-		fill_course_repository($directory);
-		fill_Db_course($db_name, $directory, $course_language, array());
-		register_course($code, $visual_code, $directory, $db_name, $teacher->name, $course['CourseCategory'], $course['Title'], $course_language, $teacher->user_id, $expiration_date);
-		$msg .= '<a href="'.api_get_path(WEB_COURSE_PATH).$directory.'/">'.$code.'</a> '.get_lang('Created').'<br />';
-	}
-    if (!empty($msg)) {
-        Display::display_normal_message($msg,false);
-    }
-}
-
-/**
- * Read the CSV-file
- * @param string $file Path to the CSV-file
- * @return array All course-information read from the file
- */
+		$expiration_date = time() + $firstExpirationDelay;
+		prepare_course_repository($directory, $code);
+		update_Db_course($db_name);
+		fill_course_repository($directory);
+		fill_Db_course($db_name, $directory, $course_language, array());
+		register_course($code, $visual_code, $directory, $db_name, $teacher->name, $course['CourseCategory'], $course['Title'], $course_language, $teacher->user_id, $expiration_date);
+		$msg .= '<a href="'.api_get_path(WEB_COURSE_PATH).$directory.'/">'.$code.'</a> '.get_lang('Created').'<br />';
+	}
+    if (!empty($msg)) {
+        Display::display_normal_message($msg,false);
+    }
+}
+
+/**
+ * Read the CSV-file
+ * @param string $file Path to the CSV-file
+ * @return array All course-information read from the file
+ */
 function parse_csv_data($file) {
-	$courses = Import :: csv_to_array($file);
-	return $courses;
-}
-
-$language_file = array ('admin', 'registration','create_course', 'document');
-
-$cidReset = true;
-
+	$courses = Import :: csv_to_array($file);
+	return $courses;
+}
+
+$language_file = array ('admin', 'registration','create_course', 'document');
+
+$cidReset = true;
+
 include '../inc/global.inc.php';
 
 $this_section = SECTION_PLATFORM_ADMIN;
-api_protect_admin_script();
+api_protect_admin_script();
 
 require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once api_get_path(LIBRARY_PATH).'import.lib.php';
@@ -152,78 +152,78 @@ require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
 require_once api_get_path(CONFIGURATION_PATH).'add_course.conf.php';
 require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php';
 require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
-
-$defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
+
+$defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
 if (is_array($extAuthSource)) {
-	$defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
-}
-
-$tool_name = get_lang('ImportCourses').' CSV';
-
+	$defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
+}
+
+$tool_name = get_lang('ImportCourses').' CSV';
+
 $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-
-set_time_limit(0);
-Display :: display_header($tool_name);
-
+
+set_time_limit(0);
+Display :: display_header($tool_name);
+
 if ($_POST['formSent']) {
 	if (empty($_FILES['import_file']['tmp_name'])) {
-		$error_message = get_lang('UplUploadFailed');
-		Display :: display_error_message($error_message, false);
+		$error_message = get_lang('UplUploadFailed');
+		Display :: display_error_message($error_message, false);
 	} else {
-		$file_type = $_POST['file_type'];
-		$courses = parse_csv_data($_FILES['import_file']['tmp_name']);
-		$errors = validate_data($courses);
+		$file_type = $_POST['file_type'];
+		$courses = parse_csv_data($_FILES['import_file']['tmp_name']);
+		$errors = validate_data($courses);
 		if (count($errors) == 0) {
-			//$users = complete_missing_data($courses);
-			save_data($courses);
-			//header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('FileImported')));
-			//exit ();
-		}
-	}
-}
-
+			//$users = complete_missing_data($courses);
+			save_data($courses);
+			//header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('FileImported')));
+			//exit ();
+		}
+	}
+}
+
 if (count($errors) != 0) {
-	$error_message = '<ul>';
+	$error_message = '<ul>';
 	foreach ($errors as $index => $error_course) {
-		$error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <b>'.$error_course['error'].'</b>: ';
-		$error_message .= $error_course['Code'].' '.$error_course['Title'];
-		$error_message .= '</li>';
-	}
-	$error_message .= '</ul>';
-	Display :: display_error_message($error_message, false);
-}
-?>
-<form method="post" action="<?php echo api_get_self(); ?>" enctype="multipart/form-data" style="margin:0px;">
-<div class="row"><div class="form_header"><?php echo $tool_name; ?></div></div>
-<div class="row">
-	<div class="label"><?php echo get_lang('ImportCSVFileLocation');?></div>
-	<div class="formw">
-		<input type="file" name="import_file"/>
-	</div>
-</div>
-<div class="row">
-	<div class="label"></div>
-	<div class="formw">
-		<button type="submit" class="save" value="<?php echo get_lang('Import'); ?>"><?php echo get_lang('Import'); ?></button>
-	</div>
-</div>
-
-
-<input type="hidden" name="formSent" value="1"/>
-
-</form>
-
-<div style="clear: both;"></div>
-
-<p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
-
-<blockquote>
-<pre>
-<b>Code</b>;<b>Title</b>;<b>CourseCategory</b>;<b>Teacher</b>;Language
-BIO0015;Biology;BIO;username;english
-</pre>
-</blockquote>
-
-<?php
-
-Display :: display_footer();
+		$error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <b>'.$error_course['error'].'</b>: ';
+		$error_message .= $error_course['Code'].' '.$error_course['Title'];
+		$error_message .= '</li>';
+	}
+	$error_message .= '</ul>';
+	Display :: display_error_message($error_message, false);
+}
+?>
+<form method="post" action="<?php echo api_get_self(); ?>" enctype="multipart/form-data" style="margin:0px;">
+<div class="row"><div class="form_header"><?php echo $tool_name; ?></div></div>
+<div class="row">
+	<div class="label"><?php echo get_lang('ImportCSVFileLocation');?></div>
+	<div class="formw">
+		<input type="file" name="import_file"/>
+	</div>
+</div>
+<div class="row">
+	<div class="label"></div>
+	<div class="formw">
+		<button type="submit" class="save" value="<?php echo get_lang('Import'); ?>"><?php echo get_lang('Import'); ?></button>
+	</div>
+</div>
+
+
+<input type="hidden" name="formSent" value="1"/>
+
+</form>
+
+<div style="clear: both;"></div>
+
+<p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
+
+<blockquote>
+<pre>
+<b>Code</b>;<b>Title</b>;<b>CourseCategory</b>;<b>Teacher</b>;Language
+BIO0015;Biology;BIO;username;english
+</pre>
+</blockquote>
+
+<?php
+
+Display :: display_footer();

+ 183 - 183
main/admin/course_user_import.php

@@ -1,242 +1,242 @@
-<?php // $Id: course_user_import.php 8216 2006-03-15 16:33:13Z turboke $
-/* For licensing terms, see /dokeos_license.txt */
-/**
-==============================================================================
-* This tool allows platform admins to update course-user relations by uploading
-* a CSVfile
-* @package dokeos.admin
-==============================================================================
-*/
-
-/**
+<?php // $Id: course_user_import.php 8216 2006-03-15 16:33:13Z turboke $
+/* For licensing terms, see /dokeos_license.txt */
+/**
+==============================================================================
+* This tool allows platform admins to update course-user relations by uploading
+* a CSVfile
+* @package dokeos.admin
+==============================================================================
+*/
+
+/**
  * Validates the imported data.
- */
+ */
 function validate_data($users_courses) {
-	$errors = array ();
-	$coursecodes = array ();
+	$errors = array ();
+	$coursecodes = array ();
 	foreach ($users_courses as $index => $user_course) {
-		$user_course['line'] = $index +1;
+		$user_course['line'] = $index +1;
 		// 1. Check whether mandatory fields are set.
-		$mandatory_fields = array ('UserName', 'CourseCode', 'Status');
+		$mandatory_fields = array ('UserName', 'CourseCode', 'Status');
 		foreach ($mandatory_fields as $key => $field) {
 			if (!isset($user_course[$field]) || strlen($user_course[$field]) == 0) {
-				$user_course['error'] = get_lang($field.'Mandatory');
-				$errors[] = $user_course;
-			}
-		}
+				$user_course['error'] = get_lang($field.'Mandatory');
+				$errors[] = $user_course;
+			}
+		}
 		// 2. Check whether coursecode exists.
 		if (isset ($user_course['CourseCode']) && strlen($user_course['CourseCode']) != 0) {
 			// 2.1 Check whethher code has been allready used by this CVS-file.
 			if (!isset($coursecodes[$user_course['CourseCode']])) {
 				// 2.1.1 Check whether course with this code exists in the system.
-				$course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
+				$course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
 				$sql = "SELECT * FROM $course_table WHERE code = '".Database::escape_string($user_course['CourseCode'])."'";
 				$res = Database::query($sql, __FILE__, __LINE__);
 				if (Database::num_rows($res) == 0) {
-					$user_course['error'] = get_lang('CodeDoesNotExists');
-					$errors[] = $user_course;
+					$user_course['error'] = get_lang('CodeDoesNotExists');
+					$errors[] = $user_course;
 				} else {
-					$coursecodes[$user_course['CourseCode']] = 1;
-				}
-			}
-		}
+					$coursecodes[$user_course['CourseCode']] = 1;
+				}
+			}
+		}
 		// 3. Check whether username exists.
-		if (isset ($user_course['UserName']) && strlen($user_course['UserName']) != 0)
-		{
+		if (isset ($user_course['UserName']) && strlen($user_course['UserName']) != 0)
+		{
 			if (UserManager::is_username_available($user_course['UserName'])) {
-				$user_course['error'] = get_lang('UnknownUser');
-				$errors[] = $user_course;
-			}
-		}
+				$user_course['error'] = get_lang('UnknownUser');
+				$errors[] = $user_course;
+			}
+		}
 		// 4. Check whether status is valid.
 		if (isset ($user_course['Status']) && strlen($user_course['Status']) != 0) {
 			if ($user_course['Status'] != COURSEMANAGER && $user_course['Status'] != STUDENT) {
-				$user_course['error'] = get_lang('UnknownStatus');
-				$errors[] = $user_course;
-			}
-		}
-	}
-	return $errors;
-}
-
-/**
+				$user_course['error'] = get_lang('UnknownStatus');
+				$errors[] = $user_course;
+			}
+		}
+	}
+	return $errors;
+}
+
+/**
  * Saves imported data.
- */
-function save_data($users_courses) {
-	$user_table= Database::get_main_table(TABLE_MAIN_USER);
-	$course_user_table= Database::get_main_table(TABLE_MAIN_COURSE_USER);
-	$csv_data = array();
-	foreach ($users_courses as $index => $user_course) {
-		$csv_data[$user_course['UserName']][$user_course['CourseCode']] = $user_course['Status'];
-	}
-	foreach($csv_data as $username => $csv_subscriptions) {
-		$user_id = 0;
+ */
+function save_data($users_courses) {
+	$user_table= Database::get_main_table(TABLE_MAIN_USER);
+	$course_user_table= Database::get_main_table(TABLE_MAIN_COURSE_USER);
+	$csv_data = array();
+	foreach ($users_courses as $index => $user_course) {
+		$csv_data[$user_course['UserName']][$user_course['CourseCode']] = $user_course['Status'];
+	}
+	foreach($csv_data as $username => $csv_subscriptions) {
+		$user_id = 0;
 		$sql = "SELECT * FROM $user_table u WHERE u.username = '".Database::escape_string($username)."'";
 		$res = Database::query($sql, __FILE__, __LINE__);
 		$obj = Database::fetch_object($res);
-		$user_id = $obj->user_id;
-		$sql = "SELECT * FROM $course_user_table cu WHERE cu.user_id = $user_id";
+		$user_id = $obj->user_id;
+		$sql = "SELECT * FROM $course_user_table cu WHERE cu.user_id = $user_id";
 		$res = Database::query($sql, __FILE__, __LINE__);
-		$db_subscriptions = array();
-		while($obj = Database::fetch_object($res)) {
-			$db_subscriptions[$obj->course_code] = $obj->status;
-		}
-
-		$to_subscribe = array_diff(array_keys($csv_subscriptions),array_keys($db_subscriptions));
-		$to_unsubscribe = array_diff(array_keys($db_subscriptions),array_keys($csv_subscriptions));
-
-        global $inserted_in_course;
+		$db_subscriptions = array();
+		while($obj = Database::fetch_object($res)) {
+			$db_subscriptions[$obj->course_code] = $obj->status;
+		}
+
+		$to_subscribe = array_diff(array_keys($csv_subscriptions),array_keys($db_subscriptions));
+		$to_unsubscribe = array_diff(array_keys($db_subscriptions),array_keys($csv_subscriptions));
+
+        global $inserted_in_course;
         if (!isset($inserted_in_course)) {
         	$inserted_in_course = array();
         }
-		if($_POST['subscribe'])	{
-			foreach($to_subscribe as $index => $course_code) {
-                if(CourseManager :: course_exists($course_code)) {
-                    CourseManager::add_user_to_course($user_id,$course_code,$csv_subscriptions[$course_code]);
+		if($_POST['subscribe'])	{
+			foreach($to_subscribe as $index => $course_code) {
+                if(CourseManager :: course_exists($course_code)) {
+                    CourseManager::add_user_to_course($user_id,$course_code,$csv_subscriptions[$course_code]);
                     $course_info = CourseManager::get_course_information($course_code);
                     $inserted_in_course[$course_code] = $course_info['title'];
-                }
-                if (CourseManager :: course_exists($course_code,true)) {
+                }
+                if (CourseManager :: course_exists($course_code,true)) {
                     // Also subscribe to virtual courses through check on visual code.
-                    $list = CourseManager :: get_courses_info_from_visual_code($course_code);
-                    foreach ($list as $vcourse) {
-                        if ($vcourse['code'] == $course_code) {
+                    $list = CourseManager :: get_courses_info_from_visual_code($course_code);
+                    foreach ($list as $vcourse) {
+                        if ($vcourse['code'] == $course_code) {
                             // Ignore, this has already been inserted.
-                        } else {
-                            CourseManager::add_user_to_course($user_id,$vcourse['code'],$csv_subscriptions[$course_code]);
-                            $inserted_in_course[$vcourse['code']] = $vcourse['title'];
-                        }
-                    }
-                }
-			}
-		}
-		if($_POST['unsubscribe']) {
-			foreach($to_unsubscribe as $index => $course_code) {
-                if(CourseManager :: course_exists($course_code)) {
-                    CourseManager::unsubscribe_user($user_id,$course_code);
+                        } else {
+                            CourseManager::add_user_to_course($user_id,$vcourse['code'],$csv_subscriptions[$course_code]);
+                            $inserted_in_course[$vcourse['code']] = $vcourse['title'];
+                        }
+                    }
+                }
+			}
+		}
+		if($_POST['unsubscribe']) {
+			foreach($to_unsubscribe as $index => $course_code) {
+                if(CourseManager :: course_exists($course_code)) {
+                    CourseManager::unsubscribe_user($user_id,$course_code);
                     $course_info = CourseManager::get_course_information($course_code);
                     $inserted_in_course[$course_code] = $course_info['title'];
-                }
-                if (CourseManager :: course_exists($course_code,true)) {
-                    // also subscribe to virtual courses through check on visual code
-                    $list = CourseManager :: get_courses_info_from_visual_code($course_code);
-                    foreach ($list as $vcourse) {
-                        if ($vcourse['code'] == $course_code) {
+                }
+                if (CourseManager :: course_exists($course_code,true)) {
+                    // also subscribe to virtual courses through check on visual code
+                    $list = CourseManager :: get_courses_info_from_visual_code($course_code);
+                    foreach ($list as $vcourse) {
+                        if ($vcourse['code'] == $course_code) {
                             // Ignore, this has already been inserted.
-                        } else {
-                            CourseManager::unsubscribe_user($user_id,$vcourse['code']);
-                            $inserted_in_course[$vcourse['code']] = $vcourse['title'];
-                        }
-                    }
-                }
-			}
-		}
-	}
-}
-
-/**
+                        } else {
+                            CourseManager::unsubscribe_user($user_id,$vcourse['code']);
+                            $inserted_in_course[$vcourse['code']] = $vcourse['title'];
+                        }
+                    }
+                }
+			}
+		}
+	}
+}
+
+/**
  * Reads CSV-file.
- * @param string $file Path to the CSV-file
- * @return array All course-information read from the file
- */
-function parse_csv_data($file) {
-	$courses = Import :: csv_to_array($file);
-	return $courses;
-}
+ * @param string $file Path to the CSV-file
+ * @return array All course-information read from the file
+ */
+function parse_csv_data($file) {
+	$courses = Import :: csv_to_array($file);
+	return $courses;
+}
 
 // Language files that should be included,
-$language_file = array ('admin', 'registration');
-
-$cidReset = true;
-
+$language_file = array ('admin', 'registration');
+
+$cidReset = true;
+
 // Including the global Dokeos file.
 include '../inc/global.inc.php';
-
+
 // Setting the section (for the tabs).
 $this_section = SECTION_PLATFORM_ADMIN;
 
 // Protecting the admin section.
-api_protect_admin_script();
-
+api_protect_admin_script();
+
 // Including additional libraries.
 require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once api_get_path(LIBRARY_PATH).'import.lib.php';
 require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
 require_once api_get_path(LIBRARY_PATH).'course.lib.php';
 require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
-
-$tool_name = get_lang('AddUsersToACourse').' CSV';
-
-$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-
-set_time_limit(0);
-
+
+$tool_name = get_lang('AddUsersToACourse').' CSV';
+
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+
+set_time_limit(0);
+
 // Creating the form.
-$form = new FormValidator('course_user_import');
-$form->addElement('header', '', $tool_name);
-$form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
-$form->addElement('checkbox', 'subscribe', get_lang('Action'), get_lang('SubscribeUserIfNotAllreadySubscribed'));
-$form->addElement('checkbox', 'unsubscribe', '', get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
-$form->addElement('style_submit_button', 'submit',get_lang('Import'),'class="save"');
-if ($form->validate()) {
-	$users_courses = parse_csv_data($_FILES['import_file']['tmp_name']);
-	$errors = validate_data($users_courses);
-	if (count($errors) == 0) {
-        $inserted_in_course = array();
-		save_data($users_courses);
+$form = new FormValidator('course_user_import');
+$form->addElement('header', '', $tool_name);
+$form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
+$form->addElement('checkbox', 'subscribe', get_lang('Action'), get_lang('SubscribeUserIfNotAllreadySubscribed'));
+$form->addElement('checkbox', 'unsubscribe', '', get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
+$form->addElement('style_submit_button', 'submit',get_lang('Import'),'class="save"');
+if ($form->validate()) {
+	$users_courses = parse_csv_data($_FILES['import_file']['tmp_name']);
+	$errors = validate_data($users_courses);
+	if (count($errors) == 0) {
+        $inserted_in_course = array();
+		save_data($users_courses);
         // Build the alert message in case there were visual codes subscribed to.
-        if ($_POST['subscribe']) {
-            $warn = get_lang('UsersSubscribedToBecauseVisualCode').': ';
-        } else {
-            $warn = get_lang('UsersUnsubscribedFromBecauseVisualCode').': ';
-        }
-        if (count($inserted_in_course) > 1) {
+        if ($_POST['subscribe']) {
+            $warn = get_lang('UsersSubscribedToBecauseVisualCode').': ';
+        } else {
+            $warn = get_lang('UsersUnsubscribedFromBecauseVisualCode').': ';
+        }
+        if (count($inserted_in_course) > 1) {
         	// The users have been inserted in more than one course.
-            foreach ($inserted_in_course as $code => $info) {
-            	$warn .= ' '.$info.' ('.$code.'),';
-            }
-            $warn = substr($warn,0,-1);
-        }
-        Security::clear_token();
-        $tok = Security::get_token();
-		header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('FileImported')).'&warn='.urlencode($warn).'&sec_token='.$tok);
-		exit ();
-	}
-}
-
+            foreach ($inserted_in_course as $code => $info) {
+            	$warn .= ' '.$info.' ('.$code.'),';
+            }
+            $warn = substr($warn,0,-1);
+        }
+        Security::clear_token();
+        $tok = Security::get_token();
+		header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('FileImported')).'&warn='.urlencode($warn).'&sec_token='.$tok);
+		exit ();
+	}
+}
+
 // Displaying the header.
-Display :: display_header($tool_name);
-
+Display :: display_header($tool_name);
+
 // Displaying the tool title.
-// api_display_tool_title($tool_name);
-
-if (count($errors) != 0) {
-	$error_message = '<ul>';
-	foreach ($errors as $index => $error_course) {
+// api_display_tool_title($tool_name);
+
+if (count($errors) != 0) {
+	$error_message = '<ul>';
+	foreach ($errors as $index => $error_course) {
 		$error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <strong>'.$error_course['error'].'</strong>: ';
-		$error_message .= $error_course['Code'].' '.$error_course['Title'];
-		$error_message .= '</li>';
-	}
-	$error_message .= '</ul>';
-	Display :: display_error_message($error_message);
-}
-
+		$error_message .= $error_course['Code'].' '.$error_course['Title'];
+		$error_message .= '</li>';
+	}
+	$error_message .= '</ul>';
+	Display :: display_error_message($error_message);
+}
+
 // Displaying the form.
-$form->display();
-?>
-<p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
-<blockquote>
-<pre>
-<b>UserName</b>;<b>CourseCode</b>;<b>Status</b>
-jdoe;course01;<?php echo COURSEMANAGER; ?>
-
+$form->display();
+?>
+<p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
+<blockquote>
+<pre>
+<b>UserName</b>;<b>CourseCode</b>;<b>Status</b>
+jdoe;course01;<?php echo COURSEMANAGER; ?>
+
 adam;course01;<?php echo STUDENT; ?>
-</pre>
-<?php
-echo COURSEMANAGER.': '.get_lang('Teacher').'<br />';
-echo STUDENT.': '.get_lang('Student').'<br />';
-?>
-</blockquote>
-<?php
+</pre>
+<?php
+echo COURSEMANAGER.': '.get_lang('Teacher').'<br />';
+echo STUDENT.': '.get_lang('Student').'<br />';
+?>
+</blockquote>
+<?php
 // Footer.
-Display :: display_footer();
+Display :: display_footer();

+ 264 - 264
main/admin/resume_session.php

@@ -1,264 +1,264 @@
-<?php // $Id: resume_session.php 20709 2009-05-15 19:12:37Z ivantcholakov $
-/* For licensing terms, see /dokeos_license.txt */
-/**
-==============================================================================
-*	@author Bart Mollet
-*	@package dokeos.admin
-==============================================================================
-*/
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file = 'admin';
-$cidReset = true;
-require '../inc/global.inc.php';
-
-// setting the section (for the tabs)
-$this_section=SECTION_PLATFORM_ADMIN;
-
-api_protect_admin_script(true);
-$tool_name = get_lang('SessionOverview');
-$interbreadcrumb[]=array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[]=array('url' => 'session_list.php','name' => get_lang('SessionList'));
-
-// Database Table Definitions
-$tbl_session						= Database::get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_rel_class				= Database::get_main_table(TABLE_MAIN_SESSION_CLASS);
-$tbl_session_rel_course				= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_course							= Database::get_main_table(TABLE_MAIN_COURSE);
-$tbl_user							= Database::get_main_table(TABLE_MAIN_USER);
-$tbl_session_rel_user				= Database::get_main_table(TABLE_MAIN_SESSION_USER);
-$tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-$tbl_class							= Database::get_main_table(TABLE_MAIN_CLASS);
-$tbl_class_rel_user					= Database::get_main_table(TABLE_MAIN_CLASS_USER);
-
-$id_session = (int)$_GET['id_session'];
-
-$sql = 'SELECT name, nbr_courses, nbr_users, nbr_classes, DATE_FORMAT(date_start,"%d-%m-%Y") as date_start, DATE_FORMAT(date_end,"%d-%m-%Y") as date_end, lastname, firstname, username, session_admin_id, nb_days_access_before_beginning, nb_days_access_after_end
-		FROM '.$tbl_session.'
-		LEFT JOIN '.$tbl_user.'
-			ON id_coach = user_id
-		WHERE '.$tbl_session.'.id='.$id_session;
-
-$rs = Database::query($sql, __FILE__, __LINE__);
-$session = Database::store_result($rs);
-$session = $session[0];
-
-if(!api_is_platform_admin() && $session['session_admin_id']!=$_user['user_id'])
-{
-	api_not_allowed(true);
-}
-
-
-if($_GET['action'] == 'delete')
-{
-	$idChecked = $_GET['idChecked'];
-	if(is_array($idChecked)) {
-		$my_temp = array();
-		foreach ($idChecked as $id){
-			$my_temp[]= Database::escape_string($id);// forcing the escape_string
-		}
-		$idChecked = $my_temp;
-
-		$idChecked="'".implode("','",$idChecked)."'";
-
-		Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND course_code IN($idChecked)",__FILE__,__LINE__);
-
-		$nbr_affected_rows=mysql_affected_rows();
-
-		Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code IN($idChecked)",__FILE__,__LINE__);
-
-		Database::query("UPDATE $tbl_session SET nbr_courses=nbr_courses-$nbr_affected_rows WHERE id='$id_session'",__FILE__,__LINE__);
-	}
-
-	if(!empty($_GET['class'])){
-		Database::query("DELETE FROM $tbl_session_rel_class WHERE session_id='$id_session' AND class_id=".Database::escape_string($_GET['class']),__FILE__,__LINE__);
-
-		$nbr_affected_rows=mysql_affected_rows();
-
-		Database::query("UPDATE $tbl_session SET nbr_classes=nbr_classes-$nbr_affected_rows WHERE id='$id_session'",__FILE__,__LINE__);
-
-	}
-
-	if(!empty($_GET['user'])){
-		Database::query("DELETE FROM $tbl_session_rel_user WHERE id_session='$id_session' AND id_user=".intval($_GET['user']),__FILE__,__LINE__);
-		$nbr_affected_rows=mysql_affected_rows();
-		Database::query("UPDATE $tbl_session SET nbr_users=nbr_users-$nbr_affected_rows WHERE id='$id_session'",__FILE__,__LINE__);
-
-		Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND id_user=".intval($_GET['user']),__FILE__,__LINE__);
-		$nbr_affected_rows=mysql_affected_rows();
-		Database::query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows WHERE id_session='$id_session'",__FILE__,__LINE__);
-	}
-}
-
-
-
-
-Display::display_header($tool_name);
-if (!empty($_GET['warn'])) {
-    Display::display_warning_message(urldecode($_GET['warn']));
-}
-
-api_display_tool_title($tool_name);
-?>
-<!-- General properties -->
-<table class="data_table" width="100%">
-<tr>
-  <th colspan="2"><?php echo get_lang('GeneralProperties'); ?>
-  	<a href="session_edit.php?page=resume_session.php&id=<?php echo $id_session; ?>"><?php Display::display_icon('edit.gif', get_lang('Edit')); ?></a></th>
-  </th>
-</tr>
-<tr>
-	<td><?php echo get_lang('SessionName');?> :</td>
-	<td><?php echo $session['name'] ?></td>
-</tr>
-<tr>
-	<td><?php echo get_lang('GeneralCoach'); ?> :</td>
-	<td><?php echo api_get_person_name($session['firstname'], $session['lastname']).' ('.$session['username'].')' ?></td>
-</tr>
-<tr>
-	<td><?php echo get_lang('Date'); ?> :</td>
-	<td>
-	<?php
-		if($session['date_start']=='00-00-0000')
-			echo get_lang('NoTimeLimits');
-		else
-			echo get_lang('From').' '.$session['date_start'].' '.get_lang('To').' '.$session['date_end'];
-		 ?>
-	</td>
-</tr>
-
-<!-- show nb_days_before and nb_days_after only if they are different from 0 -->
-<tr>
-	<td>
-		<?php echo api_ucfirst(get_lang('DaysBefore')) ?> :
-	</td>
-	<td>
-		<?php echo intval($session['nb_days_access_before_beginning']) ?>
-	</td>
-</tr>
-<tr>
-	<td>
-		<?php echo api_ucfirst(get_lang('DaysAfter')) ?> :
-	</td>
-	<td>
-		<?php echo intval($session['nb_days_access_after_end']) ?>
-	</td>
-</tr>
-</table>
-
-<br />
-
-<!--List of courses -->
-<table class="data_table" width="100%">
-<tr>
-  <th colspan="4"><?php echo get_lang('CourseList'); ?>
-  	<a href="add_courses_to_session.php?page=resume_session.php&id_session=<?php echo $id_session; ?>"><?php Display::display_icon('edit.gif', get_lang('Edit')); ?></a></th>
-  </th>
-</tr>
-<tr>
-  <tr>
-  <th width="35%"><?php echo get_lang('CourseTitle'); ?></th>
-  <th width="30%"><?php echo get_lang('CourseCoach'); ?></th>
-  <th width="20%"><?php echo get_lang('UsersNumber'); ?></th>
-  <th width="15%"><?php echo get_lang('Actions'); ?></th>
-</tr>
-</tr>
-<?php
-if($session['nbr_courses']==0){
-	echo '
-		<tr>
-			<td colspan="4">'.get_lang('NoCoursesForThisSession').'</td>
-		</tr>';
-}
-else {
-	// select the courses
-	$sql = "SELECT code,title,visual_code, nbr_users, lastname, firstname, username
-			FROM $tbl_course,$tbl_session_rel_course
-			LEFT JOIN $tbl_user
-				ON $tbl_session_rel_course.id_coach = $tbl_user.user_id
-			WHERE course_code=code
-			AND id_session='$id_session'
-			ORDER BY title";
-	$result=Database::query($sql,__FILE__,__LINE__);
-	$courses=Database::store_result($result);
-	foreach($courses as $course){
-		//select the number of users
-		$sql = 'SELECT COUNT(id_user) as nb_users FROM '.$tbl_session_rel_course_rel_user.' WHERE course_code="'.Database::escape_string($course['code']).'" AND id_session='.intval($id_session);
-		$rs = Database::query($sql, __FILE__, __LINE__);
-		$course['nbr_users'] = mysql_result($rs,0,0);
-		if (empty($course['username'])) {
-			$coach = get_lang('None');
-		} else {
-			$coach = api_get_person_name($course['firstname'], $course['lastname']).' ('.$course['username'].')';
-		}
-
-		$orig_param = '&origin=resume_session';
-		//hide_course_breadcrumb the parameter has been added to hide the name of the course, that appeared in the default $interbreadcrumb
-		echo '
-		<tr>
-			<td>'.$course['title'].' ('.$course['visual_code'].')</td>
-			<td>'.$coach.'</td>
-			<td>'.$course['nbr_users'].'</td>
-			<td>
-				<a href="../tracking/courseLog.php?id_session='.$id_session.'&cidReq='.$course['code'].$orig_param.'&hide_course_breadcrumb=1">'.Display::return_icon('statistics.gif', get_lang('Tracking')).'</a>&nbsp;
-				<a href="session_course_edit.php?id_session='.$id_session.'&page=resume_session.php&course_code='.$course['code'].''.$orig_param.'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>
-				<a href="'.api_get_self().'?id_session='.$id_session.'&action=delete&idChecked[]='.$course['code'].'" onclick="javascript:if(!confirm(\''.get_lang('ConfirmYourChoice').'\')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>
-			</td>
-		</tr>';
-	}
-}
-?>
-</table>
-
-<br />
-
-<!--List of courses -->
-<table class="data_table" width="100%">
-<tr>
-  <th colspan="4"><?php echo get_lang('UserList'); ?>
-  	<a href="add_users_to_session.php?page=resume_session.php&id_session=<?php echo $id_session; ?>"><?php Display::display_icon('edit.gif', get_lang('Edit')); ?></a></th>
-  </th>
-</tr>
-</tr>
-<?php
-if($session['nbr_users']==0){
-	echo '
-		<tr>
-			<td colspan="2">'.get_lang('NoUsersForThisSession').'</td>
-		</tr>';
-}
-else {
-
-	// classe development, obsolete for the moment
-	$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
-	$sql = 'SELECT '.$tbl_user.'.user_id, lastname, firstname, username
-			FROM '.$tbl_user.'
-			INNER JOIN '.$tbl_session_rel_user.'
-				ON '.$tbl_user.'.user_id = '.$tbl_session_rel_user.'.id_user
-				AND '.$tbl_session_rel_user.'.id_session = '.$id_session.$order_clause;
-
-	$result=Database::query($sql,__FILE__,__LINE__);
-	$users=Database::store_result($result);
-	$orig_param = '&origin=resume_session&id_session='.$id_session; // change breadcrumb in destination page
-	foreach($users as $user){
-		echo '<tr>
-					<td width="90%">
-						<b>'.api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')</b>
-					</td>
-					<td>
-						<a href="../mySpace/myStudents.php?student='.$user['user_id'].''.$orig_param.'">'.Display::return_icon('statistics.gif', get_lang('Reporting')).'</a>&nbsp;<a href="'.api_get_self().'?id_session='.$id_session.'&action=delete&user='.$user['user_id'].'" onclick="javascript:if(!confirm(\''.get_lang('ConfirmYourChoice').'\')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>
-					</td>
-				  </tr>';
-	}
-}
-?>
-</table>
-<?php
-// footer
-Display :: display_footer();
-?>
+<?php // $Id: resume_session.php 20709 2009-05-15 19:12:37Z ivantcholakov $
+/* For licensing terms, see /dokeos_license.txt */
+/**
+==============================================================================
+*	@author Bart Mollet
+*	@package dokeos.admin
+==============================================================================
+*/
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
+*/
+
+// name of the language file that needs to be included
+$language_file = 'admin';
+$cidReset = true;
+require '../inc/global.inc.php';
+
+// setting the section (for the tabs)
+$this_section=SECTION_PLATFORM_ADMIN;
+
+api_protect_admin_script(true);
+$tool_name = get_lang('SessionOverview');
+$interbreadcrumb[]=array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[]=array('url' => 'session_list.php','name' => get_lang('SessionList'));
+
+// Database Table Definitions
+$tbl_session						= Database::get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_rel_class				= Database::get_main_table(TABLE_MAIN_SESSION_CLASS);
+$tbl_session_rel_course				= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+$tbl_course							= Database::get_main_table(TABLE_MAIN_COURSE);
+$tbl_user							= Database::get_main_table(TABLE_MAIN_USER);
+$tbl_session_rel_user				= Database::get_main_table(TABLE_MAIN_SESSION_USER);
+$tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+$tbl_class							= Database::get_main_table(TABLE_MAIN_CLASS);
+$tbl_class_rel_user					= Database::get_main_table(TABLE_MAIN_CLASS_USER);
+
+$id_session = (int)$_GET['id_session'];
+
+$sql = 'SELECT name, nbr_courses, nbr_users, nbr_classes, DATE_FORMAT(date_start,"%d-%m-%Y") as date_start, DATE_FORMAT(date_end,"%d-%m-%Y") as date_end, lastname, firstname, username, session_admin_id, nb_days_access_before_beginning, nb_days_access_after_end
+		FROM '.$tbl_session.'
+		LEFT JOIN '.$tbl_user.'
+			ON id_coach = user_id
+		WHERE '.$tbl_session.'.id='.$id_session;
+
+$rs = Database::query($sql, __FILE__, __LINE__);
+$session = Database::store_result($rs);
+$session = $session[0];
+
+if(!api_is_platform_admin() && $session['session_admin_id']!=$_user['user_id'])
+{
+	api_not_allowed(true);
+}
+
+
+if($_GET['action'] == 'delete')
+{
+	$idChecked = $_GET['idChecked'];
+	if(is_array($idChecked)) {
+		$my_temp = array();
+		foreach ($idChecked as $id){
+			$my_temp[]= Database::escape_string($id);// forcing the escape_string
+		}
+		$idChecked = $my_temp;
+
+		$idChecked="'".implode("','",$idChecked)."'";
+
+		Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND course_code IN($idChecked)",__FILE__,__LINE__);
+
+		$nbr_affected_rows=mysql_affected_rows();
+
+		Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code IN($idChecked)",__FILE__,__LINE__);
+
+		Database::query("UPDATE $tbl_session SET nbr_courses=nbr_courses-$nbr_affected_rows WHERE id='$id_session'",__FILE__,__LINE__);
+	}
+
+	if(!empty($_GET['class'])){
+		Database::query("DELETE FROM $tbl_session_rel_class WHERE session_id='$id_session' AND class_id=".Database::escape_string($_GET['class']),__FILE__,__LINE__);
+
+		$nbr_affected_rows=mysql_affected_rows();
+
+		Database::query("UPDATE $tbl_session SET nbr_classes=nbr_classes-$nbr_affected_rows WHERE id='$id_session'",__FILE__,__LINE__);
+
+	}
+
+	if(!empty($_GET['user'])){
+		Database::query("DELETE FROM $tbl_session_rel_user WHERE id_session='$id_session' AND id_user=".intval($_GET['user']),__FILE__,__LINE__);
+		$nbr_affected_rows=mysql_affected_rows();
+		Database::query("UPDATE $tbl_session SET nbr_users=nbr_users-$nbr_affected_rows WHERE id='$id_session'",__FILE__,__LINE__);
+
+		Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND id_user=".intval($_GET['user']),__FILE__,__LINE__);
+		$nbr_affected_rows=mysql_affected_rows();
+		Database::query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows WHERE id_session='$id_session'",__FILE__,__LINE__);
+	}
+}
+
+
+
+
+Display::display_header($tool_name);
+if (!empty($_GET['warn'])) {
+    Display::display_warning_message(urldecode($_GET['warn']));
+}
+
+api_display_tool_title($tool_name);
+?>
+<!-- General properties -->
+<table class="data_table" width="100%">
+<tr>
+  <th colspan="2"><?php echo get_lang('GeneralProperties'); ?>
+  	<a href="session_edit.php?page=resume_session.php&id=<?php echo $id_session; ?>"><?php Display::display_icon('edit.gif', get_lang('Edit')); ?></a></th>
+  </th>
+</tr>
+<tr>
+	<td><?php echo get_lang('SessionName');?> :</td>
+	<td><?php echo $session['name'] ?></td>
+</tr>
+<tr>
+	<td><?php echo get_lang('GeneralCoach'); ?> :</td>
+	<td><?php echo api_get_person_name($session['firstname'], $session['lastname']).' ('.$session['username'].')' ?></td>
+</tr>
+<tr>
+	<td><?php echo get_lang('Date'); ?> :</td>
+	<td>
+	<?php
+		if($session['date_start']=='00-00-0000')
+			echo get_lang('NoTimeLimits');
+		else
+			echo get_lang('From').' '.$session['date_start'].' '.get_lang('To').' '.$session['date_end'];
+		 ?>
+	</td>
+</tr>
+
+<!-- show nb_days_before and nb_days_after only if they are different from 0 -->
+<tr>
+	<td>
+		<?php echo api_ucfirst(get_lang('DaysBefore')) ?> :
+	</td>
+	<td>
+		<?php echo intval($session['nb_days_access_before_beginning']) ?>
+	</td>
+</tr>
+<tr>
+	<td>
+		<?php echo api_ucfirst(get_lang('DaysAfter')) ?> :
+	</td>
+	<td>
+		<?php echo intval($session['nb_days_access_after_end']) ?>
+	</td>
+</tr>
+</table>
+
+<br />
+
+<!--List of courses -->
+<table class="data_table" width="100%">
+<tr>
+  <th colspan="4"><?php echo get_lang('CourseList'); ?>
+  	<a href="add_courses_to_session.php?page=resume_session.php&id_session=<?php echo $id_session; ?>"><?php Display::display_icon('edit.gif', get_lang('Edit')); ?></a></th>
+  </th>
+</tr>
+<tr>
+  <tr>
+  <th width="35%"><?php echo get_lang('CourseTitle'); ?></th>
+  <th width="30%"><?php echo get_lang('CourseCoach'); ?></th>
+  <th width="20%"><?php echo get_lang('UsersNumber'); ?></th>
+  <th width="15%"><?php echo get_lang('Actions'); ?></th>
+</tr>
+</tr>
+<?php
+if($session['nbr_courses']==0){
+	echo '
+		<tr>
+			<td colspan="4">'.get_lang('NoCoursesForThisSession').'</td>
+		</tr>';
+}
+else {
+	// select the courses
+	$sql = "SELECT code,title,visual_code, nbr_users, lastname, firstname, username
+			FROM $tbl_course,$tbl_session_rel_course
+			LEFT JOIN $tbl_user
+				ON $tbl_session_rel_course.id_coach = $tbl_user.user_id
+			WHERE course_code=code
+			AND id_session='$id_session'
+			ORDER BY title";
+	$result=Database::query($sql,__FILE__,__LINE__);
+	$courses=Database::store_result($result);
+	foreach($courses as $course){
+		//select the number of users
+		$sql = 'SELECT COUNT(id_user) as nb_users FROM '.$tbl_session_rel_course_rel_user.' WHERE course_code="'.Database::escape_string($course['code']).'" AND id_session='.intval($id_session);
+		$rs = Database::query($sql, __FILE__, __LINE__);
+		$course['nbr_users'] = mysql_result($rs,0,0);
+		if (empty($course['username'])) {
+			$coach = get_lang('None');
+		} else {
+			$coach = api_get_person_name($course['firstname'], $course['lastname']).' ('.$course['username'].')';
+		}
+
+		$orig_param = '&origin=resume_session';
+		//hide_course_breadcrumb the parameter has been added to hide the name of the course, that appeared in the default $interbreadcrumb
+		echo '
+		<tr>
+			<td>'.$course['title'].' ('.$course['visual_code'].')</td>
+			<td>'.$coach.'</td>
+			<td>'.$course['nbr_users'].'</td>
+			<td>
+				<a href="../tracking/courseLog.php?id_session='.$id_session.'&cidReq='.$course['code'].$orig_param.'&hide_course_breadcrumb=1">'.Display::return_icon('statistics.gif', get_lang('Tracking')).'</a>&nbsp;
+				<a href="session_course_edit.php?id_session='.$id_session.'&page=resume_session.php&course_code='.$course['code'].''.$orig_param.'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>
+				<a href="'.api_get_self().'?id_session='.$id_session.'&action=delete&idChecked[]='.$course['code'].'" onclick="javascript:if(!confirm(\''.get_lang('ConfirmYourChoice').'\')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>
+			</td>
+		</tr>';
+	}
+}
+?>
+</table>
+
+<br />
+
+<!--List of courses -->
+<table class="data_table" width="100%">
+<tr>
+  <th colspan="4"><?php echo get_lang('UserList'); ?>
+  	<a href="add_users_to_session.php?page=resume_session.php&id_session=<?php echo $id_session; ?>"><?php Display::display_icon('edit.gif', get_lang('Edit')); ?></a></th>
+  </th>
+</tr>
+</tr>
+<?php
+if($session['nbr_users']==0){
+	echo '
+		<tr>
+			<td colspan="2">'.get_lang('NoUsersForThisSession').'</td>
+		</tr>';
+}
+else {
+
+	// classe development, obsolete for the moment
+	$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
+	$sql = 'SELECT '.$tbl_user.'.user_id, lastname, firstname, username
+			FROM '.$tbl_user.'
+			INNER JOIN '.$tbl_session_rel_user.'
+				ON '.$tbl_user.'.user_id = '.$tbl_session_rel_user.'.id_user
+				AND '.$tbl_session_rel_user.'.id_session = '.$id_session.$order_clause;
+
+	$result=Database::query($sql,__FILE__,__LINE__);
+	$users=Database::store_result($result);
+	$orig_param = '&origin=resume_session&id_session='.$id_session; // change breadcrumb in destination page
+	foreach($users as $user){
+		echo '<tr>
+					<td width="90%">
+						<b>'.api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')</b>
+					</td>
+					<td>
+						<a href="../mySpace/myStudents.php?student='.$user['user_id'].''.$orig_param.'">'.Display::return_icon('statistics.gif', get_lang('Reporting')).'</a>&nbsp;<a href="'.api_get_self().'?id_session='.$id_session.'&action=delete&user='.$user['user_id'].'" onclick="javascript:if(!confirm(\''.get_lang('ConfirmYourChoice').'\')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>
+					</td>
+				  </tr>';
+	}
+}
+?>
+</table>
+<?php
+// footer
+Display :: display_footer();
+?>

+ 371 - 371
main/admin/session_add.php

@@ -1,371 +1,371 @@
-<?php
-/* For licensing terms, see /dokeos_license.txt */
-
-/**
-==============================================================================
-*	@package dokeos.admin
-* 	@todo use formvalidator for the form
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file='admin';
-
-$cidReset=true;
-
-// including the global Dokeos file
-require_once('../inc/global.inc.php');
-
-// including additional libraries
-require_once(api_get_path(LIBRARY_PATH).'sessionmanager.lib.php');
-require_once ('../inc/lib/xajax/xajax.inc.php');
-$xajax = new xajax();
-//$xajax->debugOn();
-$xajax -> registerFunction ('search_coachs');
-
-// setting the section (for the tabs)
-$this_section=SECTION_PLATFORM_ADMIN;
-
-api_protect_admin_script(true);
-
-$formSent=0;
-$errorMsg='';
-
-$interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[]=array('url' => "session_list.php","name" => get_lang('SessionList'));
-
-// Database Table Definitions
-$tbl_user		= Database::get_main_table(TABLE_MAIN_USER);
-$tbl_session	= Database::get_main_table(TABLE_MAIN_SESSION);
-
-function search_coachs($needle)
-{
-	global $tbl_user;
-
-	$xajax_response = new XajaxResponse();
-	$return = '';
-
-	if(!empty($needle))
-	{
-		// xajax send utf8 datas... datas in db can be non-utf8 datas
-		$charset = api_get_setting('platform_charset');
-		$needle = api_convert_encoding($needle, $charset, 'utf-8');
-
-		$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
-
-		// search users where username or firstname or lastname begins likes $needle
-		$sql = 'SELECT username, lastname, firstname FROM '.$tbl_user.' user
-				WHERE (username LIKE "'.$needle.'%"
-				OR firstname LIKE "'.$needle.'%"
-				OR lastname LIKE "'.$needle.'%")
-				AND status=1'.
-				$order_clause.
-				' LIMIT 10';
-
-		global $_configuration;
-		if ($_configuration['multiple_access_urls']==true) {
-			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-			$access_url_id = api_get_current_access_url_id();
-			if ($access_url_id != -1){
-
-				$sql = 'SELECT username, lastname, firstname FROM '.$tbl_user.' user
-				INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id)
-				WHERE access_url_id = '.$access_url_id.'  AND (username LIKE "'.$needle.'%"
-				OR firstname LIKE "'.$needle.'%"
-				OR lastname LIKE "'.$needle.'%")
-				AND status=1'.
-				$order_clause.
-				' LIMIT 10';
-
-			}
-		}
-
-		$rs = Database::query($sql, __FILE__, __LINE__);
-		while ($user = Database :: fetch_array($rs)) {
-			$return .= '<a href="javascript: void(0);" onclick="javascript: fill_coach_field(\''.$user['username'].'\')">'.api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')</a><br />';
-		}
-	}
-	$xajax_response -> addAssign('ajax_list_coachs','innerHTML', api_utf8_encode($return));
-	return $xajax_response;
-}
-$xajax -> processRequests();
-
-$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
-
-$htmlHeadXtra[] = '
-<script type="text/javascript">
-function fill_coach_field (username) {
-
-	document.getElementById("coach_username").value = username;
-	document.getElementById("ajax_list_coachs").innerHTML = "";
-
-}
-</script>';
-
-
-if ($_POST['formSent']) {
-	$formSent=1;
-	$name= $_POST['name'];
-	$year_start= $_POST['year_start'];
-	$month_start=$_POST['month_start'];
-	$day_start=$_POST['day_start'];
-	$year_end=$_POST['year_end'];
-	$month_end=$_POST['month_end'];
-	$day_end=$_POST['day_end'];
-	$nb_days_acess_before = $_POST['nb_days_acess_before'];
-	$nb_days_acess_after = $_POST['nb_days_acess_after'];
-	$nolimit=$_POST['nolimit'];
-	$coach_username=$_POST['coach_username'];
-	$return = SessionManager::create_session($name,$year_start,$month_start,$day_start,$year_end,$month_end,$day_end,$nb_days_acess_before,$nb_days_acess_after,$nolimit,$coach_username);
-	if ($return == strval(intval($return))) {
-		// integer => no error on session creation
-		header('Location: add_courses_to_session.php?id_session='.$return.'&add=true&msg=');
-		exit();
-	}
-}
-
-$nb_days_acess_before = 0;
-$nb_days_acess_after = 0;
-
-$thisYear=date('Y');
-$thisMonth=date('m');
-$thisDay=date('d');
-
-
-$tool_name = get_lang('AddSession');
-
-//display the header
-Display::display_header($tool_name);
-
-// display the tool title
-// api_display_tool_title($tool_name);
-
-
-if (!empty($return)) {
-	Display::display_error_message($return,false);
-}
-?>
-<form method="post" name="form" action="<?php echo api_get_self(); ?>" style="margin:0px;">
-<input type="hidden" name="formSent" value="1">
-<div class="row"><div class="form_header"><?php echo $tool_name; ?></div></div>
-<table border="0" cellpadding="5" cellspacing="0" width="600">
-<tr>
-  <td width="30%"><?php echo get_lang('SessionName') ?>&nbsp;&nbsp;</td>
-  <td width="70%"><input type="text" name="name" size="50" maxlength="50" value="<?php if($formSent) echo api_htmlentities($name,ENT_QUOTES,$charset); ?>"></td>
-</tr>
-<tr>
-  <td width="30%"><?php echo get_lang('CoachName') ?>&nbsp;&nbsp;</td>
-  <td width="70%">
-<?php
-
-$sql = 'SELECT COUNT(1) FROM '.$tbl_user.' WHERE status=1';
-$rs = Database::query($sql, __FILE__, __LINE__);
-$count_users = Database::result($rs, 0, 0);
-
-if (intval($count_users)<50) {
-	$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
-	$sql="SELECT user_id,lastname,firstname,username FROM $tbl_user WHERE status='1'".$order_clause;
-	global $_configuration;
-	if ($_configuration['multiple_access_urls']==true) {
-		$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-		$access_url_id = api_get_current_access_url_id();
-		if ($access_url_id != -1){
-			$sql = 'SELECT username, lastname, firstname FROM '.$tbl_user.' user
-			INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id)
-			WHERE access_url_id = '.$access_url_id.'  AND status=1'.$order_clause;
-		}
-	}
-
-	$result=Database::query($sql,__FILE__,__LINE__);
-	$Coaches=Database::store_result($result);
-	?>
-	<select name="coach_username" value="true" style="width:250px;">
-		<option value="0"><?php get_lang('None'); ?></option>
-		<?php foreach($Coaches as $enreg): ?>
-		<option value="<?php echo $enreg['username']; ?>" <?php if($sent && $enreg['user_id'] == $id_coach) echo 'selected="selected"'; ?>><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
-		<?php endforeach; ?>
-	</select>
-	<?php
-} else {
-	?>
-	<input type="text" name="coach_username" id="coach_username" onkeyup="xajax_search_coachs(document.getElementById('coach_username').value)" /><div id="ajax_list_coachs"></div>
-	<?php
-}
-?>
-
-
-</td>
-</tr>
-<tr>
-  <td width="30%"><?php echo get_lang('NoTimeLimits') ?></td>
-  <td width="70%">
-  	<input type="checkbox" name="nolimit" onChange="setDisable(this)" />
-  </td>
-<tr>
-  <td width="30%"><?php echo get_lang('DateStartSession') ?>&nbsp;&nbsp;</td>
-  <td width="70%">
-  <select name="day_start">
-	<option value="1">01</option>
-	<option value="2" <?php if((!$formSent && $thisDay == 2) || ($formSent && $day_start == 2)) echo 'selected="selected"'; ?> >02</option>
-	<option value="3" <?php if((!$formSent && $thisDay == 3) || ($formSent && $day_start == 3)) echo 'selected="selected"'; ?> >03</option>
-	<option value="4" <?php if((!$formSent && $thisDay == 4) || ($formSent && $day_start == 4)) echo 'selected="selected"'; ?> >04</option>
-	<option value="5" <?php if((!$formSent && $thisDay == 5) || ($formSent && $day_start == 5)) echo 'selected="selected"'; ?> >05</option>
-	<option value="6" <?php if((!$formSent && $thisDay == 6) || ($formSent && $day_start == 6)) echo 'selected="selected"'; ?> >06</option>
-	<option value="7" <?php if((!$formSent && $thisDay == 7) || ($formSent && $day_start == 7)) echo 'selected="selected"'; ?> >07</option>
-	<option value="8" <?php if((!$formSent && $thisDay == 8) || ($formSent && $day_start == 8)) echo 'selected="selected"'; ?> >08</option>
-	<option value="9" <?php if((!$formSent && $thisDay == 9) || ($formSent && $day_start == 9)) echo 'selected="selected"'; ?> >09</option>
-	<option value="10" <?php if((!$formSent && $thisDay == 10) || ($formSent && $day_start == 10)) echo 'selected="selected"'; ?> >10</option>
-	<option value="11" <?php if((!$formSent && $thisDay == 11) || ($formSent && $day_start == 11)) echo 'selected="selected"'; ?> >11</option>
-	<option value="12" <?php if((!$formSent && $thisDay == 12) || ($formSent && $day_start == 12)) echo 'selected="selected"'; ?> >12</option>
-	<option value="13" <?php if((!$formSent && $thisDay == 13) || ($formSent && $day_start == 13)) echo 'selected="selected"'; ?> >13</option>
-	<option value="14" <?php if((!$formSent && $thisDay == 14) || ($formSent && $day_start == 14)) echo 'selected="selected"'; ?> >14</option>
-	<option value="15" <?php if((!$formSent && $thisDay == 15) || ($formSent && $day_start == 15)) echo 'selected="selected"'; ?> >15</option>
-	<option value="16" <?php if((!$formSent && $thisDay == 16) || ($formSent && $day_start == 16)) echo 'selected="selected"'; ?> >16</option>
-	<option value="17" <?php if((!$formSent && $thisDay == 17) || ($formSent && $day_start == 17)) echo 'selected="selected"'; ?> >17</option>
-	<option value="18" <?php if((!$formSent && $thisDay == 18) || ($formSent && $day_start == 18)) echo 'selected="selected"'; ?> >18</option>
-	<option value="19" <?php if((!$formSent && $thisDay == 19) || ($formSent && $day_start == 19)) echo 'selected="selected"'; ?> >19</option>
-	<option value="20" <?php if((!$formSent && $thisDay == 20) || ($formSent && $day_start == 20)) echo 'selected="selected"'; ?> >20</option>
-	<option value="21" <?php if((!$formSent && $thisDay == 21) || ($formSent && $day_start == 21)) echo 'selected="selected"'; ?> >21</option>
-	<option value="22" <?php if((!$formSent && $thisDay == 22) || ($formSent && $day_start == 22)) echo 'selected="selected"'; ?> >22</option>
-	<option value="23" <?php if((!$formSent && $thisDay == 23) || ($formSent && $day_start == 23)) echo 'selected="selected"'; ?> >23</option>
-	<option value="24" <?php if((!$formSent && $thisDay == 24) || ($formSent && $day_start == 24)) echo 'selected="selected"'; ?> >24</option>
-	<option value="25" <?php if((!$formSent && $thisDay == 25) || ($formSent && $day_start == 25)) echo 'selected="selected"'; ?> >25</option>
-	<option value="26" <?php if((!$formSent && $thisDay == 26) || ($formSent && $day_start == 26)) echo 'selected="selected"'; ?> >26</option>
-	<option value="27" <?php if((!$formSent && $thisDay == 27) || ($formSent && $day_start == 27)) echo 'selected="selected"'; ?> >27</option>
-	<option value="28" <?php if((!$formSent && $thisDay == 28) || ($formSent && $day_start == 28)) echo 'selected="selected"'; ?> >28</option>
-	<option value="29" <?php if((!$formSent && $thisDay == 29) || ($formSent && $day_start == 29)) echo 'selected="selected"'; ?> >29</option>
-	<option value="30" <?php if((!$formSent && $thisDay == 30) || ($formSent && $day_start == 30)) echo 'selected="selected"'; ?> >30</option>
-	<option value="31" <?php if((!$formSent && $thisDay == 31) || ($formSent && $day_start == 31)) echo 'selected="selected"'; ?> >31</option>
-  </select>
-  /
-  <select name="month_start">
-	<option value="1">01</option>
-	<option value="2" <?php if((!$formSent && $thisMonth == 2) || ($formSent && $month_start == 2)) echo 'selected="selected"'; ?> >02</option>
-	<option value="3" <?php if((!$formSent && $thisMonth == 3) || ($formSent && $month_start == 3)) echo 'selected="selected"'; ?> >03</option>
-	<option value="4" <?php if((!$formSent && $thisMonth == 4) || ($formSent && $month_start == 4)) echo 'selected="selected"'; ?> >04</option>
-	<option value="5" <?php if((!$formSent && $thisMonth == 5) || ($formSent && $month_start == 5)) echo 'selected="selected"'; ?> >05</option>
-	<option value="6" <?php if((!$formSent && $thisMonth == 6) || ($formSent && $month_start == 6)) echo 'selected="selected"'; ?> >06</option>
-	<option value="7" <?php if((!$formSent && $thisMonth == 7) || ($formSent && $month_start == 7)) echo 'selected="selected"'; ?> >07</option>
-	<option value="8" <?php if((!$formSent && $thisMonth == 8) || ($formSent && $month_start == 8)) echo 'selected="selected"'; ?> >08</option>
-	<option value="9" <?php if((!$formSent && $thisMonth == 9) || ($formSent && $month_start == 9)) echo 'selected="selected"'; ?> >09</option>
-	<option value="10" <?php if((!$formSent && $thisMonth == 10) || ($formSent && $month_start == 10)) echo 'selected="selected"'; ?> >10</option>
-	<option value="11" <?php if((!$formSent && $thisMonth == 11) || ($formSent && $month_start == 11)) echo 'selected="selected"'; ?> >11</option>
-	<option value="12" <?php if((!$formSent && $thisMonth == 12) || ($formSent && $month_start == 12)) echo 'selected="selected"'; ?> >12</option>
-  </select>
-  /
-  <select name="year_start">
-
-<?php
-for ($i=$thisYear-5;$i <= ($thisYear+5);$i++) {
-?>
-	<option value="<?php echo $i; ?>" <?php if((!$formSent && $thisYear == $i) || ($formSent && $year_start == $i)) echo 'selected="selected"'; ?> ><?php echo $i; ?></option>
-<?php
-}
-?>
-
-  </select>
-  </td>
-</tr>
-<tr>
-  <td width="30%"><?php echo get_lang('DateEndSession') ?>&nbsp;&nbsp;</td>
-  <td width="70%">
-  <select name="day_end">
-	<option value="1">01</option>
-	<option value="2" <?php if((!$formSent && $thisDay == 2) || ($formSent && $day_end == 2)) echo 'selected="selected"'; ?> >02</option>
-	<option value="3" <?php if((!$formSent && $thisDay == 3) || ($formSent && $day_end == 3)) echo 'selected="selected"'; ?> >03</option>
-	<option value="4" <?php if((!$formSent && $thisDay == 4) || ($formSent && $day_end == 4)) echo 'selected="selected"'; ?> >04</option>
-	<option value="5" <?php if((!$formSent && $thisDay == 5) || ($formSent && $day_end == 5)) echo 'selected="selected"'; ?> >05</option>
-	<option value="6" <?php if((!$formSent && $thisDay == 6) || ($formSent && $day_end == 6)) echo 'selected="selected"'; ?> >06</option>
-	<option value="7" <?php if((!$formSent && $thisDay == 7) || ($formSent && $day_end == 7)) echo 'selected="selected"'; ?> >07</option>
-	<option value="8" <?php if((!$formSent && $thisDay == 8) || ($formSent && $day_end == 8)) echo 'selected="selected"'; ?> >08</option>
-	<option value="9" <?php if((!$formSent && $thisDay == 9) || ($formSent && $day_end == 9)) echo 'selected="selected"'; ?> >09</option>
-	<option value="10" <?php if((!$formSent && $thisDay == 10) || ($formSent && $day_end == 10)) echo 'selected="selected"'; ?> >10</option>
-	<option value="11" <?php if((!$formSent && $thisDay == 11) || ($formSent && $day_end == 11)) echo 'selected="selected"'; ?> >11</option>
-	<option value="12" <?php if((!$formSent && $thisDay == 12) || ($formSent && $day_end == 12)) echo 'selected="selected"'; ?> >12</option>
-	<option value="13" <?php if((!$formSent && $thisDay == 13) || ($formSent && $day_end == 13)) echo 'selected="selected"'; ?> >13</option>
-	<option value="14" <?php if((!$formSent && $thisDay == 14) || ($formSent && $day_end == 14)) echo 'selected="selected"'; ?> >14</option>
-	<option value="15" <?php if((!$formSent && $thisDay == 15) || ($formSent && $day_end == 15)) echo 'selected="selected"'; ?> >15</option>
-	<option value="16" <?php if((!$formSent && $thisDay == 16) || ($formSent && $day_end == 16)) echo 'selected="selected"'; ?> >16</option>
-	<option value="17" <?php if((!$formSent && $thisDay == 17) || ($formSent && $day_end == 17)) echo 'selected="selected"'; ?> >17</option>
-	<option value="18" <?php if((!$formSent && $thisDay == 18) || ($formSent && $day_end == 18)) echo 'selected="selected"'; ?> >18</option>
-	<option value="19" <?php if((!$formSent && $thisDay == 19) || ($formSent && $day_end == 19)) echo 'selected="selected"'; ?> >19</option>
-	<option value="20" <?php if((!$formSent && $thisDay == 20) || ($formSent && $day_end == 20)) echo 'selected="selected"'; ?> >20</option>
-	<option value="21" <?php if((!$formSent && $thisDay == 21) || ($formSent && $day_end == 21)) echo 'selected="selected"'; ?> >21</option>
-	<option value="22" <?php if((!$formSent && $thisDay == 22) || ($formSent && $day_end == 22)) echo 'selected="selected"'; ?> >22</option>
-	<option value="23" <?php if((!$formSent && $thisDay == 23) || ($formSent && $day_end == 23)) echo 'selected="selected"'; ?> >23</option>
-	<option value="24" <?php if((!$formSent && $thisDay == 24) || ($formSent && $day_end == 24)) echo 'selected="selected"'; ?> >24</option>
-	<option value="25" <?php if((!$formSent && $thisDay == 25) || ($formSent && $day_end == 25)) echo 'selected="selected"'; ?> >25</option>
-	<option value="26" <?php if((!$formSent && $thisDay == 26) || ($formSent && $day_end == 26)) echo 'selected="selected"'; ?> >26</option>
-	<option value="27" <?php if((!$formSent && $thisDay == 27) || ($formSent && $day_end == 27)) echo 'selected="selected"'; ?> >27</option>
-	<option value="28" <?php if((!$formSent && $thisDay == 28) || ($formSent && $day_end == 28)) echo 'selected="selected"'; ?> >28</option>
-	<option value="29" <?php if((!$formSent && $thisDay == 29) || ($formSent && $day_end == 29)) echo 'selected="selected"'; ?> >29</option>
-	<option value="30" <?php if((!$formSent && $thisDay == 30) || ($formSent && $day_end == 30)) echo 'selected="selected"'; ?> >30</option>
-	<option value="31" <?php if((!$formSent && $thisDay == 31) || ($formSent && $day_end == 31)) echo 'selected="selected"'; ?> >31</option>
-  </select>
-  /
-  <select name="month_end">
-	<option value="1">01</option>
-	<option value="2" <?php if((!$formSent && $thisMonth == 2) || ($formSent && $month_end == 2)) echo 'selected="selected"'; ?> >02</option>
-	<option value="3" <?php if((!$formSent && $thisMonth == 3) || ($formSent && $month_end == 3)) echo 'selected="selected"'; ?> >03</option>
-	<option value="4" <?php if((!$formSent && $thisMonth == 4) || ($formSent && $month_end == 4)) echo 'selected="selected"'; ?> >04</option>
-	<option value="5" <?php if((!$formSent && $thisMonth == 5) || ($formSent && $month_end == 5)) echo 'selected="selected"'; ?> >05</option>
-	<option value="6" <?php if((!$formSent && $thisMonth == 6) || ($formSent && $month_end == 6)) echo 'selected="selected"'; ?> >06</option>
-	<option value="7" <?php if((!$formSent && $thisMonth == 7) || ($formSent && $month_end == 7)) echo 'selected="selected"'; ?> >07</option>
-	<option value="8" <?php if((!$formSent && $thisMonth == 8) || ($formSent && $month_end == 8)) echo 'selected="selected"'; ?> >08</option>
-	<option value="9" <?php if((!$formSent && $thisMonth == 9) || ($formSent && $month_end == 9)) echo 'selected="selected"'; ?> >09</option>
-	<option value="10" <?php if((!$formSent && $thisMonth == 10) || ($formSent && $month_end == 10)) echo 'selected="selected"'; ?> >10</option>
-	<option value="11" <?php if((!$formSent && $thisMonth == 11) || ($formSent && $month_end == 11)) echo 'selected="selected"'; ?> >11</option>
-	<option value="12" <?php if((!$formSent && $thisMonth == 12) || ($formSent && $month_end == 12)) echo 'selected="selected"'; ?> >12</option>
-  </select>
-  /
-  <select name="year_end">
-
-<?php
-for ($i=$thisYear-5;$i <= ($thisYear+5);$i++) {
-?>
-	<option value="<?php echo $i; ?>" <?php if((!$formSent && ($thisYear+1) == $i) || ($formSent && $year_end == $i)) echo 'selected="selected"'; ?> ><?php echo $i; ?></option>
-<?php
-}
-?>
-  </select>
-  </td>
-</tr>
-<tr>
-	<td>
-		&nbsp;
-	</td>
-	<td>
-		<a href="javascript://" onclick="if(document.getElementById('options').style.display == 'none'){document.getElementById('options').style.display = 'block';}else{document.getElementById('options').style.display = 'none';}"><?php echo get_lang('DefineSessionOptions') ?></a>
-		<div style="display: <?php if($formSent && ($nb_days_acess_before!=0 || $nb_days_acess_after!=0)) echo 'block'; else echo 'none'; ?>;" id="options">
-			<br>
-			<input type="text" name="nb_days_acess_before" value="<?php echo $nb_days_acess_before; ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysBefore') ?><br>
-			<input type="text" name="nb_days_acess_after" value="<?php echo $nb_days_acess_after; ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysAfter') ?>
-			<br>
-		</div>
-	</td>
-</tr>
-<tr>
-  <td>&nbsp;</td>
-  <td><button class="save" type="submit" value="<?php echo get_lang('NextStep') ?>"><?php echo get_lang('NextStep') ?></button>
- </td>
-</tr>
-
-</table>
-
-</form>
-<script type="text/javascript">
-
-function setDisable(select){
-	document.form.day_start.disabled = (select.checked) ? true : false;
-	document.form.month_start.disabled = (select.checked) ? true : false;
-	document.form.year_start.disabled = (select.checked) ? true : false;
-
-	document.form.day_end.disabled = (select.checked) ? true : false;
-	document.form.month_end.disabled = (select.checked) ? true : false;
-	document.form.year_end.disabled = (select.checked) ? true : false;
-
-}
-</script>
-<?php
-Display::display_footer();
-?>
+<?php
+/* For licensing terms, see /dokeos_license.txt */
+
+/**
+==============================================================================
+*	@package dokeos.admin
+* 	@todo use formvalidator for the form
+==============================================================================
+*/
+
+// name of the language file that needs to be included
+$language_file='admin';
+
+$cidReset=true;
+
+// including the global Dokeos file
+require_once('../inc/global.inc.php');
+
+// including additional libraries
+require_once(api_get_path(LIBRARY_PATH).'sessionmanager.lib.php');
+require_once ('../inc/lib/xajax/xajax.inc.php');
+$xajax = new xajax();
+//$xajax->debugOn();
+$xajax -> registerFunction ('search_coachs');
+
+// setting the section (for the tabs)
+$this_section=SECTION_PLATFORM_ADMIN;
+
+api_protect_admin_script(true);
+
+$formSent=0;
+$errorMsg='';
+
+$interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[]=array('url' => "session_list.php","name" => get_lang('SessionList'));
+
+// Database Table Definitions
+$tbl_user		= Database::get_main_table(TABLE_MAIN_USER);
+$tbl_session	= Database::get_main_table(TABLE_MAIN_SESSION);
+
+function search_coachs($needle)
+{
+	global $tbl_user;
+
+	$xajax_response = new XajaxResponse();
+	$return = '';
+
+	if(!empty($needle))
+	{
+		// xajax send utf8 datas... datas in db can be non-utf8 datas
+		$charset = api_get_setting('platform_charset');
+		$needle = api_convert_encoding($needle, $charset, 'utf-8');
+
+		$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
+
+		// search users where username or firstname or lastname begins likes $needle
+		$sql = 'SELECT username, lastname, firstname FROM '.$tbl_user.' user
+				WHERE (username LIKE "'.$needle.'%"
+				OR firstname LIKE "'.$needle.'%"
+				OR lastname LIKE "'.$needle.'%")
+				AND status=1'.
+				$order_clause.
+				' LIMIT 10';
+
+		global $_configuration;
+		if ($_configuration['multiple_access_urls']==true) {
+			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+			$access_url_id = api_get_current_access_url_id();
+			if ($access_url_id != -1){
+
+				$sql = 'SELECT username, lastname, firstname FROM '.$tbl_user.' user
+				INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id)
+				WHERE access_url_id = '.$access_url_id.'  AND (username LIKE "'.$needle.'%"
+				OR firstname LIKE "'.$needle.'%"
+				OR lastname LIKE "'.$needle.'%")
+				AND status=1'.
+				$order_clause.
+				' LIMIT 10';
+
+			}
+		}
+
+		$rs = Database::query($sql, __FILE__, __LINE__);
+		while ($user = Database :: fetch_array($rs)) {
+			$return .= '<a href="javascript: void(0);" onclick="javascript: fill_coach_field(\''.$user['username'].'\')">'.api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')</a><br />';
+		}
+	}
+	$xajax_response -> addAssign('ajax_list_coachs','innerHTML', api_utf8_encode($return));
+	return $xajax_response;
+}
+$xajax -> processRequests();
+
+$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
+
+$htmlHeadXtra[] = '
+<script type="text/javascript">
+function fill_coach_field (username) {
+
+	document.getElementById("coach_username").value = username;
+	document.getElementById("ajax_list_coachs").innerHTML = "";
+
+}
+</script>';
+
+
+if ($_POST['formSent']) {
+	$formSent=1;
+	$name= $_POST['name'];
+	$year_start= $_POST['year_start'];
+	$month_start=$_POST['month_start'];
+	$day_start=$_POST['day_start'];
+	$year_end=$_POST['year_end'];
+	$month_end=$_POST['month_end'];
+	$day_end=$_POST['day_end'];
+	$nb_days_acess_before = $_POST['nb_days_acess_before'];
+	$nb_days_acess_after = $_POST['nb_days_acess_after'];
+	$nolimit=$_POST['nolimit'];
+	$coach_username=$_POST['coach_username'];
+	$return = SessionManager::create_session($name,$year_start,$month_start,$day_start,$year_end,$month_end,$day_end,$nb_days_acess_before,$nb_days_acess_after,$nolimit,$coach_username);
+	if ($return == strval(intval($return))) {
+		// integer => no error on session creation
+		header('Location: add_courses_to_session.php?id_session='.$return.'&add=true&msg=');
+		exit();
+	}
+}
+
+$nb_days_acess_before = 0;
+$nb_days_acess_after = 0;
+
+$thisYear=date('Y');
+$thisMonth=date('m');
+$thisDay=date('d');
+
+
+$tool_name = get_lang('AddSession');
+
+//display the header
+Display::display_header($tool_name);
+
+// display the tool title
+// api_display_tool_title($tool_name);
+
+
+if (!empty($return)) {
+	Display::display_error_message($return,false);
+}
+?>
+<form method="post" name="form" action="<?php echo api_get_self(); ?>" style="margin:0px;">
+<input type="hidden" name="formSent" value="1">
+<div class="row"><div class="form_header"><?php echo $tool_name; ?></div></div>
+<table border="0" cellpadding="5" cellspacing="0" width="600">
+<tr>
+  <td width="30%"><?php echo get_lang('SessionName') ?>&nbsp;&nbsp;</td>
+  <td width="70%"><input type="text" name="name" size="50" maxlength="50" value="<?php if($formSent) echo api_htmlentities($name,ENT_QUOTES,$charset); ?>"></td>
+</tr>
+<tr>
+  <td width="30%"><?php echo get_lang('CoachName') ?>&nbsp;&nbsp;</td>
+  <td width="70%">
+<?php
+
+$sql = 'SELECT COUNT(1) FROM '.$tbl_user.' WHERE status=1';
+$rs = Database::query($sql, __FILE__, __LINE__);
+$count_users = Database::result($rs, 0, 0);
+
+if (intval($count_users)<50) {
+	$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
+	$sql="SELECT user_id,lastname,firstname,username FROM $tbl_user WHERE status='1'".$order_clause;
+	global $_configuration;
+	if ($_configuration['multiple_access_urls']==true) {
+		$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+		$access_url_id = api_get_current_access_url_id();
+		if ($access_url_id != -1){
+			$sql = 'SELECT username, lastname, firstname FROM '.$tbl_user.' user
+			INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id)
+			WHERE access_url_id = '.$access_url_id.'  AND status=1'.$order_clause;
+		}
+	}
+
+	$result=Database::query($sql,__FILE__,__LINE__);
+	$Coaches=Database::store_result($result);
+	?>
+	<select name="coach_username" value="true" style="width:250px;">
+		<option value="0"><?php get_lang('None'); ?></option>
+		<?php foreach($Coaches as $enreg): ?>
+		<option value="<?php echo $enreg['username']; ?>" <?php if($sent && $enreg['user_id'] == $id_coach) echo 'selected="selected"'; ?>><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
+		<?php endforeach; ?>
+	</select>
+	<?php
+} else {
+	?>
+	<input type="text" name="coach_username" id="coach_username" onkeyup="xajax_search_coachs(document.getElementById('coach_username').value)" /><div id="ajax_list_coachs"></div>
+	<?php
+}
+?>
+
+
+</td>
+</tr>
+<tr>
+  <td width="30%"><?php echo get_lang('NoTimeLimits') ?></td>
+  <td width="70%">
+  	<input type="checkbox" name="nolimit" onChange="setDisable(this)" />
+  </td>
+<tr>
+  <td width="30%"><?php echo get_lang('DateStartSession') ?>&nbsp;&nbsp;</td>
+  <td width="70%">
+  <select name="day_start">
+	<option value="1">01</option>
+	<option value="2" <?php if((!$formSent && $thisDay == 2) || ($formSent && $day_start == 2)) echo 'selected="selected"'; ?> >02</option>
+	<option value="3" <?php if((!$formSent && $thisDay == 3) || ($formSent && $day_start == 3)) echo 'selected="selected"'; ?> >03</option>
+	<option value="4" <?php if((!$formSent && $thisDay == 4) || ($formSent && $day_start == 4)) echo 'selected="selected"'; ?> >04</option>
+	<option value="5" <?php if((!$formSent && $thisDay == 5) || ($formSent && $day_start == 5)) echo 'selected="selected"'; ?> >05</option>
+	<option value="6" <?php if((!$formSent && $thisDay == 6) || ($formSent && $day_start == 6)) echo 'selected="selected"'; ?> >06</option>
+	<option value="7" <?php if((!$formSent && $thisDay == 7) || ($formSent && $day_start == 7)) echo 'selected="selected"'; ?> >07</option>
+	<option value="8" <?php if((!$formSent && $thisDay == 8) || ($formSent && $day_start == 8)) echo 'selected="selected"'; ?> >08</option>
+	<option value="9" <?php if((!$formSent && $thisDay == 9) || ($formSent && $day_start == 9)) echo 'selected="selected"'; ?> >09</option>
+	<option value="10" <?php if((!$formSent && $thisDay == 10) || ($formSent && $day_start == 10)) echo 'selected="selected"'; ?> >10</option>
+	<option value="11" <?php if((!$formSent && $thisDay == 11) || ($formSent && $day_start == 11)) echo 'selected="selected"'; ?> >11</option>
+	<option value="12" <?php if((!$formSent && $thisDay == 12) || ($formSent && $day_start == 12)) echo 'selected="selected"'; ?> >12</option>
+	<option value="13" <?php if((!$formSent && $thisDay == 13) || ($formSent && $day_start == 13)) echo 'selected="selected"'; ?> >13</option>
+	<option value="14" <?php if((!$formSent && $thisDay == 14) || ($formSent && $day_start == 14)) echo 'selected="selected"'; ?> >14</option>
+	<option value="15" <?php if((!$formSent && $thisDay == 15) || ($formSent && $day_start == 15)) echo 'selected="selected"'; ?> >15</option>
+	<option value="16" <?php if((!$formSent && $thisDay == 16) || ($formSent && $day_start == 16)) echo 'selected="selected"'; ?> >16</option>
+	<option value="17" <?php if((!$formSent && $thisDay == 17) || ($formSent && $day_start == 17)) echo 'selected="selected"'; ?> >17</option>
+	<option value="18" <?php if((!$formSent && $thisDay == 18) || ($formSent && $day_start == 18)) echo 'selected="selected"'; ?> >18</option>
+	<option value="19" <?php if((!$formSent && $thisDay == 19) || ($formSent && $day_start == 19)) echo 'selected="selected"'; ?> >19</option>
+	<option value="20" <?php if((!$formSent && $thisDay == 20) || ($formSent && $day_start == 20)) echo 'selected="selected"'; ?> >20</option>
+	<option value="21" <?php if((!$formSent && $thisDay == 21) || ($formSent && $day_start == 21)) echo 'selected="selected"'; ?> >21</option>
+	<option value="22" <?php if((!$formSent && $thisDay == 22) || ($formSent && $day_start == 22)) echo 'selected="selected"'; ?> >22</option>
+	<option value="23" <?php if((!$formSent && $thisDay == 23) || ($formSent && $day_start == 23)) echo 'selected="selected"'; ?> >23</option>
+	<option value="24" <?php if((!$formSent && $thisDay == 24) || ($formSent && $day_start == 24)) echo 'selected="selected"'; ?> >24</option>
+	<option value="25" <?php if((!$formSent && $thisDay == 25) || ($formSent && $day_start == 25)) echo 'selected="selected"'; ?> >25</option>
+	<option value="26" <?php if((!$formSent && $thisDay == 26) || ($formSent && $day_start == 26)) echo 'selected="selected"'; ?> >26</option>
+	<option value="27" <?php if((!$formSent && $thisDay == 27) || ($formSent && $day_start == 27)) echo 'selected="selected"'; ?> >27</option>
+	<option value="28" <?php if((!$formSent && $thisDay == 28) || ($formSent && $day_start == 28)) echo 'selected="selected"'; ?> >28</option>
+	<option value="29" <?php if((!$formSent && $thisDay == 29) || ($formSent && $day_start == 29)) echo 'selected="selected"'; ?> >29</option>
+	<option value="30" <?php if((!$formSent && $thisDay == 30) || ($formSent && $day_start == 30)) echo 'selected="selected"'; ?> >30</option>
+	<option value="31" <?php if((!$formSent && $thisDay == 31) || ($formSent && $day_start == 31)) echo 'selected="selected"'; ?> >31</option>
+  </select>
+  /
+  <select name="month_start">
+	<option value="1">01</option>
+	<option value="2" <?php if((!$formSent && $thisMonth == 2) || ($formSent && $month_start == 2)) echo 'selected="selected"'; ?> >02</option>
+	<option value="3" <?php if((!$formSent && $thisMonth == 3) || ($formSent && $month_start == 3)) echo 'selected="selected"'; ?> >03</option>
+	<option value="4" <?php if((!$formSent && $thisMonth == 4) || ($formSent && $month_start == 4)) echo 'selected="selected"'; ?> >04</option>
+	<option value="5" <?php if((!$formSent && $thisMonth == 5) || ($formSent && $month_start == 5)) echo 'selected="selected"'; ?> >05</option>
+	<option value="6" <?php if((!$formSent && $thisMonth == 6) || ($formSent && $month_start == 6)) echo 'selected="selected"'; ?> >06</option>
+	<option value="7" <?php if((!$formSent && $thisMonth == 7) || ($formSent && $month_start == 7)) echo 'selected="selected"'; ?> >07</option>
+	<option value="8" <?php if((!$formSent && $thisMonth == 8) || ($formSent && $month_start == 8)) echo 'selected="selected"'; ?> >08</option>
+	<option value="9" <?php if((!$formSent && $thisMonth == 9) || ($formSent && $month_start == 9)) echo 'selected="selected"'; ?> >09</option>
+	<option value="10" <?php if((!$formSent && $thisMonth == 10) || ($formSent && $month_start == 10)) echo 'selected="selected"'; ?> >10</option>
+	<option value="11" <?php if((!$formSent && $thisMonth == 11) || ($formSent && $month_start == 11)) echo 'selected="selected"'; ?> >11</option>
+	<option value="12" <?php if((!$formSent && $thisMonth == 12) || ($formSent && $month_start == 12)) echo 'selected="selected"'; ?> >12</option>
+  </select>
+  /
+  <select name="year_start">
+
+<?php
+for ($i=$thisYear-5;$i <= ($thisYear+5);$i++) {
+?>
+	<option value="<?php echo $i; ?>" <?php if((!$formSent && $thisYear == $i) || ($formSent && $year_start == $i)) echo 'selected="selected"'; ?> ><?php echo $i; ?></option>
+<?php
+}
+?>
+
+  </select>
+  </td>
+</tr>
+<tr>
+  <td width="30%"><?php echo get_lang('DateEndSession') ?>&nbsp;&nbsp;</td>
+  <td width="70%">
+  <select name="day_end">
+	<option value="1">01</option>
+	<option value="2" <?php if((!$formSent && $thisDay == 2) || ($formSent && $day_end == 2)) echo 'selected="selected"'; ?> >02</option>
+	<option value="3" <?php if((!$formSent && $thisDay == 3) || ($formSent && $day_end == 3)) echo 'selected="selected"'; ?> >03</option>
+	<option value="4" <?php if((!$formSent && $thisDay == 4) || ($formSent && $day_end == 4)) echo 'selected="selected"'; ?> >04</option>
+	<option value="5" <?php if((!$formSent && $thisDay == 5) || ($formSent && $day_end == 5)) echo 'selected="selected"'; ?> >05</option>
+	<option value="6" <?php if((!$formSent && $thisDay == 6) || ($formSent && $day_end == 6)) echo 'selected="selected"'; ?> >06</option>
+	<option value="7" <?php if((!$formSent && $thisDay == 7) || ($formSent && $day_end == 7)) echo 'selected="selected"'; ?> >07</option>
+	<option value="8" <?php if((!$formSent && $thisDay == 8) || ($formSent && $day_end == 8)) echo 'selected="selected"'; ?> >08</option>
+	<option value="9" <?php if((!$formSent && $thisDay == 9) || ($formSent && $day_end == 9)) echo 'selected="selected"'; ?> >09</option>
+	<option value="10" <?php if((!$formSent && $thisDay == 10) || ($formSent && $day_end == 10)) echo 'selected="selected"'; ?> >10</option>
+	<option value="11" <?php if((!$formSent && $thisDay == 11) || ($formSent && $day_end == 11)) echo 'selected="selected"'; ?> >11</option>
+	<option value="12" <?php if((!$formSent && $thisDay == 12) || ($formSent && $day_end == 12)) echo 'selected="selected"'; ?> >12</option>
+	<option value="13" <?php if((!$formSent && $thisDay == 13) || ($formSent && $day_end == 13)) echo 'selected="selected"'; ?> >13</option>
+	<option value="14" <?php if((!$formSent && $thisDay == 14) || ($formSent && $day_end == 14)) echo 'selected="selected"'; ?> >14</option>
+	<option value="15" <?php if((!$formSent && $thisDay == 15) || ($formSent && $day_end == 15)) echo 'selected="selected"'; ?> >15</option>
+	<option value="16" <?php if((!$formSent && $thisDay == 16) || ($formSent && $day_end == 16)) echo 'selected="selected"'; ?> >16</option>
+	<option value="17" <?php if((!$formSent && $thisDay == 17) || ($formSent && $day_end == 17)) echo 'selected="selected"'; ?> >17</option>
+	<option value="18" <?php if((!$formSent && $thisDay == 18) || ($formSent && $day_end == 18)) echo 'selected="selected"'; ?> >18</option>
+	<option value="19" <?php if((!$formSent && $thisDay == 19) || ($formSent && $day_end == 19)) echo 'selected="selected"'; ?> >19</option>
+	<option value="20" <?php if((!$formSent && $thisDay == 20) || ($formSent && $day_end == 20)) echo 'selected="selected"'; ?> >20</option>
+	<option value="21" <?php if((!$formSent && $thisDay == 21) || ($formSent && $day_end == 21)) echo 'selected="selected"'; ?> >21</option>
+	<option value="22" <?php if((!$formSent && $thisDay == 22) || ($formSent && $day_end == 22)) echo 'selected="selected"'; ?> >22</option>
+	<option value="23" <?php if((!$formSent && $thisDay == 23) || ($formSent && $day_end == 23)) echo 'selected="selected"'; ?> >23</option>
+	<option value="24" <?php if((!$formSent && $thisDay == 24) || ($formSent && $day_end == 24)) echo 'selected="selected"'; ?> >24</option>
+	<option value="25" <?php if((!$formSent && $thisDay == 25) || ($formSent && $day_end == 25)) echo 'selected="selected"'; ?> >25</option>
+	<option value="26" <?php if((!$formSent && $thisDay == 26) || ($formSent && $day_end == 26)) echo 'selected="selected"'; ?> >26</option>
+	<option value="27" <?php if((!$formSent && $thisDay == 27) || ($formSent && $day_end == 27)) echo 'selected="selected"'; ?> >27</option>
+	<option value="28" <?php if((!$formSent && $thisDay == 28) || ($formSent && $day_end == 28)) echo 'selected="selected"'; ?> >28</option>
+	<option value="29" <?php if((!$formSent && $thisDay == 29) || ($formSent && $day_end == 29)) echo 'selected="selected"'; ?> >29</option>
+	<option value="30" <?php if((!$formSent && $thisDay == 30) || ($formSent && $day_end == 30)) echo 'selected="selected"'; ?> >30</option>
+	<option value="31" <?php if((!$formSent && $thisDay == 31) || ($formSent && $day_end == 31)) echo 'selected="selected"'; ?> >31</option>
+  </select>
+  /
+  <select name="month_end">
+	<option value="1">01</option>
+	<option value="2" <?php if((!$formSent && $thisMonth == 2) || ($formSent && $month_end == 2)) echo 'selected="selected"'; ?> >02</option>
+	<option value="3" <?php if((!$formSent && $thisMonth == 3) || ($formSent && $month_end == 3)) echo 'selected="selected"'; ?> >03</option>
+	<option value="4" <?php if((!$formSent && $thisMonth == 4) || ($formSent && $month_end == 4)) echo 'selected="selected"'; ?> >04</option>
+	<option value="5" <?php if((!$formSent && $thisMonth == 5) || ($formSent && $month_end == 5)) echo 'selected="selected"'; ?> >05</option>
+	<option value="6" <?php if((!$formSent && $thisMonth == 6) || ($formSent && $month_end == 6)) echo 'selected="selected"'; ?> >06</option>
+	<option value="7" <?php if((!$formSent && $thisMonth == 7) || ($formSent && $month_end == 7)) echo 'selected="selected"'; ?> >07</option>
+	<option value="8" <?php if((!$formSent && $thisMonth == 8) || ($formSent && $month_end == 8)) echo 'selected="selected"'; ?> >08</option>
+	<option value="9" <?php if((!$formSent && $thisMonth == 9) || ($formSent && $month_end == 9)) echo 'selected="selected"'; ?> >09</option>
+	<option value="10" <?php if((!$formSent && $thisMonth == 10) || ($formSent && $month_end == 10)) echo 'selected="selected"'; ?> >10</option>
+	<option value="11" <?php if((!$formSent && $thisMonth == 11) || ($formSent && $month_end == 11)) echo 'selected="selected"'; ?> >11</option>
+	<option value="12" <?php if((!$formSent && $thisMonth == 12) || ($formSent && $month_end == 12)) echo 'selected="selected"'; ?> >12</option>
+  </select>
+  /
+  <select name="year_end">
+
+<?php
+for ($i=$thisYear-5;$i <= ($thisYear+5);$i++) {
+?>
+	<option value="<?php echo $i; ?>" <?php if((!$formSent && ($thisYear+1) == $i) || ($formSent && $year_end == $i)) echo 'selected="selected"'; ?> ><?php echo $i; ?></option>
+<?php
+}
+?>
+  </select>
+  </td>
+</tr>
+<tr>
+	<td>
+		&nbsp;
+	</td>
+	<td>
+		<a href="javascript://" onclick="if(document.getElementById('options').style.display == 'none'){document.getElementById('options').style.display = 'block';}else{document.getElementById('options').style.display = 'none';}"><?php echo get_lang('DefineSessionOptions') ?></a>
+		<div style="display: <?php if($formSent && ($nb_days_acess_before!=0 || $nb_days_acess_after!=0)) echo 'block'; else echo 'none'; ?>;" id="options">
+			<br>
+			<input type="text" name="nb_days_acess_before" value="<?php echo $nb_days_acess_before; ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysBefore') ?><br>
+			<input type="text" name="nb_days_acess_after" value="<?php echo $nb_days_acess_after; ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysAfter') ?>
+			<br>
+		</div>
+	</td>
+</tr>
+<tr>
+  <td>&nbsp;</td>
+  <td><button class="save" type="submit" value="<?php echo get_lang('NextStep') ?>"><?php echo get_lang('NextStep') ?></button>
+ </td>
+</tr>
+
+</table>
+
+</form>
+<script type="text/javascript">
+
+function setDisable(select){
+	document.form.day_start.disabled = (select.checked) ? true : false;
+	document.form.month_start.disabled = (select.checked) ? true : false;
+	document.form.year_start.disabled = (select.checked) ? true : false;
+
+	document.form.day_end.disabled = (select.checked) ? true : false;
+	document.form.month_end.disabled = (select.checked) ? true : false;
+	document.form.year_end.disabled = (select.checked) ? true : false;
+
+}
+</script>
+<?php
+Display::display_footer();
+?>

+ 136 - 136
main/admin/session_course_edit.php

@@ -1,136 +1,136 @@
-<?php //$id: $
-/* For licensing terms, see /dokeos_license.txt */
-/**
- * Implements the edition of course-session settings
- * @package dokeos.admin
- */
-// name of the language file that needs to be included
-$language_file='admin';
-
-$cidReset=true;
-
-require '../inc/global.inc.php';
-
-// setting the section (for the tabs)
-$this_section=SECTION_PLATFORM_ADMIN;
-
-api_protect_admin_script();
-
-$id_session=intval($_GET['id_session']);
-$course_code=trim(stripslashes($_GET['course_code']));
-
-$formSent=0;
-$errorMsg='';
-
-// Database Table Definitions
-$tbl_user			= Database::get_main_table(TABLE_MAIN_USER);
-$tbl_course			= Database::get_main_table(TABLE_MAIN_COURSE);
-$tbl_session		= Database::get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_course	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-
-$course_info=api_get_course_info($_REQUEST['course_code']);
-$tool_name=$course_info['name'];
-
-$interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[]=array('url' => "session_list.php","name" => get_lang("SessionList"));
-$interbreadcrumb[]=array('url' => "../admin/resume_session.php?id_session=".Security::remove_XSS($_REQUEST['id_session']),"name" => get_lang('SessionOverview'));
-$interbreadcrumb[]=array('url' => "session_course_list.php?id_session=$id_session","name" =>api_htmlentities($session_name,ENT_QUOTES,$charset));
-
-$result=Database::query("SELECT name,title FROM $tbl_session_course,$tbl_session,$tbl_course WHERE id_session=id AND course_code=code AND id_session='$id_session' AND course_code='".addslashes($course_code)."'",__FILE__,__LINE__);
-
-if (!list($session_name,$course_title)=mysql_fetch_row($result)) {
-	header('Location: session_course_list.php?id_session='.$id_session);
-	exit();
-}
-
-if ($_POST['formSent']) {
-	$formSent=1;
-
-	$id_coach=intval($_POST['id_coach']);
-
-
-	Database::query("UPDATE $tbl_session_course
-				   SET id_coach='$id_coach'
-				   WHERE id_session='$id_session' AND course_code='$course_code'",__FILE__,__LINE__);
-	header('Location: '.$_GET['page'].'?id_session='.$id_session);
-	exit();
-
-}else {
-	$result=Database::query("SELECT id_coach FROM $tbl_session_course WHERE id_session='$id_session' AND course_code='$course_code'",__FILE__,__LINE__);
-
-	if (!$infos=Database::fetch_array($result)) {
-		//header('Location: '.$_GET['page'].'?id_session='.$id_session);
-		exit();
-	}
-}
-
-$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
-$sql="SELECT user_id,lastname,firstname,username FROM $tbl_user WHERE status='1'".$order_clause;
-
-$result=Database::query($sql,__FILE__,__LINE__);
-
-$coaches=Database::store_result($result);
-
-Display::display_header($tool_name);
-
-$tool_name=get_lang('ModifySessionCourse');
-api_display_tool_title($tool_name);
-?>
-<form method="post" action="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&page=<?php echo Security::remove_XSS($_GET['page']) ?>" style="margin:0px;">
-<input type="hidden" name="formSent" value="1">
-
-<table border="0" cellpadding="5" cellspacing="0" width="550">
-
-<?php
-if(!empty($errorMsg))
-{
-?>
-
-<tr>
-  <td colspan="2">
-
-<?php
-	Display::display_normal_message($errorMsg);
-?>
-
-  </td>
-</tr>
-
-<?php
-}
-?>
-
-<tr>
-  <td width="30%"><?php echo get_lang("CoachName") ?>&nbsp;&nbsp;</td>
-  <td width="70%"><select name="id_coach" style="width:250px;">
-	<option value="0">----- <?php echo get_lang("Choose") ?> -----</option>
-	<option value="0" <?php if((!$sent && $enreg['user_id'] == $infos['id_coach']) || ($sent && $enreg['user_id'] == $id_coach)) echo 'selected="selected"'; ?>><?php echo get_lang('None') ?></option>
-<?php
-
-foreach($coaches as $enreg)
-{
-?>
-
-	<option value="<?php echo $enreg['user_id']; ?>" <?php if((!$sent && $enreg['user_id'] == $infos['id_coach']) || ($sent && $enreg['user_id'] == $id_coach)) echo 'selected="selected"'; ?>><?php echo api_get_person_name($enreg['lastname'], $enreg['firstname']).' ('.$enreg['username'].')'; ?></option>
-
-<?php
-}
-
-unset($coaches);
-?>
-
-  </select></td>
-</tr>
-<tr>
-  <td>&nbsp;</td>
-  <td><button class="save" type="submit" name="name" value="<?php echo get_lang('ModifyCoach') ?>"><?php echo get_lang('ModifyCoach') ?></button>
-</td>
-</tr>
-
-</table>
-
-</form>
-
-<?php
-Display::display_footer();
-?>
+<?php //$id: $
+/* For licensing terms, see /dokeos_license.txt */
+/**
+ * Implements the edition of course-session settings
+ * @package dokeos.admin
+ */
+// name of the language file that needs to be included
+$language_file='admin';
+
+$cidReset=true;
+
+require '../inc/global.inc.php';
+
+// setting the section (for the tabs)
+$this_section=SECTION_PLATFORM_ADMIN;
+
+api_protect_admin_script();
+
+$id_session=intval($_GET['id_session']);
+$course_code=trim(stripslashes($_GET['course_code']));
+
+$formSent=0;
+$errorMsg='';
+
+// Database Table Definitions
+$tbl_user			= Database::get_main_table(TABLE_MAIN_USER);
+$tbl_course			= Database::get_main_table(TABLE_MAIN_COURSE);
+$tbl_session		= Database::get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_course	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+
+$course_info=api_get_course_info($_REQUEST['course_code']);
+$tool_name=$course_info['name'];
+
+$interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[]=array('url' => "session_list.php","name" => get_lang("SessionList"));
+$interbreadcrumb[]=array('url' => "../admin/resume_session.php?id_session=".Security::remove_XSS($_REQUEST['id_session']),"name" => get_lang('SessionOverview'));
+$interbreadcrumb[]=array('url' => "session_course_list.php?id_session=$id_session","name" =>api_htmlentities($session_name,ENT_QUOTES,$charset));
+
+$result=Database::query("SELECT name,title FROM $tbl_session_course,$tbl_session,$tbl_course WHERE id_session=id AND course_code=code AND id_session='$id_session' AND course_code='".addslashes($course_code)."'",__FILE__,__LINE__);
+
+if (!list($session_name,$course_title)=mysql_fetch_row($result)) {
+	header('Location: session_course_list.php?id_session='.$id_session);
+	exit();
+}
+
+if ($_POST['formSent']) {
+	$formSent=1;
+
+	$id_coach=intval($_POST['id_coach']);
+
+
+	Database::query("UPDATE $tbl_session_course
+				   SET id_coach='$id_coach'
+				   WHERE id_session='$id_session' AND course_code='$course_code'",__FILE__,__LINE__);
+	header('Location: '.$_GET['page'].'?id_session='.$id_session);
+	exit();
+
+}else {
+	$result=Database::query("SELECT id_coach FROM $tbl_session_course WHERE id_session='$id_session' AND course_code='$course_code'",__FILE__,__LINE__);
+
+	if (!$infos=Database::fetch_array($result)) {
+		//header('Location: '.$_GET['page'].'?id_session='.$id_session);
+		exit();
+	}
+}
+
+$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
+$sql="SELECT user_id,lastname,firstname,username FROM $tbl_user WHERE status='1'".$order_clause;
+
+$result=Database::query($sql,__FILE__,__LINE__);
+
+$coaches=Database::store_result($result);
+
+Display::display_header($tool_name);
+
+$tool_name=get_lang('ModifySessionCourse');
+api_display_tool_title($tool_name);
+?>
+<form method="post" action="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&page=<?php echo Security::remove_XSS($_GET['page']) ?>" style="margin:0px;">
+<input type="hidden" name="formSent" value="1">
+
+<table border="0" cellpadding="5" cellspacing="0" width="550">
+
+<?php
+if(!empty($errorMsg))
+{
+?>
+
+<tr>
+  <td colspan="2">
+
+<?php
+	Display::display_normal_message($errorMsg);
+?>
+
+  </td>
+</tr>
+
+<?php
+}
+?>
+
+<tr>
+  <td width="30%"><?php echo get_lang("CoachName") ?>&nbsp;&nbsp;</td>
+  <td width="70%"><select name="id_coach" style="width:250px;">
+	<option value="0">----- <?php echo get_lang("Choose") ?> -----</option>
+	<option value="0" <?php if((!$sent && $enreg['user_id'] == $infos['id_coach']) || ($sent && $enreg['user_id'] == $id_coach)) echo 'selected="selected"'; ?>><?php echo get_lang('None') ?></option>
+<?php
+
+foreach($coaches as $enreg)
+{
+?>
+
+	<option value="<?php echo $enreg['user_id']; ?>" <?php if((!$sent && $enreg['user_id'] == $infos['id_coach']) || ($sent && $enreg['user_id'] == $id_coach)) echo 'selected="selected"'; ?>><?php echo api_get_person_name($enreg['lastname'], $enreg['firstname']).' ('.$enreg['username'].')'; ?></option>
+
+<?php
+}
+
+unset($coaches);
+?>
+
+  </select></td>
+</tr>
+<tr>
+  <td>&nbsp;</td>
+  <td><button class="save" type="submit" name="name" value="<?php echo get_lang('ModifyCoach') ?>"><?php echo get_lang('ModifyCoach') ?></button>
+</td>
+</tr>
+
+</table>
+
+</form>
+
+<?php
+Display::display_footer();
+?>

+ 100 - 100
main/admin/session_course_list.php

@@ -1,101 +1,101 @@
-<?php
-/* For licensing terms, see /dokeos_license.txt */
-/**
-==============================================================================
-*	@package dokeos.admin
-==============================================================================
-*/
-
-
-// name of the language file that needs to be included
-$language_file='admin';
-$cidReset=true;
-include('../inc/global.inc.php');
-
-// setting the section (for the tabs)
-$this_section=SECTION_PLATFORM_ADMIN;
-
-api_protect_admin_script();
-
-// Database Table Definitions
-$tbl_course							= Database::get_main_table(TABLE_MAIN_COURSE);
-$tbl_session						= Database::get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_rel_course				= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
-$id_session=intval($_GET['id_session']);
-$page=intval($_GET['page']);
-$action=$_REQUEST['action'];
-$sort=in_array($_GET['sort'],array('title','nbr_users'))?$_GET['sort']:'title';
-
-$result=Database::query("SELECT name FROM $tbl_session WHERE id='$id_session'",__FILE__,__LINE__);
-
-if(!list($session_name)=mysql_fetch_row($result))
-{
-	header('Location: session_list.php');
-	exit();
-}
-
-if($action == 'delete') {
-	$idChecked = $_REQUEST['idChecked'];
-	if(is_array($idChecked) && count($idChecked)>0) {
-		$my_temp = array();
-		foreach ($idChecked as $id){
-			$my_temp[]= Database::escape_string($id);// forcing the escape_string
-		}
-		$idChecked = $my_temp;
-		$idChecked="'".implode("','",$idChecked)."'";
-		Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND course_code IN($idChecked)",__FILE__,__LINE__);
-		$nbr_affected_rows=mysql_affected_rows();
-		Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code IN($idChecked)",__FILE__,__LINE__);
-
-		Database::query("UPDATE $tbl_session SET nbr_courses=nbr_courses-$nbr_affected_rows WHERE id='$id_session'",__FILE__,__LINE__);
-	}
-
-	header('Location: '.api_get_self().'?id_session='.$id_session.'&sort='.$sort);
-	exit();
-}
-
-$limit=20;
-$from=$page * $limit;
-
-$result=Database::query("SELECT code,title,nbr_users FROM $tbl_session_rel_course,$tbl_course WHERE course_code=code AND id_session='$id_session' ORDER BY $sort LIMIT $from,".($limit+1),__FILE__,__LINE__);
-$Courses=Database::store_result($result);
-$nbr_results=sizeof($Sessions);
-$tool_name = api_htmlentities($session_name,ENT_QUOTES,$charset).' : '.get_lang('CourseListInSession');
-
-$interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[]=array('url' => "session_list.php","name" => get_lang('SessionList'));
-
-Display::display_header($tool_name);
-api_display_tool_title($tool_name);
-?>
-
-<form method="post" action="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&sort=<?php echo $sort; ?>" onsubmit="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;">
-<br />
-<?php
-$tableHeader = array();
-$tableHeader[] = array(' ');
-$tableHeader[] = array(get_lang('CourseTitle'));
-$tableHeader[] = array(get_lang('NbUsers'));
-$tableHeader[] = array(get_lang('Actions'));
-
-$tableCourses = array();
-foreach($Courses as $key=>$enreg) {
-	$course = array();
-	$course[] = '<input type="checkbox" name="idChecked[]" value="'.$enreg['code'].'">';
-	$course[] = api_htmlentities($enreg['title'],ENT_QUOTES,$charset);
-	$course[] = '<a href="session_course_user_list.php?id_session='.$id_session.'&course_code='.$enreg['code'].'">'.$enreg['nbr_users'].' '.get_lang('Users').'</a>';
-	$course[] = '<a href="session_course_edit.php?id_session='.$id_session.'&page=session_course_list.php&course_code='.$enreg['code'].'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>
-				<a href="'.api_get_self().'?id_session='.$id_session.'&sort='.$sort.'&action=delete&idChecked[]='.$enreg['code'].'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset)).'\')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
-	$tableCourses[] = $course;
-}
-echo '<form method="post" action="'.api_get_self().'">';
-Display :: display_sortable_table($tableHeader, $tableCourses, array (), array ());
-echo '<select name="action">
-	<option value="delete">'.get_lang('UnsubscribeCoursesFromSession').'</option>
-	</select>
-	<button class="save" type="submit">'.get_lang('Ok').'</button>
-	</form>';
-Display::display_footer();
+<?php
+/* For licensing terms, see /dokeos_license.txt */
+/**
+==============================================================================
+*	@package dokeos.admin
+==============================================================================
+*/
+
+
+// name of the language file that needs to be included
+$language_file='admin';
+$cidReset=true;
+include('../inc/global.inc.php');
+
+// setting the section (for the tabs)
+$this_section=SECTION_PLATFORM_ADMIN;
+
+api_protect_admin_script();
+
+// Database Table Definitions
+$tbl_course							= Database::get_main_table(TABLE_MAIN_COURSE);
+$tbl_session						= Database::get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_rel_course				= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+$tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+
+$id_session=intval($_GET['id_session']);
+$page=intval($_GET['page']);
+$action=$_REQUEST['action'];
+$sort=in_array($_GET['sort'],array('title','nbr_users'))?$_GET['sort']:'title';
+
+$result=Database::query("SELECT name FROM $tbl_session WHERE id='$id_session'",__FILE__,__LINE__);
+
+if(!list($session_name)=mysql_fetch_row($result))
+{
+	header('Location: session_list.php');
+	exit();
+}
+
+if($action == 'delete') {
+	$idChecked = $_REQUEST['idChecked'];
+	if(is_array($idChecked) && count($idChecked)>0) {
+		$my_temp = array();
+		foreach ($idChecked as $id){
+			$my_temp[]= Database::escape_string($id);// forcing the escape_string
+		}
+		$idChecked = $my_temp;
+		$idChecked="'".implode("','",$idChecked)."'";
+		Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND course_code IN($idChecked)",__FILE__,__LINE__);
+		$nbr_affected_rows=mysql_affected_rows();
+		Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code IN($idChecked)",__FILE__,__LINE__);
+
+		Database::query("UPDATE $tbl_session SET nbr_courses=nbr_courses-$nbr_affected_rows WHERE id='$id_session'",__FILE__,__LINE__);
+	}
+
+	header('Location: '.api_get_self().'?id_session='.$id_session.'&sort='.$sort);
+	exit();
+}
+
+$limit=20;
+$from=$page * $limit;
+
+$result=Database::query("SELECT code,title,nbr_users FROM $tbl_session_rel_course,$tbl_course WHERE course_code=code AND id_session='$id_session' ORDER BY $sort LIMIT $from,".($limit+1),__FILE__,__LINE__);
+$Courses=Database::store_result($result);
+$nbr_results=sizeof($Sessions);
+$tool_name = api_htmlentities($session_name,ENT_QUOTES,$charset).' : '.get_lang('CourseListInSession');
+
+$interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[]=array('url' => "session_list.php","name" => get_lang('SessionList'));
+
+Display::display_header($tool_name);
+api_display_tool_title($tool_name);
+?>
+
+<form method="post" action="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&sort=<?php echo $sort; ?>" onsubmit="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;">
+<br />
+<?php
+$tableHeader = array();
+$tableHeader[] = array(' ');
+$tableHeader[] = array(get_lang('CourseTitle'));
+$tableHeader[] = array(get_lang('NbUsers'));
+$tableHeader[] = array(get_lang('Actions'));
+
+$tableCourses = array();
+foreach($Courses as $key=>$enreg) {
+	$course = array();
+	$course[] = '<input type="checkbox" name="idChecked[]" value="'.$enreg['code'].'">';
+	$course[] = api_htmlentities($enreg['title'],ENT_QUOTES,$charset);
+	$course[] = '<a href="session_course_user_list.php?id_session='.$id_session.'&course_code='.$enreg['code'].'">'.$enreg['nbr_users'].' '.get_lang('Users').'</a>';
+	$course[] = '<a href="session_course_edit.php?id_session='.$id_session.'&page=session_course_list.php&course_code='.$enreg['code'].'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>
+				<a href="'.api_get_self().'?id_session='.$id_session.'&sort='.$sort.'&action=delete&idChecked[]='.$enreg['code'].'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset)).'\')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
+	$tableCourses[] = $course;
+}
+echo '<form method="post" action="'.api_get_self().'">';
+Display :: display_sortable_table($tableHeader, $tableCourses, array (), array ());
+echo '<select name="action">
+	<option value="delete">'.get_lang('UnsubscribeCoursesFromSession').'</option>
+	</select>
+	<button class="save" type="submit">'.get_lang('Ok').'</button>
+	</form>';
+Display::display_footer();
 ?>

+ 1 - 1
main/admin/session_edit.php

@@ -94,7 +94,7 @@ if (!empty($return)) {
 
 <div class="row"><div class="form_header"><?php echo $tool_name; ?></div></div>
 
-<table border="0" cellpadding="5" cellspacing="0" width="600">
+<table border="0" cellpadding="5" cellspacing="0" width="600">
 
 <tr>
   <td width="30%"><?php echo get_lang('SessionName') ?>&nbsp;&nbsp;</td>

+ 332 - 332
main/admin/session_export.php

@@ -1,332 +1,332 @@
-<?php // $Id: session_export.php,v 1.1 2006/04/20 09:58:01 elixir_inter Exp $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004 Dokeos S.A.
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Olivier Brouckaert
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	@package dokeos.admin
-==============================================================================
-*/
-// name of the language file that needs to be included
-$language_file='admin';
-
-$cidReset=true;
-
-include('../inc/global.inc.php');
-
-// setting the section (for the tabs)
-$this_section=SECTION_PLATFORM_ADMIN;
-
-api_protect_admin_script(true);
-include(api_get_path(LIBRARY_PATH).'/fileManage.lib.php');
-
-$session_id=$_GET['session_id'];
-$formSent=0;
-$errorMsg='';
-
-// Database Table Definitions
-$tbl_user					= Database::get_main_table(TABLE_MAIN_USER);
-$tbl_course      			= Database::get_main_table(TABLE_MAIN_COURSE);
-$tbl_course_user 			= Database::get_main_table(TABLE_MAIN_COURSE_USER);
-$tbl_session      			= Database::get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_user      		= Database::get_main_table(TABLE_MAIN_SESSION_USER);
-$tbl_session_course      	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_session_course_user 	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
-
-$archivePath=api_get_path(SYS_PATH).$archiveDirName.'/';
-$archiveURL=api_get_path(WEB_CODE_PATH).'course_info/download.php?archive=';
-
-$tool_name=get_lang('ExportSessionListXMLCSV');
-
-$interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
-
-set_time_limit(0);
-
-if($_POST['formSent'] )
-{
-	$formSent=$_POST['formSent'];
-	$file_type=($_POST['file_type'] == 'csv')?'csv':'xml';
-	$session_id=$_POST['session_id'];
-	if(empty($session_id))
-	{
-		$sql = "SELECT id,name,id_coach,username,date_start,date_end FROM $tbl_session INNER JOIN $tbl_user
-					ON $tbl_user.user_id = $tbl_session.id_coach ORDER BY id";
-
-		global $_configuration;
-		if ($_configuration['multiple_access_urls']==true) {
-			$tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
-			$access_url_id = api_get_current_access_url_id();
-			if ($access_url_id != -1){
-			$sql = "SELECT id, name,id_coach,username,date_start,date_end FROM $tbl_session s INNER JOIN $tbl_session_rel_access_url as session_rel_url
-				ON (s.id= session_rel_url.session_id) INNER JOIN $tbl_user u ON (u.user_id = s.id_coach)
-				WHERE access_url_id = $access_url_id
-				ORDER BY id";
-
-			}
-		}
-		$result=Database::query($sql,__FILE__,__LINE__);
-	}
-	else
-	{
-		$sql = "SELECT id,name,username,date_start,date_end
-				FROM $tbl_session
-				INNER JOIN $tbl_user
-					ON $tbl_user.user_id = $tbl_session.id_coach
-				WHERE id='$session_id'";
-
-		$result = Database::query($sql,__FILE__,__LINE__);
-
-	}
-
-	if(Database::num_rows($result))
-	{
-		if(!file_exists($archivePath))
-		{
-			mkpath($archivePath);
-		}
-
-		if(!file_exists($archivePath.'index.html'))
-		{
-			$fp=fopen($archivePath.'index.html','w');
-
-			fputs($fp,'<html><head></head><body></body></html>');
-
-			fclose($fp);
-		}
-
-		$archiveFile='export_sessions_'.$session_id.'_'.date('Y-m-d_H-i-s').'.'.$file_type;
-
-		while( file_exists($archivePath.$archiveFile))
-		{
-			$archiveFile='export_users_'.$session_id.'_'.date('Y-m-d_H-i-s').'_'.uniqid('').'.'.$file_type;
-		}
-		$fp=fopen($archivePath.$archiveFile,'w');
-
-		if($file_type == 'csv')
-		{
-			$cvs = true;
-			fputs($fp,"SessionName;Coach;DateStart;DateEnd;Users;Courses;\n");
-		}
-		else
-		{
-			$cvs = false;
-			fputs($fp,"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<Sessions>\n");
-		}
-
-		while($row=Database::fetch_array($result))
-		{
-			$add = '';
-			$row['name'] = str_replace(';',',',$row['name']);
-			$row['username'] = str_replace(';',',',$row['username']);
-			$row['date_start'] = str_replace(';',',',$row['date_start']);
-			$row['date_end'] = str_replace(';',',',$row['date_end']);
-			if($cvs){
-				$add.= $row['name'].';'.$row['username'].';'.$row['date_start'].';'.$row['date_end'].';';
-			}
-			else {
-				$add = "\t<Session>\n"
-						 ."\t\t<SessionName>$row[name]</SessionName>\n"
-						 ."\t\t<Coach>$row[username]</Coach>\n"
-						 ."\t\t<DateStart>$row[date_start]</DateStart>\n"
-						 ."\t\t<DateEnd>$row[date_end]</DateEnd>\n";
-			}
-
-			//users
-			$sql = "SELECT DISTINCT $tbl_user.username FROM $tbl_user
-					INNER JOIN $tbl_session_user
-						ON $tbl_user.user_id = $tbl_session_user.id_user
-						AND $tbl_session_user.id_session = '".$row['id']."'";
-
-			$rsUsers = Database::query($sql,__FILE__,__LINE__);
-			$users = '';
-			while($rowUsers = Database::fetch_array($rsUsers)){
-				if($cvs){
-					$users .= str_replace(';',',',$rowUsers['username']).'|';
-				}
-				else {
-					$users .= "\t\t<User>$rowUsers[username]</User>\n";
-				}
-			}
-			if(!empty($users) && $cvs)
-				$users = api_substr($users , 0, api_strlen($users)-1);
-
-			if($cvs)
-				$users .= ';';
-
-			$add .= $users;
-
-			//courses
-			$sql = "SELECT DISTINCT $tbl_course.code, $tbl_user.username FROM $tbl_course
-					INNER JOIN $tbl_session_course
-						ON $tbl_course.code = $tbl_session_course.course_code
-						AND $tbl_session_course.id_session = '".$row['id']."'
-					LEFT JOIN $tbl_user
-						ON $tbl_user.user_id = $tbl_session_course.id_coach";
-			$rsCourses = Database::query($sql,__FILE__,__LINE__);
-
-			$courses = '';
-			while($rowCourses = Database::fetch_array($rsCourses)){
-
-				if($cvs){
-					$courses .= str_replace(';',',',$rowCourses['code']);
-					$courses .= '['.str_replace(';',',',$rowCourses['username']).'][';
-				}
-				else {
-					$courses .= "\t\t<Course>\n";
-					$courses .= "\t\t\t<CourseCode>$rowCourses[code]</CourseCode>\n";
-					$courses .= "\t\t\t<Coach>$rowCourses[username]</Coach>\n";
-				}
-
-				// rel user courses
-				$sql = "SELECT DISTINCT username
-						FROM $tbl_user
-						INNER JOIN $tbl_session_course_user
-							ON $tbl_session_course_user.id_user = $tbl_user.user_id
-							AND $tbl_session_course_user.course_code='".$rowCourses['code']."'
-							AND id_session='".$row['id']."'";
-
-				$rsUsersCourse = Database::query($sql,__FILE__,__LINE__);
-				while($rowUsersCourse = Database::fetch_array($rsUsersCourse)){
-					if($cvs){
-						$userscourse .= str_replace(';',',',$rowUsersCourse['username']).',';
-					}
-					else {
-						$courses .= "\t\t\t<User>$rowUsersCourse[username]</User>\n";
-					}
-				}
-				if($cvs){
-					if(!empty($userscourse))
-						$userscourse = api_substr($userscourse , 0, api_strlen($userscourse)-1);
-
-					$courses .= $userscourse.']|';
-				}
-				else {
-					$courses .= "\t\t</Course>\n";
-				}
-			}
-			if(!empty($courses) && $cvs)
-				$courses = api_substr($courses , 0, api_strlen($courses)-1);
-			$add .= $courses;
-
-
-
-			if($cvs) {
-				$breakline = api_is_windows_os()?"\r\n":"\n";
-				$add .= ";$breakline";
-			} else {
-				$add .= "\t</Session>\n";
-			}
-
-			fputs($fp, $add);
-		}
-
-		if(!$cvs)
-			fputs($fp,"</Sessions>\n");
-		fclose($fp);
-
-		$errorMsg=get_lang('UserListHasBeenExported').'<br/><a href="'.$archiveURL.$archiveFile.'">'.get_lang('ClickHereToDownloadTheFile').'</a>';
-	}
-}
-
-// display the header
-Display::display_header($tool_name);
-
-// display the tool title
-// api_display_tool_title($tool_name);
-
-
-//select of sessions
-$sql = "SELECT id, name FROM $tbl_session ORDER BY name";
-global $_configuration;
-if ($_configuration['multiple_access_urls']==true) {
-	$tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
-	$access_url_id = api_get_current_access_url_id();
-	if ($access_url_id != -1){
-	$sql = "SELECT id, name FROM $tbl_session s INNER JOIN $tbl_session_rel_access_url as session_rel_url
-		ON (s.id= session_rel_url.session_id)
-		WHERE access_url_id = $access_url_id
-		ORDER BY name";
-	}
-}
-
-
-$result=Database::query($sql,__FILE__,__LINE__);
-
-$Sessions=Database::store_result($result);
-?>
-
-<?php
-if(!empty($errorMsg))
-{
-	Display::display_normal_message($errorMsg, false); //main API
-}
-?>
-
-<form method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;">
-<input type="hidden" name="formSent" value="1">
-<div class="row"><div class="form_header"><?php echo $tool_name; ?></div></div>
-<table border="0" cellpadding="5" cellspacing="0">
-<tr>
-  <td nowrap="nowrap" valign="top"><?php echo get_lang('OutputFileType'); ?> :</td>
-  <td>
-	<input class="checkbox" type="radio" name="file_type" id="file_type_xml" value="xml" <?php if($formSent && $file_type == 'xml') echo 'checked="checked"'; ?>> <label for="file_type_xml">XML</label><br>
-	<input class="checkbox" type="radio" name="file_type" id="file_type_csv"  value="csv" <?php if(!$formSent || $file_type == 'csv') echo 'checked="checked"'; ?>> <label for="file_type_csv">CSV</label><br>
-  </td>
-</tr>
-<tr>
-  <td><?php echo get_lang('WhichSessionToExport'); ?> :</td>
-  <td><select name="session_id">
-	<option value=""><?php echo get_lang('AllSessions') ?></option>
-
-<?php
-foreach($Sessions as $enreg)
-{
-?>
-
-	<option value="<?php echo $enreg['id']; ?>" <?php if($session_id == $enreg['id']) echo 'selected="selected"'; ?>><?php echo $enreg['name']; ?></option>
-
-<?php
-}
-
-unset($Courses);
-?>
-
-  </select></td>
-</tr>
-<tr>
-  <td>&nbsp;</td>
-  <td>
-  <button class="save" type="submit" name="name" value="<?php echo get_lang('ExportSession') ?>"><?php echo get_lang('ExportSession') ?></button>
-  </td>
-</tr>
-</table>
-</form>
-
-<?php
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display::display_footer();
-?>
+<?php // $Id: session_export.php,v 1.1 2006/04/20 09:58:01 elixir_inter Exp $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004 Dokeos S.A.
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Olivier Brouckaert
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	@package dokeos.admin
+==============================================================================
+*/
+// name of the language file that needs to be included
+$language_file='admin';
+
+$cidReset=true;
+
+include('../inc/global.inc.php');
+
+// setting the section (for the tabs)
+$this_section=SECTION_PLATFORM_ADMIN;
+
+api_protect_admin_script(true);
+include(api_get_path(LIBRARY_PATH).'/fileManage.lib.php');
+
+$session_id=$_GET['session_id'];
+$formSent=0;
+$errorMsg='';
+
+// Database Table Definitions
+$tbl_user					= Database::get_main_table(TABLE_MAIN_USER);
+$tbl_course      			= Database::get_main_table(TABLE_MAIN_COURSE);
+$tbl_course_user 			= Database::get_main_table(TABLE_MAIN_COURSE_USER);
+$tbl_session      			= Database::get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_user      		= Database::get_main_table(TABLE_MAIN_SESSION_USER);
+$tbl_session_course      	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+$tbl_session_course_user 	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+
+
+$archivePath=api_get_path(SYS_PATH).$archiveDirName.'/';
+$archiveURL=api_get_path(WEB_CODE_PATH).'course_info/download.php?archive=';
+
+$tool_name=get_lang('ExportSessionListXMLCSV');
+
+$interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
+
+set_time_limit(0);
+
+if($_POST['formSent'] )
+{
+	$formSent=$_POST['formSent'];
+	$file_type=($_POST['file_type'] == 'csv')?'csv':'xml';
+	$session_id=$_POST['session_id'];
+	if(empty($session_id))
+	{
+		$sql = "SELECT id,name,id_coach,username,date_start,date_end FROM $tbl_session INNER JOIN $tbl_user
+					ON $tbl_user.user_id = $tbl_session.id_coach ORDER BY id";
+
+		global $_configuration;
+		if ($_configuration['multiple_access_urls']==true) {
+			$tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+			$access_url_id = api_get_current_access_url_id();
+			if ($access_url_id != -1){
+			$sql = "SELECT id, name,id_coach,username,date_start,date_end FROM $tbl_session s INNER JOIN $tbl_session_rel_access_url as session_rel_url
+				ON (s.id= session_rel_url.session_id) INNER JOIN $tbl_user u ON (u.user_id = s.id_coach)
+				WHERE access_url_id = $access_url_id
+				ORDER BY id";
+
+			}
+		}
+		$result=Database::query($sql,__FILE__,__LINE__);
+	}
+	else
+	{
+		$sql = "SELECT id,name,username,date_start,date_end
+				FROM $tbl_session
+				INNER JOIN $tbl_user
+					ON $tbl_user.user_id = $tbl_session.id_coach
+				WHERE id='$session_id'";
+
+		$result = Database::query($sql,__FILE__,__LINE__);
+
+	}
+
+	if(Database::num_rows($result))
+	{
+		if(!file_exists($archivePath))
+		{
+			mkpath($archivePath);
+		}
+
+		if(!file_exists($archivePath.'index.html'))
+		{
+			$fp=fopen($archivePath.'index.html','w');
+
+			fputs($fp,'<html><head></head><body></body></html>');
+
+			fclose($fp);
+		}
+
+		$archiveFile='export_sessions_'.$session_id.'_'.date('Y-m-d_H-i-s').'.'.$file_type;
+
+		while( file_exists($archivePath.$archiveFile))
+		{
+			$archiveFile='export_users_'.$session_id.'_'.date('Y-m-d_H-i-s').'_'.uniqid('').'.'.$file_type;
+		}
+		$fp=fopen($archivePath.$archiveFile,'w');
+
+		if($file_type == 'csv')
+		{
+			$cvs = true;
+			fputs($fp,"SessionName;Coach;DateStart;DateEnd;Users;Courses;\n");
+		}
+		else
+		{
+			$cvs = false;
+			fputs($fp,"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<Sessions>\n");
+		}
+
+		while($row=Database::fetch_array($result))
+		{
+			$add = '';
+			$row['name'] = str_replace(';',',',$row['name']);
+			$row['username'] = str_replace(';',',',$row['username']);
+			$row['date_start'] = str_replace(';',',',$row['date_start']);
+			$row['date_end'] = str_replace(';',',',$row['date_end']);
+			if($cvs){
+				$add.= $row['name'].';'.$row['username'].';'.$row['date_start'].';'.$row['date_end'].';';
+			}
+			else {
+				$add = "\t<Session>\n"
+						 ."\t\t<SessionName>$row[name]</SessionName>\n"
+						 ."\t\t<Coach>$row[username]</Coach>\n"
+						 ."\t\t<DateStart>$row[date_start]</DateStart>\n"
+						 ."\t\t<DateEnd>$row[date_end]</DateEnd>\n";
+			}
+
+			//users
+			$sql = "SELECT DISTINCT $tbl_user.username FROM $tbl_user
+					INNER JOIN $tbl_session_user
+						ON $tbl_user.user_id = $tbl_session_user.id_user
+						AND $tbl_session_user.id_session = '".$row['id']."'";
+
+			$rsUsers = Database::query($sql,__FILE__,__LINE__);
+			$users = '';
+			while($rowUsers = Database::fetch_array($rsUsers)){
+				if($cvs){
+					$users .= str_replace(';',',',$rowUsers['username']).'|';
+				}
+				else {
+					$users .= "\t\t<User>$rowUsers[username]</User>\n";
+				}
+			}
+			if(!empty($users) && $cvs)
+				$users = api_substr($users , 0, api_strlen($users)-1);
+
+			if($cvs)
+				$users .= ';';
+
+			$add .= $users;
+
+			//courses
+			$sql = "SELECT DISTINCT $tbl_course.code, $tbl_user.username FROM $tbl_course
+					INNER JOIN $tbl_session_course
+						ON $tbl_course.code = $tbl_session_course.course_code
+						AND $tbl_session_course.id_session = '".$row['id']."'
+					LEFT JOIN $tbl_user
+						ON $tbl_user.user_id = $tbl_session_course.id_coach";
+			$rsCourses = Database::query($sql,__FILE__,__LINE__);
+
+			$courses = '';
+			while($rowCourses = Database::fetch_array($rsCourses)){
+
+				if($cvs){
+					$courses .= str_replace(';',',',$rowCourses['code']);
+					$courses .= '['.str_replace(';',',',$rowCourses['username']).'][';
+				}
+				else {
+					$courses .= "\t\t<Course>\n";
+					$courses .= "\t\t\t<CourseCode>$rowCourses[code]</CourseCode>\n";
+					$courses .= "\t\t\t<Coach>$rowCourses[username]</Coach>\n";
+				}
+
+				// rel user courses
+				$sql = "SELECT DISTINCT username
+						FROM $tbl_user
+						INNER JOIN $tbl_session_course_user
+							ON $tbl_session_course_user.id_user = $tbl_user.user_id
+							AND $tbl_session_course_user.course_code='".$rowCourses['code']."'
+							AND id_session='".$row['id']."'";
+
+				$rsUsersCourse = Database::query($sql,__FILE__,__LINE__);
+				while($rowUsersCourse = Database::fetch_array($rsUsersCourse)){
+					if($cvs){
+						$userscourse .= str_replace(';',',',$rowUsersCourse['username']).',';
+					}
+					else {
+						$courses .= "\t\t\t<User>$rowUsersCourse[username]</User>\n";
+					}
+				}
+				if($cvs){
+					if(!empty($userscourse))
+						$userscourse = api_substr($userscourse , 0, api_strlen($userscourse)-1);
+
+					$courses .= $userscourse.']|';
+				}
+				else {
+					$courses .= "\t\t</Course>\n";
+				}
+			}
+			if(!empty($courses) && $cvs)
+				$courses = api_substr($courses , 0, api_strlen($courses)-1);
+			$add .= $courses;
+
+
+
+			if($cvs) {
+				$breakline = api_is_windows_os()?"\r\n":"\n";
+				$add .= ";$breakline";
+			} else {
+				$add .= "\t</Session>\n";
+			}
+
+			fputs($fp, $add);
+		}
+
+		if(!$cvs)
+			fputs($fp,"</Sessions>\n");
+		fclose($fp);
+
+		$errorMsg=get_lang('UserListHasBeenExported').'<br/><a href="'.$archiveURL.$archiveFile.'">'.get_lang('ClickHereToDownloadTheFile').'</a>';
+	}
+}
+
+// display the header
+Display::display_header($tool_name);
+
+// display the tool title
+// api_display_tool_title($tool_name);
+
+
+//select of sessions
+$sql = "SELECT id, name FROM $tbl_session ORDER BY name";
+global $_configuration;
+if ($_configuration['multiple_access_urls']==true) {
+	$tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+	$access_url_id = api_get_current_access_url_id();
+	if ($access_url_id != -1){
+	$sql = "SELECT id, name FROM $tbl_session s INNER JOIN $tbl_session_rel_access_url as session_rel_url
+		ON (s.id= session_rel_url.session_id)
+		WHERE access_url_id = $access_url_id
+		ORDER BY name";
+	}
+}
+
+
+$result=Database::query($sql,__FILE__,__LINE__);
+
+$Sessions=Database::store_result($result);
+?>
+
+<?php
+if(!empty($errorMsg))
+{
+	Display::display_normal_message($errorMsg, false); //main API
+}
+?>
+
+<form method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;">
+<input type="hidden" name="formSent" value="1">
+<div class="row"><div class="form_header"><?php echo $tool_name; ?></div></div>
+<table border="0" cellpadding="5" cellspacing="0">
+<tr>
+  <td nowrap="nowrap" valign="top"><?php echo get_lang('OutputFileType'); ?> :</td>
+  <td>
+	<input class="checkbox" type="radio" name="file_type" id="file_type_xml" value="xml" <?php if($formSent && $file_type == 'xml') echo 'checked="checked"'; ?>> <label for="file_type_xml">XML</label><br>
+	<input class="checkbox" type="radio" name="file_type" id="file_type_csv"  value="csv" <?php if(!$formSent || $file_type == 'csv') echo 'checked="checked"'; ?>> <label for="file_type_csv">CSV</label><br>
+  </td>
+</tr>
+<tr>
+  <td><?php echo get_lang('WhichSessionToExport'); ?> :</td>
+  <td><select name="session_id">
+	<option value=""><?php echo get_lang('AllSessions') ?></option>
+
+<?php
+foreach($Sessions as $enreg)
+{
+?>
+
+	<option value="<?php echo $enreg['id']; ?>" <?php if($session_id == $enreg['id']) echo 'selected="selected"'; ?>><?php echo $enreg['name']; ?></option>
+
+<?php
+}
+
+unset($Courses);
+?>
+
+  </select></td>
+</tr>
+<tr>
+  <td>&nbsp;</td>
+  <td>
+  <button class="save" type="submit" name="name" value="<?php echo get_lang('ExportSession') ?>"><?php echo get_lang('ExportSession') ?></button>
+  </td>
+</tr>
+</table>
+</form>
+
+<?php
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display::display_footer();
+?>

+ 4 - 4
main/admin/session_import.php

@@ -129,10 +129,10 @@ if ($_POST['formSent']) {
 							// Sending email to the current user.
 							if ($send_mail) {
 								$recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);
-								$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
-								$emailbody = "[NOTE:] ".get_lang('ThisIsAutomaticEmailNoReply').".\n\n".get_lang('langDear')." ".api_get_person_name($firstname, $lastname).",\n\n".get_lang('langYouAreReg')." ".api_get_setting('siteName') ." ".get_lang('langSettings')." $username\n". get_lang('langPass')." : $password\n\n".get_lang('langAddress') ." ". get_lang('langIs') ." ". $serverAddress ."\n\n".get_lang('YouWillSoonReceiveMailFromCoach')."\n\n". get_lang('langProblem'). "\n\n". get_lang('langFormula');
-								$sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
-								$email_admin = api_get_setting('emailAdministrator');
+								$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
+								$emailbody = "[NOTE:] ".get_lang('ThisIsAutomaticEmailNoReply').".\n\n".get_lang('langDear')." ".api_get_person_name($firstname, $lastname).",\n\n".get_lang('langYouAreReg')." ".api_get_setting('siteName') ." ".get_lang('langSettings')." $username\n". get_lang('langPass')." : $password\n\n".get_lang('langAddress') ." ". get_lang('langIs') ." ". $serverAddress ."\n\n".get_lang('YouWillSoonReceiveMailFromCoach')."\n\n". get_lang('langProblem'). "\n\n". get_lang('langFormula');
+								$sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
+								$email_admin = api_get_setting('emailAdministrator');
 								@api_mail($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
 							}
 						} else {

+ 143 - 143
main/admin/statistics/index.php

@@ -1,144 +1,144 @@
-<?php
-// $Id: index.php 8216 2006-11-3 18:03:15 NushiFirefox $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2006 Bart Mollet <bart.mollet@hogent.be>
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-* This tool allows the use statistics
-* @package dokeos.statistics
-==============================================================================
-*/
-// name of the language file that needs to be included
-$language_file=array('admin','tracking');
-$cidReset = true;
-
-include('../../inc/global.inc.php');
-api_protect_admin_script();
-
-$interbreadcrumb[] = array ("url" => "../index.php", "name" => get_lang('PlatformAdmin'));
-
-$tool_name = get_lang('ToolName');
-Display::display_header($tool_name);
-api_display_tool_title($tool_name);
-
-if(!$_configuration['tracking_enabled'])
-{
-	Display::display_warning_message(get_lang('TrackingDisabled'));
-	Display::display_footer();
-	exit;
-}
-require_once ('statistics.lib.php');
-
-
-$strCourse  = get_lang('Courses');
-$strUsers = get_lang('Users');
-$strSystem = get_lang('System');
-
-
-$tools[$strCourse]['action=courses'] = get_lang('CountCours');
-$tools[$strCourse]['action=tools'] = get_lang('PlatformToolAccess');
-$tools[$strCourse]['action=courselastvisit'] = get_lang('LastAccess');
-$tools[$strCourse]['action=coursebylanguage'] = get_lang('CountCourseByLanguage');
-
-
-$tools[$strUsers]['action=users'] = get_lang('CountUsers');
-$tools[$strUsers]['action=recentlogins'] = get_lang('Logins');
-$tools[$strUsers]['action=logins&amp;type=month'] = get_lang('Logins').' ('.get_lang('PeriodMonth').')';
-$tools[$strUsers]['action=logins&amp;type=day'] = get_lang('Logins').' ('.get_lang('PeriodDay').')';
-$tools[$strUsers]['action=logins&amp;type=hour'] = get_lang('Logins').' ('.get_lang('PeriodHour').')';
-$tools[$strUsers]['action=pictures'] = get_lang('CountUsers').' ('.get_lang('UserPicture').')';
-
-$tools[$strSystem]['action=activities'] = get_lang('ImportantActivities');
-
-
-echo '<table><tr>';
-foreach($tools as $section => $items)
-{
-	echo '<td valign="top">';
-	echo '<b>'.$section.'</b>';
-	echo '<ul>';
-	foreach($items as $key => $value)
-	{
-			echo '<li><a href="index.php?'.$key.'">'.$value.'</a></li>';
-	}
-	echo '</ul>';
-	echo '</td>';
-}
-echo '</tr></table>';
-$course_categories = statistics::get_course_categories();
-echo '<br/><br/>';
-switch($_GET['action'])
-{
-	case 'courses':
-		// total amount of courses
-		foreach($course_categories as $code => $name)
-		{
-			$courses[$name] = statistics::count_courses($code);
-		}
-		// courses for each course category
-		statistics::print_stats(get_lang('CountCours'),$courses);
-
-		break;
-	case 'users':
-		// total amount of users
-		statistics::print_stats(
-				get_lang('NumberOfUsers'),
-				array(
-					get_lang('Teachers') => statistics::count_users(1,null,$_GET['count_invisible_courses']),
-					get_lang('Students') => statistics::count_users(5,null,$_GET['count_invisible_courses'])
-				)
-			);
-		foreach($course_categories as $code => $name)
-		{
-			$name = str_replace(get_lang('Department'),"",$name);
-			$teachers[$name] = statistics::count_users(1,$code,$_GET['count_invisible_courses']);
-			$students[$name] = statistics::count_users(5,$code,$_GET['count_invisible_courses']);
-		}
-		// docents for each course category
-		statistics::print_stats(get_lang('Teachers'),$teachers);
-		// students for each course category
-		statistics::print_stats(get_lang('Students'),$students);
-
-		break;
-	case 'coursebylanguage':
-		statistics::print_course_by_language_stats();
-		break;
-	case 'logins':
-		statistics::print_login_stats($_GET['type']);
-		break;
-	case 'tools':
-		statistics::print_tool_stats();
-		break;
-	case 'courselastvisit':
-		statistics::print_course_last_visit();
-		break;
-	case 'recentlogins':
-		statistics::print_recent_login_stats();
-		break;
-	case 'pictures':
-		statistics::print_user_pictures_stats();
-		break;
-	case 'activities':
-		statistics::print_activities_stats();
-		break;
-}
-
-Display::display_footer();
+<?php
+// $Id: index.php 8216 2006-11-3 18:03:15 NushiFirefox $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2006 Bart Mollet <bart.mollet@hogent.be>
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+* This tool allows the use statistics
+* @package dokeos.statistics
+==============================================================================
+*/
+// name of the language file that needs to be included
+$language_file=array('admin','tracking');
+$cidReset = true;
+
+include('../../inc/global.inc.php');
+api_protect_admin_script();
+
+$interbreadcrumb[] = array ("url" => "../index.php", "name" => get_lang('PlatformAdmin'));
+
+$tool_name = get_lang('ToolName');
+Display::display_header($tool_name);
+api_display_tool_title($tool_name);
+
+if(!$_configuration['tracking_enabled'])
+{
+	Display::display_warning_message(get_lang('TrackingDisabled'));
+	Display::display_footer();
+	exit;
+}
+require_once ('statistics.lib.php');
+
+
+$strCourse  = get_lang('Courses');
+$strUsers = get_lang('Users');
+$strSystem = get_lang('System');
+
+
+$tools[$strCourse]['action=courses'] = get_lang('CountCours');
+$tools[$strCourse]['action=tools'] = get_lang('PlatformToolAccess');
+$tools[$strCourse]['action=courselastvisit'] = get_lang('LastAccess');
+$tools[$strCourse]['action=coursebylanguage'] = get_lang('CountCourseByLanguage');
+
+
+$tools[$strUsers]['action=users'] = get_lang('CountUsers');
+$tools[$strUsers]['action=recentlogins'] = get_lang('Logins');
+$tools[$strUsers]['action=logins&amp;type=month'] = get_lang('Logins').' ('.get_lang('PeriodMonth').')';
+$tools[$strUsers]['action=logins&amp;type=day'] = get_lang('Logins').' ('.get_lang('PeriodDay').')';
+$tools[$strUsers]['action=logins&amp;type=hour'] = get_lang('Logins').' ('.get_lang('PeriodHour').')';
+$tools[$strUsers]['action=pictures'] = get_lang('CountUsers').' ('.get_lang('UserPicture').')';
+
+$tools[$strSystem]['action=activities'] = get_lang('ImportantActivities');
+
+
+echo '<table><tr>';
+foreach($tools as $section => $items)
+{
+	echo '<td valign="top">';
+	echo '<b>'.$section.'</b>';
+	echo '<ul>';
+	foreach($items as $key => $value)
+	{
+			echo '<li><a href="index.php?'.$key.'">'.$value.'</a></li>';
+	}
+	echo '</ul>';
+	echo '</td>';
+}
+echo '</tr></table>';
+$course_categories = statistics::get_course_categories();
+echo '<br/><br/>';
+switch($_GET['action'])
+{
+	case 'courses':
+		// total amount of courses
+		foreach($course_categories as $code => $name)
+		{
+			$courses[$name] = statistics::count_courses($code);
+		}
+		// courses for each course category
+		statistics::print_stats(get_lang('CountCours'),$courses);
+
+		break;
+	case 'users':
+		// total amount of users
+		statistics::print_stats(
+				get_lang('NumberOfUsers'),
+				array(
+					get_lang('Teachers') => statistics::count_users(1,null,$_GET['count_invisible_courses']),
+					get_lang('Students') => statistics::count_users(5,null,$_GET['count_invisible_courses'])
+				)
+			);
+		foreach($course_categories as $code => $name)
+		{
+			$name = str_replace(get_lang('Department'),"",$name);
+			$teachers[$name] = statistics::count_users(1,$code,$_GET['count_invisible_courses']);
+			$students[$name] = statistics::count_users(5,$code,$_GET['count_invisible_courses']);
+		}
+		// docents for each course category
+		statistics::print_stats(get_lang('Teachers'),$teachers);
+		// students for each course category
+		statistics::print_stats(get_lang('Students'),$students);
+
+		break;
+	case 'coursebylanguage':
+		statistics::print_course_by_language_stats();
+		break;
+	case 'logins':
+		statistics::print_login_stats($_GET['type']);
+		break;
+	case 'tools':
+		statistics::print_tool_stats();
+		break;
+	case 'courselastvisit':
+		statistics::print_course_last_visit();
+		break;
+	case 'recentlogins':
+		statistics::print_recent_login_stats();
+		break;
+	case 'pictures':
+		statistics::print_user_pictures_stats();
+		break;
+	case 'activities':
+		statistics::print_activities_stats();
+		break;
+}
+
+Display::display_footer();
 ?>

+ 458 - 458
main/admin/statistics/statistics.lib.php

@@ -1,458 +1,458 @@
-<?php
-// $Id: index.php 8216 2006-11-3 18:03:15 NushiFirefox $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2006 Bart Mollet <bart.mollet@hogent.be>
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-/**
-==============================================================================
-* This class provides some functions for statistics
-* @package dokeos.statistics
-==============================================================================
-*/
-class Statistics
-{
-	/**
-	 * Converts a number of bytes in a formatted string
-	 * @param int $size
-	 * @return string Formatted file size
-	 */
-	function make_size_string($size) {
-		if ($size < pow(2,10)) return $size." bytes";
-		if ($size >= pow(2,10) && $size < pow(2,20)) return round($size / pow(2,10), 0)." KB";
-		if ($size >= pow(2,20) && $size < pow(2,30)) return round($size / pow(2,20), 1)." MB";
-		if ($size > pow(2,30)) return round($size / pow(2,30), 2)." GB";
-	}
-	/**
-	 * Count courses
-	 * @param string $category_code  Code of a course category. Default: count
-	 * all courses.
-	 * @return int Number of courses counted
-	 */
-	function count_courses($category_code = NULL)
-	{
-		$course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
-		$sql = "SELECT COUNT(*) AS number FROM ".$course_table." ";
-		if (isset ($category_code))
-		{
-			$sql .= " WHERE category_code = '".Database::escape_string($category_code)."'";
-		}
-		$res = Database::query($sql, __FILE__, __LINE__);
-		$obj = Database::fetch_object($res);
-		return $obj->number;
-	}
-	/**
-	 * Count users
-	 * @param int $status COURSEMANAGER or STUDENT
-	 * @param string $category_code  Code of a course category. Default: count
-	 * all users.
-	 * @return int Number of users counted
-	 */
-	function count_users($status, $category_code = NULL, $count_invisible_courses = true)
-	{
-		// Database table definitions
-		$course_user_table 	= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-		$course_table 		= Database :: get_main_table(TABLE_MAIN_COURSE);
-		$user_table 		= Database :: get_main_table(TABLE_MAIN_USER);
-
-		$sql = "SELECT COUNT(DISTINCT(user_id)) AS number FROM $user_table WHERE status = ".intval(Database::escape_string($status))." ";
-		if (isset ($category_code))
-		{
-			$sql = "SELECT COUNT(DISTINCT(cu.user_id)) AS number FROM $course_user_table cu, $course_table c WHERE cu.status = ".intval(Database::escape_string($status))." AND c.code = cu.course_code AND c.category_code = '".Database::escape_string($category_code)."'";
-		}
-		$res = Database::query($sql, __FILE__, __LINE__);
-		$obj = Database::fetch_object($res);
-		return $obj->number;
-	}
-
-	/**
-	 * Count activities from track_e_default_table
-	 * @return int Number of activities counted
-	 */
-	function get_number_of_activities()
-	{
-		// Database table definitions
-		$track_e_default  = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
-
-		$sql = "SELECT count(default_id) AS total_number_of_items FROM $track_e_default, $table_user user WHERE default_user_id = user.user_id ";
-
-		if (isset($_GET['keyword'])) {
-		$keyword = Database::escape_string($_GET['keyword']);
-		$sql .= " AND (user.username LIKE '%".$keyword."%' OR default_event_type LIKE '%".$keyword."%' OR default_value_type LIKE '%".$keyword."%' OR default_value LIKE '%".$keyword."%') ";
-		}
-
-		$res = Database::query($sql, __FILE__, __LINE__);
-		$obj = Database::fetch_object($res);
-		return $obj->total_number_of_items;
-	}
-	/**
-	 * Get activities data to display
-	 */
-	function get_activities_data($from, $number_of_items, $column, $direction)
-	{
-		global $dateTimeFormatLong;
-		$track_e_default 	= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
-		$table_user = Database::get_main_table(TABLE_MAIN_USER);
-		$table_course = Database::get_main_table(TABLE_MAIN_COURSE);
-
-		$sql = "SELECT
-				 	default_event_type  as col0,
-					default_value_type	as col1,
-					default_value		as col2,
-					user.username 	as col3,
-					default_date 	as col4
-				FROM $track_e_default track_default, $table_user user
-				WHERE track_default.default_user_id = user.user_id ";
-
-		if (isset($_GET['keyword'])) {
-		$keyword = Database::escape_string($_GET['keyword']);
-		$sql .= " AND (user.username LIKE '%".$keyword."%' OR default_event_type LIKE '%".$keyword."%' OR default_value_type LIKE '%".$keyword."%' OR default_value LIKE '%".$keyword."%') ";
-		}
-
-		if (!empty($column) && !empty($direction)) {
-			$sql .=	" ORDER BY col$column $direction";
-		} else {
-			$sql .=	" ORDER BY col4 DESC ";
-		}
-		$sql .=	" LIMIT $from,$number_of_items ";
-
-		$res = Database::query($sql, __FILE__, __LINE__);
-		$activities = array ();
-		while ($row = Database::fetch_row($res)) {
-			$row[4] = api_format_date(DATE_TIME_FORMAT_LONG, strtotime($row[4]));
-			$activities[] = $row;
-		}
-		return $activities;
-	}
-
-	/**
-	 * Get all course categories
-	 * @return array All course categories (code => name)
-	 */
-	function get_course_categories()
-	{
-		$category_table = Database :: get_main_table(TABLE_MAIN_CATEGORY);
-		$sql = "SELECT * FROM $category_table ORDER BY tree_pos";
-		$res = Database::query($sql, __FILE__, __LINE__);
-		$categories = array ();
-		while ($category = Database::fetch_object($res))
-		{
-			$categories[$category->code] = $category->name;
-		}
-		return $categories;
-	}
-	/**
-	 * Rescale data
-	 * @param array $data The data that should be rescaled
-	 * @param int $max The maximum value in the rescaled data (default = 500);
-	 * @return array The rescaled data, same key as $data
-	 */
-	function rescale($data, $max = 500)
-	{
-		$data_max = 1;
-		foreach ($data as $index => $value)
-		{
-			$data_max = ($data_max < $value ? $value : $data_max);
-		}
-		reset($data);
-		$result = array ();
-		$delta = $max / $data_max;
-		foreach ($data as $index => $value)
-		{
-			$result[$index] = (int) round($value * $delta);
-		}
-		return $result;
-	}
-	/**
-	 * Show statistics
-	 * @param string $title The title
-	 * @param array $stats
-	 * @param bool $show_total
-	 * @param bool $is_file_size
-	 */
-	function print_stats($title, $stats, $show_total = true, $is_file_size = false)
-	{
-		$total = 0;
-		$data = Statistics::rescale($stats);
-		echo '<table class="data_table" cellspacing="0" cellpadding="3">
-			  		  <tr><th colspan="'.($show_total ? '4' : '3').'">'.$title.'</th></tr>';
-		$i = 0;
-		foreach($stats as $subtitle => $number)
-		{
-			$total += $number;
-		}
-		foreach ($stats as $subtitle => $number)
-		{
-			$i = $i % 13;
-			if (api_strlen($subtitle) > 30)
-			{
-				$subtitle = '<acronym title="'.$subtitle.'">'.api_substr($subtitle, 0, 27).'...</acronym>';
-			}
-			if(!$is_file_size)
-			{
-				$number_label = number_format($number, 0, ',', '.');
-			}
-			else
-			{
-				$number_label = Statistics::make_size_string($number);
-			}
-			echo '<tr class="row_'.($i%2 == 0 ? 'odd' : 'even').'">
-								<td width="150">'.$subtitle.'</td>
-								<td width="550">
-						 			'.Display::return_icon('bar_1u.gif', get_lang('Statistics') ,array('width' => $data[$subtitle], 'height' => '10')).'
-								</td>
-								<td align="right">'.$number_label.'</td>';
-			if($show_total)
-			{
-				echo '<td align="right"> '.($total>0?number_format(100*$number/$total, 1, ',', '.'):'0').'%</td>';
-			}
-			echo '</tr>';
-			$i ++;
-		}
-		if ($show_total)
-		{
-			if(!$is_file_size)
-			{
-				$total_label = number_format($total, 0, ',', '.');
-			}
-			else
-			{
-				$total_label = Statistics::make_size_string($total);
-			}
-			echo '<tr><th  colspan="4" align="right">'.get_lang('Total').': '.$total_label.'</td></tr>';
-		}
-		echo '</table>';
-	}
-	/**
-	 * Show some stats about the number of logins
-	 * @param string $type month, hour or day
-	 */
-	function print_login_stats($type)
-	{
-		$table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-		switch($type)
-		{
-			case 'month':
-				$months = api_get_months_long();
-				$period = get_lang('PeriodMonth');
-				$sql = "SELECT DATE_FORMAT( login_date, '%Y-%m' ) AS stat_date , count( login_id ) AS number_of_logins FROM ".$table." GROUP BY stat_date ORDER BY login_date ";
-				break;
-			case 'hour':
-				$period = get_lang('PeriodHour');
-				$sql = "SELECT DATE_FORMAT( login_date, '%H' ) AS stat_date , count( login_id ) AS number_of_logins FROM ".$table." GROUP BY stat_date ORDER BY stat_date ";
-				break;
-			case 'day':
-				$week_days = api_get_week_days_long();
-				$period = get_lang('PeriodDay');
-				$sql = "SELECT DATE_FORMAT( login_date, '%w' ) AS stat_date , count( login_id ) AS number_of_logins FROM ".$table." GROUP BY stat_date ORDER BY DATE_FORMAT( login_date, '%w' ) ";
-				break;
-		}
-		$res = Database::query($sql,__FILE__,__LINE__);
-		$result = array();
-		while($obj = Database::fetch_object($res))
-		{
-			$stat_date = $obj->stat_date;
-			switch($type)
-			{
-				case 'month':
-					$stat_date = explode('-', $stat_date);
-					$stat_date[1] = $months[$stat_date[1] - 1];
-					$stat_date = implode(' ', $stat_date);
-					break;
-				case 'day':
-					$stat_date = $week_days[$stat_date];
-					break;
-			}
-			$result[$stat_date] = $obj->number_of_logins;
-		}
-		Statistics::print_stats(get_lang('Logins').' ('.$period.')', $result, true);
-	}
-	/**
-	 * Print the number of recent logins
-	 */
-	function print_recent_login_stats()
-	{
-		$total_logins = array();
-		$table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-		$sql[get_lang('Thisday')] 	 = "SELECT count(login_user_id) AS number FROM $table WHERE DATE_ADD(login_date, INTERVAL 1 DAY) >= NOW()";
-		$sql[get_lang('Last7days')]  = "SELECT count(login_user_id) AS number  FROM $table WHERE DATE_ADD(login_date, INTERVAL 7 DAY) >= NOW()";
-		$sql[get_lang('Last31days')] = "SELECT count(login_user_id) AS number  FROM $table WHERE DATE_ADD(login_date, INTERVAL 31 DAY) >= NOW()";
-		$sql[get_lang('Total')] 	 = "SELECT count(login_user_id) AS number  FROM $table";
-		foreach($sql as $index => $query)
-		{
-			$res = Database::query($query,__FILE__,__LINE__);
-			$obj = Database::fetch_object($res);
-			$total_logins[$index] = $obj->number;
-		}
-		Statistics::print_stats(get_lang('Logins'),$total_logins,false);
-	}
-	/**
-	 * Show some stats about the accesses to the different course tools
-	 */
-	function print_tool_stats()
-	{
-		$table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ACCESS);
-		$tools = array('announcement','assignment','calendar_event','chat','conference','course_description','document','dropbox','group','learnpath','link','quiz','student_publication','user','forum');
-		$tool_names = array();
-		foreach ($tools as $tool) {
-			$tool_names[$tool] = get_lang(ucfirst($tool), '');
-		}
-		$sql = "SELECT access_tool, count( access_id ) AS number_of_logins FROM $table WHERE access_tool IN ('".implode("','",$tools)."') GROUP BY access_tool ";
-		$res = Database::query($sql,__FILE__,__LINE__);
-		$result = array();
-		while($obj = Database::fetch_object($res))
-		{
-			$result[$tool_names[$obj->access_tool]] = $obj->number_of_logins;
-		}
-		Statistics::print_stats(get_lang('PlatformToolAccess'),$result,true);
-	}
-	/**
-	 * Show some stats about the number of courses per language
-	 */
-	function print_course_by_language_stats()
-	{
-		$table = Database::get_main_table(TABLE_MAIN_COURSE);
-		$sql = "SELECT course_language, count( code ) AS number_of_courses FROM $table GROUP BY course_language ";
-		$res = Database::query($sql,__FILE__,__LINE__);
-		$result = array();
-		while($obj = Database::fetch_object($res))
-		{
-			$result[$obj->course_language] = $obj->number_of_courses;
-		}
-		Statistics::print_stats(get_lang('CountCourseByLanguage'),$result,true);
-	}
-	/**
-	 * Shows the number of users having their picture uploaded in Dokeos.
-	 */
-	function print_user_pictures_stats()
-	{
-		$user_table = Database :: get_main_table(TABLE_MAIN_USER);
-		$sql = "SELECT COUNT(*) AS n FROM $user_table";
-		$res = Database::query($sql,__FILE__,__LINE__);
-		$count1 = Database::fetch_object($res);
-		$sql = "SELECT COUNT(*) AS n FROM $user_table WHERE LENGTH(picture_uri) > 0";
-		$res = Database::query($sql,__FILE__,__LINE__);
-		$count2 = Database::fetch_object($res);
-		$result[get_lang('No')] = $count1->n - $count2->n; // #users without picture
-		$result[get_lang('Yes')] = $count2->n; // #users with picture
-		Statistics::print_stats(get_lang('CountUsers').' ('.get_lang('UserPicture').')',$result,true);
-	}
-
-	function print_activities_stats() {
-
-		echo '<h4>'.get_lang('ImportantActivities').'</h4>';
-
-		// Create a search-box
-		$form = new FormValidator('search_simple','get',api_get_path(WEB_CODE_PATH).'admin/statistics/index.php?action=activities','','width=200px',false);
-		$renderer =& $form->defaultRenderer();
-		$renderer->setElementTemplate('<span>{element}</span> ');
-		$form->addElement('hidden','action','activities');
-		$form->addElement('hidden','activities_direction','DESC');
-		$form->addElement('hidden','activities_column','4');
-		$form->addElement('text','keyword',get_lang('keyword'));
-		$form->addElement('style_submit_button', 'submit', get_lang('SearchActivities'),'class="search"');
-		echo '<div class="actions">';
-			$form->display();
-		echo '</div>';
-
-
-		$table = new SortableTable('activities', array('Statistics','get_number_of_activities'), array('Statistics','get_activities_data'),4,50,'DESC');
-		$parameters = array();
-
-		$parameters['action'] = 'activities';
-		if (isset($_GET['keyword'])) {
-			$parameters['keyword'] = Security::remove_XSS($_GET['keyword']);
-		}
-
-		$table->set_additional_parameters($parameters);
-		$table->set_header(0, get_lang('EventType'));
-		$table->set_header(1, get_lang('DataType'));
-		$table->set_header(2, get_lang('Value'));
-		$table->set_header(3, get_lang('UserName'));
-		$table->set_header(4, get_lang('Date'));
-		$table->display();
-
-	}
-
-	/**
-	 * Shows statistics about the time of last visit to each course.
-	 */
-	function print_course_last_visit()
-	{
-		$columns[0] = 'access_cours_code';
-		$columns[1] = 'access_date';
-		$sql_order[SORT_ASC] = 'ASC';
-		$sql_order[SORT_DESC] = 'DESC';
-		$per_page 	= isset($_GET['per_page']) ? intval($_GET['per_page']) : 10;
-		$page_nr 	= isset($_GET['page_nr'])  ? intval($_GET['page_nr']) : 1;
-		$column 	= isset($_GET['column'])   ? intval($_GET['column']) : 0;
-		$date_diff 	= isset($_GET['date_diff'])? intval($_GET['date_diff']) : 60;
-	    if(!in_array($_GET['direction'],array(SORT_ASC,SORT_DESC))){
-	    	$direction = SORT_ASC;
-	    } else {
-	    	$direction = isset($_GET['direction']) ? $_GET['direction'] : SORT_ASC;
-	    }
-		$form = new FormValidator('courselastvisit','get');
-		$form->addElement('hidden','action','courselastvisit');
-		$form->add_textfield('date_diff',get_lang('Days'),true);
-		$form->addRule('date_diff','InvalidNumber','numeric');
-		$form->addElement('submit','ok',get_lang('Ok'));
-		$defaults['date_diff'] = 60;
-		$form->setDefaults($defaults);
-		if($form->validate()) {
-			$form->display();
-			$values = $form->exportValues();
-			$date_diff = $values['date_diff'];
-			$table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
-			$sql = "SELECT * FROM $table GROUP BY access_cours_code HAVING access_cours_code <> '' AND DATEDIFF( NOW() , access_date ) >= ". $date_diff;
-			$res = Database::query($sql,__FILE__,__LINE__);
-			$number_of_courses = Database::num_rows($res);
-			$sql .= ' ORDER BY '.$columns[$column].' '.$sql_order[$direction];
-			$from = ($page_nr -1) * $per_page;
-			$sql .= ' LIMIT '.$from.','.$per_page;
-			echo '<p>'.get_lang('LastAccess').' &gt;= '.$date_diff.' '.get_lang('Days').'</p>';
-			$res = Database::query($sql, __FILE__, __LINE__);
-			if (Database::num_rows($res) > 0)
-			{
-				$courses = array ();
-				while ($obj = Database::fetch_object($res))
-				{
-					$course = array ();
-					$course[]= '<a href="'.api_get_path(WEB_PATH).'courses/'.$obj->access_cours_code.'">'.$obj->access_cours_code.' <a>';
-					$course[] = $obj->access_date;
-					$courses[] = $course;
-				}
-				$parameters['action'] = 'courselastvisit';
-				$parameters['date_diff'] = $date_diff;
-				$table_header[] = array ("Coursecode", true);
-				$table_header[] = array ("Last login", true);
-				Display :: display_sortable_table($table_header, $courses, array ('column'=>$column,'direction'=>$direction), array (), $parameters);
-			}
-			else
-			{
-				echo get_lang('NoSearchResults');
-			}
-		}
-		else
-		{
-			$form->display();
-		}
-	}
-}
-?>
+<?php
+// $Id: index.php 8216 2006-11-3 18:03:15 NushiFirefox $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2006 Bart Mollet <bart.mollet@hogent.be>
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+/**
+==============================================================================
+* This class provides some functions for statistics
+* @package dokeos.statistics
+==============================================================================
+*/
+class Statistics
+{
+	/**
+	 * Converts a number of bytes in a formatted string
+	 * @param int $size
+	 * @return string Formatted file size
+	 */
+	function make_size_string($size) {
+		if ($size < pow(2,10)) return $size." bytes";
+		if ($size >= pow(2,10) && $size < pow(2,20)) return round($size / pow(2,10), 0)." KB";
+		if ($size >= pow(2,20) && $size < pow(2,30)) return round($size / pow(2,20), 1)." MB";
+		if ($size > pow(2,30)) return round($size / pow(2,30), 2)." GB";
+	}
+	/**
+	 * Count courses
+	 * @param string $category_code  Code of a course category. Default: count
+	 * all courses.
+	 * @return int Number of courses counted
+	 */
+	function count_courses($category_code = NULL)
+	{
+		$course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
+		$sql = "SELECT COUNT(*) AS number FROM ".$course_table." ";
+		if (isset ($category_code))
+		{
+			$sql .= " WHERE category_code = '".Database::escape_string($category_code)."'";
+		}
+		$res = Database::query($sql, __FILE__, __LINE__);
+		$obj = Database::fetch_object($res);
+		return $obj->number;
+	}
+	/**
+	 * Count users
+	 * @param int $status COURSEMANAGER or STUDENT
+	 * @param string $category_code  Code of a course category. Default: count
+	 * all users.
+	 * @return int Number of users counted
+	 */
+	function count_users($status, $category_code = NULL, $count_invisible_courses = true)
+	{
+		// Database table definitions
+		$course_user_table 	= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+		$course_table 		= Database :: get_main_table(TABLE_MAIN_COURSE);
+		$user_table 		= Database :: get_main_table(TABLE_MAIN_USER);
+
+		$sql = "SELECT COUNT(DISTINCT(user_id)) AS number FROM $user_table WHERE status = ".intval(Database::escape_string($status))." ";
+		if (isset ($category_code))
+		{
+			$sql = "SELECT COUNT(DISTINCT(cu.user_id)) AS number FROM $course_user_table cu, $course_table c WHERE cu.status = ".intval(Database::escape_string($status))." AND c.code = cu.course_code AND c.category_code = '".Database::escape_string($category_code)."'";
+		}
+		$res = Database::query($sql, __FILE__, __LINE__);
+		$obj = Database::fetch_object($res);
+		return $obj->number;
+	}
+
+	/**
+	 * Count activities from track_e_default_table
+	 * @return int Number of activities counted
+	 */
+	function get_number_of_activities()
+	{
+		// Database table definitions
+		$track_e_default  = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
+
+		$sql = "SELECT count(default_id) AS total_number_of_items FROM $track_e_default, $table_user user WHERE default_user_id = user.user_id ";
+
+		if (isset($_GET['keyword'])) {
+		$keyword = Database::escape_string($_GET['keyword']);
+		$sql .= " AND (user.username LIKE '%".$keyword."%' OR default_event_type LIKE '%".$keyword."%' OR default_value_type LIKE '%".$keyword."%' OR default_value LIKE '%".$keyword."%') ";
+		}
+
+		$res = Database::query($sql, __FILE__, __LINE__);
+		$obj = Database::fetch_object($res);
+		return $obj->total_number_of_items;
+	}
+	/**
+	 * Get activities data to display
+	 */
+	function get_activities_data($from, $number_of_items, $column, $direction)
+	{
+		global $dateTimeFormatLong;
+		$track_e_default 	= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
+		$table_user = Database::get_main_table(TABLE_MAIN_USER);
+		$table_course = Database::get_main_table(TABLE_MAIN_COURSE);
+
+		$sql = "SELECT
+				 	default_event_type  as col0,
+					default_value_type	as col1,
+					default_value		as col2,
+					user.username 	as col3,
+					default_date 	as col4
+				FROM $track_e_default track_default, $table_user user
+				WHERE track_default.default_user_id = user.user_id ";
+
+		if (isset($_GET['keyword'])) {
+		$keyword = Database::escape_string($_GET['keyword']);
+		$sql .= " AND (user.username LIKE '%".$keyword."%' OR default_event_type LIKE '%".$keyword."%' OR default_value_type LIKE '%".$keyword."%' OR default_value LIKE '%".$keyword."%') ";
+		}
+
+		if (!empty($column) && !empty($direction)) {
+			$sql .=	" ORDER BY col$column $direction";
+		} else {
+			$sql .=	" ORDER BY col4 DESC ";
+		}
+		$sql .=	" LIMIT $from,$number_of_items ";
+
+		$res = Database::query($sql, __FILE__, __LINE__);
+		$activities = array ();
+		while ($row = Database::fetch_row($res)) {
+			$row[4] = api_format_date(DATE_TIME_FORMAT_LONG, strtotime($row[4]));
+			$activities[] = $row;
+		}
+		return $activities;
+	}
+
+	/**
+	 * Get all course categories
+	 * @return array All course categories (code => name)
+	 */
+	function get_course_categories()
+	{
+		$category_table = Database :: get_main_table(TABLE_MAIN_CATEGORY);
+		$sql = "SELECT * FROM $category_table ORDER BY tree_pos";
+		$res = Database::query($sql, __FILE__, __LINE__);
+		$categories = array ();
+		while ($category = Database::fetch_object($res))
+		{
+			$categories[$category->code] = $category->name;
+		}
+		return $categories;
+	}
+	/**
+	 * Rescale data
+	 * @param array $data The data that should be rescaled
+	 * @param int $max The maximum value in the rescaled data (default = 500);
+	 * @return array The rescaled data, same key as $data
+	 */
+	function rescale($data, $max = 500)
+	{
+		$data_max = 1;
+		foreach ($data as $index => $value)
+		{
+			$data_max = ($data_max < $value ? $value : $data_max);
+		}
+		reset($data);
+		$result = array ();
+		$delta = $max / $data_max;
+		foreach ($data as $index => $value)
+		{
+			$result[$index] = (int) round($value * $delta);
+		}
+		return $result;
+	}
+	/**
+	 * Show statistics
+	 * @param string $title The title
+	 * @param array $stats
+	 * @param bool $show_total
+	 * @param bool $is_file_size
+	 */
+	function print_stats($title, $stats, $show_total = true, $is_file_size = false)
+	{
+		$total = 0;
+		$data = Statistics::rescale($stats);
+		echo '<table class="data_table" cellspacing="0" cellpadding="3">
+			  		  <tr><th colspan="'.($show_total ? '4' : '3').'">'.$title.'</th></tr>';
+		$i = 0;
+		foreach($stats as $subtitle => $number)
+		{
+			$total += $number;
+		}
+		foreach ($stats as $subtitle => $number)
+		{
+			$i = $i % 13;
+			if (api_strlen($subtitle) > 30)
+			{
+				$subtitle = '<acronym title="'.$subtitle.'">'.api_substr($subtitle, 0, 27).'...</acronym>';
+			}
+			if(!$is_file_size)
+			{
+				$number_label = number_format($number, 0, ',', '.');
+			}
+			else
+			{
+				$number_label = Statistics::make_size_string($number);
+			}
+			echo '<tr class="row_'.($i%2 == 0 ? 'odd' : 'even').'">
+								<td width="150">'.$subtitle.'</td>
+								<td width="550">
+						 			'.Display::return_icon('bar_1u.gif', get_lang('Statistics') ,array('width' => $data[$subtitle], 'height' => '10')).'
+								</td>
+								<td align="right">'.$number_label.'</td>';
+			if($show_total)
+			{
+				echo '<td align="right"> '.($total>0?number_format(100*$number/$total, 1, ',', '.'):'0').'%</td>';
+			}
+			echo '</tr>';
+			$i ++;
+		}
+		if ($show_total)
+		{
+			if(!$is_file_size)
+			{
+				$total_label = number_format($total, 0, ',', '.');
+			}
+			else
+			{
+				$total_label = Statistics::make_size_string($total);
+			}
+			echo '<tr><th  colspan="4" align="right">'.get_lang('Total').': '.$total_label.'</td></tr>';
+		}
+		echo '</table>';
+	}
+	/**
+	 * Show some stats about the number of logins
+	 * @param string $type month, hour or day
+	 */
+	function print_login_stats($type)
+	{
+		$table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
+		switch($type)
+		{
+			case 'month':
+				$months = api_get_months_long();
+				$period = get_lang('PeriodMonth');
+				$sql = "SELECT DATE_FORMAT( login_date, '%Y-%m' ) AS stat_date , count( login_id ) AS number_of_logins FROM ".$table." GROUP BY stat_date ORDER BY login_date ";
+				break;
+			case 'hour':
+				$period = get_lang('PeriodHour');
+				$sql = "SELECT DATE_FORMAT( login_date, '%H' ) AS stat_date , count( login_id ) AS number_of_logins FROM ".$table." GROUP BY stat_date ORDER BY stat_date ";
+				break;
+			case 'day':
+				$week_days = api_get_week_days_long();
+				$period = get_lang('PeriodDay');
+				$sql = "SELECT DATE_FORMAT( login_date, '%w' ) AS stat_date , count( login_id ) AS number_of_logins FROM ".$table." GROUP BY stat_date ORDER BY DATE_FORMAT( login_date, '%w' ) ";
+				break;
+		}
+		$res = Database::query($sql,__FILE__,__LINE__);
+		$result = array();
+		while($obj = Database::fetch_object($res))
+		{
+			$stat_date = $obj->stat_date;
+			switch($type)
+			{
+				case 'month':
+					$stat_date = explode('-', $stat_date);
+					$stat_date[1] = $months[$stat_date[1] - 1];
+					$stat_date = implode(' ', $stat_date);
+					break;
+				case 'day':
+					$stat_date = $week_days[$stat_date];
+					break;
+			}
+			$result[$stat_date] = $obj->number_of_logins;
+		}
+		Statistics::print_stats(get_lang('Logins').' ('.$period.')', $result, true);
+	}
+	/**
+	 * Print the number of recent logins
+	 */
+	function print_recent_login_stats()
+	{
+		$total_logins = array();
+		$table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
+		$sql[get_lang('Thisday')] 	 = "SELECT count(login_user_id) AS number FROM $table WHERE DATE_ADD(login_date, INTERVAL 1 DAY) >= NOW()";
+		$sql[get_lang('Last7days')]  = "SELECT count(login_user_id) AS number  FROM $table WHERE DATE_ADD(login_date, INTERVAL 7 DAY) >= NOW()";
+		$sql[get_lang('Last31days')] = "SELECT count(login_user_id) AS number  FROM $table WHERE DATE_ADD(login_date, INTERVAL 31 DAY) >= NOW()";
+		$sql[get_lang('Total')] 	 = "SELECT count(login_user_id) AS number  FROM $table";
+		foreach($sql as $index => $query)
+		{
+			$res = Database::query($query,__FILE__,__LINE__);
+			$obj = Database::fetch_object($res);
+			$total_logins[$index] = $obj->number;
+		}
+		Statistics::print_stats(get_lang('Logins'),$total_logins,false);
+	}
+	/**
+	 * Show some stats about the accesses to the different course tools
+	 */
+	function print_tool_stats()
+	{
+		$table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ACCESS);
+		$tools = array('announcement','assignment','calendar_event','chat','conference','course_description','document','dropbox','group','learnpath','link','quiz','student_publication','user','forum');
+		$tool_names = array();
+		foreach ($tools as $tool) {
+			$tool_names[$tool] = get_lang(ucfirst($tool), '');
+		}
+		$sql = "SELECT access_tool, count( access_id ) AS number_of_logins FROM $table WHERE access_tool IN ('".implode("','",$tools)."') GROUP BY access_tool ";
+		$res = Database::query($sql,__FILE__,__LINE__);
+		$result = array();
+		while($obj = Database::fetch_object($res))
+		{
+			$result[$tool_names[$obj->access_tool]] = $obj->number_of_logins;
+		}
+		Statistics::print_stats(get_lang('PlatformToolAccess'),$result,true);
+	}
+	/**
+	 * Show some stats about the number of courses per language
+	 */
+	function print_course_by_language_stats()
+	{
+		$table = Database::get_main_table(TABLE_MAIN_COURSE);
+		$sql = "SELECT course_language, count( code ) AS number_of_courses FROM $table GROUP BY course_language ";
+		$res = Database::query($sql,__FILE__,__LINE__);
+		$result = array();
+		while($obj = Database::fetch_object($res))
+		{
+			$result[$obj->course_language] = $obj->number_of_courses;
+		}
+		Statistics::print_stats(get_lang('CountCourseByLanguage'),$result,true);
+	}
+	/**
+	 * Shows the number of users having their picture uploaded in Dokeos.
+	 */
+	function print_user_pictures_stats()
+	{
+		$user_table = Database :: get_main_table(TABLE_MAIN_USER);
+		$sql = "SELECT COUNT(*) AS n FROM $user_table";
+		$res = Database::query($sql,__FILE__,__LINE__);
+		$count1 = Database::fetch_object($res);
+		$sql = "SELECT COUNT(*) AS n FROM $user_table WHERE LENGTH(picture_uri) > 0";
+		$res = Database::query($sql,__FILE__,__LINE__);
+		$count2 = Database::fetch_object($res);
+		$result[get_lang('No')] = $count1->n - $count2->n; // #users without picture
+		$result[get_lang('Yes')] = $count2->n; // #users with picture
+		Statistics::print_stats(get_lang('CountUsers').' ('.get_lang('UserPicture').')',$result,true);
+	}
+
+	function print_activities_stats() {
+
+		echo '<h4>'.get_lang('ImportantActivities').'</h4>';
+
+		// Create a search-box
+		$form = new FormValidator('search_simple','get',api_get_path(WEB_CODE_PATH).'admin/statistics/index.php?action=activities','','width=200px',false);
+		$renderer =& $form->defaultRenderer();
+		$renderer->setElementTemplate('<span>{element}</span> ');
+		$form->addElement('hidden','action','activities');
+		$form->addElement('hidden','activities_direction','DESC');
+		$form->addElement('hidden','activities_column','4');
+		$form->addElement('text','keyword',get_lang('keyword'));
+		$form->addElement('style_submit_button', 'submit', get_lang('SearchActivities'),'class="search"');
+		echo '<div class="actions">';
+			$form->display();
+		echo '</div>';
+
+
+		$table = new SortableTable('activities', array('Statistics','get_number_of_activities'), array('Statistics','get_activities_data'),4,50,'DESC');
+		$parameters = array();
+
+		$parameters['action'] = 'activities';
+		if (isset($_GET['keyword'])) {
+			$parameters['keyword'] = Security::remove_XSS($_GET['keyword']);
+		}
+
+		$table->set_additional_parameters($parameters);
+		$table->set_header(0, get_lang('EventType'));
+		$table->set_header(1, get_lang('DataType'));
+		$table->set_header(2, get_lang('Value'));
+		$table->set_header(3, get_lang('UserName'));
+		$table->set_header(4, get_lang('Date'));
+		$table->display();
+
+	}
+
+	/**
+	 * Shows statistics about the time of last visit to each course.
+	 */
+	function print_course_last_visit()
+	{
+		$columns[0] = 'access_cours_code';
+		$columns[1] = 'access_date';
+		$sql_order[SORT_ASC] = 'ASC';
+		$sql_order[SORT_DESC] = 'DESC';
+		$per_page 	= isset($_GET['per_page']) ? intval($_GET['per_page']) : 10;
+		$page_nr 	= isset($_GET['page_nr'])  ? intval($_GET['page_nr']) : 1;
+		$column 	= isset($_GET['column'])   ? intval($_GET['column']) : 0;
+		$date_diff 	= isset($_GET['date_diff'])? intval($_GET['date_diff']) : 60;
+	    if(!in_array($_GET['direction'],array(SORT_ASC,SORT_DESC))){
+	    	$direction = SORT_ASC;
+	    } else {
+	    	$direction = isset($_GET['direction']) ? $_GET['direction'] : SORT_ASC;
+	    }
+		$form = new FormValidator('courselastvisit','get');
+		$form->addElement('hidden','action','courselastvisit');
+		$form->add_textfield('date_diff',get_lang('Days'),true);
+		$form->addRule('date_diff','InvalidNumber','numeric');
+		$form->addElement('submit','ok',get_lang('Ok'));
+		$defaults['date_diff'] = 60;
+		$form->setDefaults($defaults);
+		if($form->validate()) {
+			$form->display();
+			$values = $form->exportValues();
+			$date_diff = $values['date_diff'];
+			$table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
+			$sql = "SELECT * FROM $table GROUP BY access_cours_code HAVING access_cours_code <> '' AND DATEDIFF( NOW() , access_date ) >= ". $date_diff;
+			$res = Database::query($sql,__FILE__,__LINE__);
+			$number_of_courses = Database::num_rows($res);
+			$sql .= ' ORDER BY '.$columns[$column].' '.$sql_order[$direction];
+			$from = ($page_nr -1) * $per_page;
+			$sql .= ' LIMIT '.$from.','.$per_page;
+			echo '<p>'.get_lang('LastAccess').' &gt;= '.$date_diff.' '.get_lang('Days').'</p>';
+			$res = Database::query($sql, __FILE__, __LINE__);
+			if (Database::num_rows($res) > 0)
+			{
+				$courses = array ();
+				while ($obj = Database::fetch_object($res))
+				{
+					$course = array ();
+					$course[]= '<a href="'.api_get_path(WEB_PATH).'courses/'.$obj->access_cours_code.'">'.$obj->access_cours_code.' <a>';
+					$course[] = $obj->access_date;
+					$courses[] = $course;
+				}
+				$parameters['action'] = 'courselastvisit';
+				$parameters['date_diff'] = $date_diff;
+				$table_header[] = array ("Coursecode", true);
+				$table_header[] = array ("Last login", true);
+				Display :: display_sortable_table($table_header, $courses, array ('column'=>$column,'direction'=>$direction), array (), $parameters);
+			}
+			else
+			{
+				echo get_lang('NoSearchResults');
+			}
+		}
+		else
+		{
+			$form->display();
+		}
+	}
+}
+?>

+ 164 - 164
main/admin/style_preview.php

@@ -1,165 +1,165 @@
-<?php
-include_once('../inc/global.inc.php');
-if (isset($_GET['style']) AND $_GET['style']<>'')
-{
-	$style=Security::remove_XSS($_GET['style']);
-	//$htmlHeadXtra[] = '<link href="../css/'.$_GET['style'].'/default.css" rel="stylesheet" type="text/css">';
-	echo '<link href="../css/'.$style.'/default.css" rel="stylesheet" type="text/css">';
-}
-else
-{
-	$currentstyle = api_get_setting('stylesheets');
-	echo '<link href="../css/'.$currentstyle.'/default.css" rel="stylesheet" type="text/css">';
-}
-
-
-//Display::display_header($tool_name);
-include(api_get_path(INCLUDE_PATH).'banner.inc.php');
-
-?>
-<!-- start of #main wrapper for #content and #menu divs -->
-  <!--   Begin Of script Output   -->
-  <div class="maincontent">
-    <h3>tool title</h3>
-    <div id="courseintro">
-      <p>This is the introduction text.
-    </div>
-    <div id="courseintro_icons">
-    <a href="#"><?php Display::display_icon('edit.gif', get_lang('Edit')); ?></a><a href="#"><?php Display::display_icon('delete.gif', get_lang('Delete')); ?></a></div>
-    <div class="normal-message"> Normal Message </div>
-    <div class="error-message"> Error Message </div>
-    <table width="750">
-      <tr>
-        <td>
-        <table>
-            <tr>
-              <td width="220">
-              <table id="smallcalendar">
-                  <tr id="title">
-                    <td width="10%"><a href="#"><<</a></td>
-                    <td width="80%" colspan="5" align="center"> 2006</td>
-                    <td width="10%"><a href="#">>></a></td>
-                  </tr>
-                  <tr>
-                    <td class="weekdays">Mon</td>
-                    <td class="weekdays">Tue</td>
-                    <td class="weekdays">Wed</td>
-                    <td class="weekdays">Thu</td>
-                    <td class="weekdays">Fri</td>
-                    <td class="weekdays">Sat</td>
-                    <td class="weekdays">Sun</td>
-                  </tr>
-                  <tr>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td class="days_weekend">1</td>
-                  </tr>
-                  <tr>
-                    <td class="days_week">2</td>
-                    <td class="days_week">3</td>
-                    <td class="days_week">4</td>
-                    <td class="days_week">5</td>
-                    <td class="days_week">6</td>
-                    <td class="days_weekend">7</td>
-                    <td class="days_weekend">8</td>
-                  </tr>
-                  <tr>
-                    <td class="days_week">9</td>
-                    <td class="days_week">10</td>
-                    <td class="days_week">11</td>
-                    <td class="days_week">12</td>
-                    <td class="days_week">13</td>
-                    <td class="days_weekend">14</td>
-                    <td class="days_weekend">15</td>
-                  </tr>
-                  <tr>
-                    <td class="days_week">16</td>
-                    <td class="days_week">17</td>
-                    <td class="days_week">18</td>
-                    <td class="days_week">19</td>
-                    <td class="days_week">20</td>
-                    <td class="days_weekend">21</td>
-                    <td class="days_weekend">22</td>
-                  </tr>
-                  <tr>
-                    <td class="days_week">23</td>
-                    <td class="days_today">24</td>
-                    <td class="days_week">25</td>
-                    <td class="days_week">26</td>
-                    <td class="days_week">27</td>
-                    <td class="days_weekend">28</td>
-                    <td class="days_weekend">29</td>
-                  </tr>
-                  <tr>
-                    <td class="days_week">30</td>
-                    <td class="days_week">31</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                  </tr>
-                </table>
-              </td>
-            </tr>
-          </table>
-        </td>
-        <td width="500">
-          <table width="100%">
-            <tr>
-              <td></td>
-              <td align="right"></td>
-            </tr>
-          </table>
-          <table class="data_table" width="100%">
-            <tr>
-              <th style="width:100px"><a href="#">Firstname</a>&nbsp;&#8595; </th>
-              <th style="width:100px"><a href="#">Lastname</a></th>
-            </tr>
-            <tr class="row_even">
-              <td >Firstname</td>
-              <td >Lastname</td>
-            </tr>
-            <tr class="row_odd">
-              <td >Julio</td>
-              <td >Montoya</td>
-            </tr>
-            <tr class="row_even">
-              <td >Patrick</td>
-              <td >Cool</td>
-            </tr>
-          </table>
-          <table width="100%">
-            <tr>
-              <td></td>
-              <td align="right"></td>
-            </tr>
-          </table>
-        </td>
-      </tr>
-    </table>
-  </div>
-  <div class="menu" style="width:200px">
-    <form action="#" method="post" id="loginform" name="loginform">
-      <label>Username</label>
-      <input type="text" name="login" id="login" size="15" value="" />
-      <label>Password</label>
-      <input type="password" name="password" id="password" size="15" />
-  	  <button class="login" type="submit" name="submitAuth">Enter</button>
-    </form>
-    <div class="menusection"><span class="menusectioncaption">User</span>
-      <ul class="menulist">
-        <li><a href="#">Course Management</a></li>
-        <li><a href="#">Create Course</a></li>
-      </ul>
-    </div>
-    <div class="note"><b>Example notice</b><br />
-      To modify this notice, go to the administration area of the portal.</div>
-  </div>
-<?php
-Display::display_footer();
+<?php
+include_once('../inc/global.inc.php');
+if (isset($_GET['style']) AND $_GET['style']<>'')
+{
+	$style=Security::remove_XSS($_GET['style']);
+	//$htmlHeadXtra[] = '<link href="../css/'.$_GET['style'].'/default.css" rel="stylesheet" type="text/css">';
+	echo '<link href="../css/'.$style.'/default.css" rel="stylesheet" type="text/css">';
+}
+else
+{
+	$currentstyle = api_get_setting('stylesheets');
+	echo '<link href="../css/'.$currentstyle.'/default.css" rel="stylesheet" type="text/css">';
+}
+
+
+//Display::display_header($tool_name);
+include(api_get_path(INCLUDE_PATH).'banner.inc.php');
+
+?>
+<!-- start of #main wrapper for #content and #menu divs -->
+  <!--   Begin Of script Output   -->
+  <div class="maincontent">
+    <h3>tool title</h3>
+    <div id="courseintro">
+      <p>This is the introduction text.
+    </div>
+    <div id="courseintro_icons">
+    <a href="#"><?php Display::display_icon('edit.gif', get_lang('Edit')); ?></a><a href="#"><?php Display::display_icon('delete.gif', get_lang('Delete')); ?></a></div>
+    <div class="normal-message"> Normal Message </div>
+    <div class="error-message"> Error Message </div>
+    <table width="750">
+      <tr>
+        <td>
+        <table>
+            <tr>
+              <td width="220">
+              <table id="smallcalendar">
+                  <tr id="title">
+                    <td width="10%"><a href="#"><<</a></td>
+                    <td width="80%" colspan="5" align="center"> 2006</td>
+                    <td width="10%"><a href="#">>></a></td>
+                  </tr>
+                  <tr>
+                    <td class="weekdays">Mon</td>
+                    <td class="weekdays">Tue</td>
+                    <td class="weekdays">Wed</td>
+                    <td class="weekdays">Thu</td>
+                    <td class="weekdays">Fri</td>
+                    <td class="weekdays">Sat</td>
+                    <td class="weekdays">Sun</td>
+                  </tr>
+                  <tr>
+                    <td>&nbsp;</td>
+                    <td>&nbsp;</td>
+                    <td>&nbsp;</td>
+                    <td>&nbsp;</td>
+                    <td>&nbsp;</td>
+                    <td>&nbsp;</td>
+                    <td class="days_weekend">1</td>
+                  </tr>
+                  <tr>
+                    <td class="days_week">2</td>
+                    <td class="days_week">3</td>
+                    <td class="days_week">4</td>
+                    <td class="days_week">5</td>
+                    <td class="days_week">6</td>
+                    <td class="days_weekend">7</td>
+                    <td class="days_weekend">8</td>
+                  </tr>
+                  <tr>
+                    <td class="days_week">9</td>
+                    <td class="days_week">10</td>
+                    <td class="days_week">11</td>
+                    <td class="days_week">12</td>
+                    <td class="days_week">13</td>
+                    <td class="days_weekend">14</td>
+                    <td class="days_weekend">15</td>
+                  </tr>
+                  <tr>
+                    <td class="days_week">16</td>
+                    <td class="days_week">17</td>
+                    <td class="days_week">18</td>
+                    <td class="days_week">19</td>
+                    <td class="days_week">20</td>
+                    <td class="days_weekend">21</td>
+                    <td class="days_weekend">22</td>
+                  </tr>
+                  <tr>
+                    <td class="days_week">23</td>
+                    <td class="days_today">24</td>
+                    <td class="days_week">25</td>
+                    <td class="days_week">26</td>
+                    <td class="days_week">27</td>
+                    <td class="days_weekend">28</td>
+                    <td class="days_weekend">29</td>
+                  </tr>
+                  <tr>
+                    <td class="days_week">30</td>
+                    <td class="days_week">31</td>
+                    <td>&nbsp;</td>
+                    <td>&nbsp;</td>
+                    <td>&nbsp;</td>
+                    <td>&nbsp;</td>
+                    <td>&nbsp;</td>
+                  </tr>
+                </table>
+              </td>
+            </tr>
+          </table>
+        </td>
+        <td width="500">
+          <table width="100%">
+            <tr>
+              <td></td>
+              <td align="right"></td>
+            </tr>
+          </table>
+          <table class="data_table" width="100%">
+            <tr>
+              <th style="width:100px"><a href="#">Firstname</a>&nbsp;&#8595; </th>
+              <th style="width:100px"><a href="#">Lastname</a></th>
+            </tr>
+            <tr class="row_even">
+              <td >Firstname</td>
+              <td >Lastname</td>
+            </tr>
+            <tr class="row_odd">
+              <td >Julio</td>
+              <td >Montoya</td>
+            </tr>
+            <tr class="row_even">
+              <td >Patrick</td>
+              <td >Cool</td>
+            </tr>
+          </table>
+          <table width="100%">
+            <tr>
+              <td></td>
+              <td align="right"></td>
+            </tr>
+          </table>
+        </td>
+      </tr>
+    </table>
+  </div>
+  <div class="menu" style="width:200px">
+    <form action="#" method="post" id="loginform" name="loginform">
+      <label>Username</label>
+      <input type="text" name="login" id="login" size="15" value="" />
+      <label>Password</label>
+      <input type="password" name="password" id="password" size="15" />
+  	  <button class="login" type="submit" name="submitAuth">Enter</button>
+    </form>
+    <div class="menusection"><span class="menusectioncaption">User</span>
+      <ul class="menulist">
+        <li><a href="#">Course Management</a></li>
+        <li><a href="#">Create Course</a></li>
+      </ul>
+    </div>
+    <div class="note"><b>Example notice</b><br />
+      To modify this notice, go to the administration area of the portal.</div>
+  </div>
+<?php
+Display::display_footer();
 ?>

+ 410 - 410
main/admin/user_fields.php

@@ -1,417 +1,417 @@
-<?php // $Id: $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2008 Dokeos SPRL
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	@package dokeos.admin
-==============================================================================
-*/
-// name of the language file that needs to be included
-$language_file = array('admin','registration');
-$cidReset = true;
-
-// including necessary libraries
-require ('../inc/global.inc.php');
-$libpath = api_get_path(LIBRARY_PATH);
-include_once ($libpath.'usermanager.lib.php');
-require_once ($libpath.'formvalidator/FormValidator.class.php');
-
-// section for the tabs
-$this_section=SECTION_PLATFORM_ADMIN;
-
-// user permissions
-api_protect_admin_script();
-
-// Database table definitions
-$table_admin	= Database :: get_main_table(TABLE_MAIN_ADMIN);
-$table_user 	= Database :: get_main_table(TABLE_MAIN_USER);
-$table_uf	 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD);
-$table_uf_opt 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-$table_uf_val 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
-
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
-
-// Display form
-if(1)
-{
-	$tool_name = get_lang('UserFields');
-	Display :: display_header($tool_name, "");
-	//api_display_tool_title($tool_name);
-	if (isset ($_GET['action']))
-	{
-		$check = Security::check_token('get');
-		if($check) {
-			switch ($_GET['action']) {
-				case 'show_message' :
-					Display :: display_normal_message($_GET['message']);
-					break;
-				case 'show_field' :
-					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_visible'=>'1'))) {
-						Display :: display_confirmation_message(get_lang('FieldShown'));
-					} else {
-						Display :: display_error_message(get_lang('CannotShowField'));
-					}
-					break;
-				case 'hide_field' :
-					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_visible'=>'0'))) {
-						Display :: display_confirmation_message(get_lang('FieldHidden'));
-					} else {
-						Display :: display_error_message(get_lang('CannotHideField'));
-					}
-					break;
-				case 'thaw_field' :
-					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_changeable'=>'1'))) {
-						Display :: display_confirmation_message(get_lang('FieldMadeChangeable'));
-					} else {
-						Display :: display_error_message(get_lang('CannotMakeFieldChangeable'));
-					}
-					break;
-				case 'freeze_field' :
-					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_changeable'=>'0'))) {
-						Display :: display_confirmation_message(get_lang('FieldMadeUnchangeable'));
-					} else {
-						Display :: display_error_message(get_lang('CannotMakeFieldUnchangeable'));
-					}
-					break;
-				case 'moveup' :
-					if (api_is_platform_admin() && !empty($_GET['field_id'])) {
-						if (move_user_field('moveup', $_GET['field_id'])) {
-							Display :: display_confirmation_message(get_lang('FieldMovedUp'));
-						} else {
-							Display :: display_error_message(get_lang('CannotMoveField'));
-						}
-					}
-					break;
-				case 'movedown' :
-					if (api_is_platform_admin() && !empty($_GET['field_id'])) {
-						if (move_user_field('movedown', $_GET['field_id'])) {
-							Display :: display_confirmation_message(get_lang('FieldMovedDown'));
-						} else {
-							Display :: display_error_message(get_lang('CannotMoveField'));
-						}
-					}
-					break;
-				case 'filter_on' :
-					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_filter'=>'1'))) {
-						Display :: display_confirmation_message(get_lang('FieldFilterSetOn'));
-					} else {
-						Display :: display_error_message(get_lang('CannotShowField'));
-					}
-					break;
-				case 'filter_off' :
-					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_filter'=>'0'))) {
-						Display :: display_confirmation_message(get_lang('FieldFilterSetOff'));
-					} else {
-						Display :: display_error_message(get_lang('CannotShowField'));
-					}
-					break;
-
-				case 'delete':
-					if (api_is_platform_admin() && !empty($_GET['field_id'])) {
-						if (delete_user_fields($_GET['field_id'])) {
-							Display :: display_confirmation_message(get_lang('FieldDeleted'));
-						} else {
-							Display :: display_error_message(get_lang('CannotDeleteField'));
-						}
-					}
-					break;
-			}
-			Security::clear_token();
-		}
-	}
-	if (isset ($_POST['action'])) {
-		$check = Security::check_token('get');
-		if($check) {
-			switch ($_POST['action']) {
-				default:
-					break;
-			}
-			Security::clear_token();
-		}
-	}
-
-	// Create an add-field box
-	$form = new FormValidator('add_field','post','','',null,false);
-	$renderer =& $form->defaultRenderer();
-	$renderer->setElementTemplate('<span>{element}</span> ');
-	//$form->addElement('text','label',get_lang('FieldLabel'));
-	//$form->addElement('text','type',get_lang('FieldType'));
-	//$form->addElement('text','title',get_lang('FieldTitle'));
-	//$form->addElement('text','default',get_lang('FieldDefaultValue'));
-	//$form->addElement('submit','submit',get_lang('Search'));
-	$form->addElement('static','search_advanced_link',null,'<a href="user_fields_add.php?action=fill">'.Display::return_icon('fieldadd.gif', get_lang('AddUserField')).get_lang('AddUserField').'</a>');
-	echo '<div class="actions">';
-	$form->display();
-	echo '</div>';
-
-	// Create a sortable table with user-data
-	$parameters['sec_token'] = Security::get_token();
-	$column_show  = array(1,1,1,1,1,1,1,1,1,0,0);
-	$column_order = array(1,2,3,4,5,6,7,8,9,10,11);
-	$extra_fields = UserManager::get_extra_fields(0,100,5,'ASC');
-
-	$number_of_extra_fields = count($extra_fields);
-
-	$table = new SortableTableFromArrayConfig($extra_fields, 5, 50, '', $column_show, $column_order, 'ASC');
-	$table->set_additional_parameters($parameters);
-	$table->set_header(0, '', false);
+<?php // $Id: $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos SPRL
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	@package dokeos.admin
+==============================================================================
+*/
+// name of the language file that needs to be included
+$language_file = array('admin','registration');
+$cidReset = true;
+
+// including necessary libraries
+require ('../inc/global.inc.php');
+$libpath = api_get_path(LIBRARY_PATH);
+include_once ($libpath.'usermanager.lib.php');
+require_once ($libpath.'formvalidator/FormValidator.class.php');
+
+// section for the tabs
+$this_section=SECTION_PLATFORM_ADMIN;
+
+// user permissions
+api_protect_admin_script();
+
+// Database table definitions
+$table_admin	= Database :: get_main_table(TABLE_MAIN_ADMIN);
+$table_user 	= Database :: get_main_table(TABLE_MAIN_USER);
+$table_uf	 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD);
+$table_uf_opt 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
+$table_uf_val 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
+
+$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+
+// Display form
+if(1)
+{
+	$tool_name = get_lang('UserFields');
+	Display :: display_header($tool_name, "");
+	//api_display_tool_title($tool_name);
+	if (isset ($_GET['action']))
+	{
+		$check = Security::check_token('get');
+		if($check) {
+			switch ($_GET['action']) {
+				case 'show_message' :
+					Display :: display_normal_message($_GET['message']);
+					break;
+				case 'show_field' :
+					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_visible'=>'1'))) {
+						Display :: display_confirmation_message(get_lang('FieldShown'));
+					} else {
+						Display :: display_error_message(get_lang('CannotShowField'));
+					}
+					break;
+				case 'hide_field' :
+					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_visible'=>'0'))) {
+						Display :: display_confirmation_message(get_lang('FieldHidden'));
+					} else {
+						Display :: display_error_message(get_lang('CannotHideField'));
+					}
+					break;
+				case 'thaw_field' :
+					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_changeable'=>'1'))) {
+						Display :: display_confirmation_message(get_lang('FieldMadeChangeable'));
+					} else {
+						Display :: display_error_message(get_lang('CannotMakeFieldChangeable'));
+					}
+					break;
+				case 'freeze_field' :
+					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_changeable'=>'0'))) {
+						Display :: display_confirmation_message(get_lang('FieldMadeUnchangeable'));
+					} else {
+						Display :: display_error_message(get_lang('CannotMakeFieldUnchangeable'));
+					}
+					break;
+				case 'moveup' :
+					if (api_is_platform_admin() && !empty($_GET['field_id'])) {
+						if (move_user_field('moveup', $_GET['field_id'])) {
+							Display :: display_confirmation_message(get_lang('FieldMovedUp'));
+						} else {
+							Display :: display_error_message(get_lang('CannotMoveField'));
+						}
+					}
+					break;
+				case 'movedown' :
+					if (api_is_platform_admin() && !empty($_GET['field_id'])) {
+						if (move_user_field('movedown', $_GET['field_id'])) {
+							Display :: display_confirmation_message(get_lang('FieldMovedDown'));
+						} else {
+							Display :: display_error_message(get_lang('CannotMoveField'));
+						}
+					}
+					break;
+				case 'filter_on' :
+					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_filter'=>'1'))) {
+						Display :: display_confirmation_message(get_lang('FieldFilterSetOn'));
+					} else {
+						Display :: display_error_message(get_lang('CannotShowField'));
+					}
+					break;
+				case 'filter_off' :
+					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_filter'=>'0'))) {
+						Display :: display_confirmation_message(get_lang('FieldFilterSetOff'));
+					} else {
+						Display :: display_error_message(get_lang('CannotShowField'));
+					}
+					break;
+
+				case 'delete':
+					if (api_is_platform_admin() && !empty($_GET['field_id'])) {
+						if (delete_user_fields($_GET['field_id'])) {
+							Display :: display_confirmation_message(get_lang('FieldDeleted'));
+						} else {
+							Display :: display_error_message(get_lang('CannotDeleteField'));
+						}
+					}
+					break;
+			}
+			Security::clear_token();
+		}
+	}
+	if (isset ($_POST['action'])) {
+		$check = Security::check_token('get');
+		if($check) {
+			switch ($_POST['action']) {
+				default:
+					break;
+			}
+			Security::clear_token();
+		}
+	}
+
+	// Create an add-field box
+	$form = new FormValidator('add_field','post','','',null,false);
+	$renderer =& $form->defaultRenderer();
+	$renderer->setElementTemplate('<span>{element}</span> ');
+	//$form->addElement('text','label',get_lang('FieldLabel'));
+	//$form->addElement('text','type',get_lang('FieldType'));
+	//$form->addElement('text','title',get_lang('FieldTitle'));
+	//$form->addElement('text','default',get_lang('FieldDefaultValue'));
+	//$form->addElement('submit','submit',get_lang('Search'));
+	$form->addElement('static','search_advanced_link',null,'<a href="user_fields_add.php?action=fill">'.Display::return_icon('fieldadd.gif', get_lang('AddUserField')).get_lang('AddUserField').'</a>');
+	echo '<div class="actions">';
+	$form->display();
+	echo '</div>';
+
+	// Create a sortable table with user-data
+	$parameters['sec_token'] = Security::get_token();
+	$column_show  = array(1,1,1,1,1,1,1,1,1,0,0);
+	$column_order = array(1,2,3,4,5,6,7,8,9,10,11);
+	$extra_fields = UserManager::get_extra_fields(0,100,5,'ASC');
+
+	$number_of_extra_fields = count($extra_fields);
+
+	$table = new SortableTableFromArrayConfig($extra_fields, 5, 50, '', $column_show, $column_order, 'ASC');
+	$table->set_additional_parameters($parameters);
+	$table->set_header(0, '', false);
 	$table->set_header(1, get_lang('FieldLabel'), false);
 	$table->set_header(2, get_lang('FieldType'), false);
-	$table->set_header(3, get_lang('FieldTitle'),false);
-	$table->set_header(4, get_lang('FieldDefaultValue'),false);
+	$table->set_header(3, get_lang('FieldTitle'),false);
+	$table->set_header(4, get_lang('FieldDefaultValue'),false);
 	$table->set_header(5, get_lang('FieldOrder'), false);
 	$table->set_header(6, get_lang('FieldVisibility'), false);
 	$table->set_header(7, get_lang('FieldChangeability'), false);
 	$table->set_header(8, get_lang('FieldFilter'), false);
 	$table->set_header(9, get_lang('Modify'), false);
-	$table->set_column_filter(5, 'order_filter');
-	$table->set_column_filter(6, 'modify_visibility');
-	$table->set_column_filter(7, 'modify_changeability');
-	$table->set_column_filter(8, 'modify_field_filter');
-	$table->set_column_filter(9, 'edit_filter');
-	$table->set_column_filter(2, 'type_filter');
-	$table->display();
-}
-
-
-
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display::display_footer();
-//gateway functions to the UserManager methods (provided for SorteableTable callback mechanism)
-function get_number_of_extra_fields()
-{
-	return UserManager::get_number_of_extra_fields();
-}
-function get_extra_fields($f,$n,$o,$d)
-{
-	return UserManager::get_extra_fields($f,$n,$o,$d);
-}
-
-/**
- * This functions translates the id of the form type into a human readable description
- *
- * @param integer $type the id of the form type
- * @return string the huma readable description of the field type (text, date, select drop-down, ...)
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
- * @version July 2008
- * @since Dokeos 1.8.6
- */
-function type_filter($type)
-{
-	$types[USER_FIELD_TYPE_TEXT]  				= get_lang('FieldTypeText');
-	$types[USER_FIELD_TYPE_TEXTAREA] 			= get_lang('FieldTypeTextarea');
-	$types[USER_FIELD_TYPE_RADIO] 				= get_lang('FieldTypeRadio');
-	$types[USER_FIELD_TYPE_SELECT] 				= get_lang('FieldTypeSelect');
-	$types[USER_FIELD_TYPE_SELECT_MULTIPLE] 	= get_lang('FieldTypeSelectMultiple');
-	$types[USER_FIELD_TYPE_DATE] 				= get_lang('FieldTypeDate');
-	$types[USER_FIELD_TYPE_DATETIME] 			= get_lang('FieldTypeDatetime');
-	$types[USER_FIELD_TYPE_DOUBLE_SELECT] 		= get_lang('FieldTypeDoubleSelect');
-	$types[USER_FIELD_TYPE_DIVIDER] 			= get_lang('FieldTypeDivider');
-
-	return $types[$type];
-}
-
-/**
- * Modify the display order field into up and down arrows
- *
- * @param unknown_type $field_order
- * @param	array	Url parameters
- * @param	array	The results row
- * @return	string	The link
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
- * @version July 2008
- * @since Dokeos 1.8.6
- */
-function order_filter($field_order,$url_params,$row)
-{
-	global $number_of_extra_fields;
-
-	// the up icon only has to appear when the row can be moved up (all but the first row)
-	if ($row[5]<>1)
-	{
-		$return .= '<a href="'.api_get_self().'?action=moveup&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('up.gif', get_lang('Up')).'</a>';
-	}
-	else
-	{
-		$return .= Display::return_icon('blank.gif','',array('width'=>'21px'));
-	}
-
-	// the down icon only has to appear when the row can be moved down (all but the last row)
-	if ($row[5]<>$number_of_extra_fields)
-	{
-		$return .= '<a href="'.api_get_self().'?action=movedown&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('down.gif', get_lang('Down')).'</a>';
-	}
-
-	return $return;
-}
-/**
- * Modify the visible field to show links and icons
- * @param	int 	The current visibility
- * @param	array	Url parameters
- * @param	array	The results row
- * @return	string	The link
- */
-function modify_visibility($visibility,$url_params,$row)
-{
-	return ($visibility?'<a href="'.api_get_self().'?action=hide_field&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('visible.gif', get_lang('Hide')).'</a>':'<a href="'.api_get_self().'?action=show_field&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('invisible.gif', get_lang('Show')).'</a>');
-}
-/**
- * Modify the changeability field to show links and icons
- * @param	int 	The current changeability
- * @param	array	Url parameters
- * @param	array	The results row
- * @return	string	The link
- */
-function modify_changeability($changeability,$url_params,$row)
-{
-	return ($changeability?'<a href="'.api_get_self().'?action=freeze_field&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('right.gif', get_lang('MakeUnchangeable')).'</a>':'<a href="'.api_get_self().'?action=thaw_field&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('wrong.gif', get_lang('MakeChangeable')).'</a>');
-}
-
-function modify_field_filter ($changeability,$url_params,$row)
-{
-	return ($changeability?'<a href="'.api_get_self().'?action=filter_off&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('right.gif', get_lang('FilterOff')).'</a>':'' .
-						   '<a href="'.api_get_self().'?action=filter_on&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('wrong.gif', get_lang('FilterOn')).'</a>');
-}
-
-function edit_filter($id,$url_params,$row)
-{
-	global $charset;
-	$return = '<a href="user_fields_add.php?action=edit&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('edit.gif',get_lang('Edit')).'</a>';
-	$return .= ' <a href="'.api_get_self().'?action=delete&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.gif',get_lang('Delete')).'</a>';
-	return $return;
-}
-/**
- * Move a user defined field up or down
- *
- * @param string $direction the direction we have to move the field to (up or down)
- * @param unknown_type $field_id
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
- * @version July 2008
- * @since Dokeos 1.8.6
- */
-function move_user_field($direction,$field_id)
-{
-	// Databse table definitions
-	$table_user_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
-
-	// check the parameters
-	if (!in_array($direction,array('moveup','movedown')) OR !is_numeric($field_id))
-	{
-		return false;
-	}
-
-	// determine the SQL sort direction
-	if ($direction == 'moveup')
-	{
-		$sortdirection = 'DESC';
-	}
-	else
-	{
-		$sortdirection = 'ASC';
-	}
-
-	$found = false;
-
-	$sql = "SELECT id, field_order FROM $table_user_field ORDER BY field_order $sortdirection";
-	$result = Database::query($sql,__FILE__,__LINE__);
-	while($row = Database::fetch_array($result))
-	{
-		if ($found)
-		{
-			$next_id = $row['id'];
-			$next_order = $row['field_order'];
-			break;
-		}
-
-		if ($field_id == $row['id'])
-		{
-			$this_id = $row['id'];
-			$this_order = $row['field_order'];
-			$found = true;
-		}
-	}
-
-	$sql1 = "UPDATE ".$table_user_field." SET field_order = '".Database::escape_string($next_order)."' WHERE id =  '".Database::escape_string($this_id)."'";
-	$sql2 = "UPDATE ".$table_user_field." SET field_order = '".Database::escape_string($this_order)."' WHERE id =  '".Database::escape_string($next_id)."'";
-	Database::query($sql1,__FILE__,__LINE__);
-	Database::query($sql2,__FILE__,__LINE__);
-
-	return true;
-}
-
-/**
- * Delete a user field (and also the options and values entered by the users)
- *
- * @param integer $field_id the id of the field that has to be deleted
- * @return boolean true if the field has been deleted, false if the field could not be deleted (for whatever reason)
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
- * @version July 2008
- * @since Dokeos 1.8.6
- */
-function delete_user_fields($field_id)
-{
-	// Database table definitions
-	$table_user_field 			= Database::get_main_table(TABLE_MAIN_USER_FIELD);
-	$table_user_field_options	= Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-	$table_user_field_values 	= Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
-
-	// delete the fields
-	$sql = "DELETE FROM $table_user_field WHERE id = '".Database::escape_string($field_id)."'";
-	$result = Database::query($sql,__FILE__,__LINE__);
-	if (Database::affected_rows() == 1)
-	{
-		// delete the field options
-		$sql = "DELETE FROM $table_user_field_options WHERE field_id = '".Database::escape_string($field_id)."'";
-		$result = Database::query($sql,__FILE__,__LINE__);
-
-		// delete the field values
-		$sql = "DELETE FROM $table_user_field_values WHERE field_id = '".Database::escape_string($field_id)."'";
-		$result = Database::query($sql,__FILE__,__LINE__);
-
-		// recalculate the field_order because the value is used to show/hide the up/down icon
-		// and the field_order value cannot be bigger than the number of fields
-		$sql = "SELECT * FROM $table_user_field ORDER BY field_order ASC";
-		$result = Database::query($sql,__FILE__,__LINE__);
-		$i = 1;
-		while($row = Database::fetch_array($result))
-		{
-			$sql_reorder = "UPDATE $table_user_field SET field_order = '".Database::escape_string($i)."' WHERE id = '".Database::escape_string($row['id'])."'";
-			$result_reorder = Database::query($sql_reorder,__FILE__,__LINE__);
-			$i++;
-		}
-
-		// field was deleted so we return true
-		return true;
-	}
-	else
-	{
-		// the field was not deleted so we return false
-		return false;
-	}
-}
-?>
+	$table->set_column_filter(5, 'order_filter');
+	$table->set_column_filter(6, 'modify_visibility');
+	$table->set_column_filter(7, 'modify_changeability');
+	$table->set_column_filter(8, 'modify_field_filter');
+	$table->set_column_filter(9, 'edit_filter');
+	$table->set_column_filter(2, 'type_filter');
+	$table->display();
+}
+
+
+
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display::display_footer();
+//gateway functions to the UserManager methods (provided for SorteableTable callback mechanism)
+function get_number_of_extra_fields()
+{
+	return UserManager::get_number_of_extra_fields();
+}
+function get_extra_fields($f,$n,$o,$d)
+{
+	return UserManager::get_extra_fields($f,$n,$o,$d);
+}
+
+/**
+ * This functions translates the id of the form type into a human readable description
+ *
+ * @param integer $type the id of the form type
+ * @return string the huma readable description of the field type (text, date, select drop-down, ...)
+ *
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+ * @version July 2008
+ * @since Dokeos 1.8.6
+ */
+function type_filter($type)
+{
+	$types[USER_FIELD_TYPE_TEXT]  				= get_lang('FieldTypeText');
+	$types[USER_FIELD_TYPE_TEXTAREA] 			= get_lang('FieldTypeTextarea');
+	$types[USER_FIELD_TYPE_RADIO] 				= get_lang('FieldTypeRadio');
+	$types[USER_FIELD_TYPE_SELECT] 				= get_lang('FieldTypeSelect');
+	$types[USER_FIELD_TYPE_SELECT_MULTIPLE] 	= get_lang('FieldTypeSelectMultiple');
+	$types[USER_FIELD_TYPE_DATE] 				= get_lang('FieldTypeDate');
+	$types[USER_FIELD_TYPE_DATETIME] 			= get_lang('FieldTypeDatetime');
+	$types[USER_FIELD_TYPE_DOUBLE_SELECT] 		= get_lang('FieldTypeDoubleSelect');
+	$types[USER_FIELD_TYPE_DIVIDER] 			= get_lang('FieldTypeDivider');
+
+	return $types[$type];
+}
+
+/**
+ * Modify the display order field into up and down arrows
+ *
+ * @param unknown_type $field_order
+ * @param	array	Url parameters
+ * @param	array	The results row
+ * @return	string	The link
+ *
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+ * @version July 2008
+ * @since Dokeos 1.8.6
+ */
+function order_filter($field_order,$url_params,$row)
+{
+	global $number_of_extra_fields;
+
+	// the up icon only has to appear when the row can be moved up (all but the first row)
+	if ($row[5]<>1)
+	{
+		$return .= '<a href="'.api_get_self().'?action=moveup&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('up.gif', get_lang('Up')).'</a>';
+	}
+	else
+	{
+		$return .= Display::return_icon('blank.gif','',array('width'=>'21px'));
+	}
+
+	// the down icon only has to appear when the row can be moved down (all but the last row)
+	if ($row[5]<>$number_of_extra_fields)
+	{
+		$return .= '<a href="'.api_get_self().'?action=movedown&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('down.gif', get_lang('Down')).'</a>';
+	}
+
+	return $return;
+}
+/**
+ * Modify the visible field to show links and icons
+ * @param	int 	The current visibility
+ * @param	array	Url parameters
+ * @param	array	The results row
+ * @return	string	The link
+ */
+function modify_visibility($visibility,$url_params,$row)
+{
+	return ($visibility?'<a href="'.api_get_self().'?action=hide_field&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('visible.gif', get_lang('Hide')).'</a>':'<a href="'.api_get_self().'?action=show_field&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('invisible.gif', get_lang('Show')).'</a>');
+}
+/**
+ * Modify the changeability field to show links and icons
+ * @param	int 	The current changeability
+ * @param	array	Url parameters
+ * @param	array	The results row
+ * @return	string	The link
+ */
+function modify_changeability($changeability,$url_params,$row)
+{
+	return ($changeability?'<a href="'.api_get_self().'?action=freeze_field&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('right.gif', get_lang('MakeUnchangeable')).'</a>':'<a href="'.api_get_self().'?action=thaw_field&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('wrong.gif', get_lang('MakeChangeable')).'</a>');
+}
+
+function modify_field_filter ($changeability,$url_params,$row)
+{
+	return ($changeability?'<a href="'.api_get_self().'?action=filter_off&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('right.gif', get_lang('FilterOff')).'</a>':'' .
+						   '<a href="'.api_get_self().'?action=filter_on&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('wrong.gif', get_lang('FilterOn')).'</a>');
+}
+
+function edit_filter($id,$url_params,$row)
+{
+	global $charset;
+	$return = '<a href="user_fields_add.php?action=edit&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('edit.gif',get_lang('Edit')).'</a>';
+	$return .= ' <a href="'.api_get_self().'?action=delete&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.gif',get_lang('Delete')).'</a>';
+	return $return;
+}
+/**
+ * Move a user defined field up or down
+ *
+ * @param string $direction the direction we have to move the field to (up or down)
+ * @param unknown_type $field_id
+ *
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+ * @version July 2008
+ * @since Dokeos 1.8.6
+ */
+function move_user_field($direction,$field_id)
+{
+	// Databse table definitions
+	$table_user_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
+
+	// check the parameters
+	if (!in_array($direction,array('moveup','movedown')) OR !is_numeric($field_id))
+	{
+		return false;
+	}
+
+	// determine the SQL sort direction
+	if ($direction == 'moveup')
+	{
+		$sortdirection = 'DESC';
+	}
+	else
+	{
+		$sortdirection = 'ASC';
+	}
+
+	$found = false;
+
+	$sql = "SELECT id, field_order FROM $table_user_field ORDER BY field_order $sortdirection";
+	$result = Database::query($sql,__FILE__,__LINE__);
+	while($row = Database::fetch_array($result))
+	{
+		if ($found)
+		{
+			$next_id = $row['id'];
+			$next_order = $row['field_order'];
+			break;
+		}
+
+		if ($field_id == $row['id'])
+		{
+			$this_id = $row['id'];
+			$this_order = $row['field_order'];
+			$found = true;
+		}
+	}
+
+	$sql1 = "UPDATE ".$table_user_field." SET field_order = '".Database::escape_string($next_order)."' WHERE id =  '".Database::escape_string($this_id)."'";
+	$sql2 = "UPDATE ".$table_user_field." SET field_order = '".Database::escape_string($this_order)."' WHERE id =  '".Database::escape_string($next_id)."'";
+	Database::query($sql1,__FILE__,__LINE__);
+	Database::query($sql2,__FILE__,__LINE__);
+
+	return true;
+}
+
+/**
+ * Delete a user field (and also the options and values entered by the users)
+ *
+ * @param integer $field_id the id of the field that has to be deleted
+ * @return boolean true if the field has been deleted, false if the field could not be deleted (for whatever reason)
+ *
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+ * @version July 2008
+ * @since Dokeos 1.8.6
+ */
+function delete_user_fields($field_id)
+{
+	// Database table definitions
+	$table_user_field 			= Database::get_main_table(TABLE_MAIN_USER_FIELD);
+	$table_user_field_options	= Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
+	$table_user_field_values 	= Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
+
+	// delete the fields
+	$sql = "DELETE FROM $table_user_field WHERE id = '".Database::escape_string($field_id)."'";
+	$result = Database::query($sql,__FILE__,__LINE__);
+	if (Database::affected_rows() == 1)
+	{
+		// delete the field options
+		$sql = "DELETE FROM $table_user_field_options WHERE field_id = '".Database::escape_string($field_id)."'";
+		$result = Database::query($sql,__FILE__,__LINE__);
+
+		// delete the field values
+		$sql = "DELETE FROM $table_user_field_values WHERE field_id = '".Database::escape_string($field_id)."'";
+		$result = Database::query($sql,__FILE__,__LINE__);
+
+		// recalculate the field_order because the value is used to show/hide the up/down icon
+		// and the field_order value cannot be bigger than the number of fields
+		$sql = "SELECT * FROM $table_user_field ORDER BY field_order ASC";
+		$result = Database::query($sql,__FILE__,__LINE__);
+		$i = 1;
+		while($row = Database::fetch_array($result))
+		{
+			$sql_reorder = "UPDATE $table_user_field SET field_order = '".Database::escape_string($i)."' WHERE id = '".Database::escape_string($row['id'])."'";
+			$result_reorder = Database::query($sql_reorder,__FILE__,__LINE__);
+			$i++;
+		}
+
+		// field was deleted so we return true
+		return true;
+	}
+	else
+	{
+		// the field was not deleted so we return false
+		return false;
+	}
+}
+?>

+ 741 - 741
main/admin/user_list.php

@@ -1,757 +1,757 @@
-<?php // $Id: user_list.php 22292 2009-07-22 18:32:32Z herodoto $
-/* For licensing terms, see /dokeos_license.txt */
-/**
-==============================================================================
-	@author Bart Mollet
-*	@package dokeos.admin
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file = array ('registration','admin');
-$cidReset = true;
-require ('../inc/global.inc.php');
-require_once (api_get_path(LIBRARY_PATH).'sortabletable.class.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-require_once (api_get_path(LIBRARY_PATH).'security.lib.php');
-require_once(api_get_path(LIBRARY_PATH).'xajax/xajax.inc.php');
-require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
-$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.js" type="text/javascript" language="javascript"></script>';
-$htmlHeadXtra[] = '<script type="text/javascript">
-function load_course_list (div_course,my_user_id) {
-	 $.ajax({
-		contentType: "application/x-www-form-urlencoded",
-		beforeSend: function(objeto) {
-		$("div#"+div_course).html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
-		type: "POST",
-		url: "course_user_list.php",
-		data: "user_id="+my_user_id,
-		success: function(datos) {
-			$("div#"+div_course).html(datos);
-			$("div#div_"+my_user_id).attr("class","blackboard_show");
-			$("div#div_"+my_user_id).attr("style","");
-		}
-	});
-}
-function clear_course_list (div_course) {
-	$("div#"+div_course).html("&nbsp;");
-	$("div#"+div_course).hide("");
-}
-</script>';
-$htmlHeadXtra[] = '<style type="text/css" media="screen, projection">
-.blackboard_show {
-	float:left;
-	position:absolute;
-	border:1px solid black;
-	width: 200px;
-	background-color:white;
-	z-index:99; padding: 3px;
-	display: inline;
-}
-.blackboard_hide {
-	display: none;
-}
-';
-// xajax
-$xajax = new xajax();
-$xajax->registerFunction('courses_of_user');
-//$xajax->registerFunction('empty_courses_of_user');
-$xajax->processRequests();
-
-
-/**
- * Get a formatted list of courses for given user
- * @param   int     User ID
- * @return  resource    XAJAX response
- */
-function courses_of_user($arg)
-{
-	// do some stuff based on $arg like query data from a database and
-	// put it into a variable like $newContent
-    //$newContent = 'werkt het? en met een beetje meer text, wordt dat goed opgelost? ';
-    $personal_course_list = UserManager::get_personal_session_course_list($arg);
-    $newContent = '';
-    if(count($personal_course_list)>0)
-    {
-	    foreach ($personal_course_list as $key=>$course)
-	    {
-	    	$newContent .= $course['i'].'<br />';
-	    }
-    }
-    else
-    {
-    	$newContent .= '- '.get_lang('None').' -<br />';
-    }
-    $newContent = api_convert_encoding($newContent,'utf-8',api_get_setting('platform_charset'));
-
-	// Instantiate the xajaxResponse object
-	$objResponse = new xajaxResponse();
-
-	// add a command to the response to assign the innerHTML attribute of
-	// the element with id="SomeElementId" to whatever the new content is
-	$objResponse->addAssign("user".$arg,"innerHTML", $newContent);
-	$objResponse->addReplace("coursesofuser".$arg,"alt", $newContent);
-	$objResponse->addReplace("coursesofuser".$arg,"title", $newContent);
-
-	$objResponse->addAssign("user".$arg,"style.display", "block");
-
-	//return the  xajaxResponse object
-	return $objResponse;
-}
-/**
- * Empties the XAJAX object representing the courses list
- * @param   int     User ID
- * @return  resource    XAJAX object
- */
-function empty_courses_of_user($arg)
-{
-	// do some stuff based on $arg like query data from a database and
-	// put it into a variable like $newContent
-    $newContent = '';
-	// Instantiate the xajaxResponse object
-	$objResponse = new xajaxResponse();
-	// add a command to the response to assign the innerHTML attribute of
-	// the element with id="SomeElementId" to whatever the new content is
-	$objResponse->addAssign("user".$arg,"innerHTML", $newContent);
-
-
-	//return the  xajaxResponse object
-	return $objResponse;
-}
-
-
-$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
-$htmlHeadXtra[] = '<style>
-.tooltipLinkInner {
-	position:relative;
-	float:left;
-	color:blue;
-	text-decoration:none;
-}
-</style>';
-
-$this_section = SECTION_PLATFORM_ADMIN;
-api_protect_admin_script(true);
-
-/**
-*	Make sure this function is protected because it does NOT check password!
-*
-*	This function defines globals.
-*   @param  int     User ID
-*   @return bool    False on failure, redirection on success
-*	@author Evie Embrechts
-*   @author Yannick Warnier <yannick.warnier@dokeos.com>
-*/
-function login_user($user_id) {
-	//init ---------------------------------------------------------------------
-    //Load $_user to be sure we clean it before logging in
-	global $uidReset, $loginFailed, $_configuration, $_user;
-
-	$main_user_table = Database :: get_main_table(TABLE_MAIN_USER);
-	$main_admin_table = Database :: get_main_table(TABLE_MAIN_ADMIN);
-	$track_e_login_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-
-	//logic --------------------------------------------------------------------
-	unset($_user['user_id']); // uid not in session ? prevent any hacking
-	if (!isset ($user_id)) {
-		$uidReset = true;
-		return;
-	}
-    if ($user_id != strval(intval($user_id))) {
-    	return false;
-    }
-
-	$sql_query = "SELECT * FROM $main_user_table WHERE user_id='$user_id'";
-	$sql_result = Database::query($sql_query, __FILE__, __LINE__);
-	$result = Database :: fetch_array($sql_result);
-
-    // check if the user is allowed to 'login_as'
-    $can_login_as = (api_is_platform_admin() OR (api_is_session_admin() && $result['status'] == 5 ));
-    if (!$can_login_as) { return false; }
-
-	$firstname = $result['firstname'];
-	$lastname = $result['lastname'];
-	$user_id = $result['user_id'];
-
+<?php // $Id: user_list.php 22292 2009-07-22 18:32:32Z herodoto $
+/* For licensing terms, see /dokeos_license.txt */
+/**
+==============================================================================
+	@author Bart Mollet
+*	@package dokeos.admin
+==============================================================================
+*/
+
+// name of the language file that needs to be included
+$language_file = array ('registration','admin');
+$cidReset = true;
+require ('../inc/global.inc.php');
+require_once (api_get_path(LIBRARY_PATH).'sortabletable.class.php');
+require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+require_once (api_get_path(LIBRARY_PATH).'security.lib.php');
+require_once(api_get_path(LIBRARY_PATH).'xajax/xajax.inc.php');
+require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
+$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.js" type="text/javascript" language="javascript"></script>';
+$htmlHeadXtra[] = '<script type="text/javascript">
+function load_course_list (div_course,my_user_id) {
+	 $.ajax({
+		contentType: "application/x-www-form-urlencoded",
+		beforeSend: function(objeto) {
+		$("div#"+div_course).html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
+		type: "POST",
+		url: "course_user_list.php",
+		data: "user_id="+my_user_id,
+		success: function(datos) {
+			$("div#"+div_course).html(datos);
+			$("div#div_"+my_user_id).attr("class","blackboard_show");
+			$("div#div_"+my_user_id).attr("style","");
+		}
+	});
+}
+function clear_course_list (div_course) {
+	$("div#"+div_course).html("&nbsp;");
+	$("div#"+div_course).hide("");
+}
+</script>';
+$htmlHeadXtra[] = '<style type="text/css" media="screen, projection">
+.blackboard_show {
+	float:left;
+	position:absolute;
+	border:1px solid black;
+	width: 200px;
+	background-color:white;
+	z-index:99; padding: 3px;
+	display: inline;
+}
+.blackboard_hide {
+	display: none;
+}
+';
+// xajax
+$xajax = new xajax();
+$xajax->registerFunction('courses_of_user');
+//$xajax->registerFunction('empty_courses_of_user');
+$xajax->processRequests();
+
+
+/**
+ * Get a formatted list of courses for given user
+ * @param   int     User ID
+ * @return  resource    XAJAX response
+ */
+function courses_of_user($arg)
+{
+	// do some stuff based on $arg like query data from a database and
+	// put it into a variable like $newContent
+    //$newContent = 'werkt het? en met een beetje meer text, wordt dat goed opgelost? ';
+    $personal_course_list = UserManager::get_personal_session_course_list($arg);
+    $newContent = '';
+    if(count($personal_course_list)>0)
+    {
+	    foreach ($personal_course_list as $key=>$course)
+	    {
+	    	$newContent .= $course['i'].'<br />';
+	    }
+    }
+    else
+    {
+    	$newContent .= '- '.get_lang('None').' -<br />';
+    }
+    $newContent = api_convert_encoding($newContent,'utf-8',api_get_setting('platform_charset'));
+
+	// Instantiate the xajaxResponse object
+	$objResponse = new xajaxResponse();
+
+	// add a command to the response to assign the innerHTML attribute of
+	// the element with id="SomeElementId" to whatever the new content is
+	$objResponse->addAssign("user".$arg,"innerHTML", $newContent);
+	$objResponse->addReplace("coursesofuser".$arg,"alt", $newContent);
+	$objResponse->addReplace("coursesofuser".$arg,"title", $newContent);
+
+	$objResponse->addAssign("user".$arg,"style.display", "block");
+
+	//return the  xajaxResponse object
+	return $objResponse;
+}
+/**
+ * Empties the XAJAX object representing the courses list
+ * @param   int     User ID
+ * @return  resource    XAJAX object
+ */
+function empty_courses_of_user($arg)
+{
+	// do some stuff based on $arg like query data from a database and
+	// put it into a variable like $newContent
+    $newContent = '';
+	// Instantiate the xajaxResponse object
+	$objResponse = new xajaxResponse();
+	// add a command to the response to assign the innerHTML attribute of
+	// the element with id="SomeElementId" to whatever the new content is
+	$objResponse->addAssign("user".$arg,"innerHTML", $newContent);
+
+
+	//return the  xajaxResponse object
+	return $objResponse;
+}
+
+
+$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
+$htmlHeadXtra[] = '<style>
+.tooltipLinkInner {
+	position:relative;
+	float:left;
+	color:blue;
+	text-decoration:none;
+}
+</style>';
+
+$this_section = SECTION_PLATFORM_ADMIN;
+api_protect_admin_script(true);
+
+/**
+*	Make sure this function is protected because it does NOT check password!
+*
+*	This function defines globals.
+*   @param  int     User ID
+*   @return bool    False on failure, redirection on success
+*	@author Evie Embrechts
+*   @author Yannick Warnier <yannick.warnier@dokeos.com>
+*/
+function login_user($user_id) {
+	//init ---------------------------------------------------------------------
+    //Load $_user to be sure we clean it before logging in
+	global $uidReset, $loginFailed, $_configuration, $_user;
+
+	$main_user_table = Database :: get_main_table(TABLE_MAIN_USER);
+	$main_admin_table = Database :: get_main_table(TABLE_MAIN_ADMIN);
+	$track_e_login_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
+
+	//logic --------------------------------------------------------------------
+	unset($_user['user_id']); // uid not in session ? prevent any hacking
+	if (!isset ($user_id)) {
+		$uidReset = true;
+		return;
+	}
+    if ($user_id != strval(intval($user_id))) {
+    	return false;
+    }
+
+	$sql_query = "SELECT * FROM $main_user_table WHERE user_id='$user_id'";
+	$sql_result = Database::query($sql_query, __FILE__, __LINE__);
+	$result = Database :: fetch_array($sql_result);
+
+    // check if the user is allowed to 'login_as'
+    $can_login_as = (api_is_platform_admin() OR (api_is_session_admin() && $result['status'] == 5 ));
+    if (!$can_login_as) { return false; }
+
+	$firstname = $result['firstname'];
+	$lastname = $result['lastname'];
+	$user_id = $result['user_id'];
+
 	//$message = "Attempting to login as ".api_get_person_name($firstname, $lastname)." (id ".$user_id.")";
 	if (api_is_western_name_order()) {
-		$message = sprintf(get_lang('AttemptingToLoginAs'),$firstname,$lastname,$user_id);
+		$message = sprintf(get_lang('AttemptingToLoginAs'),$firstname,$lastname,$user_id);
 	} else {
 		$message = sprintf(get_lang('AttemptingToLoginAs'), $lastname, $firstname, $user_id);
 	}
-
-	$loginFailed = false;
-	$uidReset = false;
-
-	if ($user_id) { // a uid is given (log in succeeded)
-		if ($_configuration['tracking_enabled']) {
-			$sql_query = "SELECT user.*, a.user_id is_admin,
-				UNIX_TIMESTAMP(login.login_date) login_date
-				FROM $main_user_table
-				LEFT JOIN $main_admin_table a
-				ON user.user_id = a.user_id
-				LEFT JOIN $track_e_login_table login
-				ON user.user_id = login.login_user_id
-				WHERE user.user_id = '".$user_id."'
-				ORDER BY login.login_date DESC LIMIT 1";
-		} else {
-			$sql_query = "SELECT user.*, a.user_id is_admin
-				FROM $main_user_table
-				LEFT JOIN $main_admin_table a
-				ON user.user_id = a.user_id
-				WHERE user.user_id = '".$user_id."'";
-		}
-
-		$sql_result = Database::query($sql_query, __FILE__, __LINE__);
-
-
-		if (Database::num_rows($sql_result) > 0) {
-			// Extracting the user data
-
-			$user_data = Database::fetch_array($sql_result);
-
-            //Delog the current user
-
-			LoginDelete($_SESSION["_user"]["user_id"]);
-
-			// Cleaning session variables
-			unset($_SESSION['_user']);
-			unset($_SESSION['is_platformAdmin']);
-			unset($_SESSION['is_allowedCreateCourse']);
-			unset($_SESSION['_uid']);
-
-
-			$_user['firstName'] 	= $user_data['firstname'];
-			$_user['lastName'] 		= $user_data['lastname'];
-			$_user['mail'] 			= $user_data['email'];
-			$_user['lastLogin'] 	= $user_data['login_date'];
-			$_user['official_code'] = $user_data['official_code'];
-			$_user['picture_uri'] 	= $user_data['picture_uri'];
-			$_user['user_id']		= $user_data['user_id'];
-            $_user['status']        = $user_data['status'];
-
-			$is_platformAdmin = (bool) (!is_null($user_data['is_admin']));
-			$is_allowedCreateCourse = (bool) ($user_data['status'] == 1);
-
-			// Filling session variables with new data
-			$_SESSION['_uid'] = $user_id;
-			$_SESSION['_user'] = $_user;
-			$_SESSION['is_platformAdmin'] = $is_platformAdmin;
-			$_SESSION['is_allowedCreateCourse'] = $is_allowedCreateCourse;
-			$_SESSION['login_as'] = true; // will be usefull later to know if the user is actually an admin or not (example reporting)s
-
-			$target_url = api_get_path(WEB_PATH)."user_portal.php";
-			//$message .= "<br/>Login successful. Go to <a href=\"$target_url\">$target_url</a>";
-			$message .= '<br />'.sprintf(get_lang('LoginSuccessfulGoToX'),'<a href="'.$target_url.'">'.$target_url.'</a>');
-			Display :: display_header(get_lang('UserList'));
-			Display :: display_normal_message($message,false);
-			Display :: display_footer();
-			exit;
-		} else {
-			exit ("<br />WARNING UNDEFINED UID !! ");
-		}
-	}
-}
-/**
- * Get the total number of users on the platform
- * @see SortableTable#get_total_number_of_items()
- */
-function get_number_of_users()
-{
-	$user_table = Database :: get_main_table(TABLE_MAIN_USER);
-	$sql = "SELECT COUNT(u.user_id) AS total_number_of_items FROM $user_table u";
-
-	// adding the filter to see the user's only of the current access_url
-    global $_configuration;
-    if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
-    	$access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-    	$sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
-    }
-
-	if ( isset ($_GET['keyword'])) {
-		$keyword = Database::escape_string($_GET['keyword']);
-		$sql .= " WHERE (u.firstname LIKE '%".$keyword."%' OR u.lastname LIKE '%".$keyword."%'  OR u.username LIKE '%".$keyword."%' OR u.email LIKE '%".$keyword."%'  OR u.official_code LIKE '%".$keyword."%') ";
-	} elseif (isset ($_GET['keyword_firstname'])) {
-		$admin_table = Database :: get_main_table(TABLE_MAIN_ADMIN);
-		$keyword_firstname = Database::escape_string($_GET['keyword_firstname']);
-		$keyword_lastname = Database::escape_string($_GET['keyword_lastname']);
-		$keyword_email = Database::escape_string($_GET['keyword_email']);
-		$keyword_officialcode = Database::escape_string($_GET['keyword_officialcode']);
-		$keyword_username = Database::escape_string($_GET['keyword_username']);
-		$keyword_status = Database::escape_string($_GET['keyword_status']);
-		$query_admin_table = '';
-		$keyword_admin = '';
-		if ($keyword_status == SESSIONADMIN) {
-			$keyword_status = '%';
-			$query_admin_table = " , $admin_table a ";
-			$keyword_admin = ' AND a.user_id = u.user_id ';
-		}
-		$keyword_active = isset($_GET['keyword_active']);
-		$keyword_inactive = isset($_GET['keyword_inactive']);
-		$sql .= $query_admin_table .
-				" WHERE (u.firstname LIKE '%".$keyword_firstname."%' " .
-				"AND u.lastname LIKE '%".$keyword_lastname."%' " .
-				"AND u.username LIKE '%".$keyword_username."%'  " .
-				"AND u.email LIKE '%".$keyword_email."%'   " .
-				"AND u.official_code LIKE '%".$keyword_officialcode."%'    " .
-				"AND u.status LIKE '".$keyword_status."'" .
-				$keyword_admin;
-		if($keyword_active && !$keyword_inactive) {
-			$sql .= " AND u.active='1'";
-		} elseif($keyword_inactive && !$keyword_active) {
-			$sql .= " AND u.active='0'";
-		}
-		$sql .= " ) ";
-	}
-
-    // adding the filter to see the user's only of the current access_url
-	if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
-    		$sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
-    }
-
-	$res = Database::query($sql, __FILE__, __LINE__);
-	$obj = Database::fetch_object($res);
-	return $obj->total_number_of_items;
-}
-/**
- * Get the users to display on the current page (fill the sortable-table)
- * @param   int     offset of first user to recover
- * @param   int     Number of users to get
- * @param   int     Column to sort on
- * @param   string  Order (ASC,DESC)
- * @see SortableTable#get_table_data($from)
- */
-function get_user_data($from, $number_of_items, $column, $direction)
-{
-	$user_table = Database :: get_main_table(TABLE_MAIN_USER);
-	$sql = "SELECT
-                 u.user_id				AS col0,
-                 u.official_code		AS col1,
+
+	$loginFailed = false;
+	$uidReset = false;
+
+	if ($user_id) { // a uid is given (log in succeeded)
+		if ($_configuration['tracking_enabled']) {
+			$sql_query = "SELECT user.*, a.user_id is_admin,
+				UNIX_TIMESTAMP(login.login_date) login_date
+				FROM $main_user_table
+				LEFT JOIN $main_admin_table a
+				ON user.user_id = a.user_id
+				LEFT JOIN $track_e_login_table login
+				ON user.user_id = login.login_user_id
+				WHERE user.user_id = '".$user_id."'
+				ORDER BY login.login_date DESC LIMIT 1";
+		} else {
+			$sql_query = "SELECT user.*, a.user_id is_admin
+				FROM $main_user_table
+				LEFT JOIN $main_admin_table a
+				ON user.user_id = a.user_id
+				WHERE user.user_id = '".$user_id."'";
+		}
+
+		$sql_result = Database::query($sql_query, __FILE__, __LINE__);
+
+
+		if (Database::num_rows($sql_result) > 0) {
+			// Extracting the user data
+
+			$user_data = Database::fetch_array($sql_result);
+
+            //Delog the current user
+
+			LoginDelete($_SESSION["_user"]["user_id"]);
+
+			// Cleaning session variables
+			unset($_SESSION['_user']);
+			unset($_SESSION['is_platformAdmin']);
+			unset($_SESSION['is_allowedCreateCourse']);
+			unset($_SESSION['_uid']);
+
+
+			$_user['firstName'] 	= $user_data['firstname'];
+			$_user['lastName'] 		= $user_data['lastname'];
+			$_user['mail'] 			= $user_data['email'];
+			$_user['lastLogin'] 	= $user_data['login_date'];
+			$_user['official_code'] = $user_data['official_code'];
+			$_user['picture_uri'] 	= $user_data['picture_uri'];
+			$_user['user_id']		= $user_data['user_id'];
+            $_user['status']        = $user_data['status'];
+
+			$is_platformAdmin = (bool) (!is_null($user_data['is_admin']));
+			$is_allowedCreateCourse = (bool) ($user_data['status'] == 1);
+
+			// Filling session variables with new data
+			$_SESSION['_uid'] = $user_id;
+			$_SESSION['_user'] = $_user;
+			$_SESSION['is_platformAdmin'] = $is_platformAdmin;
+			$_SESSION['is_allowedCreateCourse'] = $is_allowedCreateCourse;
+			$_SESSION['login_as'] = true; // will be usefull later to know if the user is actually an admin or not (example reporting)s
+
+			$target_url = api_get_path(WEB_PATH)."user_portal.php";
+			//$message .= "<br/>Login successful. Go to <a href=\"$target_url\">$target_url</a>";
+			$message .= '<br />'.sprintf(get_lang('LoginSuccessfulGoToX'),'<a href="'.$target_url.'">'.$target_url.'</a>');
+			Display :: display_header(get_lang('UserList'));
+			Display :: display_normal_message($message,false);
+			Display :: display_footer();
+			exit;
+		} else {
+			exit ("<br />WARNING UNDEFINED UID !! ");
+		}
+	}
+}
+/**
+ * Get the total number of users on the platform
+ * @see SortableTable#get_total_number_of_items()
+ */
+function get_number_of_users()
+{
+	$user_table = Database :: get_main_table(TABLE_MAIN_USER);
+	$sql = "SELECT COUNT(u.user_id) AS total_number_of_items FROM $user_table u";
+
+	// adding the filter to see the user's only of the current access_url
+    global $_configuration;
+    if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
+    	$access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+    	$sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
+    }
+
+	if ( isset ($_GET['keyword'])) {
+		$keyword = Database::escape_string($_GET['keyword']);
+		$sql .= " WHERE (u.firstname LIKE '%".$keyword."%' OR u.lastname LIKE '%".$keyword."%'  OR u.username LIKE '%".$keyword."%' OR u.email LIKE '%".$keyword."%'  OR u.official_code LIKE '%".$keyword."%') ";
+	} elseif (isset ($_GET['keyword_firstname'])) {
+		$admin_table = Database :: get_main_table(TABLE_MAIN_ADMIN);
+		$keyword_firstname = Database::escape_string($_GET['keyword_firstname']);
+		$keyword_lastname = Database::escape_string($_GET['keyword_lastname']);
+		$keyword_email = Database::escape_string($_GET['keyword_email']);
+		$keyword_officialcode = Database::escape_string($_GET['keyword_officialcode']);
+		$keyword_username = Database::escape_string($_GET['keyword_username']);
+		$keyword_status = Database::escape_string($_GET['keyword_status']);
+		$query_admin_table = '';
+		$keyword_admin = '';
+		if ($keyword_status == SESSIONADMIN) {
+			$keyword_status = '%';
+			$query_admin_table = " , $admin_table a ";
+			$keyword_admin = ' AND a.user_id = u.user_id ';
+		}
+		$keyword_active = isset($_GET['keyword_active']);
+		$keyword_inactive = isset($_GET['keyword_inactive']);
+		$sql .= $query_admin_table .
+				" WHERE (u.firstname LIKE '%".$keyword_firstname."%' " .
+				"AND u.lastname LIKE '%".$keyword_lastname."%' " .
+				"AND u.username LIKE '%".$keyword_username."%'  " .
+				"AND u.email LIKE '%".$keyword_email."%'   " .
+				"AND u.official_code LIKE '%".$keyword_officialcode."%'    " .
+				"AND u.status LIKE '".$keyword_status."'" .
+				$keyword_admin;
+		if($keyword_active && !$keyword_inactive) {
+			$sql .= " AND u.active='1'";
+		} elseif($keyword_inactive && !$keyword_active) {
+			$sql .= " AND u.active='0'";
+		}
+		$sql .= " ) ";
+	}
+
+    // adding the filter to see the user's only of the current access_url
+	if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
+    		$sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
+    }
+
+	$res = Database::query($sql, __FILE__, __LINE__);
+	$obj = Database::fetch_object($res);
+	return $obj->total_number_of_items;
+}
+/**
+ * Get the users to display on the current page (fill the sortable-table)
+ * @param   int     offset of first user to recover
+ * @param   int     Number of users to get
+ * @param   int     Column to sort on
+ * @param   string  Order (ASC,DESC)
+ * @see SortableTable#get_table_data($from)
+ */
+function get_user_data($from, $number_of_items, $column, $direction)
+{
+	$user_table = Database :: get_main_table(TABLE_MAIN_USER);
+	$sql = "SELECT
+                 u.user_id				AS col0,
+                 u.official_code		AS col1,
 				 ".(api_is_western_name_order()
                  ? "u.firstname 			AS col2,
                  u.lastname 			AS col3,"
                  : "u.lastname 			AS col2,
                  u.firstname 			AS col3,")."
-                 u.username				AS col4,
-                 u.email				AS col5,
-                 u.status				AS col6,
-                 u.active				AS col7,
-                 u.user_id				AS col8 ".
-                 ", u.expiration_date      AS exp ".
-            " FROM $user_table u ";
-
-    // adding the filter to see the user's only of the current access_url
-    global $_configuration;
-    if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
-    	$access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-    	$sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
-    }
-
-	if (isset ($_GET['keyword'])) {
-		$keyword = Database::escape_string($_GET['keyword']);
-		$sql .= " WHERE (u.firstname LIKE '%".$keyword."%' OR u.lastname LIKE '%".$keyword."%'  OR u.username LIKE '%".$keyword."%'  OR u.official_code LIKE '%".$keyword."%' OR u.email LIKE '%".$keyword."%' )";
-	} elseif (isset ($_GET['keyword_firstname'])) {
-		$admin_table = Database :: get_main_table(TABLE_MAIN_ADMIN);
-		$keyword_firstname = Database::escape_string($_GET['keyword_firstname']);
-		$keyword_lastname = Database::escape_string($_GET['keyword_lastname']);
-		$keyword_email = Database::escape_string($_GET['keyword_email']);
-		$keyword_officialcode = Database::escape_string($_GET['keyword_officialcode']);
-		$keyword_username = Database::escape_string($_GET['keyword_username']);
-		$keyword_status = Database::escape_string($_GET['keyword_status']);
-		$query_admin_table = '';
-		$keyword_admin = '';
-
-		if ($keyword_status == SESSIONADMIN) {
-			$keyword_status = '%';
-			$query_admin_table = " , $admin_table a ";
-			$keyword_admin = ' AND a.user_id = u.user_id ';
-		}
-		$keyword_active = isset($_GET['keyword_active']);
-		$keyword_inactive = isset($_GET['keyword_inactive']);
-		$sql .= $query_admin_table." WHERE (u.firstname LIKE '%".$keyword_firstname."%' " .
-				"AND u.lastname LIKE '%".$keyword_lastname."%' " .
-				"AND u.username LIKE '%".$keyword_username."%'  " .
-				"AND u.email LIKE '%".$keyword_email."%'   " .
-				"AND u.official_code LIKE '%".$keyword_officialcode."%'    " .
-				"AND u.status LIKE '".$keyword_status."'" .
-				$keyword_admin;
-
-		if ($keyword_active && !$keyword_inactive) {
-			$sql .= " AND u.active='1'";
-		} elseif($keyword_inactive && !$keyword_active) {
-			$sql .= " AND u.active='0'";
-		}
-		$sql .= " ) ";
-	}
-
-    // adding the filter to see the user's only of the current access_url
-	if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
-    		$sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
-    }
-
-    if (!in_array($direction, array('ASC','DESC'))) {
-    	$direction = 'ASC';
-    }
-    $column = intval($column);
-    $from = intval($from);
-    $number_of_items = intval($number_of_items);
-
-	$sql .= " ORDER BY col$column $direction ";
-	$sql .= " LIMIT $from,$number_of_items";
-	$res = Database::query($sql, __FILE__, __LINE__);
-
-	$users = array ();
-    $t = time();
-	while ($user = Database::fetch_row($res)) {
-        if ($user[7] == 1 && $user[9] != '0000-00-00 00:00:00') {
-            // check expiration date
-            $expiration_time = convert_mysql_date($user[9]);
-            // if expiration date is passed, store a special value for active field
-            if ($expiration_time < $t) {
-        	   $user[7] = '-1';
-            }
-        }
-        // forget about the expiration date field
-        $users[] = array($user[0],$user[1],$user[2],$user[3],$user[4],$user[5],$user[6],$user[7],$user[8]);
-	}
-	return $users;
-}
-/**
-* Returns a mailto-link
-* @param string $email An email-address
-* @return string HTML-code with a mailto-link
-*/
-function email_filter($email)
-{
-	return Display :: encrypted_mailto_link($email, $email);
-}
-/**
- * Build the modify-column of the table
- * @param   int     The user id
- * @param   string  URL params to add to table links
- * @param   array   Row of elements to alter
- * @return string Some HTML-code with modify-buttons
- */
-function modify_filter($user_id,$url_params,$row)
-{
-	global $charset;
-	global $_user;
-	$statusname = api_get_status_langvars();
-	$user_is_anonymous = false;
-	if ($row['6'] == $statusname[ANONYMOUS]) {
-		$user_is_anonymous =true;
-	}
-	if (!$user_is_anonymous) {
-		$result .= '<a  href="javascript:void(0)" onclick="load_course_list(\'div_'.$user_id.'\','.$user_id.')">
-					<img onclick="load_course_list(\'div_'.$user_id.'\','.$user_id.')" onmouseout="clear_course_list (\'div_'.$user_id.'\')" src="../img/course.gif" title="'.get_lang('Courses').'" alt="'.get_lang('Courses').'"/>
-					<div class="blackboard_hide" id="div_'.$user_id.'">&nbsp;&nbsp;</div>
-					</a>&nbsp;&nbsp;';
-	} else {
-		$result .= Display::return_icon('course_na.gif',get_lang('Courses')).'&nbsp;&nbsp;';
-	}
-
-	if (api_is_platform_admin()) {
-		if (!$user_is_anonymous) {
-			$result .= '<a href="user_information.php?user_id='.$user_id.'">'.Display::return_icon('synthese_view.gif', get_lang('Info')).'</a>&nbsp;&nbsp;';
-		} else {
-			$result .= Display::return_icon('synthese_view_na.gif', get_lang('Info')).'&nbsp;&nbsp;';
-		}
-	}
-
-    //only allow platform admins to login_as, or session admins only for students (not teachers nor other admins)
-    if (api_is_platform_admin() || (api_is_session_admin() && $row['6'] == $statusname[STUDENT])) {
-    	if (!$user_is_anonymous) {
-        	$result .= '<a href="user_list.php?action=login_as&amp;user_id='.$user_id.'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>&nbsp;&nbsp;';
-    	} else {
-    		$result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';
-    	}
-    } else {
-    	$result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';
-    }
-	if ($row['6'] != $statusname[STUDENT]) {
-		$result .= Display::return_icon('statistics_na.gif', get_lang('Reporting')).'&nbsp;&nbsp;';
-	} else {
-		$result .= '<a href="../mySpace/myStudents.php?student='.$user_id.'">'.Display::return_icon('statistics.gif', get_lang('Reporting')).'</a>&nbsp;&nbsp;';
-	}
-
-	if (api_is_platform_admin()) {
-		if (!$user_is_anonymous) {
-			$result .= '<a href="user_edit.php?user_id='.$user_id.'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>&nbsp;&nbsp;';
-		} else {
-				$result .= Display::return_icon('edit_na.gif', get_lang('Edit')).'</a>&nbsp;&nbsp;';
-		}
-
-		if ($row[0]<>$_user['user_id'] && $user_is_anonymous == false) {
-			// you cannot lock yourself out otherwise you could disable all the accounts including your own => everybody is locked out and nobody can change it anymore.
-			$result .= '<a href="user_list.php?action=delete_user&amp;user_id='.$user_id.'&amp;'.$url_params.'&amp;sec_token='.$_SESSION['sec_token'].'"  onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
-		} else {
-			$result .= Display::return_icon('delete_na.gif', get_lang('Delete'));
-		}
-	}
-	return $result;
-}
-
-
-/**
- * Build the active-column of the table to lock or unlock a certain user
- * lock = the user can no longer use this account
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
- * @param int $active the current state of the account
- * @param int $user_id The user id
- * @param string $url_params
- * @return string Some HTML-code with the lock/unlock button
- */
-function active_filter($active, $url_params, $row) {
-	global $_user;
-
-	if ($active=='1') {
-		$action='lock';
-		$image='right';
-	} elseif ($active=='-1') {
-    	$action='edit';
-        $image='expired';
-    } elseif ($active=='0') {
-		$action='unlock';
-		$image='wrong';
-	}
-
-    if ($action=='edit') {
-        $result = Display::return_icon($image.'.gif', get_lang('AccountExpired'));
-    }elseif ($row['0']<>$_user['user_id']) { // you cannot lock yourself out otherwise you could disable all the accounts including your own => everybody is locked out and nobody can change it anymore.
-		$result = '<a href="user_list.php?action='.$action.'&amp;user_id='.$row['0'].'&amp;'.$url_params.'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon($image.'.gif', get_lang(ucfirst($action))).'</a>';
-	}
-	return $result;
-}
-
-/**
- * Lock or unlock a user
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
- * @param int $status, do we want to lock the user ($status=lock) or unlock it ($status=unlock)
- * @param int $user_id The user id
- * @return language variable
- */
-function lock_unlock_user($status,$user_id)
-{
-	$user_table = Database :: get_main_table(TABLE_MAIN_USER);
-	if ($status=='lock')
-	{
-		$status_db='0';
-		$return_message=get_lang('UserLocked');
-	}
-	if ($status=='unlock')
-	{
-		$status_db='1';
-		$return_message=get_lang('UserUnlocked');
-	}
-
-	if(($status_db=='1' OR $status_db=='0') AND is_numeric($user_id))
-	{
-		$sql="UPDATE $user_table SET active='".Database::escape_string($status_db)."' WHERE user_id='".Database::escape_string($user_id)."'";
-		$result = Database::query($sql, __FILE__, __LINE__);
-	}
-
-	if ($result)
-	{
-		return $return_message;
-	}
-}
-
-/**
- * Instead of displaying the integer of the status, we give a translation for the status
- *
- * @param integer $status
- * @return string translation
- *
- * @version march 2008
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
- */
-function status_filter($status)
-{
-	$statusname = api_get_status_langvars();
-	return $statusname[$status];
-}
-
-
-/**
-==============================================================================
-		INIT SECTION
-==============================================================================
-*/
-$action = $_GET["action"];
-$login_as_user_id = $_GET["user_id"];
-
-
-
-// Login as ...
-if ($_GET['action'] == "login_as" && isset ($login_as_user_id))
-{
-	login_user($login_as_user_id);
-}
-
-if (isset ($_GET['search']) && $_GET['search'] == 'advanced')
-{
-	$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
-	$interbreadcrumb[] = array ("url" => 'user_list.php', "name" => get_lang('UserList'));
-	$tool_name = get_lang('SearchAUser');
-	Display :: display_header($tool_name);
-	//api_display_tool_title($tool_name);
-	$form = new FormValidator('advanced_search','get');
-	$form->addElement('header', '', $tool_name);
-	$form->add_textfield('keyword_firstname',get_lang('FirstName'),false);
-	$form->add_textfield('keyword_lastname',get_lang('LastName'),false);
-	$form->add_textfield('keyword_username',get_lang('LoginName'),false);
-	$form->add_textfield('keyword_email',get_lang('Email'),false);
-	$form->add_textfield('keyword_officialcode',get_lang('OfficialCode'),false);
-	$status_options = array();
-	$status_options['%'] = get_lang('All');
-	$status_options[STUDENT] = get_lang('Student');
-	$status_options[COURSEMANAGER] = get_lang('Teacher');
-	$status_options[SESSIONADMIN] = get_lang('Administrator');//
-	$form->addElement('select','keyword_status',get_lang('Status'),$status_options);
-	$active_group = array();
-	$active_group[] = $form->createElement('checkbox','keyword_active','',get_lang('Active'));
-	$active_group[] = $form->createElement('checkbox','keyword_inactive','',get_lang('Inactive'));
-	$form->addGroup($active_group,'',get_lang('ActiveAccount'),'<br/>',false);
-	$form->addElement('style_submit_button', 'submit',get_lang('SearchUsers'),'class="search"');
-	$defaults['keyword_active'] = 1;
-	$defaults['keyword_inactive'] = 1;
-	$form->setDefaults($defaults);
-	$form->display();
-}
-else
-{
-	$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
-	$tool_name = get_lang('UserList');
-	Display :: display_header($tool_name, "");
-
-	//api_display_tool_title($tool_name);
-	if (isset ($_GET['action'])) {
-		$check = Security::check_token('get');
-		if($check) {
-			switch ($_GET['action']) {
-				case 'show_message' :
-                    if (!empty($_GET['warn'])) {
-                    	Display::display_warning_message(urldecode($_GET['warn']));
-                    }
-                    if (!empty($_GET['message'])) {
-                        Display :: display_normal_message(stripslashes($_GET['message']));
-                    }
-					break;
-				case 'delete_user' :
-					if (api_is_platform_admin()) {
-						if ($user_id != $_user['user_id'] && UserManager :: delete_user($_GET['user_id'])) {
-							Display :: display_normal_message(get_lang('UserDeleted'));
-						} else {
-							Display :: display_error_message(get_lang('CannotDeleteUserBecauseOwnsCourse'));
-						}
-					}
-					break;
-				case 'lock' :
-					$message=lock_unlock_user('lock',$_GET['user_id']);
-					Display :: display_normal_message($message);
-					break;
-				case 'unlock';
-					$message=lock_unlock_user('unlock',$_GET['user_id']);
-					Display :: display_normal_message($message);
-					break;
-
-			}
-			Security::clear_token();
-		}
-	}
-	if (isset ($_POST['action']))
-	{
-		$check = Security::check_token('get');
-		if($check)
-		{
-			switch ($_POST['action'])
-			{
-				case 'delete' :
-					if (api_is_platform_admin()) {
-						$number_of_selected_users = count($_POST['id']);
-						$number_of_deleted_users = 0;
-						if (is_array($_POST['id'])) {
-							foreach ($_POST['id'] as $index => $user_id)
-							{
-								if($user_id != $_user['user_id'])
-								{
-									if(UserManager :: delete_user($user_id))
-									{
-										$number_of_deleted_users++;
-									}
-								}
-							}
-						}
-						if($number_of_selected_users == $number_of_deleted_users)
-						{
-							Display :: display_normal_message(get_lang('SelectedUsersDeleted'));
-						}
-						else
-						{
-							Display :: display_error_message(get_lang('SomeUsersNotDeleted'));
-						}
-					}
-					break;
-			}
-			Security::clear_token();
-		}
-	}
-	// Create a search-box
-	$form = new FormValidator('search_simple','get','','',null,false);
-	$renderer =& $form->defaultRenderer();
-	$renderer->setElementTemplate('<span>{element}</span> ');
-	$form->addElement('text','keyword',get_lang('keyword'));
-	$form->addElement('style_submit_button', 'submit',get_lang('Search'),'class="search"');
-	$form->addElement('static','search_advanced_link',null,'<a href="user_list.php?search=advanced">'.get_lang('AdvancedSearch').'</a>');
-	echo '<div class="actions" style="width:100%;">';
-	if (api_is_platform_admin()) {
-		echo '<span style="float:right; padding-top:7px;">'.
-			 '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_add.php">'.Display::return_icon('add_user_big.gif',get_lang('AddUsers')).get_lang('AddUsers').'</a>'.
-			 '</span>';
-	}
-	$form->display();
-	echo '</div>';
-	if (isset ($_GET['keyword'])) {
-		$parameters = array ('keyword' => Security::remove_XSS($_GET['keyword']));
-	} elseif (isset ($_GET['keyword_firstname'])) {
-		$parameters['keyword_firstname'] 	= Security::remove_XSS($_GET['keyword_firstname']);
-		$parameters['keyword_lastname']	 	= Security::remove_XSS($_GET['keyword_lastname']);
-		$parameters['keyword_email'] 	 	= Security::remove_XSS($_GET['keyword_email']);
-		$parameters['keyword_officialcode'] = Security::remove_XSS($_GET['keyword_officialcode']);
-		$parameters['keyword_status'] 		= Security::remove_XSS($_GET['keyword_status']);
-		$parameters['keyword_active'] 		= Security::remove_XSS($_GET['keyword_active']);
-		$parameters['keyword_inactive'] 	= Security::remove_XSS($_GET['keyword_inactive']);
-	}
-	// Create a sortable table with user-data
-	$parameters['sec_token'] = Security::get_token();
+                 u.username				AS col4,
+                 u.email				AS col5,
+                 u.status				AS col6,
+                 u.active				AS col7,
+                 u.user_id				AS col8 ".
+                 ", u.expiration_date      AS exp ".
+            " FROM $user_table u ";
+
+    // adding the filter to see the user's only of the current access_url
+    global $_configuration;
+    if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
+    	$access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+    	$sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
+    }
+
+	if (isset ($_GET['keyword'])) {
+		$keyword = Database::escape_string($_GET['keyword']);
+		$sql .= " WHERE (u.firstname LIKE '%".$keyword."%' OR u.lastname LIKE '%".$keyword."%'  OR u.username LIKE '%".$keyword."%'  OR u.official_code LIKE '%".$keyword."%' OR u.email LIKE '%".$keyword."%' )";
+	} elseif (isset ($_GET['keyword_firstname'])) {
+		$admin_table = Database :: get_main_table(TABLE_MAIN_ADMIN);
+		$keyword_firstname = Database::escape_string($_GET['keyword_firstname']);
+		$keyword_lastname = Database::escape_string($_GET['keyword_lastname']);
+		$keyword_email = Database::escape_string($_GET['keyword_email']);
+		$keyword_officialcode = Database::escape_string($_GET['keyword_officialcode']);
+		$keyword_username = Database::escape_string($_GET['keyword_username']);
+		$keyword_status = Database::escape_string($_GET['keyword_status']);
+		$query_admin_table = '';
+		$keyword_admin = '';
+
+		if ($keyword_status == SESSIONADMIN) {
+			$keyword_status = '%';
+			$query_admin_table = " , $admin_table a ";
+			$keyword_admin = ' AND a.user_id = u.user_id ';
+		}
+		$keyword_active = isset($_GET['keyword_active']);
+		$keyword_inactive = isset($_GET['keyword_inactive']);
+		$sql .= $query_admin_table." WHERE (u.firstname LIKE '%".$keyword_firstname."%' " .
+				"AND u.lastname LIKE '%".$keyword_lastname."%' " .
+				"AND u.username LIKE '%".$keyword_username."%'  " .
+				"AND u.email LIKE '%".$keyword_email."%'   " .
+				"AND u.official_code LIKE '%".$keyword_officialcode."%'    " .
+				"AND u.status LIKE '".$keyword_status."'" .
+				$keyword_admin;
+
+		if ($keyword_active && !$keyword_inactive) {
+			$sql .= " AND u.active='1'";
+		} elseif($keyword_inactive && !$keyword_active) {
+			$sql .= " AND u.active='0'";
+		}
+		$sql .= " ) ";
+	}
+
+    // adding the filter to see the user's only of the current access_url
+	if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
+    		$sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
+    }
+
+    if (!in_array($direction, array('ASC','DESC'))) {
+    	$direction = 'ASC';
+    }
+    $column = intval($column);
+    $from = intval($from);
+    $number_of_items = intval($number_of_items);
+
+	$sql .= " ORDER BY col$column $direction ";
+	$sql .= " LIMIT $from,$number_of_items";
+	$res = Database::query($sql, __FILE__, __LINE__);
+
+	$users = array ();
+    $t = time();
+	while ($user = Database::fetch_row($res)) {
+        if ($user[7] == 1 && $user[9] != '0000-00-00 00:00:00') {
+            // check expiration date
+            $expiration_time = convert_mysql_date($user[9]);
+            // if expiration date is passed, store a special value for active field
+            if ($expiration_time < $t) {
+        	   $user[7] = '-1';
+            }
+        }
+        // forget about the expiration date field
+        $users[] = array($user[0],$user[1],$user[2],$user[3],$user[4],$user[5],$user[6],$user[7],$user[8]);
+	}
+	return $users;
+}
+/**
+* Returns a mailto-link
+* @param string $email An email-address
+* @return string HTML-code with a mailto-link
+*/
+function email_filter($email)
+{
+	return Display :: encrypted_mailto_link($email, $email);
+}
+/**
+ * Build the modify-column of the table
+ * @param   int     The user id
+ * @param   string  URL params to add to table links
+ * @param   array   Row of elements to alter
+ * @return string Some HTML-code with modify-buttons
+ */
+function modify_filter($user_id,$url_params,$row)
+{
+	global $charset;
+	global $_user;
+	$statusname = api_get_status_langvars();
+	$user_is_anonymous = false;
+	if ($row['6'] == $statusname[ANONYMOUS]) {
+		$user_is_anonymous =true;
+	}
+	if (!$user_is_anonymous) {
+		$result .= '<a  href="javascript:void(0)" onclick="load_course_list(\'div_'.$user_id.'\','.$user_id.')">
+					<img onclick="load_course_list(\'div_'.$user_id.'\','.$user_id.')" onmouseout="clear_course_list (\'div_'.$user_id.'\')" src="../img/course.gif" title="'.get_lang('Courses').'" alt="'.get_lang('Courses').'"/>
+					<div class="blackboard_hide" id="div_'.$user_id.'">&nbsp;&nbsp;</div>
+					</a>&nbsp;&nbsp;';
+	} else {
+		$result .= Display::return_icon('course_na.gif',get_lang('Courses')).'&nbsp;&nbsp;';
+	}
+
+	if (api_is_platform_admin()) {
+		if (!$user_is_anonymous) {
+			$result .= '<a href="user_information.php?user_id='.$user_id.'">'.Display::return_icon('synthese_view.gif', get_lang('Info')).'</a>&nbsp;&nbsp;';
+		} else {
+			$result .= Display::return_icon('synthese_view_na.gif', get_lang('Info')).'&nbsp;&nbsp;';
+		}
+	}
+
+    //only allow platform admins to login_as, or session admins only for students (not teachers nor other admins)
+    if (api_is_platform_admin() || (api_is_session_admin() && $row['6'] == $statusname[STUDENT])) {
+    	if (!$user_is_anonymous) {
+        	$result .= '<a href="user_list.php?action=login_as&amp;user_id='.$user_id.'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>&nbsp;&nbsp;';
+    	} else {
+    		$result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';
+    	}
+    } else {
+    	$result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';
+    }
+	if ($row['6'] != $statusname[STUDENT]) {
+		$result .= Display::return_icon('statistics_na.gif', get_lang('Reporting')).'&nbsp;&nbsp;';
+	} else {
+		$result .= '<a href="../mySpace/myStudents.php?student='.$user_id.'">'.Display::return_icon('statistics.gif', get_lang('Reporting')).'</a>&nbsp;&nbsp;';
+	}
+
+	if (api_is_platform_admin()) {
+		if (!$user_is_anonymous) {
+			$result .= '<a href="user_edit.php?user_id='.$user_id.'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>&nbsp;&nbsp;';
+		} else {
+				$result .= Display::return_icon('edit_na.gif', get_lang('Edit')).'</a>&nbsp;&nbsp;';
+		}
+
+		if ($row[0]<>$_user['user_id'] && $user_is_anonymous == false) {
+			// you cannot lock yourself out otherwise you could disable all the accounts including your own => everybody is locked out and nobody can change it anymore.
+			$result .= '<a href="user_list.php?action=delete_user&amp;user_id='.$user_id.'&amp;'.$url_params.'&amp;sec_token='.$_SESSION['sec_token'].'"  onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
+		} else {
+			$result .= Display::return_icon('delete_na.gif', get_lang('Delete'));
+		}
+	}
+	return $result;
+}
+
+
+/**
+ * Build the active-column of the table to lock or unlock a certain user
+ * lock = the user can no longer use this account
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+ * @param int $active the current state of the account
+ * @param int $user_id The user id
+ * @param string $url_params
+ * @return string Some HTML-code with the lock/unlock button
+ */
+function active_filter($active, $url_params, $row) {
+	global $_user;
+
+	if ($active=='1') {
+		$action='lock';
+		$image='right';
+	} elseif ($active=='-1') {
+    	$action='edit';
+        $image='expired';
+    } elseif ($active=='0') {
+		$action='unlock';
+		$image='wrong';
+	}
+
+    if ($action=='edit') {
+        $result = Display::return_icon($image.'.gif', get_lang('AccountExpired'));
+    }elseif ($row['0']<>$_user['user_id']) { // you cannot lock yourself out otherwise you could disable all the accounts including your own => everybody is locked out and nobody can change it anymore.
+		$result = '<a href="user_list.php?action='.$action.'&amp;user_id='.$row['0'].'&amp;'.$url_params.'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon($image.'.gif', get_lang(ucfirst($action))).'</a>';
+	}
+	return $result;
+}
+
+/**
+ * Lock or unlock a user
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+ * @param int $status, do we want to lock the user ($status=lock) or unlock it ($status=unlock)
+ * @param int $user_id The user id
+ * @return language variable
+ */
+function lock_unlock_user($status,$user_id)
+{
+	$user_table = Database :: get_main_table(TABLE_MAIN_USER);
+	if ($status=='lock')
+	{
+		$status_db='0';
+		$return_message=get_lang('UserLocked');
+	}
+	if ($status=='unlock')
+	{
+		$status_db='1';
+		$return_message=get_lang('UserUnlocked');
+	}
+
+	if(($status_db=='1' OR $status_db=='0') AND is_numeric($user_id))
+	{
+		$sql="UPDATE $user_table SET active='".Database::escape_string($status_db)."' WHERE user_id='".Database::escape_string($user_id)."'";
+		$result = Database::query($sql, __FILE__, __LINE__);
+	}
+
+	if ($result)
+	{
+		return $return_message;
+	}
+}
+
+/**
+ * Instead of displaying the integer of the status, we give a translation for the status
+ *
+ * @param integer $status
+ * @return string translation
+ *
+ * @version march 2008
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+ */
+function status_filter($status)
+{
+	$statusname = api_get_status_langvars();
+	return $statusname[$status];
+}
+
+
+/**
+==============================================================================
+		INIT SECTION
+==============================================================================
+*/
+$action = $_GET["action"];
+$login_as_user_id = $_GET["user_id"];
+
+
+
+// Login as ...
+if ($_GET['action'] == "login_as" && isset ($login_as_user_id))
+{
+	login_user($login_as_user_id);
+}
+
+if (isset ($_GET['search']) && $_GET['search'] == 'advanced')
+{
+	$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+	$interbreadcrumb[] = array ("url" => 'user_list.php', "name" => get_lang('UserList'));
+	$tool_name = get_lang('SearchAUser');
+	Display :: display_header($tool_name);
+	//api_display_tool_title($tool_name);
+	$form = new FormValidator('advanced_search','get');
+	$form->addElement('header', '', $tool_name);
+	$form->add_textfield('keyword_firstname',get_lang('FirstName'),false);
+	$form->add_textfield('keyword_lastname',get_lang('LastName'),false);
+	$form->add_textfield('keyword_username',get_lang('LoginName'),false);
+	$form->add_textfield('keyword_email',get_lang('Email'),false);
+	$form->add_textfield('keyword_officialcode',get_lang('OfficialCode'),false);
+	$status_options = array();
+	$status_options['%'] = get_lang('All');
+	$status_options[STUDENT] = get_lang('Student');
+	$status_options[COURSEMANAGER] = get_lang('Teacher');
+	$status_options[SESSIONADMIN] = get_lang('Administrator');//
+	$form->addElement('select','keyword_status',get_lang('Status'),$status_options);
+	$active_group = array();
+	$active_group[] = $form->createElement('checkbox','keyword_active','',get_lang('Active'));
+	$active_group[] = $form->createElement('checkbox','keyword_inactive','',get_lang('Inactive'));
+	$form->addGroup($active_group,'',get_lang('ActiveAccount'),'<br/>',false);
+	$form->addElement('style_submit_button', 'submit',get_lang('SearchUsers'),'class="search"');
+	$defaults['keyword_active'] = 1;
+	$defaults['keyword_inactive'] = 1;
+	$form->setDefaults($defaults);
+	$form->display();
+}
+else
+{
+	$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+	$tool_name = get_lang('UserList');
+	Display :: display_header($tool_name, "");
+
+	//api_display_tool_title($tool_name);
+	if (isset ($_GET['action'])) {
+		$check = Security::check_token('get');
+		if($check) {
+			switch ($_GET['action']) {
+				case 'show_message' :
+                    if (!empty($_GET['warn'])) {
+                    	Display::display_warning_message(urldecode($_GET['warn']));
+                    }
+                    if (!empty($_GET['message'])) {
+                        Display :: display_normal_message(stripslashes($_GET['message']));
+                    }
+					break;
+				case 'delete_user' :
+					if (api_is_platform_admin()) {
+						if ($user_id != $_user['user_id'] && UserManager :: delete_user($_GET['user_id'])) {
+							Display :: display_normal_message(get_lang('UserDeleted'));
+						} else {
+							Display :: display_error_message(get_lang('CannotDeleteUserBecauseOwnsCourse'));
+						}
+					}
+					break;
+				case 'lock' :
+					$message=lock_unlock_user('lock',$_GET['user_id']);
+					Display :: display_normal_message($message);
+					break;
+				case 'unlock';
+					$message=lock_unlock_user('unlock',$_GET['user_id']);
+					Display :: display_normal_message($message);
+					break;
+
+			}
+			Security::clear_token();
+		}
+	}
+	if (isset ($_POST['action']))
+	{
+		$check = Security::check_token('get');
+		if($check)
+		{
+			switch ($_POST['action'])
+			{
+				case 'delete' :
+					if (api_is_platform_admin()) {
+						$number_of_selected_users = count($_POST['id']);
+						$number_of_deleted_users = 0;
+						if (is_array($_POST['id'])) {
+							foreach ($_POST['id'] as $index => $user_id)
+							{
+								if($user_id != $_user['user_id'])
+								{
+									if(UserManager :: delete_user($user_id))
+									{
+										$number_of_deleted_users++;
+									}
+								}
+							}
+						}
+						if($number_of_selected_users == $number_of_deleted_users)
+						{
+							Display :: display_normal_message(get_lang('SelectedUsersDeleted'));
+						}
+						else
+						{
+							Display :: display_error_message(get_lang('SomeUsersNotDeleted'));
+						}
+					}
+					break;
+			}
+			Security::clear_token();
+		}
+	}
+	// Create a search-box
+	$form = new FormValidator('search_simple','get','','',null,false);
+	$renderer =& $form->defaultRenderer();
+	$renderer->setElementTemplate('<span>{element}</span> ');
+	$form->addElement('text','keyword',get_lang('keyword'));
+	$form->addElement('style_submit_button', 'submit',get_lang('Search'),'class="search"');
+	$form->addElement('static','search_advanced_link',null,'<a href="user_list.php?search=advanced">'.get_lang('AdvancedSearch').'</a>');
+	echo '<div class="actions" style="width:100%;">';
+	if (api_is_platform_admin()) {
+		echo '<span style="float:right; padding-top:7px;">'.
+			 '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_add.php">'.Display::return_icon('add_user_big.gif',get_lang('AddUsers')).get_lang('AddUsers').'</a>'.
+			 '</span>';
+	}
+	$form->display();
+	echo '</div>';
+	if (isset ($_GET['keyword'])) {
+		$parameters = array ('keyword' => Security::remove_XSS($_GET['keyword']));
+	} elseif (isset ($_GET['keyword_firstname'])) {
+		$parameters['keyword_firstname'] 	= Security::remove_XSS($_GET['keyword_firstname']);
+		$parameters['keyword_lastname']	 	= Security::remove_XSS($_GET['keyword_lastname']);
+		$parameters['keyword_email'] 	 	= Security::remove_XSS($_GET['keyword_email']);
+		$parameters['keyword_officialcode'] = Security::remove_XSS($_GET['keyword_officialcode']);
+		$parameters['keyword_status'] 		= Security::remove_XSS($_GET['keyword_status']);
+		$parameters['keyword_active'] 		= Security::remove_XSS($_GET['keyword_active']);
+		$parameters['keyword_inactive'] 	= Security::remove_XSS($_GET['keyword_inactive']);
+	}
+	// Create a sortable table with user-data
+	$parameters['sec_token'] = Security::get_token();
 	$table = new SortableTable('users', 'get_number_of_users', 'get_user_data', (api_is_western_name_order() xor api_sort_by_first_name()) ? 3 : 2);
-	$table->set_additional_parameters($parameters);
-	$table->set_header(0, '', false);
-	$table->set_header(1, get_lang('OfficialCode'));
+	$table->set_additional_parameters($parameters);
+	$table->set_header(0, '', false);
+	$table->set_header(1, get_lang('OfficialCode'));
 	if (api_is_western_name_order()) {
 		$table->set_header(2, get_lang('FirstName'));
 		$table->set_header(3, get_lang('LastName'));
 	} else {
-		$table->set_header(2, get_lang('LastName'));
-		$table->set_header(3, get_lang('FirstName'));
+		$table->set_header(2, get_lang('LastName'));
+		$table->set_header(3, get_lang('FirstName'));
 	}
-	$table->set_header(4, get_lang('LoginName'));
-	$table->set_header(5, get_lang('Email'));
-	$table->set_header(6, get_lang('Status'));
-	$table->set_header(7, get_lang('Active'));
-	$table->set_header(8, get_lang('Modify'));
-	$table->set_column_filter(5, 'email_filter');
-	$table->set_column_filter(6, 'status_filter');
-	$table->set_column_filter(7, 'active_filter');
-	$table->set_column_filter(8, 'modify_filter');
-	if (api_is_platform_admin())
-		$table->set_form_actions(array ('delete' => get_lang('DeleteFromPlatform')));
-	$table->display();
-}
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display :: display_footer();
-?>
+	$table->set_header(4, get_lang('LoginName'));
+	$table->set_header(5, get_lang('Email'));
+	$table->set_header(6, get_lang('Status'));
+	$table->set_header(7, get_lang('Active'));
+	$table->set_header(8, get_lang('Modify'));
+	$table->set_column_filter(5, 'email_filter');
+	$table->set_column_filter(6, 'status_filter');
+	$table->set_column_filter(7, 'active_filter');
+	$table->set_column_filter(8, 'modify_filter');
+	if (api_is_platform_admin())
+		$table->set_form_actions(array ('delete' => get_lang('DeleteFromPlatform')));
+	$table->display();
+}
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display :: display_footer();
+?>

+ 337 - 337
main/auth/my_progress.php

@@ -1,375 +1,375 @@
-<?php
-/* For licensing terms, see /dokeos_license.txt */
-// name of the language file that needs to be included
-$language_file = array('registration','tracking','exercice','admin');
-
-$cidReset = true;
-$this_section = 'session_my_space';
-
-require ('../inc/global.inc.php');
-
-require_once (api_get_path(LIBRARY_PATH).'tracking.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'course.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
-require_once ('../newscorm/learnpath.class.php');
-
-$nameTools=get_lang('MyProgress');
-
-api_block_anonymous_users();
-
-Display :: display_header($nameTools);
-
-// Database table definitions
-$tbl_course 				= Database :: get_main_table(TABLE_MAIN_COURSE);
-$tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
-$tbl_session 				= Database :: get_main_table(TABLE_MAIN_SESSION);
-$tbl_course_user 			= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-$tbl_session_course 		= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_session_course_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-$tbl_stats_lastaccess 		= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
-$tbl_stats_exercices 		= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-$tbl_course_lp_view 		= Database :: get_course_table(TABLE_LP_VIEW);
-$tbl_course_lp_view_item 	= Database :: get_course_table(TABLE_LP_ITEM_VIEW);
-$tbl_course_lp 				= Database :: get_course_table(TABLE_LP_MAIN);
-$tbl_course_lp_item 		= Database :: get_course_table(TABLE_LP_ITEM);
-$tbl_course_quiz 			= Database :: get_course_table(TABLE_QUIZ_TEST);
-
-
-// get course list
-$sql = 'SELECT course_code FROM '.$tbl_course_user.' WHERE user_id='.intval($_user['user_id']);
-$rs = Database::query($sql, __FILE__, __LINE__);
-$Courses = array();
-while($row = Database :: fetch_array($rs)) {
-	$Courses[$row['course_code']] = CourseManager::get_course_information($row['course_code']);
-}
-
-// get the list of sessions where the user is subscribed as student
-$sql = 'SELECT DISTINCT course_code FROM '.Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER).' WHERE id_user='.intval($_user['user_id']);
-$rs = Database::query($sql, __FILE__, __LINE__);
-while($row = Database :: fetch_array($rs)) {
-	$Courses[$row['course_code']] = CourseManager::get_course_information($row['course_code']);
-}
-
-echo '<div class="actions-title" >';
-echo $nameTools;
-echo '</div>';
-$now=date('Y-m-d');
-?>
-<table class="data_table" width="100%">
-<tr class="tableName">
-	<td colspan="6">
-		<strong><?php echo get_lang('MyCourses'); ?></strong>
-	</td>
-</tr>
-<tr>
-  <th><?php echo get_lang('Course'); ?></th>
-  <th><?php echo get_lang('Time'); ?></th>
-  <th><?php echo get_lang('Progress'); ?></th>
+<?php
+/* For licensing terms, see /dokeos_license.txt */
+// name of the language file that needs to be included
+$language_file = array('registration','tracking','exercice','admin');
+
+$cidReset = true;
+$this_section = 'session_my_space';
+
+require ('../inc/global.inc.php');
+
+require_once (api_get_path(LIBRARY_PATH).'tracking.lib.php');
+require_once (api_get_path(LIBRARY_PATH).'course.lib.php');
+require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
+require_once ('../newscorm/learnpath.class.php');
+
+$nameTools=get_lang('MyProgress');
+
+api_block_anonymous_users();
+
+Display :: display_header($nameTools);
+
+// Database table definitions
+$tbl_course 				= Database :: get_main_table(TABLE_MAIN_COURSE);
+$tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
+$tbl_session 				= Database :: get_main_table(TABLE_MAIN_SESSION);
+$tbl_course_user 			= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+$tbl_session_course 		= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
+$tbl_session_course_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+$tbl_stats_lastaccess 		= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
+$tbl_stats_exercices 		= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+$tbl_course_lp_view 		= Database :: get_course_table(TABLE_LP_VIEW);
+$tbl_course_lp_view_item 	= Database :: get_course_table(TABLE_LP_ITEM_VIEW);
+$tbl_course_lp 				= Database :: get_course_table(TABLE_LP_MAIN);
+$tbl_course_lp_item 		= Database :: get_course_table(TABLE_LP_ITEM);
+$tbl_course_quiz 			= Database :: get_course_table(TABLE_QUIZ_TEST);
+
+
+// get course list
+$sql = 'SELECT course_code FROM '.$tbl_course_user.' WHERE user_id='.intval($_user['user_id']);
+$rs = Database::query($sql, __FILE__, __LINE__);
+$Courses = array();
+while($row = Database :: fetch_array($rs)) {
+	$Courses[$row['course_code']] = CourseManager::get_course_information($row['course_code']);
+}
+
+// get the list of sessions where the user is subscribed as student
+$sql = 'SELECT DISTINCT course_code FROM '.Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER).' WHERE id_user='.intval($_user['user_id']);
+$rs = Database::query($sql, __FILE__, __LINE__);
+while($row = Database :: fetch_array($rs)) {
+	$Courses[$row['course_code']] = CourseManager::get_course_information($row['course_code']);
+}
+
+echo '<div class="actions-title" >';
+echo $nameTools;
+echo '</div>';
+$now=date('Y-m-d');
+?>
+<table class="data_table" width="100%">
+<tr class="tableName">
+	<td colspan="6">
+		<strong><?php echo get_lang('MyCourses'); ?></strong>
+	</td>
+</tr>
+<tr>
+  <th><?php echo get_lang('Course'); ?></th>
+  <th><?php echo get_lang('Time'); ?></th>
+  <th><?php echo get_lang('Progress'); ?></th>
   <th><?php
-  echo get_lang('Score');
+  echo get_lang('Score');
   Display :: display_icon('info3.gif',get_lang('ScormAndLPTestTotalAverage') , array ('align' => 'absmiddle', 'hspace' => '3px'));
-  ?></th>
-  <th><?php echo get_lang('LastConnexion'); ?></th>
-  <th><?php echo get_lang('Details'); ?></th>
-</tr>
-
-<?php
-$i = 0;
-$totalWeighting = 0;
-$totalScore = 0;
-$totalItem = 0;
-$totalProgress = 0;
-
-foreach($Courses as $enreg) {
-	$weighting = 0;
-	$lastConnexion = Tracking :: get_last_connection_date_on_the_course($_user['user_id'],$enreg['code']);
-	$progress = Tracking :: get_avg_student_progress($_user['user_id'], $enreg['code']);
-	$total_time_login=Tracking :: get_time_spent_on_the_course($_user['user_id'], $enreg['code']);
-	$time = api_time_to_hms($total_time_login);
-	$pourcentageScore = Tracking :: get_average_test_scorm_and_lp ($_user['user_id'], $enreg['code']);
-?>
-
-<tr class='<?php echo $i?'row_odd':'row_even'; ?>'>
-  	<td>
-		<?php echo api_html_entity_decode($enreg['title'],ENT_QUOTES,$charset); ?>
-  	</td>
-  	<td align='center'>
-		<?php echo $time; ?>
-  	</td>
-  	<td align='center'>
-  		<?php echo $progress.'%'; ?>
-  	</td>
-  	<td align='center'>
+  ?></th>
+  <th><?php echo get_lang('LastConnexion'); ?></th>
+  <th><?php echo get_lang('Details'); ?></th>
+</tr>
+
+<?php
+$i = 0;
+$totalWeighting = 0;
+$totalScore = 0;
+$totalItem = 0;
+$totalProgress = 0;
+
+foreach($Courses as $enreg) {
+	$weighting = 0;
+	$lastConnexion = Tracking :: get_last_connection_date_on_the_course($_user['user_id'],$enreg['code']);
+	$progress = Tracking :: get_avg_student_progress($_user['user_id'], $enreg['code']);
+	$total_time_login=Tracking :: get_time_spent_on_the_course($_user['user_id'], $enreg['code']);
+	$time = api_time_to_hms($total_time_login);
+	$pourcentageScore = Tracking :: get_average_test_scorm_and_lp ($_user['user_id'], $enreg['code']);
+?>
+
+<tr class='<?php echo $i?'row_odd':'row_even'; ?>'>
+  	<td>
+		<?php echo api_html_entity_decode($enreg['title'],ENT_QUOTES,$charset); ?>
+  	</td>
+  	<td align='center'>
+		<?php echo $time; ?>
+  	</td>
+  	<td align='center'>
+  		<?php echo $progress.'%'; ?>
+  	</td>
+  	<td align='center'>
 		<?php
-		if (!is_null($pourcentageScore)) {
+		if (!is_null($pourcentageScore)) {
 			echo $pourcentageScore.'%';
-		} else {
-			echo '0%';
-		}
-		?>
-  	</td>
-  	<td align='center' >
-		<?php echo $lastConnexion ?>
-  	</td>
-  	<td align='center'>
-		<a href="<?php echo api_get_self(); ?>?course=<?php echo $enreg['code']; ?>"> <?php Display::display_icon('2rightarrow.gif', get_lang('Details')); ?> </a>
-  	</td>
-</tr>
-<?php
-	$i=$i ? 0 : 1;
-}
-?>
-</table>
-<br /><br />
-<?php
-/*
- * **********************************************************************************************
- *
- * 	Details for one course
- *
- * **********************************************************************************************
- */
-	if(isset($_GET['course'])) {
-		$course = Database::escape_string($_GET['course']);
-		$a_infosCours = CourseManager::get_course_information($course);
-
-		//get coach and session_name if there is one and if session_mode is activated
-		if(api_get_setting('use_session_mode')=='true') {
-			$tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
-			$tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
-			$tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
-			$tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+		} else {
+			echo '0%';
+		}
+		?>
+  	</td>
+  	<td align='center' >
+		<?php echo $lastConnexion ?>
+  	</td>
+  	<td align='center'>
+		<a href="<?php echo api_get_self(); ?>?course=<?php echo $enreg['code']; ?>"> <?php Display::display_icon('2rightarrow.gif', get_lang('Details')); ?> </a>
+  	</td>
+</tr>
+<?php
+	$i=$i ? 0 : 1;
+}
+?>
+</table>
+<br /><br />
+<?php
+/*
+ * **********************************************************************************************
+ *
+ * 	Details for one course
+ *
+ * **********************************************************************************************
+ */
+	if(isset($_GET['course'])) {
+		$course = Database::escape_string($_GET['course']);
+		$a_infosCours = CourseManager::get_course_information($course);
+
+		//get coach and session_name if there is one and if session_mode is activated
+		if(api_get_setting('use_session_mode')=='true') {
+			$tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
+			$tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
+			$tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
+			$tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 
 			$sql = 'SELECT id_session
-					FROM '.$tbl_session_course_user.' session_course_user
-					WHERE session_course_user.id_user = '.intval($_user['user_id']).'
-					AND session_course_user.course_code = "'.Database::escape_string($course).'"
-					ORDER BY id_session DESC';
-			$rs = Database::query($sql,__FILE__,__LINE__);
+					FROM '.$tbl_session_course_user.' session_course_user
+					WHERE session_course_user.id_user = '.intval($_user['user_id']).'
+					AND session_course_user.course_code = "'.Database::escape_string($course).'"
+					ORDER BY id_session DESC';
+			$rs = Database::query($sql,__FILE__,__LINE__);
 
 			$row=Database::fetch_array($rs);
-			if (!empty ($row[0]))
-			{
+			if (!empty ($row[0]))
+			{
 				$session_id =intval($row[0]);
-			}
+			}
 			//$session_id =intval(Database::result($rs,0,0));
 
-			if($session_id>0)
-			{
-				// get session name and coach of the session
+			if($session_id>0)
+			{
+				// get session name and coach of the session
 				$sql = 'SELECT name, id_coach FROM '.$tbl_session.'
-						WHERE id='.$session_id;
+						WHERE id='.$session_id;
 				$rs = Database::query($sql,__FILE__,__LINE__);
-				$session_name = Database::result($rs,0,'name');
-				$session_coach_id = intval(Database::result($rs,0,'id_coach'));
+				$session_name = Database::result($rs,0,'name');
+				$session_coach_id = intval(Database::result($rs,0,'id_coach'));
 
-				// get coach of the course in the session
+				// get coach of the course in the session
 				$sql = 'SELECT id_coach FROM '.$tbl_session_course.'
-						WHERE id_session='.$session_id.'
-						AND course_code = "'.Database::escape_string($_GET['course']).'"';
+						WHERE id_session='.$session_id.'
+						AND course_code = "'.Database::escape_string($_GET['course']).'"';
 				$rs = Database::query($sql,__FILE__,__LINE__);
-				$session_course_coach_id = intval(Database::result($rs,0,0));
-
-				if($session_course_coach_id!=0)
-				{
-					$coach_infos = UserManager :: get_user_info_by_id($session_course_coach_id);
-					$a_infosCours['tutor_name'] = api_get_person_name($coach_infos['firstname'], $coach_infos['lastname']);
-				}
-				else if($session_coach_id!=0)
-				{
-					$coach_infos = UserManager :: get_user_info_by_id($session_coach_id);
-					$a_infosCours['tutor_name'] = api_get_person_name($coach_infos['firstname'], $coach_infos['lastname']);
-				}
-			}
-		} // end if(api_get_setting('use_session_mode')=='true')
-
-		$tableTitle = $a_infosCours['title'].' | Coach : '.$a_infosCours['tutor_name'].((!empty($session_name)) ? ' | '.get_lang('Session').' : '.$session_name : '');
-
-
-		?>
-		<table class="data_table" width="100%">
-			<tr class="tableName">
-				<td colspan="4">
-					<strong><?php echo $tableTitle; ?></strong>
-				</td>
-			</tr>
-			<tr>
-			  <th class="head" style="color:#000"><?php echo get_lang('Learnpath'); ?></th>
-			  <th class="head" style="color:#000"><?php echo get_lang('Time'); ?></th>
-			  <th class="head" style="color:#000"><?php echo get_lang('Progress'); ?></th>
-			  <th class="head" style="color:#000"><?php echo get_lang('LastConnexion'); ?></th>
-			</tr>
-			<?php
-				$sqlLearnpath = "SELECT lp.name,lp.id FROM ".$a_infosCours['db_name'].".".$tbl_course_lp." AS lp";
-				$resultLearnpath = Database::query($sqlLearnpath);
-				if(Database::num_rows($resultLearnpath)>0) {
-					while($a_learnpath = Database::fetch_array($resultLearnpath)) {
-						$progress = learnpath :: get_db_progress($a_learnpath['id'],$_user['user_id'], '%',$a_infosCours['db_name']);
-
-						// calculates last connection time
-						$sql = 'SELECT MAX(start_time)
-									FROM '.$a_infosCours['db_name'].'.'.$tbl_course_lp_view_item.' AS item_view
-									INNER JOIN '.$a_infosCours['db_name'].'.'.$tbl_course_lp_view.' AS view
-										ON item_view.lp_view_id = view.id
-										AND view.lp_id = '.$a_learnpath['id'].'
-										AND view.user_id = '.$_user['user_id'];
-						$rs = Database::query($sql, __FILE__, __LINE__);
-						$start_time = Database::result($rs, 0, 0);
-
-						// calculates time
-						$sql = 'SELECT SUM(total_time)
-									FROM '.$a_infosCours['db_name'].'.'.$tbl_course_lp_view_item.' AS item_view
-									INNER JOIN '.$a_infosCours['db_name'].'.'.$tbl_course_lp_view.' AS view
-										ON item_view.lp_view_id = view.id
-										AND view.lp_id = '.$a_learnpath['id'].'
-										AND view.user_id = '.$_user['user_id'];
-						$rs = Database::query($sql, __FILE__, __LINE__);
-						$total_time = Database::result($rs, 0, 0);
-
-
-						echo "<tr>
-								<td>
-							 ";
-						echo 		stripslashes($a_learnpath['name']);
-						echo "	</td>
-								<td align='center'>
-							 ";
-						echo api_time_to_hms($total_time);
-						echo "	</td>
-								<td align='center'>
-							 ";
-						echo		$progress;
-						echo "	</td>
-								<td align='center' width=180px >
-							 ";
-						if($start_time!=''){
-							echo $lastConnexion;
-						}
-						else{
-							echo '-';
-						}
-						echo "	</td>
-							  </tr>
-							 ";
-					}
-
-				}
-				else
-				{
-					echo "	<tr>
-								<td colspan='4'>
-									".get_lang('NoLearnpath')."
-								</td>
-							</tr>
-						 ";
-				}
-
-
-
-			?>
-			<tr>
-			  <th class="head" style="color:#000"><?php echo get_lang('Exercices'); ?></th>
-			  <th class="head" style="color:#000"><?php echo get_lang('Score'); ?></th>
-			  <th class="head" style="color:#000"><?php echo get_lang('Attempts'); ?></th>
-			  <th class="head" style="color:#000"><?php echo get_lang('Details'); ?></th>
-			</tr>
-
-			<?php
-
-				$sql='SELECT visibility FROM '.$a_infosCours['db_name'].'.'.TABLE_TOOL_LIST.' WHERE name="quiz"';
-				$resultVisibilityTests = Database::query($sql);
+				$session_course_coach_id = intval(Database::result($rs,0,0));
+
+				if($session_course_coach_id!=0)
+				{
+					$coach_infos = UserManager :: get_user_info_by_id($session_course_coach_id);
+					$a_infosCours['tutor_name'] = api_get_person_name($coach_infos['firstname'], $coach_infos['lastname']);
+				}
+				else if($session_coach_id!=0)
+				{
+					$coach_infos = UserManager :: get_user_info_by_id($session_coach_id);
+					$a_infosCours['tutor_name'] = api_get_person_name($coach_infos['firstname'], $coach_infos['lastname']);
+				}
+			}
+		} // end if(api_get_setting('use_session_mode')=='true')
+
+		$tableTitle = $a_infosCours['title'].' | Coach : '.$a_infosCours['tutor_name'].((!empty($session_name)) ? ' | '.get_lang('Session').' : '.$session_name : '');
+
+
+		?>
+		<table class="data_table" width="100%">
+			<tr class="tableName">
+				<td colspan="4">
+					<strong><?php echo $tableTitle; ?></strong>
+				</td>
+			</tr>
+			<tr>
+			  <th class="head" style="color:#000"><?php echo get_lang('Learnpath'); ?></th>
+			  <th class="head" style="color:#000"><?php echo get_lang('Time'); ?></th>
+			  <th class="head" style="color:#000"><?php echo get_lang('Progress'); ?></th>
+			  <th class="head" style="color:#000"><?php echo get_lang('LastConnexion'); ?></th>
+			</tr>
+			<?php
+				$sqlLearnpath = "SELECT lp.name,lp.id FROM ".$a_infosCours['db_name'].".".$tbl_course_lp." AS lp";
+				$resultLearnpath = Database::query($sqlLearnpath);
+				if(Database::num_rows($resultLearnpath)>0) {
+					while($a_learnpath = Database::fetch_array($resultLearnpath)) {
+						$progress = learnpath :: get_db_progress($a_learnpath['id'],$_user['user_id'], '%',$a_infosCours['db_name']);
+
+						// calculates last connection time
+						$sql = 'SELECT MAX(start_time)
+									FROM '.$a_infosCours['db_name'].'.'.$tbl_course_lp_view_item.' AS item_view
+									INNER JOIN '.$a_infosCours['db_name'].'.'.$tbl_course_lp_view.' AS view
+										ON item_view.lp_view_id = view.id
+										AND view.lp_id = '.$a_learnpath['id'].'
+										AND view.user_id = '.$_user['user_id'];
+						$rs = Database::query($sql, __FILE__, __LINE__);
+						$start_time = Database::result($rs, 0, 0);
+
+						// calculates time
+						$sql = 'SELECT SUM(total_time)
+									FROM '.$a_infosCours['db_name'].'.'.$tbl_course_lp_view_item.' AS item_view
+									INNER JOIN '.$a_infosCours['db_name'].'.'.$tbl_course_lp_view.' AS view
+										ON item_view.lp_view_id = view.id
+										AND view.lp_id = '.$a_learnpath['id'].'
+										AND view.user_id = '.$_user['user_id'];
+						$rs = Database::query($sql, __FILE__, __LINE__);
+						$total_time = Database::result($rs, 0, 0);
+
+
+						echo "<tr>
+								<td>
+							 ";
+						echo 		stripslashes($a_learnpath['name']);
+						echo "	</td>
+								<td align='center'>
+							 ";
+						echo api_time_to_hms($total_time);
+						echo "	</td>
+								<td align='center'>
+							 ";
+						echo		$progress;
+						echo "	</td>
+								<td align='center' width=180px >
+							 ";
+						if($start_time!=''){
+							echo $lastConnexion;
+						}
+						else{
+							echo '-';
+						}
+						echo "	</td>
+							  </tr>
+							 ";
+					}
+
+				}
+				else
+				{
+					echo "	<tr>
+								<td colspan='4'>
+									".get_lang('NoLearnpath')."
+								</td>
+							</tr>
+						 ";
+				}
+
+
+
+			?>
+			<tr>
+			  <th class="head" style="color:#000"><?php echo get_lang('Exercices'); ?></th>
+			  <th class="head" style="color:#000"><?php echo get_lang('Score'); ?></th>
+			  <th class="head" style="color:#000"><?php echo get_lang('Attempts'); ?></th>
+			  <th class="head" style="color:#000"><?php echo get_lang('Details'); ?></th>
+			</tr>
+
+			<?php
+
+				$sql='SELECT visibility FROM '.$a_infosCours['db_name'].'.'.TABLE_TOOL_LIST.' WHERE name="quiz"';
+				$resultVisibilityTests = Database::query($sql);
 
 				if (Database::result($resultVisibilityTests,0,'visibility')==1) {
-					$sqlExercices = "	SELECT quiz.title,id, results_disabled
-									FROM ".$a_infosCours['db_name'].".".$tbl_course_quiz." AS quiz
+					$sqlExercices = "	SELECT quiz.title,id, results_disabled
+									FROM ".$a_infosCours['db_name'].".".$tbl_course_quiz." AS quiz
 									WHERE active='1'";
 
-					$resuktExercices = Database::query($sqlExercices);
+					$resuktExercices = Database::query($sqlExercices);
 					if (Database::num_rows($resuktExercices)>0) {
 						while ($a_exercices = Database::fetch_array($resuktExercices)) {
-							$sqlEssais = "	SELECT COUNT(ex.exe_id) as essais
-											FROM $tbl_stats_exercices AS ex
-											WHERE ex.exe_user_id='".$_user['user_id']."' AND ex.exe_cours_id = '".$a_infosCours['code']."'
-											AND ex.exe_exo_id = ".$a_exercices['id']."
-											AND orig_lp_id = 0
-											AND orig_lp_item_id = 0	"
-										 ;
-							$resultEssais = Database::query($sqlEssais);
-							$a_essais = Database::fetch_array($resultEssais);
-
-							$sqlScore = "SELECT exe_id , exe_result,exe_weighting
-										 FROM $tbl_stats_exercices
-										 WHERE exe_user_id = ".$_user['user_id']."
-											 AND exe_cours_id = '".$a_infosCours['code']."'
-											 AND exe_exo_id = ".$a_exercices['id']."
-											 AND orig_lp_id = 0
+							$sqlEssais = "	SELECT COUNT(ex.exe_id) as essais
+											FROM $tbl_stats_exercices AS ex
+											WHERE ex.exe_user_id='".$_user['user_id']."' AND ex.exe_cours_id = '".$a_infosCours['code']."'
+											AND ex.exe_exo_id = ".$a_exercices['id']."
+											AND orig_lp_id = 0
+											AND orig_lp_item_id = 0	"
+										 ;
+							$resultEssais = Database::query($sqlEssais);
+							$a_essais = Database::fetch_array($resultEssais);
+
+							$sqlScore = "SELECT exe_id , exe_result,exe_weighting
+										 FROM $tbl_stats_exercices
+										 WHERE exe_user_id = ".$_user['user_id']."
+											 AND exe_cours_id = '".$a_infosCours['code']."'
+											 AND exe_exo_id = ".$a_exercices['id']."
+											 AND orig_lp_id = 0
 											 AND orig_lp_item_id = 0
-										ORDER BY exe_date DESC LIMIT 1";
-
-							$resultScore = Database::query($sqlScore);
-							$score = 0;
-							while($a_score = Database::fetch_array($resultScore)) {
-								$score = $score + $a_score['exe_result'];
-								$weighting = $weighting + $a_score['exe_weighting'];
-								$exe_id = $a_score['exe_id'];
+										ORDER BY exe_date DESC LIMIT 1";
+
+							$resultScore = Database::query($sqlScore);
+							$score = 0;
+							while($a_score = Database::fetch_array($resultScore)) {
+								$score = $score + $a_score['exe_result'];
+								$weighting = $weighting + $a_score['exe_weighting'];
+								$exe_id = $a_score['exe_id'];
 							}
 
-							if  ($weighting>0) {
+							if  ($weighting>0) {
 								// i.e 10.50%
-								$pourcentageScore = round(($score*100)/$weighting,2);
-							} else {
+								$pourcentageScore = round(($score*100)/$weighting,2);
+							} else {
 								$pourcentageScore=0;
-							}
+							}
 
-							$weighting = 0;
+							$weighting = 0;
 
-							echo '<tr>
-									<td>';
-							echo $a_exercices['title'];
+							echo '<tr>
+									<td>';
+							echo $a_exercices['title'];
 							echo '</td>';
 
 							if ($a_exercices['results_disabled']==0) {
 								echo '<td align="center">';
-								if ($a_essais['essais']>0) {
-									echo $pourcentageScore.'%';
-								} else {
-									echo '/';
+								if ($a_essais['essais']>0) {
+									echo $pourcentageScore.'%';
+								} else {
+									echo '/';
 								}
 								echo '</td>';
-								echo '<td align="center">';
-								echo  $a_essais['essais'];
-								echo '</td>
-										<td align="center" width="25">';
-								if($a_essais['essais']>0)
-									echo '<a href="../exercice/exercise_show.php?origin=myprogress&id='.$exe_id.'&cidReq='.$a_infosCours['code'].'&id_session='.Security::remove_XSS($_GET['id_session']).'"> '.Display::return_icon('quiz.gif', get_lang('Quiz')).' </a>';
-								echo '</td>';
-							} else {
+								echo '<td align="center">';
+								echo  $a_essais['essais'];
+								echo '</td>
+										<td align="center" width="25">';
+								if($a_essais['essais']>0)
+									echo '<a href="../exercice/exercise_show.php?origin=myprogress&id='.$exe_id.'&cidReq='.$a_infosCours['code'].'&id_session='.Security::remove_XSS($_GET['id_session']).'"> '.Display::return_icon('quiz.gif', get_lang('Quiz')).' </a>';
+								echo '</td>';
+							} else {
 								// we show or not the results if the teacher wants to
 								echo '<td align="center">';
-								echo get_lang('CantShowResults');
+								echo get_lang('CantShowResults');
+								echo '</td>';
+								echo '<td align="center">';
+								echo ' -- ';
+								echo '</td>
+										<td align="center" width="25">';
+								echo ' -- ';
 								echo '</td>';
-								echo '<td align="center">';
-								echo ' -- ';
-								echo '</td>
-										<td align="center" width="25">';
-								echo ' -- ';
-								echo '</td>';
-
-							}
-							echo '</tr>';
-						}
-					} else {
-						echo '<tr><td colspan="4">'.get_lang('NoEx').'</td></tr>';
-					}
-				}
-				else{
-					echo '<tr><td colspan="4">'.get_lang('NoEx').'</td></tr>';
-				}
-
-			?>
-		</table>
-		<?php
-	}
-
-Display :: display_footer();
-?>
+
+							}
+							echo '</tr>';
+						}
+					} else {
+						echo '<tr><td colspan="4">'.get_lang('NoEx').'</td></tr>';
+					}
+				}
+				else{
+					echo '<tr><td colspan="4">'.get_lang('NoEx').'</td></tr>';
+				}
+
+			?>
+		</table>
+		<?php
+	}
+
+Display :: display_footer();
+?>

+ 460 - 460
main/auth/openid/login.php

@@ -1,467 +1,467 @@
-<?php
-/**
- * OpenID login method
+<?php
+/**
+ * OpenID login method
  *
- * The OpenID login method relies on authentication servers providing a public
- * URL that can confirm the identity of a person, thus avoiding the spread
- * use of password transmissions over non-secure lines (for Dokeos, it is a
- * good way of avoiding password theft)
- */
-/**
- * Initialisation
- */
-require_once 'openid.conf.php';
-require_once 'openid.lib.php';
-require_once 'xrds.lib.php';
-
+ * The OpenID login method relies on authentication servers providing a public
+ * URL that can confirm the identity of a person, thus avoiding the spread
+ * use of password transmissions over non-secure lines (for Dokeos, it is a
+ * good way of avoiding password theft)
+ */
+/**
+ * Initialisation
+ */
+require_once 'openid.conf.php';
+require_once 'openid.lib.php';
+require_once 'xrds.lib.php';
+
 function openid_form()
-{
-	return '<div class="menusection"><span class="menusectioncaption">'.get_lang('OpenIdAuthentication').'</span><form name="openid_login" method="post"><label for="openid_url">'.get_lang('OpenIDURL').' <a href="main/auth/openid/whatis.php" title="'.get_lang('OpenIDWhatIs').'">'.Display::return_icon('info3.gif',get_lang('Info')).'</a></label><input type="text" id="openid_url" name="openid_url" style="background: url(main/img/openid_small_logo.png) no-repeat; background-color: #fff; background-position: 0 50%; padding-left:18px;" value="http://"></input><input type="submit" name="openid_login" value="'.get_lang('Enter').'" /><br /><br /></form></div>';
-}
-
-/**
- * The initial step of OpenID authentication responsible for the following:
- *  - Perform discovery on the claimed OpenID.
- *  - If possible, create an association with the Provider's endpoint.
- *  - Create the authentication request.
- *  - Perform the appropriate redirect.
- *
- * @param $claimed_id The OpenID to authenticate
- * @param $return_to The endpoint to return to from the OpenID Provider
- */
+{
+	return '<div class="menusection"><span class="menusectioncaption">'.get_lang('OpenIdAuthentication').'</span><form name="openid_login" method="post"><label for="openid_url">'.get_lang('OpenIDURL').' <a href="main/auth/openid/whatis.php" title="'.get_lang('OpenIDWhatIs').'">'.Display::return_icon('info3.gif',get_lang('Info')).'</a></label><input type="text" id="openid_url" name="openid_url" style="background: url(main/img/openid_small_logo.png) no-repeat; background-color: #fff; background-position: 0 50%; padding-left:18px;" value="http://"></input><input type="submit" name="openid_login" value="'.get_lang('Enter').'" /><br /><br /></form></div>';
+}
+
+/**
+ * The initial step of OpenID authentication responsible for the following:
+ *  - Perform discovery on the claimed OpenID.
+ *  - If possible, create an association with the Provider's endpoint.
+ *  - Create the authentication request.
+ *  - Perform the appropriate redirect.
+ *
+ * @param $claimed_id The OpenID to authenticate
+ * @param $return_to The endpoint to return to from the OpenID Provider
+ */
 function openid_begin($claimed_id, $return_to = '', $form_values = array())
-{
-
-  $claimed_id = _openid_normalize($claimed_id);
-
-  $services = openid_discovery($claimed_id);
-  if (count($services) == 0) {
-    echo 'Sorry, that is not a valid OpenID. Please ensure you have spelled your ID correctly.';
-    return;
-  }
-
-  $op_endpoint = $services[0]['uri'];
-  // Store the discovered endpoint in the session (so we don't have to rediscover).
-  $_SESSION['openid_op_endpoint'] = $op_endpoint;
-  // Store the claimed_id in the session (for handling delegation).
-  $_SESSION['openid_claimed_id'] = $claimed_id;
-  // Store the login form values so we can pass them to
-  // user_exteral_login later.
-  $_SESSION['openid_user_login_values'] = $form_values;
-
-  // If bcmath is present, then create an association
-  $assoc_handle = '';
-  if (function_exists('bcadd')) {
-    $assoc_handle = openid_association($op_endpoint);
-  }
-
-  // Now that there is an association created, move on
-  // to request authentication from the IdP
-  $identity = (!empty($services[0]['delegate'])) ? $services[0]['delegate'] : $claimed_id;
-  if (isset($services[0]['types']) && is_array($services[0]['types']) && in_array(OPENID_NS_2_0 .'/server', $services[0]['types'])) {
-    $identity = 'http://openid.net/identifier_select/2.0';
-  }
-  $authn_request = openid_authentication_request($claimed_id, $identity, $return_to, $assoc_handle, $services[0]['version']);
-
-  if ($services[0]['version'] == 2) {
-    openid_redirect($op_endpoint, $authn_request);
-  }
-  else {
-    openid_redirect_http($op_endpoint, $authn_request);
-  }
-}
-
-/**
- * Completes OpenID authentication by validating returned data from the OpenID
- * Provider.
- *
- * @param $response Array of returned from the OpenID provider (typically $_REQUEST).
- *
- * @return $response Response values for further processing with
- *   $response['status'] set to one of 'success', 'failed' or 'cancel'.
- */
+{
+
+  $claimed_id = _openid_normalize($claimed_id);
+
+  $services = openid_discovery($claimed_id);
+  if (count($services) == 0) {
+    echo 'Sorry, that is not a valid OpenID. Please ensure you have spelled your ID correctly.';
+    return;
+  }
+
+  $op_endpoint = $services[0]['uri'];
+  // Store the discovered endpoint in the session (so we don't have to rediscover).
+  $_SESSION['openid_op_endpoint'] = $op_endpoint;
+  // Store the claimed_id in the session (for handling delegation).
+  $_SESSION['openid_claimed_id'] = $claimed_id;
+  // Store the login form values so we can pass them to
+  // user_exteral_login later.
+  $_SESSION['openid_user_login_values'] = $form_values;
+
+  // If bcmath is present, then create an association
+  $assoc_handle = '';
+  if (function_exists('bcadd')) {
+    $assoc_handle = openid_association($op_endpoint);
+  }
+
+  // Now that there is an association created, move on
+  // to request authentication from the IdP
+  $identity = (!empty($services[0]['delegate'])) ? $services[0]['delegate'] : $claimed_id;
+  if (isset($services[0]['types']) && is_array($services[0]['types']) && in_array(OPENID_NS_2_0 .'/server', $services[0]['types'])) {
+    $identity = 'http://openid.net/identifier_select/2.0';
+  }
+  $authn_request = openid_authentication_request($claimed_id, $identity, $return_to, $assoc_handle, $services[0]['version']);
+
+  if ($services[0]['version'] == 2) {
+    openid_redirect($op_endpoint, $authn_request);
+  }
+  else {
+    openid_redirect_http($op_endpoint, $authn_request);
+  }
+}
+
+/**
+ * Completes OpenID authentication by validating returned data from the OpenID
+ * Provider.
+ *
+ * @param $response Array of returned from the OpenID provider (typically $_REQUEST).
+ *
+ * @return $response Response values for further processing with
+ *   $response['status'] set to one of 'success', 'failed' or 'cancel'.
+ */
 function openid_complete($response)
-{
-  // Default to failed response
-  $response['status'] = 'failed';
-  if (isset($_SESSION['openid_op_endpoint']) && isset($_SESSION['openid_claimed_id'])) {
-    _openid_fix_post($response);
-    $op_endpoint = $_SESSION['openid_op_endpoint'];
-    $claimed_id = $_SESSION['openid_claimed_id'];
-    unset($_SESSION['openid_op_endpoint']);
-    unset($_SESSION['openid_claimed_id']);
-    if (isset($response['openid.mode'])) {
-      if ($response['openid.mode'] == 'cancel') {
-        $response['status'] = 'cancel';
-      }
-      else {
-        if (openid_verify_assertion($op_endpoint, $response)) {
-          $response['openid.identity'] = $claimed_id;
-          $response['status'] = 'success';
-        }
-      }
-    }
-  }
-  return $response;
-}
-
-/**
- * Perform discovery on a claimed ID to determine the OpenID provider endpoint.
- *
- * @param $claimed_id The OpenID URL to perform discovery on.
- *
- * @return Array of services discovered (including OpenID version, endpoint
- * URI, etc).
- */
-function openid_discovery($claimed_id) {
-
-  $services = array();
-
-  $xrds_url = $claimed_id;
-  if (_openid_is_xri($claimed_id)) {
-    $xrds_url = 'http://xri.net/'. $claimed_id;
-  }
-  $url = @parse_url($xrds_url);
-  if ($url['scheme'] == 'http' || $url['scheme'] == 'https') {
-    // For regular URLs, try Yadis resolution first, then HTML-based discovery
-    $headers = array('Accept' => 'application/xrds+xml');
-    //TODO
-    $result = openid_http_request($xrds_url, $headers);
-
-    if (!isset($result->error)) {
-      if (isset($result->headers['Content-Type']) && preg_match("/application\/xrds\+xml/", $result->headers['Content-Type'])) {
-        // Parse XML document to find URL
-        $services = xrds_parse($result->data);
-      }
-      else {
-        $xrds_url = NULL;
-        if (isset($result->headers['X-XRDS-Location'])) {
-          $xrds_url = $result->headers['X-XRDS-Location'];
-        }
-        else {
-          // Look for meta http-equiv link in HTML head
-          $xrds_url = _openid_meta_httpequiv('X-XRDS-Location', $result->data);
-        }
-        if (!empty($xrds_url)) {
-          $headers = array('Accept' => 'application/xrds+xml');
-          //TODO
-          $xrds_result = openid_http_request($xrds_url, $headers);
-          if (!isset($xrds_result->error)) {
-            $services = xrds_parse($xrds_result->data);
-          }
-        }
-      }
-
-      // Check for HTML delegation
-      if (count($services) == 0) {
-        // Look for 2.0 links
-        $uri = _openid_link_href('openid2.provider', $result->data);
-        $delegate = _openid_link_href('openid2.local_id', $result->data);
-        $version = 2;
-
-        // 1.0 links
-        if (empty($uri)) {
-          $uri = _openid_link_href('openid.server', $result->data);
-          $delegate = _openid_link_href('openid.delegate', $result->data);
-          $version = 1;
-        }
-        if (!empty($uri)) {
-          $services[] = array('uri' => $uri, 'delegate' => $delegate, 'version' => $version);
-        }
-      }
-    }
-  }
-  return $services;
-}
-
-/**
- * Attempt to create a shared secret with the OpenID Provider.
- *
- * @param $op_endpoint URL of the OpenID Provider endpoint.
- *
- * @return $assoc_handle The association handle.
- */
-function openid_association($op_endpoint) {
-
-  // Remove Old Associations:
-  //TODO
-  $openid_association = Database::get_main_table(TABLE_MAIN_OPENID_ASSOCIATION);
-  Database::query("DELETE FROM $openid_association WHERE created + expires_in < %d", time());
-
-  // Check to see if we have an association for this IdP already
-  $assoc_handle = Database::query("SELECT assoc_handle FROM $openid_association WHERE idp_endpoint_uri = '%s'", $op_endpoint);
-  if (Database::num_rows($assoc_handle)<=1) {
-    $mod = OPENID_DH_DEFAULT_MOD;
-    $gen = OPENID_DH_DEFAULT_GEN;
-    $r = _openid_dh_rand($mod);
-    $private = bcadd($r, 1);
-    $public = bcpowmod($gen, $private, $mod);
-
-    // If there is no existing association, then request one
-    $assoc_request = openid_association_request($public);
-    $assoc_message = _openid_encode_message(_openid_create_message($assoc_request));
-    $assoc_headers = array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8');
-    //TODO
-    $assoc_result = openid_http_request($op_endpoint, $assoc_headers, 'POST', $assoc_message);
-    if (isset($assoc_result->error)) {
-      return FALSE;
-    }
-
-    $assoc_response = _openid_parse_message($assoc_result->data);
-    if (isset($assoc_response['mode']) && $assoc_response['mode'] == 'error') {
-        return FALSE;
-    }
-
-    if ($assoc_response['session_type'] == 'DH-SHA1') {
-      $spub = _openid_dh_base64_to_long($assoc_response['dh_server_public']);
-      $enc_mac_key = base64_decode($assoc_response['enc_mac_key']);
-      $shared = bcpowmod($spub, $private, $mod);
-      $assoc_response['mac_key'] = base64_encode(_openid_dh_xorsecret($shared, $enc_mac_key));
-    }
-    //TODO
-   	$openid_association = Database::get_main_table(TABLE_MAIN_OPENID_ASSOCIATION);
-    Database::query(sprintf("INSERT INTO $openid_association (idp_endpoint_uri, session_type, assoc_handle, assoc_type, expires_in, mac_key, created) VALUES('%s', '%s', '%s', '%s', %d, '%s', %d)",
-             $op_endpoint, $assoc_response['session_type'], $assoc_response['assoc_handle'], $assoc_response['assoc_type'], $assoc_response['expires_in'], $assoc_response['mac_key'], time()));
-
-    $assoc_handle = $assoc_response['assoc_handle'];
-  }
-
-  return $assoc_handle;
-}
-
-/**
- * ?
- */
-function openid_association_request($public) {
-  require_once(api_get_path(SYS_CODE_PATH).'auth/openid/openid.conf.php');
-
-  $request = array(
-    'openid.ns' => OPENID_NS_2_0,
-    'openid.mode' => 'associate',
-    'openid.session_type' => 'DH-SHA1',
-    'openid.assoc_type' => 'HMAC-SHA1'
-  );
-
-  if ($request['openid.session_type'] == 'DH-SHA1' || $request['openid.session_type'] == 'DH-SHA256') {
-    $cpub = _openid_dh_long_to_base64($public);
-    $request['openid.dh_consumer_public'] = $cpub;
-  }
-
-  return $request;
-}
-
-/**
+{
+  // Default to failed response
+  $response['status'] = 'failed';
+  if (isset($_SESSION['openid_op_endpoint']) && isset($_SESSION['openid_claimed_id'])) {
+    _openid_fix_post($response);
+    $op_endpoint = $_SESSION['openid_op_endpoint'];
+    $claimed_id = $_SESSION['openid_claimed_id'];
+    unset($_SESSION['openid_op_endpoint']);
+    unset($_SESSION['openid_claimed_id']);
+    if (isset($response['openid.mode'])) {
+      if ($response['openid.mode'] == 'cancel') {
+        $response['status'] = 'cancel';
+      }
+      else {
+        if (openid_verify_assertion($op_endpoint, $response)) {
+          $response['openid.identity'] = $claimed_id;
+          $response['status'] = 'success';
+        }
+      }
+    }
+  }
+  return $response;
+}
+
+/**
+ * Perform discovery on a claimed ID to determine the OpenID provider endpoint.
+ *
+ * @param $claimed_id The OpenID URL to perform discovery on.
+ *
+ * @return Array of services discovered (including OpenID version, endpoint
+ * URI, etc).
+ */
+function openid_discovery($claimed_id) {
+
+  $services = array();
+
+  $xrds_url = $claimed_id;
+  if (_openid_is_xri($claimed_id)) {
+    $xrds_url = 'http://xri.net/'. $claimed_id;
+  }
+  $url = @parse_url($xrds_url);
+  if ($url['scheme'] == 'http' || $url['scheme'] == 'https') {
+    // For regular URLs, try Yadis resolution first, then HTML-based discovery
+    $headers = array('Accept' => 'application/xrds+xml');
+    //TODO
+    $result = openid_http_request($xrds_url, $headers);
+
+    if (!isset($result->error)) {
+      if (isset($result->headers['Content-Type']) && preg_match("/application\/xrds\+xml/", $result->headers['Content-Type'])) {
+        // Parse XML document to find URL
+        $services = xrds_parse($result->data);
+      }
+      else {
+        $xrds_url = NULL;
+        if (isset($result->headers['X-XRDS-Location'])) {
+          $xrds_url = $result->headers['X-XRDS-Location'];
+        }
+        else {
+          // Look for meta http-equiv link in HTML head
+          $xrds_url = _openid_meta_httpequiv('X-XRDS-Location', $result->data);
+        }
+        if (!empty($xrds_url)) {
+          $headers = array('Accept' => 'application/xrds+xml');
+          //TODO
+          $xrds_result = openid_http_request($xrds_url, $headers);
+          if (!isset($xrds_result->error)) {
+            $services = xrds_parse($xrds_result->data);
+          }
+        }
+      }
+
+      // Check for HTML delegation
+      if (count($services) == 0) {
+        // Look for 2.0 links
+        $uri = _openid_link_href('openid2.provider', $result->data);
+        $delegate = _openid_link_href('openid2.local_id', $result->data);
+        $version = 2;
+
+        // 1.0 links
+        if (empty($uri)) {
+          $uri = _openid_link_href('openid.server', $result->data);
+          $delegate = _openid_link_href('openid.delegate', $result->data);
+          $version = 1;
+        }
+        if (!empty($uri)) {
+          $services[] = array('uri' => $uri, 'delegate' => $delegate, 'version' => $version);
+        }
+      }
+    }
+  }
+  return $services;
+}
+
+/**
+ * Attempt to create a shared secret with the OpenID Provider.
  *
- */
-function openid_authentication_request($claimed_id, $identity, $return_to = '', $assoc_handle = '', $version = 2) {
-
-  $realm = ($return_to) ? $return_to : api_get_self();
-
-  $ns = ($version == 2) ? OPENID_NS_2_0 : OPENID_NS_1_0;
-  $request =  array(
-    'openid.ns' => $ns,
-    'openid.mode' => 'checkid_setup',
-    'openid.identity' => $identity,
-    'openid.claimed_id' => $claimed_id,
-    'openid.assoc_handle' => $assoc_handle,
-    'openid.return_to' => $return_to,
-  );
-
-  if ($version == 2) {
-    $request['openid.realm'] = $realm;
-  }
-  else {
-    $request['openid.trust_root'] = $realm;
-  }
-
-  // Simple Registration - we don't ask lastname and firstname because the only
+ * @param $op_endpoint URL of the OpenID Provider endpoint.
+ *
+ * @return $assoc_handle The association handle.
+ */
+function openid_association($op_endpoint) {
+
+  // Remove Old Associations:
+  //TODO
+  $openid_association = Database::get_main_table(TABLE_MAIN_OPENID_ASSOCIATION);
+  Database::query("DELETE FROM $openid_association WHERE created + expires_in < %d", time());
+
+  // Check to see if we have an association for this IdP already
+  $assoc_handle = Database::query("SELECT assoc_handle FROM $openid_association WHERE idp_endpoint_uri = '%s'", $op_endpoint);
+  if (Database::num_rows($assoc_handle)<=1) {
+    $mod = OPENID_DH_DEFAULT_MOD;
+    $gen = OPENID_DH_DEFAULT_GEN;
+    $r = _openid_dh_rand($mod);
+    $private = bcadd($r, 1);
+    $public = bcpowmod($gen, $private, $mod);
+
+    // If there is no existing association, then request one
+    $assoc_request = openid_association_request($public);
+    $assoc_message = _openid_encode_message(_openid_create_message($assoc_request));
+    $assoc_headers = array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8');
+    //TODO
+    $assoc_result = openid_http_request($op_endpoint, $assoc_headers, 'POST', $assoc_message);
+    if (isset($assoc_result->error)) {
+      return FALSE;
+    }
+
+    $assoc_response = _openid_parse_message($assoc_result->data);
+    if (isset($assoc_response['mode']) && $assoc_response['mode'] == 'error') {
+        return FALSE;
+    }
+
+    if ($assoc_response['session_type'] == 'DH-SHA1') {
+      $spub = _openid_dh_base64_to_long($assoc_response['dh_server_public']);
+      $enc_mac_key = base64_decode($assoc_response['enc_mac_key']);
+      $shared = bcpowmod($spub, $private, $mod);
+      $assoc_response['mac_key'] = base64_encode(_openid_dh_xorsecret($shared, $enc_mac_key));
+    }
+    //TODO
+   	$openid_association = Database::get_main_table(TABLE_MAIN_OPENID_ASSOCIATION);
+    Database::query(sprintf("INSERT INTO $openid_association (idp_endpoint_uri, session_type, assoc_handle, assoc_type, expires_in, mac_key, created) VALUES('%s', '%s', '%s', '%s', %d, '%s', %d)",
+             $op_endpoint, $assoc_response['session_type'], $assoc_response['assoc_handle'], $assoc_response['assoc_type'], $assoc_response['expires_in'], $assoc_response['mac_key'], time()));
+
+    $assoc_handle = $assoc_response['assoc_handle'];
+  }
+
+  return $assoc_handle;
+}
+
+/**
+ * ?
+ */
+function openid_association_request($public) {
+  require_once(api_get_path(SYS_CODE_PATH).'auth/openid/openid.conf.php');
+
+  $request = array(
+    'openid.ns' => OPENID_NS_2_0,
+    'openid.mode' => 'associate',
+    'openid.session_type' => 'DH-SHA1',
+    'openid.assoc_type' => 'HMAC-SHA1'
+  );
+
+  if ($request['openid.session_type'] == 'DH-SHA1' || $request['openid.session_type'] == 'DH-SHA256') {
+    $cpub = _openid_dh_long_to_base64($public);
+    $request['openid.dh_consumer_public'] = $cpub;
+  }
+
+  return $request;
+}
+
+/**
+ *
+ */
+function openid_authentication_request($claimed_id, $identity, $return_to = '', $assoc_handle = '', $version = 2) {
+
+  $realm = ($return_to) ? $return_to : api_get_self();
+
+  $ns = ($version == 2) ? OPENID_NS_2_0 : OPENID_NS_1_0;
+  $request =  array(
+    'openid.ns' => $ns,
+    'openid.mode' => 'checkid_setup',
+    'openid.identity' => $identity,
+    'openid.claimed_id' => $claimed_id,
+    'openid.assoc_handle' => $assoc_handle,
+    'openid.return_to' => $return_to,
+  );
+
+  if ($version == 2) {
+    $request['openid.realm'] = $realm;
+  }
+  else {
+    $request['openid.trust_root'] = $realm;
+  }
+
+  // Simple Registration - we don't ask lastname and firstname because the only
   // available similar data is "fullname" and we would have to guess where to split
-  $request['openid.sreg.required'] = 'nickname,email';
-  $request['openid.ns.sreg'] = "http://openid.net/extensions/sreg/1.1";
-
-  //$request = array_merge($request, module_invoke_all('openid', 'request', $request));
-  //$request = array_merge($request);
-
-  return $request;
-}
-
-/**
- * Attempt to verify the response received from the OpenID Provider.
- *
- * @param $op_endpoint The OpenID Provider URL.
- * @param $response Array of repsonse values from the provider.
- *
- * @return boolean
- */
-function openid_verify_assertion($op_endpoint, $response) {
-
-  $valid = FALSE;
-
-	//TODO
-  $openid_association = Database::get_main_table(TABLE_MAIN_OPENID_ASSOCIATION);
-  $sql = sprintf("SELECT * FROM $openid_association WHERE assoc_handle = '%s'", $response['openid.assoc_handle']);
-  $res = Database::query($sql);
-  $association = Database::fetch_object($res);
-  if ($association && isset($association->session_type)) {
-    $keys_to_sign = explode(',', $response['openid.signed']);
-    $self_sig = _openid_signature($association, $response, $keys_to_sign);
-    if ($self_sig == $response['openid.sig']) {
-      $valid = TRUE;
-    }
-    else {
-      $valid = FALSE;
-    }
-  }
-  else {
-    $request = $response;
-    $request['openid.mode'] = 'check_authentication';
-    $message = _openid_create_message($request);
-    $headers = array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8');
-    $result = openid_http_request($op_endpoint, $headers, 'POST', _openid_encode_message($message));
-    if (!isset($result->error)) {
-      $response = _openid_parse_message($result->data);
-      if (strtolower(trim($response['is_valid'])) == 'true') {
-        $valid = TRUE;
-      }
-      else {
-        $valid = FALSE;
-      }
-    }
-  }
-
-  return $valid;
-}
-
-/**
- * Make a HTTP request - This function has been copied straight over from Drupal 6 code (drupal_http_request)
- */
-function openid_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) {
-  $result = new stdClass();
-
-  // Parse the URL and make sure we can handle the schema.
-  $uri = parse_url($url);
-
-  switch ($uri['scheme']) {
-    case 'http':
-      $port = isset($uri['port']) ? $uri['port'] : 80;
-      $host = $uri['host'] . ($port != 80 ? ':'. $port : '');
-      $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
-      break;
-    case 'https':
-      // Note: Only works for PHP 4.3 compiled with OpenSSL.
-      $port = isset($uri['port']) ? $uri['port'] : 443;
-      $host = $uri['host'] . ($port != 443 ? ':'. $port : '');
-      $fp = @fsockopen('ssl://'. $uri['host'], $port, $errno, $errstr, 20);
-      break;
-    default:
-      $result->error = 'invalid schema '. $uri['scheme'];
-      return $result;
-  }
-
-  // Make sure the socket opened properly.
-  if (!$fp) {
-    // When a network error occurs, we make sure that it is a negative number so
-    // it can clash with the HTTP status codes.
-    $result->code = -$errno;
-    $result->error = trim($errstr);
-    return $result;
-  }
-
-  // Construct the path to act on.
-  $path = isset($uri['path']) ? $uri['path'] : '/';
-  if (isset($uri['query'])) {
-    $path .= '?'. $uri['query'];
-  }
-
-  // Create HTTP request.
-  $defaults = array(
-    // RFC 2616: "non-standard ports MUST, default ports MAY be included".
-    // We don't add the port to prevent from breaking rewrite rules checking the
-    // host that do not take into account the port number.
-    'Host' => "Host: $host",
-    'User-Agent' => 'User-Agent: Dokeos (+http://dokeos.com/)',
-    'Content-Length' => 'Content-Length: '. strlen($data)
-  );
-
-  // If the server url has a user then attempt to use basic authentication
-  if (isset($uri['user'])) {
-    $defaults['Authorization'] = 'Authorization: Basic '. base64_encode($uri['user'] . (!empty($uri['pass']) ? ":". $uri['pass'] : ''));
-  }
-
-  foreach ($headers as $header => $value) {
-    $defaults[$header] = $header .': '. $value;
-  }
-
-  $request = $method .' '. $path ." HTTP/1.0\r\n";
-  $request .= implode("\r\n", $defaults);
-  $request .= "\r\n\r\n";
-  if ($data) {
-    $request .= $data ."\r\n";
-  }
-  $result->request = $request;
-
-  fwrite($fp, $request);
-
-  // Fetch response.
-  $response = '';
-  while (!feof($fp) && $chunk = fread($fp, 1024)) {
-    $response .= $chunk;
-  }
-  fclose($fp);
-
-  // Parse response.
-  list($split, $result->data) = explode("\r\n\r\n", $response, 2);
-  $split = preg_split("/\r\n|\n|\r/", $split);
-
-  list($protocol, $code, $text) = explode(' ', trim(array_shift($split)), 3);
-  $result->headers = array();
-
-  // Parse headers.
-  while ($line = trim(array_shift($split))) {
-    list($header, $value) = explode(':', $line, 2);
-    if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
-      // RFC 2109: the Set-Cookie response header comprises the token Set-
-      // Cookie:, followed by a comma-separated list of one or more cookies.
-      $result->headers[$header] .= ','. trim($value);
-    }
-    else {
-      $result->headers[$header] = trim($value);
-    }
-  }
-
-  $responses = array(
-    100 => 'Continue', 101 => 'Switching Protocols',
-    200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
-    300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
-    400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed',
-    500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'
-  );
-  // RFC 2616 states that all unknown HTTP codes must be treated the same as the
-  // base code in their class.
-  if (!isset($responses[$code])) {
-    $code = floor($code / 100) * 100;
-  }
-
-  switch ($code) {
-    case 200: // OK
-    case 304: // Not modified
-      break;
-    case 301: // Moved permanently
-    case 302: // Moved temporarily
-    case 307: // Moved temporarily
-      $location = $result->headers['Location'];
-
-      if ($retry) {
-        $result = openid_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
-        $result->redirect_code = $result->code;
-      }
-      $result->redirect_url = $location;
-
-      break;
-    default:
-      $result->error = $text;
-  }
-
-  $result->code = $code;
-  return $result;
+  $request['openid.sreg.required'] = 'nickname,email';
+  $request['openid.ns.sreg'] = "http://openid.net/extensions/sreg/1.1";
+
+  //$request = array_merge($request, module_invoke_all('openid', 'request', $request));
+  //$request = array_merge($request);
+
+  return $request;
+}
+
+/**
+ * Attempt to verify the response received from the OpenID Provider.
+ *
+ * @param $op_endpoint The OpenID Provider URL.
+ * @param $response Array of repsonse values from the provider.
+ *
+ * @return boolean
+ */
+function openid_verify_assertion($op_endpoint, $response) {
+
+  $valid = FALSE;
+
+	//TODO
+  $openid_association = Database::get_main_table(TABLE_MAIN_OPENID_ASSOCIATION);
+  $sql = sprintf("SELECT * FROM $openid_association WHERE assoc_handle = '%s'", $response['openid.assoc_handle']);
+  $res = Database::query($sql);
+  $association = Database::fetch_object($res);
+  if ($association && isset($association->session_type)) {
+    $keys_to_sign = explode(',', $response['openid.signed']);
+    $self_sig = _openid_signature($association, $response, $keys_to_sign);
+    if ($self_sig == $response['openid.sig']) {
+      $valid = TRUE;
+    }
+    else {
+      $valid = FALSE;
+    }
+  }
+  else {
+    $request = $response;
+    $request['openid.mode'] = 'check_authentication';
+    $message = _openid_create_message($request);
+    $headers = array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8');
+    $result = openid_http_request($op_endpoint, $headers, 'POST', _openid_encode_message($message));
+    if (!isset($result->error)) {
+      $response = _openid_parse_message($result->data);
+      if (strtolower(trim($response['is_valid'])) == 'true') {
+        $valid = TRUE;
+      }
+      else {
+        $valid = FALSE;
+      }
+    }
+  }
+
+  return $valid;
+}
+
+/**
+ * Make a HTTP request - This function has been copied straight over from Drupal 6 code (drupal_http_request)
+ */
+function openid_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) {
+  $result = new stdClass();
+
+  // Parse the URL and make sure we can handle the schema.
+  $uri = parse_url($url);
+
+  switch ($uri['scheme']) {
+    case 'http':
+      $port = isset($uri['port']) ? $uri['port'] : 80;
+      $host = $uri['host'] . ($port != 80 ? ':'. $port : '');
+      $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
+      break;
+    case 'https':
+      // Note: Only works for PHP 4.3 compiled with OpenSSL.
+      $port = isset($uri['port']) ? $uri['port'] : 443;
+      $host = $uri['host'] . ($port != 443 ? ':'. $port : '');
+      $fp = @fsockopen('ssl://'. $uri['host'], $port, $errno, $errstr, 20);
+      break;
+    default:
+      $result->error = 'invalid schema '. $uri['scheme'];
+      return $result;
+  }
+
+  // Make sure the socket opened properly.
+  if (!$fp) {
+    // When a network error occurs, we make sure that it is a negative number so
+    // it can clash with the HTTP status codes.
+    $result->code = -$errno;
+    $result->error = trim($errstr);
+    return $result;
+  }
+
+  // Construct the path to act on.
+  $path = isset($uri['path']) ? $uri['path'] : '/';
+  if (isset($uri['query'])) {
+    $path .= '?'. $uri['query'];
+  }
+
+  // Create HTTP request.
+  $defaults = array(
+    // RFC 2616: "non-standard ports MUST, default ports MAY be included".
+    // We don't add the port to prevent from breaking rewrite rules checking the
+    // host that do not take into account the port number.
+    'Host' => "Host: $host",
+    'User-Agent' => 'User-Agent: Dokeos (+http://dokeos.com/)',
+    'Content-Length' => 'Content-Length: '. strlen($data)
+  );
+
+  // If the server url has a user then attempt to use basic authentication
+  if (isset($uri['user'])) {
+    $defaults['Authorization'] = 'Authorization: Basic '. base64_encode($uri['user'] . (!empty($uri['pass']) ? ":". $uri['pass'] : ''));
+  }
+
+  foreach ($headers as $header => $value) {
+    $defaults[$header] = $header .': '. $value;
+  }
+
+  $request = $method .' '. $path ." HTTP/1.0\r\n";
+  $request .= implode("\r\n", $defaults);
+  $request .= "\r\n\r\n";
+  if ($data) {
+    $request .= $data ."\r\n";
+  }
+  $result->request = $request;
+
+  fwrite($fp, $request);
+
+  // Fetch response.
+  $response = '';
+  while (!feof($fp) && $chunk = fread($fp, 1024)) {
+    $response .= $chunk;
+  }
+  fclose($fp);
+
+  // Parse response.
+  list($split, $result->data) = explode("\r\n\r\n", $response, 2);
+  $split = preg_split("/\r\n|\n|\r/", $split);
+
+  list($protocol, $code, $text) = explode(' ', trim(array_shift($split)), 3);
+  $result->headers = array();
+
+  // Parse headers.
+  while ($line = trim(array_shift($split))) {
+    list($header, $value) = explode(':', $line, 2);
+    if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
+      // RFC 2109: the Set-Cookie response header comprises the token Set-
+      // Cookie:, followed by a comma-separated list of one or more cookies.
+      $result->headers[$header] .= ','. trim($value);
+    }
+    else {
+      $result->headers[$header] = trim($value);
+    }
+  }
+
+  $responses = array(
+    100 => 'Continue', 101 => 'Switching Protocols',
+    200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
+    300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
+    400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed',
+    500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'
+  );
+  // RFC 2616 states that all unknown HTTP codes must be treated the same as the
+  // base code in their class.
+  if (!isset($responses[$code])) {
+    $code = floor($code / 100) * 100;
+  }
+
+  switch ($code) {
+    case 200: // OK
+    case 304: // Not modified
+      break;
+    case 301: // Moved permanently
+    case 302: // Moved temporarily
+    case 307: // Moved temporarily
+      $location = $result->headers['Location'];
+
+      if ($retry) {
+        $result = openid_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
+        $result->redirect_code = $result->code;
+      }
+      $result->redirect_url = $location;
+
+      break;
+    default:
+      $result->error = $text;
+  }
+
+  $result->code = $code;
+  return $result;
 }

+ 160 - 160
main/blog/blog_admin.php

@@ -1,176 +1,176 @@
-<?php //$Id: announcements.php 16702 2008-11-10 13:02:30Z elixir_inter $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2008 Dokeos SPRL
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) various contributors
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
-	info@dokeos.com
-
-==============================================================================
-
-    BLOG HOMEPAGE
-
-	This file takes care of all blog navigation and displaying.
-
-	@package dokeos.blogs
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file = "blog";
-
-require_once('../inc/global.inc.php');
-$this_section=SECTION_COURSES;
-
-$blog_table_attachment 	= Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
-
-/* ------------	ACCESS RIGHTS ------------ */
-// notice for unauthorized people.
-api_protect_course_script(true);
-
-//------------ ONLY USERS REGISTERED IN THE COURSE----------------------
-if((!$is_allowed_in_course || !$is_courseMember) && !api_is_allowed_to_edit())
-{
-	api_not_allowed(true);//print headers/footers
-}
-
-
-if (api_is_allowed_to_edit())
-{
+<?php //$Id: announcements.php 16702 2008-11-10 13:02:30Z elixir_inter $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2008 Dokeos SPRL
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) various contributors
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	info@dokeos.com
+
+==============================================================================
+
+    BLOG HOMEPAGE
+
+	This file takes care of all blog navigation and displaying.
+
+	@package dokeos.blogs
+==============================================================================
+*/
+
+// name of the language file that needs to be included
+$language_file = "blog";
+
+require_once('../inc/global.inc.php');
+$this_section=SECTION_COURSES;
+
+$blog_table_attachment 	= Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
+
+/* ------------	ACCESS RIGHTS ------------ */
+// notice for unauthorized people.
+api_protect_course_script(true);
+
+//------------ ONLY USERS REGISTERED IN THE COURSE----------------------
+if((!$is_allowed_in_course || !$is_courseMember) && !api_is_allowed_to_edit())
+{
+	api_not_allowed(true);//print headers/footers
+}
+
+
+if (api_is_allowed_to_edit())
+{
 
 	require_once(api_get_path(LIBRARY_PATH) . "blog.lib.php");
 	$nameTools = get_lang("blog_management");
 
-	// showing the header if we are not in the learning path, if we are in
-	// the learning path, we do not include the banner so we have to explicitly
-	// include the stylesheet, which is normally done in the header
-	if ($_GET['origin'] != 'learnpath') {
-		$interbreadcrumb[]= array (
-		'url' => 'blog_admin.php?',
-		'name' => $nameTools
-		);
-		$my_url='';
-		if (isset($_GET['action']) && $_GET['action']=='add') {
-			$current_section=get_lang('AddBlog');
-			$my_url='action=add';
-		} elseif (isset($_GET['action']) && $_GET['action']=='edit') {
-			$current_section=get_lang('EditBlog');
-			$my_url='action=edit&amp;blog_id='.Security::remove_XSS($_GET['blog_id']);
+	// showing the header if we are not in the learning path, if we are in
+	// the learning path, we do not include the banner so we have to explicitly
+	// include the stylesheet, which is normally done in the header
+	if ($_GET['origin'] != 'learnpath') {
+		$interbreadcrumb[]= array (
+		'url' => 'blog_admin.php?',
+		'name' => $nameTools
+		);
+		$my_url='';
+		if (isset($_GET['action']) && $_GET['action']=='add') {
+			$current_section=get_lang('AddBlog');
+			$my_url='action=add';
+		} elseif (isset($_GET['action']) && $_GET['action']=='edit') {
+			$current_section=get_lang('EditBlog');
+			$my_url='action=edit&amp;blog_id='.Security::remove_XSS($_GET['blog_id']);
 		}
-		$interbreadcrumb[]= array (
-		'url' => 'blog_admin.php?'.$my_url,
-		'name' => $current_section
+		$interbreadcrumb[]= array (
+		'url' => 'blog_admin.php?'.$my_url,
+		'name' => $current_section
 		);
-		Display::display_header('');
-	} else {
-		echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"".$clarolineRepositoryWeb."css/default.css\"/>";
-	}
-	/*
-	==============================================================================
-		PROCESSING..
-	==============================================================================
-	*/
-	$get_blog_name	   = Security::remove_XSS($_POST['blog_name']);
-	$get_blog_subtitle = Security::remove_XSS($_POST['blog_subtitle']);
-	$get_blog_id       = Security::remove_XSS($_POST['blog_id']);
-
-	if (!empty($_POST['new_blog_submit']) AND !empty($_POST['blog_name'])) {
-		if (strlen(trim($_POST['blog_name']))>0)  {
-			Blog::create_blog($get_blog_name,$get_blog_subtitle);
-			Display::display_confirmation_message(get_lang('BlogStored'));
-		}
-
-	}
-	if (!empty($_POST['edit_blog_submit']) AND !empty($_POST['blog_name'])) {
-		if (strlen(trim($_POST['blog_name']))>0) {
-			Blog::edit_blog($get_blog_id,$get_blog_name,$get_blog_subtitle);
-			Display::display_confirmation_message(get_lang('BlogEdited'));
-		}
-	}
-	if (isset($_GET['action']) && $_GET['action'] == 'visibility') {
-		Blog::change_blog_visibility(Database::escape_string((int)$_GET['blog_id']));
-		Display::display_confirmation_message(get_lang('VisibilityChanged'));
-	}
-	if (isset($_GET['action']) && $_GET['action'] == 'delete') {
-		Blog::delete_blog(Database::escape_string((int)$_GET['blog_id']));
-		Display::display_confirmation_message(get_lang('BlogDeleted'));
-	}
-
-	/*
-	==============================================================================
-		DISPLAY
-	==============================================================================
-	*/
-	//api_display_tool_title($nameTools);
-	//api_introductionsection(TOOL_BLOG);
-
-
-		if (isset($_GET['action']) && $_GET['action'] == 'add') {
+		Display::display_header('');
+	} else {
+		echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"".$clarolineRepositoryWeb."css/default.css\"/>";
+	}
+	/*
+	==============================================================================
+		PROCESSING..
+	==============================================================================
+	*/
+	$get_blog_name	   = Security::remove_XSS($_POST['blog_name']);
+	$get_blog_subtitle = Security::remove_XSS($_POST['blog_subtitle']);
+	$get_blog_id       = Security::remove_XSS($_POST['blog_id']);
+
+	if (!empty($_POST['new_blog_submit']) AND !empty($_POST['blog_name'])) {
+		if (strlen(trim($_POST['blog_name']))>0)  {
+			Blog::create_blog($get_blog_name,$get_blog_subtitle);
+			Display::display_confirmation_message(get_lang('BlogStored'));
+		}
+
+	}
+	if (!empty($_POST['edit_blog_submit']) AND !empty($_POST['blog_name'])) {
+		if (strlen(trim($_POST['blog_name']))>0) {
+			Blog::edit_blog($get_blog_id,$get_blog_name,$get_blog_subtitle);
+			Display::display_confirmation_message(get_lang('BlogEdited'));
+		}
+	}
+	if (isset($_GET['action']) && $_GET['action'] == 'visibility') {
+		Blog::change_blog_visibility(Database::escape_string((int)$_GET['blog_id']));
+		Display::display_confirmation_message(get_lang('VisibilityChanged'));
+	}
+	if (isset($_GET['action']) && $_GET['action'] == 'delete') {
+		Blog::delete_blog(Database::escape_string((int)$_GET['blog_id']));
+		Display::display_confirmation_message(get_lang('BlogDeleted'));
+	}
+
+	/*
+	==============================================================================
+		DISPLAY
+	==============================================================================
+	*/
+	//api_display_tool_title($nameTools);
+	//api_introductionsection(TOOL_BLOG);
+
+
+		if (isset($_GET['action']) && $_GET['action'] == 'add') {
 			// we show the form if
-			// 1. no post data
-			// 2. there is post data and one of the required form elements is empty
-			if (!$_POST OR (!empty($_POST) AND (empty($_POST['new_blog_submit']) OR empty($_POST['blog_name'])))) {
-				// if there is post data there is certainly an error in the form
-				/*if ($_POST){
-					Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'));
-				}*/
-				if (strlen($_POST['blog_name'])==0) {
-				if (count($_POST)>0) {
-					Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'));
-				}
+			// 1. no post data
+			// 2. there is post data and one of the required form elements is empty
+			if (!$_POST OR (!empty($_POST) AND (empty($_POST['new_blog_submit']) OR empty($_POST['blog_name'])))) {
+				// if there is post data there is certainly an error in the form
+				/*if ($_POST){
+					Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'));
+				}*/
+				if (strlen($_POST['blog_name'])==0) {
+				if (count($_POST)>0) {
+					Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'));
+				}
 
 
 			}
-			Blog::display_new_blog_form();
-		}
-		}
+			Blog::display_new_blog_form();
+		}
+		}
 
-		if (isset($_GET['action']) && $_GET['action'] == 'edit') {
+		if (isset($_GET['action']) && $_GET['action'] == 'edit') {
 			// we show the form if
-			// 1. no post data
-			// 2. there is post data and one of the three form elements is empty
-			if (!$_POST OR (!empty($_POST) AND (empty($_POST['edit_blog_submit']) OR empty($_POST['blog_name']) )))
-			{
-				// if there is post data there is certainly an error in the form
-				if ($_POST) {
-					Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'));
-				}
-			Blog::display_edit_blog_form(Database::escape_string((int)$_GET['blog_id']));
-			}
-		}
-
-		echo '<div class="actions">';
-		echo "<a href='".api_get_self()."?".api_get_cidreq()."&action=add'>",Display::return_icon('blog_new.gif',get_lang('AddBlog')),get_lang('AddBlog')."</a>";
-		echo '</div>';
-		/*echo "<table width=\"100%\" border=\"0\" cellspacing=\"2\" class='data_table'>";
-		echo	"<tr>",
-					 "<th>",get_lang('Title'),"</th>\n",
-					 "<th>",get_lang('Subtitle'),"</th>\n",
-					 "<th>",get_lang('Modify'),"</th>\n",
-				"</tr>\n";
-
-		echo "</table>";*/
+			// 1. no post data
+			// 2. there is post data and one of the three form elements is empty
+			if (!$_POST OR (!empty($_POST) AND (empty($_POST['edit_blog_submit']) OR empty($_POST['blog_name']) )))
+			{
+				// if there is post data there is certainly an error in the form
+				if ($_POST) {
+					Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'));
+				}
+			Blog::display_edit_blog_form(Database::escape_string((int)$_GET['blog_id']));
+			}
+		}
+
+		echo '<div class="actions">';
+		echo "<a href='".api_get_self()."?".api_get_cidreq()."&action=add'>",Display::return_icon('blog_new.gif',get_lang('AddBlog')),get_lang('AddBlog')."</a>";
+		echo '</div>';
+		/*echo "<table width=\"100%\" border=\"0\" cellspacing=\"2\" class='data_table'>";
+		echo	"<tr>",
+					 "<th>",get_lang('Title'),"</th>\n",
+					 "<th>",get_lang('Subtitle'),"</th>\n",
+					 "<th>",get_lang('Modify'),"</th>\n",
+				"</tr>\n";
+
+		echo "</table>";*/
 		Blog::display_blog_list();
 
-	} else {
+	} else {
 		api_not_allowed(true);
-	}
-
-// Display the footer
-Display::display_footer();
+	}
+
+// Display the footer
+Display::display_footer();
 ?>

+ 126 - 126
main/blog/calendar.php

@@ -1,131 +1,131 @@
-<?php
-// name of the language file that needs to be included
+<?php
+// name of the language file that needs to be included
 $language_file = 'agenda';
-
+
 // including the global
-include('../inc/global.inc.php');
-
-// the variables for the days and the months
-// Defining the shorts for the days
-$DaysShort = api_get_week_days_short();
-// Defining the days of the week to allow translation of the days
-$DaysLong = api_get_week_days_long();
-// Defining the months of the year to allow translation of the months
-$MonthsLong = api_get_months_long();
-
-?>
-<html>
-<head>
-<title>Calendar</title>
-
-<style type="text/css">
-table.calendar
-{
+include('../inc/global.inc.php');
+
+// the variables for the days and the months
+// Defining the shorts for the days
+$DaysShort = api_get_week_days_short();
+// Defining the days of the week to allow translation of the days
+$DaysLong = api_get_week_days_long();
+// Defining the months of the year to allow translation of the months
+$MonthsLong = api_get_months_long();
+
+?>
+<html>
+<head>
+<title>Calendar</title>
+
+<style type="text/css">
+table.calendar
+{
 	width: 100%;
-	font-size: 11px;
-	font-family: verdana, arial, helvetica, sans-serif;
-}
-table.calendar .monthyear
-{
-	background-color: #4171B5;
-	text-align: center;
-	color: #ffffff;
-}
-table.calendar .daynames
-{
-	background-color: #D3DFF1;
-	text-align: center;
-}
-table.calendar td
-{
-	width: 25px;
-	height: 25px;
+	font-size: 11px;
+	font-family: verdana, arial, helvetica, sans-serif;
+}
+table.calendar .monthyear
+{
+	background-color: #4171B5;
+	text-align: center;
+	color: #ffffff;
+}
+table.calendar .daynames
+{
+	background-color: #D3DFF1;
+	text-align: center;
+}
+table.calendar td
+{
+	width: 25px;
+	height: 25px;
 	background-color: #f5f5f5;
-	text-align: center;
-}
-table.calendar td.selected
-{
+	text-align: center;
+}
+table.calendar td.selected
+{
 	border: 1px solid #ff0000;
-	background-color: #FFCECE;
-}
-table.calendar td a
-{
-	width: 25px;
-	height: 25px;
-	text-decoration: none;
-}
-table.calendar td a:hover
-{
-	background-color: #ffff00;
-}
-table.calendar .monthyear a
-{
-	text-align: center;
-	color: #ffffff;
-}
-table.calendar .monthyear a:hover
-{
-	text-align: center;
-	color: #ff0000;
-	background-color: #ffff00;
-}
-</style>
-<script language="JavaScript" type="text/javascript">
-<!--
-    /* added 2004-06-10 by Michael Keck
-     *       we need this for Backwards-Compatibility and resolving problems
-     *       with non DOM browsers, which may have problems with css 2 (like NC 4)
-    */
-    var isDOM      = (typeof(document.getElementsByTagName) != 'undefined'
-                      && typeof(document.createElement) != 'undefined')
-                   ? 1 : 0;
-    var isIE4      = (typeof(document.all) != 'undefined'
-                      && parseInt(navigator.appVersion) >= 4)
-                   ? 1 : 0;
-    var isNS4      = (typeof(document.layers) != 'undefined')
-                   ? 1 : 0;
-    var capable    = (isDOM || isIE4 || isNS4)
-                   ? 1 : 0;
-    // Uggly fix for Opera and Konqueror 2.2 that are half DOM compliant
-    if (capable) {
-        if (typeof(window.opera) != 'undefined') {
-            var browserName = ' ' + navigator.userAgent.toLowerCase();
-            if ((browserName.indexOf('konqueror 7') == 0)) {
-                capable = 0;
-            }
-        } else if (typeof(navigator.userAgent) != 'undefined') {
-            var browserName = ' ' + navigator.userAgent.toLowerCase();
-            if ((browserName.indexOf('konqueror') > 0) && (browserName.indexOf('konqueror/3') == 0)) {
-                capable = 0;
-            }
-        } // end if... else if...
-    } // end if
-//-->
-</script>
-<script type="text/javascript" src="tbl_change.js"></script>
-<script type="text/javascript">
-<!--
-var month_names = new Array(
-<?php
-foreach($MonthsLong as $index => $month)
-{
-	echo '"'.$month.'",';
-}
-?>
-"");
-var day_names = new Array(
-<?php
-foreach($DaysShort as $index => $day)
-{
-	echo '"'.$day.'",';
-}
-?>
-"");
-//-->
-</script>
-</head>
-<body onLoad="initCalendar();">
-<div id="calendar_data"></div>
-<div id="clock_data"></div>
-</body>
-</html>
+	background-color: #FFCECE;
+}
+table.calendar td a
+{
+	width: 25px;
+	height: 25px;
+	text-decoration: none;
+}
+table.calendar td a:hover
+{
+	background-color: #ffff00;
+}
+table.calendar .monthyear a
+{
+	text-align: center;
+	color: #ffffff;
+}
+table.calendar .monthyear a:hover
+{
+	text-align: center;
+	color: #ff0000;
+	background-color: #ffff00;
+}
+</style>
+<script language="JavaScript" type="text/javascript">
+<!--
+    /* added 2004-06-10 by Michael Keck
+     *       we need this for Backwards-Compatibility and resolving problems
+     *       with non DOM browsers, which may have problems with css 2 (like NC 4)
+    */
+    var isDOM      = (typeof(document.getElementsByTagName) != 'undefined'
+                      && typeof(document.createElement) != 'undefined')
+                   ? 1 : 0;
+    var isIE4      = (typeof(document.all) != 'undefined'
+                      && parseInt(navigator.appVersion) >= 4)
+                   ? 1 : 0;
+    var isNS4      = (typeof(document.layers) != 'undefined')
+                   ? 1 : 0;
+    var capable    = (isDOM || isIE4 || isNS4)
+                   ? 1 : 0;
+    // Uggly fix for Opera and Konqueror 2.2 that are half DOM compliant
+    if (capable) {
+        if (typeof(window.opera) != 'undefined') {
+            var browserName = ' ' + navigator.userAgent.toLowerCase();
+            if ((browserName.indexOf('konqueror 7') == 0)) {
+                capable = 0;
+            }
+        } else if (typeof(navigator.userAgent) != 'undefined') {
+            var browserName = ' ' + navigator.userAgent.toLowerCase();
+            if ((browserName.indexOf('konqueror') > 0) && (browserName.indexOf('konqueror/3') == 0)) {
+                capable = 0;
+            }
+        } // end if... else if...
+    } // end if
+//-->
+</script>
+<script type="text/javascript" src="tbl_change.js"></script>
+<script type="text/javascript">
+<!--
+var month_names = new Array(
+<?php
+foreach($MonthsLong as $index => $month)
+{
+	echo '"'.$month.'",';
+}
+?>
+"");
+var day_names = new Array(
+<?php
+foreach($DaysShort as $index => $day)
+{
+	echo '"'.$day.'",';
+}
+?>
+"");
+//-->
+</script>
+</head>
+<body onLoad="initCalendar();">
+<div id="calendar_data"></div>
+<div id="clock_data"></div>
+</body>
+</html>

+ 158 - 158
main/blog/tbl_change.js

@@ -1,159 +1,159 @@
-var day;
-var month;
-var year;
-var hour;
-var minute;
-var second;
-var clock_set = 0;
-
-/**
- * Opens calendar window.
- *
- * @param   string      form name
- * @param   string      field name
- */
-function openCalendar(form, field) {
-    window.open("./calendar.php", "calendar", "width=220,height=200,status=no");
-	day = eval("document." + form + "." + field + "day.options["+ "document." + form + "." + field + "day.selectedIndex].value");
-    month = eval("document." + form + "." + field + "month.options["+ "document." + form + "." + field + "month.selectedIndex].value");
-   	month = month-1;
-    year = eval("document." + form + "." + field + "year.options["+ "document." + form + "." + field + "year.selectedIndex].value");
-	formName = form;
-	fieldName =field;
-}
-
-/**
- * Formats number to two digits.
- *
- * @param   int number to format.
- */
-function formatNum2(i, valtype) {
-    f = (i < 10 ? '0' : '') + i;
-    if (valtype && valtype != '') {
-        switch(valtype) {
-            case 'month':
-                f = (f > 12 ? 12 : f);
-                break;
-
-            case 'day':
-                f = (f > 31 ? 31 : f);
-                break;
-        }
-    }
-
-    return f;
-}
-
-/**
- * Formats number to four digits.
- *
- * @param   int number to format.
- */
-function formatNum4(i) {
-    return (i < 1000 ? i < 100 ? i < 10 ? '000' : '00' : '0' : '') + i;
-}
-
-/**
- * Initializes calendar window.
- */
-function initCalendar() {
-    if (!year && !month && !day) {
-		day = window.opener.day;
-		month = window.opener.month;
+var day;
+var month;
+var year;
+var hour;
+var minute;
+var second;
+var clock_set = 0;
+
+/**
+ * Opens calendar window.
+ *
+ * @param   string      form name
+ * @param   string      field name
+ */
+function openCalendar(form, field) {
+    window.open("./calendar.php", "calendar", "width=220,height=200,status=no");
+	day = eval("document." + form + "." + field + "day.options["+ "document." + form + "." + field + "day.selectedIndex].value");
+    month = eval("document." + form + "." + field + "month.options["+ "document." + form + "." + field + "month.selectedIndex].value");
+   	month = month-1;
+    year = eval("document." + form + "." + field + "year.options["+ "document." + form + "." + field + "year.selectedIndex].value");
+	formName = form;
+	fieldName =field;
+}
+
+/**
+ * Formats number to two digits.
+ *
+ * @param   int number to format.
+ */
+function formatNum2(i, valtype) {
+    f = (i < 10 ? '0' : '') + i;
+    if (valtype && valtype != '') {
+        switch(valtype) {
+            case 'month':
+                f = (f > 12 ? 12 : f);
+                break;
+
+            case 'day':
+                f = (f > 31 ? 31 : f);
+                break;
+        }
+    }
+
+    return f;
+}
+
+/**
+ * Formats number to four digits.
+ *
+ * @param   int number to format.
+ */
+function formatNum4(i) {
+    return (i < 1000 ? i < 100 ? i < 10 ? '000' : '00' : '0' : '') + i;
+}
+
+/**
+ * Initializes calendar window.
+ */
+function initCalendar() {
+    if (!year && !month && !day) {
+		day = window.opener.day;
+		month = window.opener.month;
 		year  = window.opener.year;
-        if (isNaN(year) || isNaN(month) || isNaN(day) || day == 0) {
-            dt      = new Date();
-            year    = dt.getFullYear();
-            month   = dt.getMonth();
-            day     = dt.getDate();
-        }
-    } else {
-        /* Moving in calendar */
-        if (month > 11) {
-            month = 0;
-            year++;
-        }
-        if (month < 0) {
-            month = 11;
-            year--;
-        }
-    }
-
-    if (document.getElementById) {
-        cnt = document.getElementById("calendar_data");
-    } else if (document.all) {
-        cnt = document.all["calendar_data"];
-    }
-
-    cnt.innerHTML = "";
-
-    str = ""
-
-    //heading table
-    str += '<table class="calendar"><tr><th class="monthyear" width="50%">';
-    str += '<a href="javascript:month--; initCalendar();">&laquo;</a> ';
-    str += month_names[month];
-    str += ' <a href="javascript:month++; initCalendar();">&raquo;</a>';
-    str += '</th><th class="monthyear" width="50%">';
-    str += '<a href="javascript:year--; initCalendar();">&laquo;</a> ';
-    str += year;
-    str += ' <a href="javascript:year++; initCalendar();">&raquo;</a>';
-    str += '</th></tr></table>';
-
-    str += '<table class="calendar"><tr>';
-    for (i = 0; i < 7; i++) {
-        str += "<th  class='daynames'>" + day_names[i] + "</th>";
-    }
-    str += "</tr>";
-
-    var firstDay = new Date(year, month, 1).getDay();
-    var lastDay = new Date(year, month + 1, 0).getDate();
-
-    str += "<tr>";
-
-    dayInWeek = 0;
-    for (i = 0; i < firstDay; i++) {
-        str += "<td>&nbsp;</td>";
-        dayInWeek++;
-    }
-    for (i = 1; i <= lastDay; i++) {
-        if (dayInWeek == 7) {
-            str += "</tr><tr>";
-            dayInWeek = 0;
-        }
-
-        dispmonth = 1 + month;
-        actVal = formatNum4(year) + "-" + formatNum2(dispmonth, 'month') + "-" + formatNum2(i, 'day');
-        if (i == day) {
-            style = ' class="selected"';
-        } else {
-            style = '';
-        }
-        str += "<td" + style + "><a href=\"javascript:returnDate(" + i +","+month+","+year + ");\">" + i + "</a></td>"
-        dayInWeek++;
-    }
-    for (i = dayInWeek; i < 7; i++) {
-        str += "<td>&nbsp;</td>";
-    }
-
-    str += "</tr></table>";
-
-    cnt.innerHTML = str;
-}
-
-/**
- * Returns date from calendar.
- *
- * @param   string     date text
- */
-function returnDate(d,m,y) {
-	cmd = "window.opener.document."+window.opener.formName+"."+window.opener.fieldName+"day.selectedIndex = "+(d-1);
-	eval(cmd);
-	cmd = "window.opener.document."+window.opener.formName+"."+window.opener.fieldName+"month.selectedIndex = "+m;
-	eval(cmd);
-	date = new Date();
-    year = date.getFullYear()-1;
-	cmd = "window.opener.document."+window.opener.formName+"."+window.opener.fieldName+"year.selectedIndex = "+(y-year);
-	eval(cmd);
-    window.close();
-}
+        if (isNaN(year) || isNaN(month) || isNaN(day) || day == 0) {
+            dt      = new Date();
+            year    = dt.getFullYear();
+            month   = dt.getMonth();
+            day     = dt.getDate();
+        }
+    } else {
+        /* Moving in calendar */
+        if (month > 11) {
+            month = 0;
+            year++;
+        }
+        if (month < 0) {
+            month = 11;
+            year--;
+        }
+    }
+
+    if (document.getElementById) {
+        cnt = document.getElementById("calendar_data");
+    } else if (document.all) {
+        cnt = document.all["calendar_data"];
+    }
+
+    cnt.innerHTML = "";
+
+    str = ""
+
+    //heading table
+    str += '<table class="calendar"><tr><th class="monthyear" width="50%">';
+    str += '<a href="javascript:month--; initCalendar();">&laquo;</a> ';
+    str += month_names[month];
+    str += ' <a href="javascript:month++; initCalendar();">&raquo;</a>';
+    str += '</th><th class="monthyear" width="50%">';
+    str += '<a href="javascript:year--; initCalendar();">&laquo;</a> ';
+    str += year;
+    str += ' <a href="javascript:year++; initCalendar();">&raquo;</a>';
+    str += '</th></tr></table>';
+
+    str += '<table class="calendar"><tr>';
+    for (i = 0; i < 7; i++) {
+        str += "<th  class='daynames'>" + day_names[i] + "</th>";
+    }
+    str += "</tr>";
+
+    var firstDay = new Date(year, month, 1).getDay();
+    var lastDay = new Date(year, month + 1, 0).getDate();
+
+    str += "<tr>";
+
+    dayInWeek = 0;
+    for (i = 0; i < firstDay; i++) {
+        str += "<td>&nbsp;</td>";
+        dayInWeek++;
+    }
+    for (i = 1; i <= lastDay; i++) {
+        if (dayInWeek == 7) {
+            str += "</tr><tr>";
+            dayInWeek = 0;
+        }
+
+        dispmonth = 1 + month;
+        actVal = formatNum4(year) + "-" + formatNum2(dispmonth, 'month') + "-" + formatNum2(i, 'day');
+        if (i == day) {
+            style = ' class="selected"';
+        } else {
+            style = '';
+        }
+        str += "<td" + style + "><a href=\"javascript:returnDate(" + i +","+month+","+year + ");\">" + i + "</a></td>"
+        dayInWeek++;
+    }
+    for (i = dayInWeek; i < 7; i++) {
+        str += "<td>&nbsp;</td>";
+    }
+
+    str += "</tr></table>";
+
+    cnt.innerHTML = str;
+}
+
+/**
+ * Returns date from calendar.
+ *
+ * @param   string     date text
+ */
+function returnDate(d,m,y) {
+	cmd = "window.opener.document."+window.opener.formName+"."+window.opener.fieldName+"day.selectedIndex = "+(d-1);
+	eval(cmd);
+	cmd = "window.opener.document."+window.opener.formName+"."+window.opener.fieldName+"month.selectedIndex = "+m;
+	eval(cmd);
+	date = new Date();
+    year = date.getFullYear()-1;
+	cmd = "window.opener.document."+window.opener.formName+"."+window.opener.fieldName+"year.selectedIndex = "+(y-year);
+	eval(cmd);
+    window.close();
+}

+ 4678 - 4678
main/calendar/agenda.inc.php

@@ -1,4797 +1,4797 @@
-<?php //$Id: agenda.inc.php 22324 2009-07-23 17:44:22Z cfasanando $
-/* For licensing terms, see /dokeos_license.txt */
-/*
-==============================================================================
-	@author: Patrick Cool, patrick.cool@UGent.be
-	@version: 1.1
-	@todo: synchronisation with the function in myagenda.php (for instance: using one function for the mini_calendar
-==============================================================================
-	Large parts of the code are recycled from the old agenda tool, but I
-	reworked it and cleaned the code to make it more readable. The code for
-	the small calender on the left is taken from the My Agenda tool.
-
-	Reabability is also the reason why I use the if ($is_allowed_to_edit)
-	check for each part of the code. I'm aware that is duplication, but
-	it makes the code much easier to read.
-==============================================================================
-*/
-
-/*
------------------------------------------------------------
-	Constants and variables
------------------------------------------------------------
-*/
-// the variables for the days and the months
-// Defining the shorts for the days
+<?php //$Id: agenda.inc.php 22324 2009-07-23 17:44:22Z cfasanando $
+/* For licensing terms, see /dokeos_license.txt */
+/*
+==============================================================================
+	@author: Patrick Cool, patrick.cool@UGent.be
+	@version: 1.1
+	@todo: synchronisation with the function in myagenda.php (for instance: using one function for the mini_calendar
+==============================================================================
+	Large parts of the code are recycled from the old agenda tool, but I
+	reworked it and cleaned the code to make it more readable. The code for
+	the small calender on the left is taken from the My Agenda tool.
+
+	Reabability is also the reason why I use the if ($is_allowed_to_edit)
+	check for each part of the code. I'm aware that is duplication, but
+	it makes the code much easier to read.
+==============================================================================
+*/
+
+/*
+-----------------------------------------------------------
+	Constants and variables
+-----------------------------------------------------------
+*/
+// the variables for the days and the months
+// Defining the shorts for the days
 $DaysShort = api_get_week_days_short();
-// Defining the days of the week to allow translation of the days
+// Defining the days of the week to allow translation of the days
 $DaysLong = api_get_week_days_long();
-// Defining the months of the year to allow translation of the months
+// Defining the months of the year to allow translation of the months
 $MonthsLong = api_get_months_long();
-
-/*
-==============================================================================
-		FUNCTIONS
-==============================================================================
-*/
-
-/**
-* Retrieves all the agenda items from the table
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @author Yannick Warnier <yannick.warnier@dokeos.com> - cleanup
-* @param integer $month: the integer value of the month we are viewing
-* @param integer $year: the 4-digit year indication e.g. 2005
-* @return array
-*/
-function get_calendar_items($month, $year)
-{
-	global $_user, $_course;
-	global $is_allowed_to_edit;
-	global $select_month, $select_year;
-	$month=Database::escape_string($month);
-	$year=Database::escape_string($year);
-
-	// database variables
-	$TABLEAGENDA=Database::get_course_table(TABLE_AGENDA);
-	$TABLE_ITEM_PROPERTY=Database::get_course_table(TABLE_ITEM_PROPERTY);
-
-    $month_first_day = mktime(0,0,0,$month,1,$year);
-    $month_last_day  = mktime(0,0,0,$month+1,1,$year)-1;
-    if($month==12)
-    {
-        $month_last_day = mktime(0,0,0,1,1,$year+1)-1;
-    }
-
-	$group_memberships=GroupManager::get_group_ids($_course['dbName'], $_user['user_id']);
-    $repeats = array();
-
-	$session_condition = intval($_SESSION['id_session'])==0 ? '' : ' AND agenda.session_id IN (0,'.intval($_SESSION['id_session']).') ';
-
-
-	/*--------------------------------------------------
-			CONSTRUCT THE SQL STATEMENT
-	  --------------------------------------------------*/
-
-    $start = 0;
-    $stop = 0;
-	// this is to make a difference between showing everything (all months) or only the current month)
-	// $show_all_current is a part of the sql statement
-	if ($_SESSION['show']!=="showall")
-	{
-		$show_all_current=" AND MONTH(start_date)=$select_month AND year(start_date)=$select_year";
-        $start = mktime(0,0,0,$select_month,1,$select_year);
-        $stop = 0;
-        if(empty($select_year)){$select_year = date('Y');}
-        if(empty($select_month)){$select_month = date('m');}
-        if($select_month==12)
-        {
-            $stop = mktime(0,0,0,1,1,$select_year+1)-1;
-        }
-        else
-        {
-            $stop = mktime(0,0,0,$select_month+1,1,$select_year)-1;
-        }
-	}
-	else
-	{
-		$show_all_current="";
-        $start = time();
-        $stop = mktime(0,0,0,1,1,2038);//by default, set year to maximum for mktime()
-	}
-
-	// by default we use the id of the current user. The course administrator can see the agenda of other users by using the user / group filter
-	$user_id=$_user['user_id'];
-	if ($_SESSION['user']!==null)
-	{
-		$user_id=intval($_SESSION['user']);
-	}
-	if ($_SESSION['group']!==null)
-	{
-		$group_id=intval($_SESSION['group']);
-	}
-	if ($_SESSION['toolgroup']!==null)
-	{
-		$group_id=intval($_SESSION['toolgroup']);
-	}
-
-    $repeats = array(); //placeholder for repeated events
-	//echo "user:".$_SESSION['user']."group: ".$_SESSION['group'];
-	// A. you are a course admin
-	//if ($is_courseAdmin)
-
-	$session_condition = intval($_SESSION['id_session'])==0 ? '' : ' AND agenda.session_id IN (0,'.intval($_SESSION['id_session']).') ';
-
-	if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()))
-	{
-		// A.1. you are a course admin with a USER filter
-		// => see only the messages of this specific user + the messages of the group (s)he is member of.
-		if (!empty($_SESSION['user']))
-		{
-			$group_memberships=GroupManager::get_group_ids($_course['dbName'],$_SESSION['user']);
-			if (is_array($group_memberships) && count($group_memberships)>0)
-			{
-				$sql="SELECT
-					agenda.*, toolitemproperties.*
-					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
-					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-					AND	( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id IN (0, ".implode(", ", $group_memberships).") )
-					AND toolitemproperties.visibility='1'
-					$session_condition
-					ORDER BY start_date ".$_SESSION['sort'];
-			}
-			else
-			{
-				$sql="SELECT
-					agenda.*, toolitemproperties.*
-					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
-					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-					AND ( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id='0')
-					AND toolitemproperties.visibility='1'
-					$session_condition
-					ORDER BY start_date ".$_SESSION['sort'];
-			}
-		}
-		// A.2. you are a course admin with a GROUP filter
-		// => see only the messages of this specific group
-		elseif (!empty($_SESSION['group']))
-		{
-			$sql="SELECT
-				agenda.*, toolitemproperties.*
-				FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-				WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
-				AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-				AND ( toolitemproperties.to_group_id=$group_id OR toolitemproperties.to_group_id='0')
-				AND toolitemproperties.visibility='1'
-				$session_condition
-				GROUP BY toolitemproperties.ref
-				ORDER BY start_date ".$_SESSION['sort'];
-		}
-		// A.3 you are a course admin without any group or user filter
-		else
-		{
-			// A.3.a you are a course admin without user or group filter but WITH studentview
-			// => see all the messages of all the users and groups without editing possibilities
-			if ($_GET['isStudentView']=='true')
-			{
-				$sql="SELECT
-					agenda.*, toolitemproperties.*
-					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-					WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
-					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-					AND toolitemproperties.visibility='1'
-					$session_condition
-					GROUP BY toolitemproperties.ref
-					ORDER BY start_date ".$_SESSION['sort'];
-
-			}
-			// A.3.b you are a course admin without user or group filter and WITHOUT studentview (= the normal course admin view)
-			// => see all the messages of all the users and groups with editing possibilities
-			else
-			{
-				$sql="SELECT
-					agenda.*, toolitemproperties.*
-					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-					WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
-					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-					AND ( toolitemproperties.visibility='0' or toolitemproperties.visibility='1')
-					$session_condition
-					GROUP BY toolitemproperties.ref
-					ORDER BY start_date ".$_SESSION['sort'];
-			}
-		}
-
-	} //if (is_allowed_to_edit() OR( api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()))
-
-	// B. you are a student
-	else
-	{
-		if (is_array($group_memberships) and count($group_memberships)>0)
-		{
-			$sql="SELECT
-				agenda.*, toolitemproperties.*
-				FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-				WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
-				AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-				AND	( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id IN (0, ".implode(", ", $group_memberships).") )
-				AND toolitemproperties.visibility='1'
-				$session_condition
-				ORDER BY start_date ".$_SESSION['sort'];
-		}
-		else
-		{
-			if ($_user['user_id'])
-			{
-				$sql="SELECT
-					agenda.*, toolitemproperties.*
-					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
-					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-					AND ( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id='0')
-					AND toolitemproperties.visibility='1'
-					$session_condition
-					ORDER BY start_date ".$_SESSION['sort'];
-			}
-			else
-			{
-				$sql="SELECT
-					agenda.*, toolitemproperties.*
-					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
-					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-					AND toolitemproperties.to_group_id='0'
-					AND toolitemproperties.visibility='1'
-					$session_condition
-					ORDER BY start_date ".$_SESSION['sort'];
-			}
-		}
-	} // you are a student
-
-	//echo "<pre>".$sql."</pre>";
-	$result=Database::query($sql,__FILE__,__LINE__) or die(Database::error());
-
-	/////////////////
-	$data=array();
-	while ($row=Database::fetch_array($result))
-	{
-		$datum_item=(int)substr($row["start_date"],8,2);
-		$data[$datum_item][intval($datum_item)][] = $row;
-	}
-	return $data;
-}
-
-
-/**
-* show the mini calender of the given month
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @param array an array containing all the agenda items for the given month
-* @param integer $month: the integer value of the month we are viewing
-* @param integer $year: the 4-digit year indication e.g. 2005
-* @param string $monthName: the language variable for the mont name
-* @return html code
-* @todo refactor this so that $monthName is no longer needed as a parameter
-*/
-function display_minimonthcalendar($agendaitems, $month, $year, $monthName)
-{
-	global $DaysShort;
-	//Handle leap year
-	$numberofdays = array (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
-	if (($year % 400 == 0) or ($year % 4 == 0 and $year % 100 <> 0))
-		$numberofdays[2] = 29;
-	//Get the first day of the month
-	$dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
-	//Start the week on monday
-	$startdayofweek = $dayone['wday'] <> 0 ? ($dayone['wday'] - 1) : 6;
-	$backwardsURL = api_get_self()."?".api_get_cidreq()."&amp;coursePath=".(empty($_GET['coursePath'])?'':Security::remove_XSS($_GET['coursePath']))."&amp;courseCode=".(empty($_GET['courseCode'])?'':Security::remove_XSS($_GET['courseCode']))."&amp;month=". ($month == 1 ? 12 : $month -1)."&amp;year=". ($month == 1 ? $year -1 : $year);
-	$forewardsURL = api_get_self()."?".api_get_cidreq()."&amp;coursePath=".(empty($_GET['coursePath'])?'':Security::remove_XSS($_GET['coursePath']))."&amp;courseCode=".(empty($_GET['courseCode'])?'':Security::remove_XSS($_GET['courseCode']))."&amp;month=". ($month == 12 ? 1 : $month +1)."&amp;year=". ($month == 12 ? $year +1 : $year);
-
-	echo 	"<table class=\"data_table\">\n",
-			"<tr>\n",
-			"<th width=\"10%\"><a href=\"", $backwardsURL, "\"> &laquo; </a></th>\n",
-			"<th width=\"80%\" colspan=\"5\">", $monthName, " ", $year, "</th>\n",
-			"<th  width=\"10%\"><a href=\"", $forewardsURL, "\"> &raquo; </a></th>\n", "</tr>\n";
-	echo "<tr>\n";
-	for ($ii = 1; $ii < 8; $ii ++)
-	{
-		echo "<td class=\"weekdays\">", $DaysShort[$ii % 7], "</td>\n";
-	}
-	echo "</tr>\n";
-	$curday = -1;
-	$today = getdate();
-	while ($curday <= $numberofdays[$month])
-	{
-		echo "<tr>\n";
-		for ($ii = 0; $ii < 7; $ii ++)
-		{
-			if (($curday == -1) && ($ii == $startdayofweek))
-			{
-				$curday = 1;
-			}
-			if (($curday > 0) && ($curday <= $numberofdays[$month]))
-			{
-				$bgcolor = $ii < 5 ? $class="class=\"days_week\"" : $class="class=\"days_weekend\"";
-				$dayheader = "$curday";
-				if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon']))
-				{
-					$dayheader = "$curday";
-					$class = "class=\"days_today\"";
-				}
-				echo "\t<td ".$class.">";
-				if (!empty($agendaitems[$curday]))
-				{
-					$month_curday = array();
-					$items_curday = $agendaitems[$curday][$curday];
-
-					foreach ($items_curday as $item_curday) {
-						$start_date_item = $item_curday['start_date'];
-						$month_item = (int)substr($start_date_item,5,2);
-						if($month == $month_item) {
-							$month_curday[] = $item_curday['start_date'];
-						}
+
+/*
+==============================================================================
+		FUNCTIONS
+==============================================================================
+*/
+
+/**
+* Retrieves all the agenda items from the table
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @author Yannick Warnier <yannick.warnier@dokeos.com> - cleanup
+* @param integer $month: the integer value of the month we are viewing
+* @param integer $year: the 4-digit year indication e.g. 2005
+* @return array
+*/
+function get_calendar_items($month, $year)
+{
+	global $_user, $_course;
+	global $is_allowed_to_edit;
+	global $select_month, $select_year;
+	$month=Database::escape_string($month);
+	$year=Database::escape_string($year);
+
+	// database variables
+	$TABLEAGENDA=Database::get_course_table(TABLE_AGENDA);
+	$TABLE_ITEM_PROPERTY=Database::get_course_table(TABLE_ITEM_PROPERTY);
+
+    $month_first_day = mktime(0,0,0,$month,1,$year);
+    $month_last_day  = mktime(0,0,0,$month+1,1,$year)-1;
+    if($month==12)
+    {
+        $month_last_day = mktime(0,0,0,1,1,$year+1)-1;
+    }
+
+	$group_memberships=GroupManager::get_group_ids($_course['dbName'], $_user['user_id']);
+    $repeats = array();
+
+	$session_condition = intval($_SESSION['id_session'])==0 ? '' : ' AND agenda.session_id IN (0,'.intval($_SESSION['id_session']).') ';
+
+
+	/*--------------------------------------------------
+			CONSTRUCT THE SQL STATEMENT
+	  --------------------------------------------------*/
+
+    $start = 0;
+    $stop = 0;
+	// this is to make a difference between showing everything (all months) or only the current month)
+	// $show_all_current is a part of the sql statement
+	if ($_SESSION['show']!=="showall")
+	{
+		$show_all_current=" AND MONTH(start_date)=$select_month AND year(start_date)=$select_year";
+        $start = mktime(0,0,0,$select_month,1,$select_year);
+        $stop = 0;
+        if(empty($select_year)){$select_year = date('Y');}
+        if(empty($select_month)){$select_month = date('m');}
+        if($select_month==12)
+        {
+            $stop = mktime(0,0,0,1,1,$select_year+1)-1;
+        }
+        else
+        {
+            $stop = mktime(0,0,0,$select_month+1,1,$select_year)-1;
+        }
+	}
+	else
+	{
+		$show_all_current="";
+        $start = time();
+        $stop = mktime(0,0,0,1,1,2038);//by default, set year to maximum for mktime()
+	}
+
+	// by default we use the id of the current user. The course administrator can see the agenda of other users by using the user / group filter
+	$user_id=$_user['user_id'];
+	if ($_SESSION['user']!==null)
+	{
+		$user_id=intval($_SESSION['user']);
+	}
+	if ($_SESSION['group']!==null)
+	{
+		$group_id=intval($_SESSION['group']);
+	}
+	if ($_SESSION['toolgroup']!==null)
+	{
+		$group_id=intval($_SESSION['toolgroup']);
+	}
+
+    $repeats = array(); //placeholder for repeated events
+	//echo "user:".$_SESSION['user']."group: ".$_SESSION['group'];
+	// A. you are a course admin
+	//if ($is_courseAdmin)
+
+	$session_condition = intval($_SESSION['id_session'])==0 ? '' : ' AND agenda.session_id IN (0,'.intval($_SESSION['id_session']).') ';
+
+	if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()))
+	{
+		// A.1. you are a course admin with a USER filter
+		// => see only the messages of this specific user + the messages of the group (s)he is member of.
+		if (!empty($_SESSION['user']))
+		{
+			$group_memberships=GroupManager::get_group_ids($_course['dbName'],$_SESSION['user']);
+			if (is_array($group_memberships) && count($group_memberships)>0)
+			{
+				$sql="SELECT
+					agenda.*, toolitemproperties.*
+					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
+					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+					AND	( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id IN (0, ".implode(", ", $group_memberships).") )
+					AND toolitemproperties.visibility='1'
+					$session_condition
+					ORDER BY start_date ".$_SESSION['sort'];
+			}
+			else
+			{
+				$sql="SELECT
+					agenda.*, toolitemproperties.*
+					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
+					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+					AND ( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id='0')
+					AND toolitemproperties.visibility='1'
+					$session_condition
+					ORDER BY start_date ".$_SESSION['sort'];
+			}
+		}
+		// A.2. you are a course admin with a GROUP filter
+		// => see only the messages of this specific group
+		elseif (!empty($_SESSION['group']))
+		{
+			$sql="SELECT
+				agenda.*, toolitemproperties.*
+				FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+				WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
+				AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+				AND ( toolitemproperties.to_group_id=$group_id OR toolitemproperties.to_group_id='0')
+				AND toolitemproperties.visibility='1'
+				$session_condition
+				GROUP BY toolitemproperties.ref
+				ORDER BY start_date ".$_SESSION['sort'];
+		}
+		// A.3 you are a course admin without any group or user filter
+		else
+		{
+			// A.3.a you are a course admin without user or group filter but WITH studentview
+			// => see all the messages of all the users and groups without editing possibilities
+			if ($_GET['isStudentView']=='true')
+			{
+				$sql="SELECT
+					agenda.*, toolitemproperties.*
+					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+					WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
+					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+					AND toolitemproperties.visibility='1'
+					$session_condition
+					GROUP BY toolitemproperties.ref
+					ORDER BY start_date ".$_SESSION['sort'];
+
+			}
+			// A.3.b you are a course admin without user or group filter and WITHOUT studentview (= the normal course admin view)
+			// => see all the messages of all the users and groups with editing possibilities
+			else
+			{
+				$sql="SELECT
+					agenda.*, toolitemproperties.*
+					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+					WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
+					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+					AND ( toolitemproperties.visibility='0' or toolitemproperties.visibility='1')
+					$session_condition
+					GROUP BY toolitemproperties.ref
+					ORDER BY start_date ".$_SESSION['sort'];
+			}
+		}
+
+	} //if (is_allowed_to_edit() OR( api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()))
+
+	// B. you are a student
+	else
+	{
+		if (is_array($group_memberships) and count($group_memberships)>0)
+		{
+			$sql="SELECT
+				agenda.*, toolitemproperties.*
+				FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+				WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
+				AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+				AND	( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id IN (0, ".implode(", ", $group_memberships).") )
+				AND toolitemproperties.visibility='1'
+				$session_condition
+				ORDER BY start_date ".$_SESSION['sort'];
+		}
+		else
+		{
+			if ($_user['user_id'])
+			{
+				$sql="SELECT
+					agenda.*, toolitemproperties.*
+					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
+					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+					AND ( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id='0')
+					AND toolitemproperties.visibility='1'
+					$session_condition
+					ORDER BY start_date ".$_SESSION['sort'];
+			}
+			else
+			{
+				$sql="SELECT
+					agenda.*, toolitemproperties.*
+					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
+					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+					AND toolitemproperties.to_group_id='0'
+					AND toolitemproperties.visibility='1'
+					$session_condition
+					ORDER BY start_date ".$_SESSION['sort'];
+			}
+		}
+	} // you are a student
+
+	//echo "<pre>".$sql."</pre>";
+	$result=Database::query($sql,__FILE__,__LINE__) or die(Database::error());
+
+	/////////////////
+	$data=array();
+	while ($row=Database::fetch_array($result))
+	{
+		$datum_item=(int)substr($row["start_date"],8,2);
+		$data[$datum_item][intval($datum_item)][] = $row;
+	}
+	return $data;
+}
+
+
+/**
+* show the mini calender of the given month
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @param array an array containing all the agenda items for the given month
+* @param integer $month: the integer value of the month we are viewing
+* @param integer $year: the 4-digit year indication e.g. 2005
+* @param string $monthName: the language variable for the mont name
+* @return html code
+* @todo refactor this so that $monthName is no longer needed as a parameter
+*/
+function display_minimonthcalendar($agendaitems, $month, $year, $monthName)
+{
+	global $DaysShort;
+	//Handle leap year
+	$numberofdays = array (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
+	if (($year % 400 == 0) or ($year % 4 == 0 and $year % 100 <> 0))
+		$numberofdays[2] = 29;
+	//Get the first day of the month
+	$dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
+	//Start the week on monday
+	$startdayofweek = $dayone['wday'] <> 0 ? ($dayone['wday'] - 1) : 6;
+	$backwardsURL = api_get_self()."?".api_get_cidreq()."&amp;coursePath=".(empty($_GET['coursePath'])?'':Security::remove_XSS($_GET['coursePath']))."&amp;courseCode=".(empty($_GET['courseCode'])?'':Security::remove_XSS($_GET['courseCode']))."&amp;month=". ($month == 1 ? 12 : $month -1)."&amp;year=". ($month == 1 ? $year -1 : $year);
+	$forewardsURL = api_get_self()."?".api_get_cidreq()."&amp;coursePath=".(empty($_GET['coursePath'])?'':Security::remove_XSS($_GET['coursePath']))."&amp;courseCode=".(empty($_GET['courseCode'])?'':Security::remove_XSS($_GET['courseCode']))."&amp;month=". ($month == 12 ? 1 : $month +1)."&amp;year=". ($month == 12 ? $year +1 : $year);
+
+	echo 	"<table class=\"data_table\">\n",
+			"<tr>\n",
+			"<th width=\"10%\"><a href=\"", $backwardsURL, "\"> &laquo; </a></th>\n",
+			"<th width=\"80%\" colspan=\"5\">", $monthName, " ", $year, "</th>\n",
+			"<th  width=\"10%\"><a href=\"", $forewardsURL, "\"> &raquo; </a></th>\n", "</tr>\n";
+	echo "<tr>\n";
+	for ($ii = 1; $ii < 8; $ii ++)
+	{
+		echo "<td class=\"weekdays\">", $DaysShort[$ii % 7], "</td>\n";
+	}
+	echo "</tr>\n";
+	$curday = -1;
+	$today = getdate();
+	while ($curday <= $numberofdays[$month])
+	{
+		echo "<tr>\n";
+		for ($ii = 0; $ii < 7; $ii ++)
+		{
+			if (($curday == -1) && ($ii == $startdayofweek))
+			{
+				$curday = 1;
+			}
+			if (($curday > 0) && ($curday <= $numberofdays[$month]))
+			{
+				$bgcolor = $ii < 5 ? $class="class=\"days_week\"" : $class="class=\"days_weekend\"";
+				$dayheader = "$curday";
+				if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon']))
+				{
+					$dayheader = "$curday";
+					$class = "class=\"days_today\"";
+				}
+				echo "\t<td ".$class.">";
+				if (!empty($agendaitems[$curday]))
+				{
+					$month_curday = array();
+					$items_curday = $agendaitems[$curday][$curday];
+
+					foreach ($items_curday as $item_curday) {
+						$start_date_item = $item_curday['start_date'];
+						$month_item = (int)substr($start_date_item,5,2);
+						if($month == $month_item) {
+							$month_curday[] = $item_curday['start_date'];
+						}
 					}
 
 					if (!empty($month_curday)) {
-						echo "<a href=\"".api_get_self()."?".api_get_cidreq()."&amp;action=view&amp;view=day&amp;day=".$curday."&amp;month=".$month."&amp;year=".$year."#".$curday."\">".$dayheader."</a>";
-					} else {
-						echo $dayheader;
-					}
+						echo "<a href=\"".api_get_self()."?".api_get_cidreq()."&amp;action=view&amp;view=day&amp;day=".$curday."&amp;month=".$month."&amp;year=".$year."#".$curday."\">".$dayheader."</a>";
+					} else {
+						echo $dayheader;
+					}
+				}
+				else
+				{
+					echo $dayheader;
 				}
-				else
-				{
-					echo $dayheader;
-				}
-				// "a".$dayheader." <span class=\"agendaitem\">".$agendaitems[$curday]."</span>\n";
-				echo "</td>\n";
-				$curday ++;
-			}
-			else
-			{
-				echo "<td>&nbsp;</td>\n";
-			}
-		}
-		echo "</tr>\n";
-	}
-	echo "</table>\n";
-}
-
-
-/**
-* show the calender of the given month
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @param integer $month: the integer value of the month we are viewing
-* @param integer $year: the 4-digit year indication e.g. 2005
-* @return html code
-*/
-function display_monthcalendar($month, $year)
-{
-	global $MonthsLong;
-	global $DaysShort;
-	global $origin;
-
-	// grabbing all the calendar items for this year and storing it in a array
-	$data=get_calendar_items($month,$year);
-//	$data_global=get_global_calendar_items($month,$year);
-//	$data_global=get_global_agenda_items($agendaitems, $day, $month, $year, $week, $type);
-	//Handle leap year
-	$numberofdays = array(0,31,28,31,30,31,30,31,31,30,31,30,31);
-	if (($year%400 == 0) or ($year%4==0 and $year%100<>0)) $numberofdays[2] = 29;
-
-	//Get the first day of the month
-	$dayone = getdate(mktime(0,0,0,$month,1,$year));
-  	//Start the week on monday
-	$startdayofweek = $dayone['wday']<>0 ? ($dayone['wday']-1) : 6;
-
-	$backwardsURL = api_get_self()."?".api_get_cidreq()."&amp;origin=$origin&amp;month=".($month==1 ? 12 : $month-1)."&amp;year=".($month==1 ? $year-1 : $year);
-	$forewardsURL = api_get_self()."?".api_get_cidreq()."&amp;origin=$origin&amp;month=".($month==12 ? 1 : $month+1)."&amp;year=".($month==12 ? $year+1 : $year);
-
-	   $maand_array_maandnummer=$month-1;
-
-	echo "<table class=\"data_table\">\n",
-		"<tr>\n",
-		"<th width=\"10%\"><a href=\"",$backwardsURL,"\"> &laquo; </a></th>\n",
-		"<th width=\"80%\" colspan=\"5\">",$MonthsLong[$maand_array_maandnummer]," ",$year,"</th>\n",
-		"<th width=\"10%\"><a href=\"",$forewardsURL,"\"> &raquo; </a></th>\n",
-		"</tr>\n";
-
-	echo "<tr>\n";
-
-	for ($ii=1;$ii<8; $ii++)
-	{
-		echo "<td class=\"weekdays\" width=\"14%\">",$DaysShort[$ii%7],"</td>\n";
-	}
-
-	echo "</tr>\n";
-	$curday = -1;
-	$today = getdate();
-	while ($curday <=$numberofdays[$month])
-  	{
+				// "a".$dayheader." <span class=\"agendaitem\">".$agendaitems[$curday]."</span>\n";
+				echo "</td>\n";
+				$curday ++;
+			}
+			else
+			{
+				echo "<td>&nbsp;</td>\n";
+			}
+		}
+		echo "</tr>\n";
+	}
+	echo "</table>\n";
+}
+
+
+/**
+* show the calender of the given month
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @param integer $month: the integer value of the month we are viewing
+* @param integer $year: the 4-digit year indication e.g. 2005
+* @return html code
+*/
+function display_monthcalendar($month, $year)
+{
+	global $MonthsLong;
+	global $DaysShort;
+	global $origin;
+
+	// grabbing all the calendar items for this year and storing it in a array
+	$data=get_calendar_items($month,$year);
+//	$data_global=get_global_calendar_items($month,$year);
+//	$data_global=get_global_agenda_items($agendaitems, $day, $month, $year, $week, $type);
+	//Handle leap year
+	$numberofdays = array(0,31,28,31,30,31,30,31,31,30,31,30,31);
+	if (($year%400 == 0) or ($year%4==0 and $year%100<>0)) $numberofdays[2] = 29;
+
+	//Get the first day of the month
+	$dayone = getdate(mktime(0,0,0,$month,1,$year));
+  	//Start the week on monday
+	$startdayofweek = $dayone['wday']<>0 ? ($dayone['wday']-1) : 6;
+
+	$backwardsURL = api_get_self()."?".api_get_cidreq()."&amp;origin=$origin&amp;month=".($month==1 ? 12 : $month-1)."&amp;year=".($month==1 ? $year-1 : $year);
+	$forewardsURL = api_get_self()."?".api_get_cidreq()."&amp;origin=$origin&amp;month=".($month==12 ? 1 : $month+1)."&amp;year=".($month==12 ? $year+1 : $year);
+
+	   $maand_array_maandnummer=$month-1;
+
+	echo "<table class=\"data_table\">\n",
+		"<tr>\n",
+		"<th width=\"10%\"><a href=\"",$backwardsURL,"\"> &laquo; </a></th>\n",
+		"<th width=\"80%\" colspan=\"5\">",$MonthsLong[$maand_array_maandnummer]," ",$year,"</th>\n",
+		"<th width=\"10%\"><a href=\"",$forewardsURL,"\"> &raquo; </a></th>\n",
+		"</tr>\n";
+
+	echo "<tr>\n";
+
+	for ($ii=1;$ii<8; $ii++)
+	{
+		echo "<td class=\"weekdays\" width=\"14%\">",$DaysShort[$ii%7],"</td>\n";
+	}
+
+	echo "</tr>\n";
+	$curday = -1;
+	$today = getdate();
+	while ($curday <=$numberofdays[$month])
+  	{
 		echo "<tr>\n";
-    	for ($ii=0; $ii<7; $ii++)
-	  	{
-	  		if (($curday == -1)&&($ii==$startdayofweek))
-			{
-	    		$curday = 1;
-			}
-			if (($curday>0)&&($curday<=$numberofdays[$month]))
-			{
-				$bgcolor = $ii<5 ? "class=\"row_odd\"" : "class=\"row_even\"";
-
-				$dayheader = "$curday";
-
-				if (key_exists($curday,$data)) {
-					$dayheader="<a href='".api_get_self()."?".api_get_cidreq()."&amp;view=list&amp;origin=$origin&amp;month=$month&amp;year=$year&amp;day=$curday#$curday'>".$curday."</a>";
-					foreach ($data[$curday] as $key=>$agenda_item)
-					{
-						foreach ($agenda_item as $key=>$value) {
-							$month_start_date = (int)substr($value['start_date'],5,2);
-							if ($month == $month_start_date) {
-								$start_time= date("H:i",strtotime($value['start_date']));
-								$end_time= date("H:i",strtotime($value['end_date']));
-								$dayheader .= '<br />'.get_lang("StartTimeWindow").'&nbsp;<i>'.$start_time.'</i>&nbsp;-&nbsp;'.get_lang("EndTimeWindow").'&nbsp;<i>'.$end_time.'&nbsp;</i>';
-								$dayheader .= '<br />';
-								$dayheader .= $value['title'];
-								$dayheader .= '<br/>';
-							}
-								//$agendaitems = get_global_agenda_items($agendaitems, $curday, $month, $year, $startdayofweek, "month_view");
-								//echo $agendaitems['title'];
-						}
-
+    	for ($ii=0; $ii<7; $ii++)
+	  	{
+	  		if (($curday == -1)&&($ii==$startdayofweek))
+			{
+	    		$curday = 1;
+			}
+			if (($curday>0)&&($curday<=$numberofdays[$month]))
+			{
+				$bgcolor = $ii<5 ? "class=\"row_odd\"" : "class=\"row_even\"";
+
+				$dayheader = "$curday";
+
+				if (key_exists($curday,$data)) {
+					$dayheader="<a href='".api_get_self()."?".api_get_cidreq()."&amp;view=list&amp;origin=$origin&amp;month=$month&amp;year=$year&amp;day=$curday#$curday'>".$curday."</a>";
+					foreach ($data[$curday] as $key=>$agenda_item)
+					{
+						foreach ($agenda_item as $key=>$value) {
+							$month_start_date = (int)substr($value['start_date'],5,2);
+							if ($month == $month_start_date) {
+								$start_time= date("H:i",strtotime($value['start_date']));
+								$end_time= date("H:i",strtotime($value['end_date']));
+								$dayheader .= '<br />'.get_lang("StartTimeWindow").'&nbsp;<i>'.$start_time.'</i>&nbsp;-&nbsp;'.get_lang("EndTimeWindow").'&nbsp;<i>'.$end_time.'&nbsp;</i>';
+								$dayheader .= '<br />';
+								$dayheader .= $value['title'];
+								$dayheader .= '<br/>';
+							}
+								//$agendaitems = get_global_agenda_items($agendaitems, $curday, $month, $year, $startdayofweek, "month_view");
+								//echo $agendaitems['title'];
+						}
+
 					}
-				}
-
-				if (($curday==$today['mday'])&&($year ==$today['year'])&&($month == $today['mon']))
-				{
-			echo "<td id=\"today\" ",$bgcolor,"\">".$dayheader." \n";
-      }
-				else
-				{
-			echo "<td id=\"days\" ",$bgcolor,"\">".$dayheader." \n";
-				}
-			echo "</td>\n";
-
-	      		$curday++;
-	    }
-	  		else
-	    {
-	echo "<td>&nbsp;</td>";
-
-	    }
-		}
-	echo "</tr>";
-    }
-echo "</table>";
-}
-
-
-/**
-* returns all the javascript that is required for easily selecting the target people/groups this goes into the $htmlHeadXtra[] array
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @return javascript code
-*/
-function to_javascript()
-{
-$Send2All=get_lang("Send2All");
-
-
-return "<script type=\"text/javascript\" language=\"JavaScript\">
-
-<!-- Begin javascript menu swapper
-
-function move(fbox,	tbox)
-{
-	var	arrFbox	= new Array();
-	var	arrTbox	= new Array();
-	var	arrLookup =	new	Array();
-
-	var	i;
-	for	(i = 0;	i <	tbox.options.length; i++)
-	{
-		arrLookup[tbox.options[i].text]	= tbox.options[i].value;
-		arrTbox[i] = tbox.options[i].text;
-	}
-
-	var	fLength	= 0;
-	var	tLength	= arrTbox.length;
-
-	for(i =	0; i < fbox.options.length;	i++)
-	{
-		arrLookup[fbox.options[i].text]	= fbox.options[i].value;
-
-		if (fbox.options[i].selected &&	fbox.options[i].value != \"\")
-		{
-			arrTbox[tLength] = fbox.options[i].text;
-			tLength++;
-		}
-		else
-		{
-			arrFbox[fLength] = fbox.options[i].text;
-			fLength++;
-		}
-	}
-
-	//arrFbox.sort();
+				}
+
+				if (($curday==$today['mday'])&&($year ==$today['year'])&&($month == $today['mon']))
+				{
+			echo "<td id=\"today\" ",$bgcolor,"\">".$dayheader." \n";
+      }
+				else
+				{
+			echo "<td id=\"days\" ",$bgcolor,"\">".$dayheader." \n";
+				}
+			echo "</td>\n";
+
+	      		$curday++;
+	    }
+	  		else
+	    {
+	echo "<td>&nbsp;</td>";
+
+	    }
+		}
+	echo "</tr>";
+    }
+echo "</table>";
+}
+
+
+/**
+* returns all the javascript that is required for easily selecting the target people/groups this goes into the $htmlHeadXtra[] array
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @return javascript code
+*/
+function to_javascript()
+{
+$Send2All=get_lang("Send2All");
+
+
+return "<script type=\"text/javascript\" language=\"JavaScript\">
+
+<!-- Begin javascript menu swapper
+
+function move(fbox,	tbox)
+{
+	var	arrFbox	= new Array();
+	var	arrTbox	= new Array();
+	var	arrLookup =	new	Array();
+
+	var	i;
+	for	(i = 0;	i <	tbox.options.length; i++)
+	{
+		arrLookup[tbox.options[i].text]	= tbox.options[i].value;
+		arrTbox[i] = tbox.options[i].text;
+	}
+
+	var	fLength	= 0;
+	var	tLength	= arrTbox.length;
+
+	for(i =	0; i < fbox.options.length;	i++)
+	{
+		arrLookup[fbox.options[i].text]	= fbox.options[i].value;
+
+		if (fbox.options[i].selected &&	fbox.options[i].value != \"\")
+		{
+			arrTbox[tLength] = fbox.options[i].text;
+			tLength++;
+		}
+		else
+		{
+			arrFbox[fLength] = fbox.options[i].text;
+			fLength++;
+		}
+	}
+
+	//arrFbox.sort();
 	//arrTbox.sort()
-
-	var arrFboxGroup = new Array();
-	var arrFboxUser = new Array();
+
+	var arrFboxGroup = new Array();
+	var arrFboxUser = new Array();
 	var prefix_x;
 
-	for (x = 0; x < arrFbox.length; x++) {
+	for (x = 0; x < arrFbox.length; x++) {
 		prefix_x = arrFbox[x].substring(0,2);
-		if (prefix_x == 'G:') {
+		if (prefix_x == 'G:') {
 			arrFboxGroup.push(arrFbox[x]);
-		} else {
+		} else {
 			arrFboxUser.push(arrFbox[x]);
 		}
 	}
 
-	arrFboxGroup.sort();
-	arrFboxUser.sort();
+	arrFboxGroup.sort();
+	arrFboxUser.sort();
 	arrFbox = arrFboxGroup.concat(arrFboxUser);
 
-	var arrTboxGroup = new Array();
+	var arrTboxGroup = new Array();
 	var arrTboxUser = new Array();
 	var prefix_y;
 
-	for (y = 0; y < arrTbox.length; y++) {
+	for (y = 0; y < arrTbox.length; y++) {
 		prefix_y = arrTbox[y].substring(0,2);
-		if (prefix_y == 'G:') {
-			arrTboxGroup.push(arrTbox[y]);
-		} else {
-			arrTboxUser.push(arrTbox[y]);
+		if (prefix_y == 'G:') {
+			arrTboxGroup.push(arrTbox[y]);
+		} else {
+			arrTboxUser.push(arrTbox[y]);
 		}
 	}
 
-	arrTboxGroup.sort();
-	arrTboxUser.sort();
-	arrTbox = arrTboxGroup.concat(arrTboxUser);
-
-	fbox.length	= 0;
-	tbox.length	= 0;
-
-	var	c;
-	for(c =	0; c < arrFbox.length; c++)
-	{
-		var	no = new Option();
-		no.value = arrLookup[arrFbox[c]];
-		no.text	= arrFbox[c];
-		fbox[c]	= no;
-	}
-	for(c =	0; c < arrTbox.length; c++)
-	{
-		var	no = new Option();
-		no.value = arrLookup[arrTbox[c]];
-		no.text	= arrTbox[c];
-		tbox[c]	= no;
-	}
-}
-
-function checkDate(month, day, year)
-{
+	arrTboxGroup.sort();
+	arrTboxUser.sort();
+	arrTbox = arrTboxGroup.concat(arrTboxUser);
+
+	fbox.length	= 0;
+	tbox.length	= 0;
+
+	var	c;
+	for(c =	0; c < arrFbox.length; c++)
+	{
+		var	no = new Option();
+		no.value = arrLookup[arrFbox[c]];
+		no.text	= arrFbox[c];
+		fbox[c]	= no;
+	}
+	for(c =	0; c < arrTbox.length; c++)
+	{
+		var	no = new Option();
+		no.value = arrLookup[arrTbox[c]];
+		no.text	= arrTbox[c];
+		tbox[c]	= no;
+	}
+}
+
+function checkDate(month, day, year)
+{
   var monthLength =
-    new Array(31,28,31,30,31,30,31,31,30,31,30,31);
-
-  if (!day || !month || !year)
-    return false;
-
-  // check for bisestile year
-  if (year/4 == parseInt(year/4))
-    monthLength[1] = 29;
-
-  if (month < 1 || month > 12)
-    return false;
-
-  if (day > monthLength[month-1])
-    return false;
-
-  return true;
+    new Array(31,28,31,30,31,30,31,31,30,31,30,31);
+
+  if (!day || !month || !year)
+    return false;
+
+  // check for bisestile year
+  if (year/4 == parseInt(year/4))
+    monthLength[1] = 29;
+
+  if (month < 1 || month > 12)
+    return false;
+
+  if (day > monthLength[month-1])
+    return false;
+
+  return true;
 }
-
+
 function mktime()
 {
-    var no, ma = 0, mb = 0, i = 0, d = new Date(), argv = arguments, argc = argv.length;
+    var no, ma = 0, mb = 0, i = 0, d = new Date(), argv = arguments, argc = argv.length;
     d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1972);
-    var dateManip = {
-        0: function(tt){ return d.setHours(tt); },
-        1: function(tt){ return d.setMinutes(tt); },
-        2: function(tt){ set = d.setSeconds(tt); mb = d.getDate() - 1; return set; },
-        3: function(tt){ set = d.setMonth(parseInt(tt)-1); ma = d.getFullYear() - 1972; return set; },
-        4: function(tt){ return d.setDate(tt+mb); },
-        5: function(tt){ return d.setYear(tt+ma); }
+    var dateManip = {
+        0: function(tt){ return d.setHours(tt); },
+        1: function(tt){ return d.setMinutes(tt); },
+        2: function(tt){ set = d.setSeconds(tt); mb = d.getDate() - 1; return set; },
+        3: function(tt){ set = d.setMonth(parseInt(tt)-1); ma = d.getFullYear() - 1972; return set; },
+        4: function(tt){ return d.setDate(tt+mb); },
+        5: function(tt){ return d.setYear(tt+ma); }
     };
-    for( i = 0; i < argc; i++ ){
-        no = parseInt(argv[i]*1);
-        if (isNaN(no)) {
-            return false;
-        } else {
-            // arg is number, lets manipulate date object
-            if(!dateManip[i](no)){
-                // failed
-                return false;
-            }
-        }
+    for( i = 0; i < argc; i++ ){
+        no = parseInt(argv[i]*1);
+        if (isNaN(no)) {
+            return false;
+        } else {
+            // arg is number, lets manipulate date object
+            if(!dateManip[i](no)){
+                // failed
+                return false;
+            }
+        }
     }
-    return Math.floor(d.getTime()/1000);
+    return Math.floor(d.getTime()/1000);
+}
+
+function validate()
+{
+	var	f =	document.new_calendar_item;
+	f.submit();
+	return true;
 }
 
-function validate()
-{
-	var	f =	document.new_calendar_item;
-	f.submit();
-	return true;
-}
-
-function selectAll(cbList,bSelect,showwarning)
+function selectAll(cbList,bSelect,showwarning)
 {
-		var start_day = document.new_calendar_item.fday.value;
-		var start_month = document.new_calendar_item.fmonth.value;
+		var start_day = document.new_calendar_item.fday.value;
+		var start_month = document.new_calendar_item.fmonth.value;
 		var start_year = document.new_calendar_item.fyear.value;
 		var start_hour = document.new_calendar_item.fhour.value;
-		var start_minute = document.new_calendar_item.fminute.value;
-		var start_date = mktime(start_hour,start_minute,0,start_month,start_day,start_year)
+		var start_minute = document.new_calendar_item.fminute.value;
+		var start_date = mktime(start_hour,start_minute,0,start_month,start_day,start_year)
 
-		var ends_day = document.new_calendar_item.end_fday.value;
-		var ends_month = document.new_calendar_item.end_fmonth.value;
+		var ends_day = document.new_calendar_item.end_fday.value;
+		var ends_month = document.new_calendar_item.end_fmonth.value;
 		var ends_year = document.new_calendar_item.end_fyear.value;
 		var ends_hour = document.new_calendar_item.end_fhour.value;
-		var ends_minute = document.new_calendar_item.end_fminute.value;
+		var ends_minute = document.new_calendar_item.end_fminute.value;
 		var ends_date = mktime(ends_hour,ends_minute,0,ends_month,ends_day,ends_year)
 
-		msg_err1 = document.getElementById(\"err_date\");
-		msg_err2 = document.getElementById(\"err_start_date\");
-		msg_err3 = document.getElementById(\"err_end_date\");
-		msg_err4 = document.getElementById(\"err_title\");
+		msg_err1 = document.getElementById(\"err_date\");
+		msg_err2 = document.getElementById(\"err_start_date\");
+		msg_err3 = document.getElementById(\"err_end_date\");
+		msg_err4 = document.getElementById(\"err_title\");
 
 		if (start_date > ends_date) {
 			msg_err1.style.display =\"block\";
-			msg_err1.innerHTML=\"".get_lang('EndDateCannotBeBeforeTheStartDate')."\";
+			msg_err1.innerHTML=\"".get_lang('EndDateCannotBeBeforeTheStartDate')."\";
 			msg_err2.innerHTML=\"\";msg_err3.innerHTML=\"\";
-		} else if (checkDate(start_month,start_day,start_year) == false) {
-			msg_err2.style.display =\"block\";
-			msg_err2.innerHTML=\"".get_lang('InvalidDate')."\";
+		} else if (checkDate(start_month,start_day,start_year) == false) {
+			msg_err2.style.display =\"block\";
+			msg_err2.innerHTML=\"".get_lang('InvalidDate')."\";
 			msg_err1.innerHTML=\"\";msg_err3.innerHTML=\"\";
-		} else if (checkDate(ends_month,ends_day,ends_year) == false) {
-			msg_err3.style.display =\"block\";
-			msg_err3.innerHTML=\"".get_lang('InvalidDate')."\";
+		} else if (checkDate(ends_month,ends_day,ends_year) == false) {
+			msg_err3.style.display =\"block\";
+			msg_err3.innerHTML=\"".get_lang('InvalidDate')."\";
 			msg_err1.innerHTML=\"\";msg_err2.innerHTML=\"\";
-		} else if (document.new_calendar_item.title.value == '') {
-			msg_err4.style.display =\"block\";
-			msg_err4.innerHTML=\"".get_lang('FieldRequired')."\";
+		} else if (document.new_calendar_item.title.value == '') {
+			msg_err4.style.display =\"block\";
+			msg_err4.innerHTML=\"".get_lang('FieldRequired')."\";
 			msg_err1.innerHTML=\"\";msg_err2.innerHTML=\"\";msg_err3.innerHTML=\"\";
-		}  else {
-			if (cbList.length <	1) {
-				if (!confirm(\"".get_lang('Send2All')."\")) {
+		}  else {
+			if (cbList.length <	1) {
+				if (!confirm(\"".get_lang('Send2All')."\")) {
 					return false;
 				}
 			}
-			for	(var i=0; i<cbList.length; i++)
+			for	(var i=0; i<cbList.length; i++)
 			cbList[i].selected = cbList[i].checked = bSelect;
-			document.new_calendar_item.submit();
+			document.new_calendar_item.submit();
+		}
+
+}
+
+	function reverseAll(cbList)
+	{
+		for	(var i=0; i<cbList.length; i++)
+		{
+			cbList[i].checked  = !(cbList[i].checked)
+			cbList[i].selected = !(cbList[i].selected)
 		}
-
-}
-
-	function reverseAll(cbList)
-	{
-		for	(var i=0; i<cbList.length; i++)
-		{
-			cbList[i].checked  = !(cbList[i].checked)
-			cbList[i].selected = !(cbList[i].selected)
-		}
-	}
-
-function plus_attachment() {
-				if (document.getElementById('options').style.display == 'none') {
-					document.getElementById('options').style.display = 'block';
-					document.getElementById('plus').innerHTML='&nbsp;<img style=\"vertical-align:middle;\" src=\"../img/div_hide.gif\" alt=\"\" />&nbsp;".get_lang('AddAnAttachment')."';
-				} else {
-				document.getElementById('options').style.display = 'none';
-				document.getElementById('plus').innerHTML='&nbsp;<img style=\"vertical-align:middle;\" src=\"../img/div_show.gif\" alt=\"\" />&nbsp;".get_lang('AddAnAttachment')."';
-				}
-}
-
-function plus_repeated_event() {
-				if (document.getElementById('options2').style.display == 'none') {
-					document.getElementById('options2').style.display = 'block';
-					document.getElementById('plus2').innerHTML='&nbsp;<img style=\"vertical-align:middle;\" src=\"../img/div_hide.gif\" alt=\"\" />&nbsp;".get_lang('RepeatEvent')."';
-				} else {
-				document.getElementById('options2').style.display = 'none';
-				document.getElementById('plus2').innerHTML='&nbsp;<img style=\"vertical-align:middle;\" src=\"../img/div_show.gif\" alt=\"\" />&nbsp;".get_lang('RepeatEvent')."';
-				}
-}
-
-/*
-function plus_ical() {
-				if (document.getElementById('icalform').style.display == 'none') {
-					document.getElementById('icalform').style.display = 'block';
-					document.getElementById('plusical').innerHTML='';
-				}
-}
-*/
-
-//	End	-->
-</script>";
-}
-
-
-/**
-* returns the javascript for setting a filter. This is a jump menu
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @return javascript code
-*/
-function user_group_filter_javascript()
-{
-return "<script language=\"JavaScript\" type=\"text/JavaScript\">
-<!--
-function MM_jumpMenu(targ,selObj,restore){
-  eval(targ+\".location='\"+selObj.options[selObj.selectedIndex].value+\"'\");
-  if (restore) selObj.selectedIndex=0;
-}
-//-->
-</script>
-";
-}
-
-
-/**
-* this function gets all the users of the current course
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @return array: associative array where the key is the id of the user and the value is an array containing
-			the first name, the last name, the user id
-*/
-function get_course_users()
-{
-	global $tbl_user;
-	global $tbl_courseUser, $tbl_session_course_user;
-	global $_cid;
-
-	// not 100% if this is necessary, this however prevents a notice
-	if (!isset($courseadmin_filter))
-		{$courseadmin_filter='';}
+	}
+
+function plus_attachment() {
+				if (document.getElementById('options').style.display == 'none') {
+					document.getElementById('options').style.display = 'block';
+					document.getElementById('plus').innerHTML='&nbsp;<img style=\"vertical-align:middle;\" src=\"../img/div_hide.gif\" alt=\"\" />&nbsp;".get_lang('AddAnAttachment')."';
+				} else {
+				document.getElementById('options').style.display = 'none';
+				document.getElementById('plus').innerHTML='&nbsp;<img style=\"vertical-align:middle;\" src=\"../img/div_show.gif\" alt=\"\" />&nbsp;".get_lang('AddAnAttachment')."';
+				}
+}
+
+function plus_repeated_event() {
+				if (document.getElementById('options2').style.display == 'none') {
+					document.getElementById('options2').style.display = 'block';
+					document.getElementById('plus2').innerHTML='&nbsp;<img style=\"vertical-align:middle;\" src=\"../img/div_hide.gif\" alt=\"\" />&nbsp;".get_lang('RepeatEvent')."';
+				} else {
+				document.getElementById('options2').style.display = 'none';
+				document.getElementById('plus2').innerHTML='&nbsp;<img style=\"vertical-align:middle;\" src=\"../img/div_show.gif\" alt=\"\" />&nbsp;".get_lang('RepeatEvent')."';
+				}
+}
+
+/*
+function plus_ical() {
+				if (document.getElementById('icalform').style.display == 'none') {
+					document.getElementById('icalform').style.display = 'block';
+					document.getElementById('plusical').innerHTML='';
+				}
+}
+*/
+
+//	End	-->
+</script>";
+}
+
+
+/**
+* returns the javascript for setting a filter. This is a jump menu
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @return javascript code
+*/
+function user_group_filter_javascript()
+{
+return "<script language=\"JavaScript\" type=\"text/JavaScript\">
+<!--
+function MM_jumpMenu(targ,selObj,restore){
+  eval(targ+\".location='\"+selObj.options[selObj.selectedIndex].value+\"'\");
+  if (restore) selObj.selectedIndex=0;
+}
+//-->
+</script>
+";
+}
+
+
+/**
+* this function gets all the users of the current course
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @return array: associative array where the key is the id of the user and the value is an array containing
+			the first name, the last name, the user id
+*/
+function get_course_users()
+{
+	global $tbl_user;
+	global $tbl_courseUser, $tbl_session_course_user;
+	global $_cid;
+
+	// not 100% if this is necessary, this however prevents a notice
+	if (!isset($courseadmin_filter))
+		{$courseadmin_filter='';}
 
 	$order_clause = api_sort_by_first_name() ? ' ORDER BY u.firstname, u.lastname' : ' ORDER BY u.lastname, u.firstname';
-	$sql = "SELECT u.user_id uid, u.lastname lastName, u.firstname firstName
-			FROM $tbl_user as u, $tbl_courseUser as cu
-			WHERE cu.course_code = '".$_cid."'
+	$sql = "SELECT u.user_id uid, u.lastname lastName, u.firstname firstName
+			FROM $tbl_user as u, $tbl_courseUser as cu
+			WHERE cu.course_code = '".$_cid."'
 			AND cu.user_id = u.user_id $courseadmin_filter".$order_clause;
-	$result = Database::query($sql,__FILE__,__LINE__);
-	while($user=Database::fetch_array($result)){
-		$users[$user[0]] = $user;
-	}
-
-	if(!empty($_SESSION['id_session'])){
-		$sql = "SELECT u.user_id uid, u.lastname lastName, u.firstName firstName
-				FROM $tbl_session_course_user AS session_course_user
-				INNER JOIN $tbl_user u
-					ON u.user_id = session_course_user.id_user
-				WHERE id_session='".intval($_SESSION['id_session'])."'
-				AND course_code='$_cid'";
-
-		$result = Database::query($sql,__FILE__,__LINE__);
-		while($user=Database::fetch_array($result)){
-			$users[$user[0]] = $user;
+	$result = Database::query($sql,__FILE__,__LINE__);
+	while($user=Database::fetch_array($result)){
+		$users[$user[0]] = $user;
+	}
+
+	if(!empty($_SESSION['id_session'])){
+		$sql = "SELECT u.user_id uid, u.lastname lastName, u.firstName firstName
+				FROM $tbl_session_course_user AS session_course_user
+				INNER JOIN $tbl_user u
+					ON u.user_id = session_course_user.id_user
+				WHERE id_session='".intval($_SESSION['id_session'])."'
+				AND course_code='$_cid'";
+
+		$result = Database::query($sql,__FILE__,__LINE__);
+		while($user=Database::fetch_array($result)){
+			$users[$user[0]] = $user;
 		}
 	}
-	return $users;
-
-}
-
-
-/**
-* this function gets all the groups of the course
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @return array
-*/
-function get_course_groups()
-{
-	$group_list = array();
-	$group_list = CourseManager::get_group_list_of_course(api_get_course_id(), intval($_SESSION['id_session']));
-	return $group_list;
-}
-
-
-/**
-* this function shows the form for sending a message to a specific group or user.
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @return html code
-*/
-function show_to_form($to_already_selected)
-{
-	$user_list=get_course_users();
-	$group_list=get_course_groups();
-
-	echo "\n<table id=\"recipient_list\" style=\"display: none;\">\n";
-		echo "\t<tr>\n";
-		// the form containing all the groups and all the users of the course
-		echo "\t\t<td>\n";
-		echo "<strong>".get_lang('Users')."</strong><br />";
-			construct_not_selected_select_form($group_list,$user_list,$to_already_selected);
-		echo "\t\t</td>\n";
-		// the buttons for adding or removing groups/users
-		echo "\n\t\t<td valign=\"middle\">\n";
-		echo "\t\t<input type=\"button\" ",
-					"onclick=\"move(document.getElementById('not_selected_form'),document.getElementById('selected_form'))\" ",
-					"value=\"   &gt;&gt;   \" />",
-
-					"\n\t\t<p>&nbsp;</p>",
-
-					"\n\t\t<input type=\"button\" ",
-					"onclick=\"move(document.getElementById('selected_form'),document.getElementById('not_selected_form'))\" ",
-					"value=\"   &lt;&lt;   \" />";
-		echo "\t\t</td>\n";
-		echo "\n\t\t<td>\n";
-		echo "<strong>".get_lang('DestinationUsers')."</strong><br />";
-			construct_selected_select_form($group_list,$user_list,$to_already_selected);
-		echo "\t\t</td>\n";
-		echo "\t</tr>\n";
-	echo "</table>";
-}
-
-
-/**
-* this function shows the form with the user that were not selected
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @return html code
-*/
-function construct_not_selected_select_form($group_list=null, $user_list=null,$to_already_selected=array())
-{
-	echo "\t\t<select id=\"not_selected_form\" name=\"not_selected_form[]\" size=\"5\" multiple=\"multiple\" style=\"width:200px\">\n";
-
-	// adding the groups to the select form
-
-	if (isset($to_already_selected) && $to_already_selected==='everyone') {
-		echo "\t\t<option value=\"\">--------------------------------------------</option>\n";
-	} else {
-		if (is_array($group_list))
-		{
-			foreach($group_list as $this_group)
-			{
-				//api_display_normal_message("group " . $thisGroup[id] . $thisGroup[name]);
-				if (!is_array($to_already_selected) || !in_array("GROUP:".$this_group['id'],$to_already_selected)) // $to_already_selected is the array containing the groups (and users) that are already selected
-					{
-					echo	"\t\t<option value=\"GROUP:".$this_group['id']."\">",
-						"G: ",$this_group['name']," &ndash; " . $this_group['userNb'] . " " . get_lang('Users') .
-						"</option>\n";
-				}
-			}
-			// a divider
-
-		}
-		echo	"<option value=\"\">--------------------------------------------</option>";
-		// adding the individual users to the select form
-		foreach($user_list as $this_user)
-		{
-			if (!is_array($to_already_selected) || !in_array("USER:".$this_user['uid'],$to_already_selected)) // $to_already_selected is the array containing the users (and groups) that are already selected
-			{
-				echo	"\t\t<option value=\"USER:",$this_user['uid'],"\">",
+	return $users;
+
+}
+
+
+/**
+* this function gets all the groups of the course
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @return array
+*/
+function get_course_groups()
+{
+	$group_list = array();
+	$group_list = CourseManager::get_group_list_of_course(api_get_course_id(), intval($_SESSION['id_session']));
+	return $group_list;
+}
+
+
+/**
+* this function shows the form for sending a message to a specific group or user.
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @return html code
+*/
+function show_to_form($to_already_selected)
+{
+	$user_list=get_course_users();
+	$group_list=get_course_groups();
+
+	echo "\n<table id=\"recipient_list\" style=\"display: none;\">\n";
+		echo "\t<tr>\n";
+		// the form containing all the groups and all the users of the course
+		echo "\t\t<td>\n";
+		echo "<strong>".get_lang('Users')."</strong><br />";
+			construct_not_selected_select_form($group_list,$user_list,$to_already_selected);
+		echo "\t\t</td>\n";
+		// the buttons for adding or removing groups/users
+		echo "\n\t\t<td valign=\"middle\">\n";
+		echo "\t\t<input type=\"button\" ",
+					"onclick=\"move(document.getElementById('not_selected_form'),document.getElementById('selected_form'))\" ",
+					"value=\"   &gt;&gt;   \" />",
+
+					"\n\t\t<p>&nbsp;</p>",
+
+					"\n\t\t<input type=\"button\" ",
+					"onclick=\"move(document.getElementById('selected_form'),document.getElementById('not_selected_form'))\" ",
+					"value=\"   &lt;&lt;   \" />";
+		echo "\t\t</td>\n";
+		echo "\n\t\t<td>\n";
+		echo "<strong>".get_lang('DestinationUsers')."</strong><br />";
+			construct_selected_select_form($group_list,$user_list,$to_already_selected);
+		echo "\t\t</td>\n";
+		echo "\t</tr>\n";
+	echo "</table>";
+}
+
+
+/**
+* this function shows the form with the user that were not selected
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @return html code
+*/
+function construct_not_selected_select_form($group_list=null, $user_list=null,$to_already_selected=array())
+{
+	echo "\t\t<select id=\"not_selected_form\" name=\"not_selected_form[]\" size=\"5\" multiple=\"multiple\" style=\"width:200px\">\n";
+
+	// adding the groups to the select form
+
+	if (isset($to_already_selected) && $to_already_selected==='everyone') {
+		echo "\t\t<option value=\"\">--------------------------------------------</option>\n";
+	} else {
+		if (is_array($group_list))
+		{
+			foreach($group_list as $this_group)
+			{
+				//api_display_normal_message("group " . $thisGroup[id] . $thisGroup[name]);
+				if (!is_array($to_already_selected) || !in_array("GROUP:".$this_group['id'],$to_already_selected)) // $to_already_selected is the array containing the groups (and users) that are already selected
+					{
+					echo	"\t\t<option value=\"GROUP:".$this_group['id']."\">",
+						"G: ",$this_group['name']," &ndash; " . $this_group['userNb'] . " " . get_lang('Users') .
+						"</option>\n";
+				}
+			}
+			// a divider
+
+		}
+		echo	"<option value=\"\">--------------------------------------------</option>";
+		// adding the individual users to the select form
+		foreach($user_list as $this_user)
+		{
+			if (!is_array($to_already_selected) || !in_array("USER:".$this_user['uid'],$to_already_selected)) // $to_already_selected is the array containing the users (and groups) that are already selected
+			{
+				echo	"\t\t<option value=\"USER:",$this_user['uid'],"\">",
 					"",api_get_person_name($this_user['firstName'], $this_user['lastName']),
-					"</option>\n";
-			}
+					"</option>\n";
+			}
 		}
-	}
-		echo "\t\t</select>\n";
-}
-
-/**
-* This function shows the form with the user that were selected
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @return html code
-*/
-function construct_selected_select_form($group_list=null, $user_list=null,$to_already_selected)
-{
-	// we separate the $to_already_selected array (containing groups AND users into
-	// two separate arrays
-	if (is_array($to_already_selected))
-	{
-		 $groupuser=separate_users_groups($to_already_selected);
-	}
-	$groups_to_already_selected=$groupuser['groups'];
-	$users_to_already_selected=$groupuser['users'];
-
-	// we load all the groups and all the users into a reference array that we use to search the name of the group / user
-	$ref_array_groups=get_course_groups();
+	}
+		echo "\t\t</select>\n";
+}
+
+/**
+* This function shows the form with the user that were selected
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @return html code
+*/
+function construct_selected_select_form($group_list=null, $user_list=null,$to_already_selected)
+{
+	// we separate the $to_already_selected array (containing groups AND users into
+	// two separate arrays
+	if (is_array($to_already_selected))
+	{
+		 $groupuser=separate_users_groups($to_already_selected);
+	}
+	$groups_to_already_selected=$groupuser['groups'];
+	$users_to_already_selected=$groupuser['users'];
+
+	// we load all the groups and all the users into a reference array that we use to search the name of the group / user
+	$ref_array_groups=get_course_groups();
 
 	$ref_array_users=get_course_users();
-	// we construct the form of the already selected groups / users
-	echo "\t\t<select id=\"selected_form\" name=\"selectedform[]\" size=\"5\" multiple=\"multiple\" style=\"width:200px\">";
-	if(is_array($to_already_selected))
-	{
-		$select_options_group = array();
-		$select_options_user = array();
+	// we construct the form of the already selected groups / users
+	echo "\t\t<select id=\"selected_form\" name=\"selectedform[]\" size=\"5\" multiple=\"multiple\" style=\"width:200px\">";
+	if(is_array($to_already_selected))
+	{
+		$select_options_group = array();
+		$select_options_user = array();
 		$select_options_groupuser = array();
-		foreach($to_already_selected as $groupuser)
-		{
-			list($type,$id)=explode(":",$groupuser);
-			if ($type=="GROUP")
-			{
-				$select_options_group[] = "\t\t<option value=\"".$groupuser."\">G: ".$ref_array_groups[$id]['name']."</option>";
+		foreach($to_already_selected as $groupuser)
+		{
+			list($type,$id)=explode(":",$groupuser);
+			if ($type=="GROUP")
+			{
+				$select_options_group[] = "\t\t<option value=\"".$groupuser."\">G: ".$ref_array_groups[$id]['name']."</option>";
 				//echo "\t\t<option value=\"".$groupuser."\">G: ".$ref_array_groups[$id]['name']."</option>";
 			}
-			else
+			else
 			{
 				$select_options_user[] = "\t\t<option value=\"".$groupuser."\">".api_get_person_name($ref_array_users[$id]['firstName'], $ref_array_users[$id]['lastName'])."</option>";
 				//echo "\t\t<option value=\"".$groupuser."\">".api_get_person_name($ref_array_users[$id]['firstName'], $ref_array_users[$id]['lastName'])."</option>";
 			}
-		}
-		$select_options_group[] = "<option value=\"\">--------------------------------------------</option>";
-		$select_options_groupuser = array_merge($select_options_group,$select_options_user);
+		}
+		$select_options_group[] = "<option value=\"\">--------------------------------------------</option>";
+		$select_options_groupuser = array_merge($select_options_group,$select_options_user);
 
-		foreach($select_options_groupuser as $select_options) {
-			echo $select_options;
+		foreach($select_options_groupuser as $select_options) {
+			echo $select_options;
 		}
-	} else {
+	} else {
 			if($to_already_selected=='everyone'){
-				// adding the groups to the select form
-				if (is_array($group_list))
-				{
-					foreach($group_list as $this_group)
-					{
-						//api_display_normal_message("group " . $thisGroup[id] . $thisGroup[name]);
-						if (!is_array($to_already_selected) || !in_array("GROUP:".$this_group['id'],$to_already_selected)) // $to_already_selected is the array containing the groups (and users) that are already selected
-							{
-							echo	"\t\t<option value=\"GROUP:".$this_group['id']."\">",
-								"G: ",$this_group['name']," &ndash; " . $this_group['userNb'] . " " . get_lang('Users') .
-								"</option>\n";
-						}
+				// adding the groups to the select form
+				if (is_array($group_list))
+				{
+					foreach($group_list as $this_group)
+					{
+						//api_display_normal_message("group " . $thisGroup[id] . $thisGroup[name]);
+						if (!is_array($to_already_selected) || !in_array("GROUP:".$this_group['id'],$to_already_selected)) // $to_already_selected is the array containing the groups (and users) that are already selected
+							{
+							echo	"\t\t<option value=\"GROUP:".$this_group['id']."\">",
+								"G: ",$this_group['name']," &ndash; " . $this_group['userNb'] . " " . get_lang('Users') .
+								"</option>\n";
+						}
 					}
-				}
-				echo	"<option value=\"\">--------------------------------------------</option>";
-				// adding the individual users to the select form
-				foreach($user_list as $this_user)
-				{
-					if (!is_array($to_already_selected) || !in_array("USER:".$this_user['uid'],$to_already_selected)) // $to_already_selected is the array containing the users (and groups) that are already selected
-					{
-						echo	"\t\t<option value=\"USER:",$this_user['uid'],"\">",
+				}
+				echo	"<option value=\"\">--------------------------------------------</option>";
+				// adding the individual users to the select form
+				foreach($user_list as $this_user)
+				{
+					if (!is_array($to_already_selected) || !in_array("USER:".$this_user['uid'],$to_already_selected)) // $to_already_selected is the array containing the users (and groups) that are already selected
+					{
+						echo	"\t\t<option value=\"USER:",$this_user['uid'],"\">",
 							"",api_get_person_name($this_user['firstName'], $this_user['lastName']),
-							"</option>\n";
-					}
-				}
-			}
-	}
-	echo "</select>\n";
-}
-
-
-
-/**
-* This function stores the Agenda Item in the table calendar_event and updates the item_property table also
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @return integer the id of the last added agenda item
-*/
-function store_new_agenda_item() {
-	global $_user, $_course;
-	$TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
-    $t_agenda_repeat = Database::get_course_Table(TABLE_AGENDA_REPEAT);
-
-	// some filtering of the input data
-	$title=strip_tags(trim($_POST['title'])); // no html allowed in the title
-	$content=trim($_POST['content']);
-	$start_date=(int)$_POST['fyear']."-".(int)$_POST['fmonth']."-".(int)$_POST['fday']." ".(int)$_POST['fhour'].":".(int)$_POST['fminute'].":00";
-	$end_date=(int)$_POST['end_fyear']."-".(int)$_POST['end_fmonth']."-".(int)$_POST['end_fday']." ".(int)$_POST['end_fhour'].":".(int)$_POST['end_fminute'].":00";
-
-	$content=stripslashes($content);
-	$title=Database::escape_string(Security::remove_XSS($title));
-	$content = Database::escape_string(Security::remove_XSS($content,COURSEMANAGERLOWSECURITY));
-	$start_date=Database::escape_string($start_date);
-	$end_date=Database::escape_string($end_date);
-
-
-	// store in the table calendar_event
-	$sql = "INSERT INTO ".$TABLEAGENDA."
-					        (title,content, start_date, end_date)
-					        VALUES
-					        ('".$title."','".$content."', '".$start_date."','".$end_date."')";
-	$result = Database::query($sql,__FILE__,__LINE__);
-	$last_id = Database::insert_id();
-
-	// store in last_tooledit (first the groups, then the users
-	$to=$_POST['selectedform'];
-
-	if ((!is_null($to)) || (!empty($_SESSION['toolgroup']))) // !is_null($to): when no user is selected we send it to everyone
-	{
-		$send_to=separate_users_groups($to);
-		// storing the selected groups
-		if (is_array($send_to['groups'])) {
-			foreach ($send_to['groups'] as $group) {
-				api_item_property_update($_course, TOOL_CALENDAR_EVENT, $last_id,"AgendaAdded", $_user['user_id'], $group,'',$start_date, $end_date);
-			}
-		}
-		// storing the selected users
-		if (is_array($send_to['users'])) {
-			foreach ($send_to['users'] as $user) {
-				api_item_property_update($_course, TOOL_CALENDAR_EVENT, $last_id,"AgendaAdded", $_user['user_id'],'',$user, $start_date,$end_date);
-			}
-		}
-	}
-	else // the message is sent to everyone, so we set the group to 0
-	{
-		api_item_property_update($_course, TOOL_CALENDAR_EVENT, $last_id,"AgendaAdded", $_user['user_id'], '','',$start_date,$end_date);
-	}
-	// storing the resources
-	store_resources($_SESSION['source_type'],$last_id);
-
-    //if repetitive, insert element into agenda_repeat table
-    if(!empty($_POST['repeat']) && !empty($_POST['repeat_type'])) {
-    	if(!empty($_POST['repeat_end_year']) && !empty($_POST['repeat_end_month']) && !empty($_POST['repeat_end_day'])) {
-        	$end_y = intval($_POST['repeat_end_year']);
-            $end_m = intval($_POST['repeat_end_month']);
-            $end_d = intval($_POST['repeat_end_day']);
-            $end = mktime((int)$_POST['fhour'],(int)$_POST['fminute'],0,$end_m,$end_d,$end_y);
-            $now = time();
-            $type = Database::escape_string($_POST['repeat_type']);
-
-        	if ($end > $now && in_array($type,array('daily','weekly','monthlyByDate','monthlyByDay','monthlyByDayR','yearly'))) {
-        	   $sql = "INSERT INTO $t_agenda_repeat (cal_id, cal_type, cal_end)" .
-                    " VALUES ($last_id,'$type',$end)";
-               $res = Database::query($sql,__FILE__,__LINE__);
-            }
-        }
-    }
-	return $last_id;
-}
-
-/**
- * Stores the given agenda item as an announcement (unlinked copy)
- * @param	integer		Agenda item's ID
- * @return	integer		New announcement item's ID
- */
-function store_agenda_item_as_announcement($item_id){
-	$table_agenda = Database::get_course_table(TABLE_AGENDA);
-	$table_ann = Database::get_course_table(TABLE_ANNOUNCEMENT);
-	//check params
-	if(empty($item_id) or $item_id != strval(intval($item_id))){return -1;}
-	//get the agenda item
-
-	$item_id=Database::escape_string($item_id);
-	$sql = "SELECT * FROM $table_agenda WHERE id = '".$item_id."'";
-	$res = Database::query($sql,__FILE__,__LINE__);
-	if(Database::num_rows($res)>0){
-		$row = Database::fetch_array($res);
-		//we have the agenda event, copy it
-		//get the maximum value for display order in announcement table
-		$sql_max = "SELECT MAX(display_order) FROM $table_ann";
-		$res_max = Database::query($sql_max,__FILE__,__LINE__);
-		$row_max = Database::fetch_array($res_max);
-		$max = $row_max[0]+1;
-		//build the announcement text
-		$content = $row['start_date']." - ".$row['end_date']."\n\n".$row['content'];
-		//insert announcement
-
-		$sql_ins = "INSERT INTO $table_ann (title,content,end_date,display_order) " .
-				"VALUES ('".Security::remove_XSS($row['title'])."','".$content."','".$row['end_date']."','$max')";
-		$res_ins = Database::query($sql_ins,__FILE__,__LINE__);
-		if($res > 0)
-		{
-			$ann_id = Database::get_last_insert_id();
-			//Now also get the list of item_properties rows for this agenda_item (calendar_event)
-			//and copy them into announcement item_properties
-			$table_props = Database::get_course_table(TABLE_ITEM_PROPERTY);
-			$sql_props = "SELECT * FROM $table_props WHERE tool = 'calendar_event' AND ref='$item_id'";
-			$res_props = Database::query($sql_props,__FILE__,__LINE__);
-			if(Database::num_rows($res_props)>0)
-			{
-				while($row_props = Database::fetch_array($res_props))
-				{
-					//insert into announcement item_property
-					$time = date("Y-m-d H:i:s", time());
-					$sql_ins_props = "INSERT INTO $table_props " .
-							"(tool, insert_user_id, insert_date, " .
-							"lastedit_date, ref, lastedit_type," .
-							"lastedit_user_id, to_group_id, to_user_id, " .
-							"visibility, start_visible, end_visible)" .
-							" VALUES " .
-							"('announcement','".$row_props['insert_user_id']."','".$time."'," .
-							"'$time','$ann_id','AnnouncementAdded'," .
-							"'".$row_props['last_edit_user_id']."','".$row_props['to_group_id']."','".$row_props['to_user_id']."'," .
-							"'".$row_props['visibility']."','".$row_props['start_visible']."','".$row_props['end_visible']."')";
-					$res_ins_props = Database::query($sql_ins_props,__FILE__,__LINE__);
-					if($res_ins_props <= 0){
-						error_log('SQL Error in '.__FILE__.' at line '.__LINE__.': '.$sql_ins_props);
-					}else{
-						//copy was a success
-						return $ann_id;
-					}
-				}
-			}
-		}else{
-			return -1;
-		}
-	}
-	return -1;
-}
-
-/**
-* This function separates the users from the groups
-* users have a value USER:XXX (with XXX the dokeos id
-* groups have a value GROUP:YYY (with YYY the group id)
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @return array
-*/
-function separate_users_groups($to)
-{
-	$grouplist = array();
-    $userlist  = array();
-    $send_to = null;
-	if(is_array($to) && count($to)>0)
-    {
-        foreach($to as $to_item)
-    	{
-    	list($type, $id) = explode(':', $to_item);
-    	switch($type)
-    		{
-    		case 'GROUP':
-    			$grouplist[] =$id;
-    			break;
-    		case 'USER':
-    			$userlist[] =$id;
-    			break;
-    		}
-    	}
-        $send_to['groups']=$grouplist;
-        $send_to['users']=$userlist;
-    }
-    return $send_to;
-}
-
-
-
-/**
-* returns all the users and all the groups a specific Agenda item has been sent to
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @return array
-*/
-function sent_to($tool, $id)
-{
-	global $_course;
-	$TABLE_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
-
-	$tool=Database::escape_string($tool);
-	$id=Database::escape_string($id);
-
-	$sql="SELECT * FROM $TABLE_ITEM_PROPERTY WHERE tool='".$tool."' AND ref='".$id."'";
-	$result=Database::query($sql,__FILE__,__LINE__);
-	while ($row=Database::fetch_array($result))
-	{
-		// if to_group_id is null then it is sent to a specific user
-		// if to_group_id = 0 then it is sent to everybody
-		if (!is_null($row['to_group_id']) )
-		{
-			$sent_to_group[]=$row['to_group_id'];
-			//echo $row['to_group_id'];
-		}
-		// if to_user_id <> 0 then it is sent to a specific user
-		if ($row['to_user_id']<>0)
-		{
-			$sent_to_user[]=$row['to_user_id'];
-		}
-	}
-	if (isset($sent_to_group))
-	{
-		$sent_to['groups']=$sent_to_group;
-	}
-	if (isset($sent_to_user))
-	{
-		$sent_to['users']=$sent_to_user;
-	}
-	return $sent_to;
-}
-
-
-
-/**
-* constructs the form to display all the groups and users the message has been sent to
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @param  array $sent_to_array: a 2 dimensional array containing the groups and the users
-*				the first level is a distinction between groups and users: $sent_to_array['groups'] and $sent_to_array['users']
-*				$sent_to_array['groups'] (resp. $sent_to_array['users']) is also an array containing all the id's of the
-*				groups (resp. users) who have received this message.
-* @return html
-*/
-function sent_to_form($sent_to_array)
-{
-	// we find all the names of the groups
-	$group_names=get_course_groups();
-
-	count($sent_to_array);
-
-	// we count the number of users and the number of groups
-	if (isset($sent_to_array['users']))
-	{
-		$number_users=count($sent_to_array['users']);
-	}
-	else
-	{
-		$number_users=0;
-	}
-	if (isset($sent_to_array['groups']))
-	{
-		$number_groups=count($sent_to_array['groups']);
-	}
-	else
-	{
-		$number_groups=0;
-	}
-	$total_numbers=$number_users+$number_groups;
-
-	// starting the form if there is more than one user/group
-	if ($total_numbers >1)
-	{
-	$output="<select name=\"sent to\">\n";
-	$output.="<option>".get_lang("SentTo")."</option>";
-	// outputting the name of the groups
-	if (is_array($sent_to_array['groups']))
-		{
-		foreach ($sent_to_array['groups'] as $group_id)
-			{
-			$output.="\t<option value=\"\">G: ".$group_names[$group_id]['name']."</option>\n";
-			}
-		}
-	if (isset($sent_to_array['users']))
-	{
-		if (is_array($sent_to_array['users']))
-			{
-			foreach ($sent_to_array['users'] as $user_id)
-				{
-				$user_info=api_get_user_info($user_id);
-				$output.="\t<option value=\"\">".api_get_person_name($user_info['firstName'], $user_info['lastName'])."</option>\n";
-				}
-			}
-	}
-
-	// ending the form
-	$output.="</select>\n";
-	}
-	else // there is only one user/group
-	{
-		if (is_array($sent_to_array['users']))
-		{
-			$user_info=api_get_user_info($sent_to_array['users'][0]);
-			echo api_get_person_name($user_info['firstName'], $user_info['lastName']);
-		}
-		if (is_array($sent_to_array['groups']) and $sent_to_array['groups'][0]!==0)
-		{
-			$group_id=$sent_to_array['groups'][0];
-			echo $group_names[$group_id]['name'];
-		}
-		if (is_array($sent_to_array['groups']) and $sent_to_array['groups'][0]==0)
-		{
-			echo get_lang("Everybody");
-		}
-		//.$sent_to_array['groups'][0];
-	}
-
-	echo $output;
-}
-
-
-/**
-* This function displays a dropdown list that allows the course administrator do view the calendar items of one specific group
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-function show_group_filter_form()
-{
-	$group_list=get_course_groups();
+							"</option>\n";
+					}
+				}
+			}
+	}
+	echo "</select>\n";
+}
 
-	echo "<select name=\"select\" onchange=\"javascript: MM_jumpMenu('parent',this,0)\">";
-	echo "<option value=\"agenda.php?group=none\">show all groups</option>";
-	foreach($group_list as $this_group)
-	{
-		// echo "<option value=\"agenda.php?isStudentView=true&amp;group=".$this_group['id']."\">".$this_group['name']."</option>";
-		echo "<option value=\"agenda.php?group=".$this_group['id']."\" ";
-		echo ($this_group['id']==$_SESSION['group'])? " selected":"" ;
-		echo ">".$this_group['name']."</option>";
-	}
-	echo "</select>";
-}
-
-
-
-/**
-* This function displays a dropdown list that allows the course administrator do view the calendar items of one specific group
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-function show_user_filter_form()
-{
-	$user_list=get_course_users();
 
-	echo "<select name=\"select\" onchange=\"javascript: MM_jumpMenu('parent',this,0)\">";
-	echo "<option value=\"agenda.php?user=none\">show all users</option>";
-	foreach($user_list as $this_user)
-		{
-		// echo "<option value=\"agenda.php?isStudentView=true&amp;user=".$this_user['uid']."\">".api_get_person_name($this_user['firstName'], $this_user['lastName'])."</option>";
-		echo "<option value=\"agenda.php?user=".$this_user['uid']."\" ";
-		echo ($this_user['uid']==$_SESSION['user'])? " selected":"" ;
-		echo ">".api_get_person_name($this_user['firstName'], $this_user['lastName'])."</option>";
-		}
-	echo "</select>";
-}
-
-
-
-/**
-* This function displays a dropdown list that allows the course administrator do view the calendar items of one specific group
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-function show_user_group_filter_form()
-{
-	echo "\n<select name=\"select\" onchange=\"javascript: MM_jumpMenu('parent',this,0)\">";
 
-	// Groups
-	$option = "\n\t<optgroup label=\"".get_lang("Groups")."\">";
-	$group_list=get_course_groups();
-	//echo "\n\t<option value=\"agenda.php?user=none\">".get_lang("ShowAll")."</option>";
+/**
+* This function stores the Agenda Item in the table calendar_event and updates the item_property table also
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @return integer the id of the last added agenda item
+*/
+function store_new_agenda_item() {
+	global $_user, $_course;
+	$TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
+    $t_agenda_repeat = Database::get_course_Table(TABLE_AGENDA_REPEAT);
 
-	$group_available_to_access =array();
+	// some filtering of the input data
+	$title=strip_tags(trim($_POST['title'])); // no html allowed in the title
+	$content=trim($_POST['content']);
+	$start_date=(int)$_POST['fyear']."-".(int)$_POST['fmonth']."-".(int)$_POST['fday']." ".(int)$_POST['fhour'].":".(int)$_POST['fminute'].":00";
+	$end_date=(int)$_POST['end_fyear']."-".(int)$_POST['end_fmonth']."-".(int)$_POST['end_fday']." ".(int)$_POST['end_fhour'].":".(int)$_POST['end_fminute'].":00";
 
-	if(!empty($group_list)){
-		foreach($group_list as $this_group) {
-			// echo "<option value=\"agenda.php?isStudentView=true&amp;group=".$this_group['id']."\">".$this_group['name']."</option>";
-			$has_access = GroupManager::user_has_access(api_get_user_id(),$this_group['id'],GROUP_TOOL_CALENDAR);
-			$result = GroupManager::get_group_properties($this_group['id']);
+	$content=stripslashes($content);
+	$title=Database::escape_string(Security::remove_XSS($title));
+	$content = Database::escape_string(Security::remove_XSS($content,COURSEMANAGERLOWSECURITY));
+	$start_date=Database::escape_string($start_date);
+	$end_date=Database::escape_string($end_date);
 
-			if ($result['calendar_state']!='0') {
-				$group_available_to_access[]=$this_group['id'];
-			}
 
-			// lastedit
-			if ($has_access || $result['calendar_state']=='1') {
-				$option.= "\n\t\t<option value=\"agenda.php?group=".$this_group['id']."\" ";
-				$option.= ($this_group['id']==$_SESSION['group'])? " selected":"" ;
-				$option.=  ">".$this_group['name']."</option>";
-			}
-		}
-	}
+	// store in the table calendar_event
+	$sql = "INSERT INTO ".$TABLEAGENDA."
+					        (title,content, start_date, end_date)
+					        VALUES
+					        ('".$title."','".$content."', '".$start_date."','".$end_date."')";
+	$result = Database::query($sql,__FILE__,__LINE__);
+	$last_id = Database::insert_id();
 
-	$all =  "\n\t<option value=\"agenda.php?user=none\">".get_lang("ShowAll")."</option>";
-	$option = $all.$option;
+	// store in last_tooledit (first the groups, then the users
+	$to=$_POST['selectedform'];
 
-	$option.= "\n\t</optgroup>";
-	echo $option;
+	if ((!is_null($to)) || (!empty($_SESSION['toolgroup']))) // !is_null($to): when no user is selected we send it to everyone
+	{
+		$send_to=separate_users_groups($to);
+		// storing the selected groups
+		if (is_array($send_to['groups'])) {
+			foreach ($send_to['groups'] as $group) {
+				api_item_property_update($_course, TOOL_CALENDAR_EVENT, $last_id,"AgendaAdded", $_user['user_id'], $group,'',$start_date, $end_date);
+			}
+		}
+		// storing the selected users
+		if (is_array($send_to['users'])) {
+			foreach ($send_to['users'] as $user) {
+				api_item_property_update($_course, TOOL_CALENDAR_EVENT, $last_id,"AgendaAdded", $_user['user_id'],'',$user, $start_date,$end_date);
+			}
+		}
+	}
+	else // the message is sent to everyone, so we set the group to 0
+	{
+		api_item_property_update($_course, TOOL_CALENDAR_EVENT, $last_id,"AgendaAdded", $_user['user_id'], '','',$start_date,$end_date);
+	}
+	// storing the resources
+	store_resources($_SESSION['source_type'],$last_id);
 
-	global $_course;
+    //if repetitive, insert element into agenda_repeat table
+    if(!empty($_POST['repeat']) && !empty($_POST['repeat_type'])) {
+    	if(!empty($_POST['repeat_end_year']) && !empty($_POST['repeat_end_month']) && !empty($_POST['repeat_end_day'])) {
+        	$end_y = intval($_POST['repeat_end_year']);
+            $end_m = intval($_POST['repeat_end_month']);
+            $end_d = intval($_POST['repeat_end_day']);
+            $end = mktime((int)$_POST['fhour'],(int)$_POST['fminute'],0,$end_m,$end_d,$end_y);
+            $now = time();
+            $type = Database::escape_string($_POST['repeat_type']);
 
-	// Users
-	echo "\n\t<optgroup label=\"".get_lang("Users")."\">";
-	$user_list=get_course_users();
-	foreach($user_list as $this_user) {
-		echo "\n\t\t<option value=\"agenda.php?user=".$this_user['uid']."\" ";
-		echo ($this_user['uid']==$_SESSION['user'])? " selected":"" ;
-		echo ">".api_get_person_name($this_user['firstName'], $this_user['lastName'])."</option>";
-	}
-	echo "\n\t</optgroup>";
-	echo "</select>";
-}
-
-
-
-/**
-* This tools loads all the users and all the groups who have received a specific item (in this case an agenda item)
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-function load_edit_users($tool, $id)
-{
-	global $_course;
-	$tool=Database::escape_string($tool);
-	$id=Database::escape_string($id);
-	$TABLE_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
-
-	$sql="SELECT * FROM $TABLE_ITEM_PROPERTY WHERE tool='$tool' AND ref='$id'";
-	$result=Database::query($sql,__FILE__,__LINE__) or die (Database::error());
-	while ($row=Database::fetch_array($result))
-		{
-		$to_group=$row['to_group_id'];
-		switch ($to_group)
-			{
-			// it was send to one specific user
-			case null:
-				$to[]="USER:".$row['to_user_id'];
-				break;
-			// it was sent to everyone
-			case 0:
-				 return "everyone";
-				 exit;
-				break;
-			default:
-				$to[]="GROUP:".$row['to_group_id'];
-			}
-		}
-	return $to;
-}
-
-
-/**
-* This functions swithes the visibility a course resource using the visible field in 'last_tooledit' values: 0 = invisible
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-function change_visibility($tool,$id)
-{
-	global $_course;
-	$TABLE_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
-	$tool=Database::escape_string($tool);
-	$id=Database::escape_string($id);
-
-	$sql="SELECT * FROM $TABLE_ITEM_PROPERTY WHERE tool='".TOOL_CALENDAR_EVENT."' AND ref='$id'";
-	$result=Database::query($sql,__FILE__,__LINE__) or die (Database::error());
-	$row=Database::fetch_array($result);
-
-	if ($row['visibility']=='1')
-	{
-		$sql_visibility="UPDATE $TABLE_ITEM_PROPERTY SET visibility='0' WHERE tool='$tool' AND ref='$id'";
-		api_item_property_update($_course,TOOL_CALENDAR_EVENT,$id,"invisible",api_get_user_id());
-	}
-	else
-	{
-		$sql_visibility="UPDATE $TABLE_ITEM_PROPERTY SET visibility='1' WHERE tool='$tool' AND ref='$id'";
-		api_item_property_update($_course,TOOL_CALENDAR_EVENT,$id,"visible",api_get_user_id());
-	}
-}
-
-
-
-/**
-* The links that allows the course administrator to add a new agenda item, to filter on groups or users
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-function display_courseadmin_links() {
-	echo "<a href='".api_get_self()."?".api_get_cidreq()."&action=add&amp;view=".(($_SESSION['view']=='month')?"list":Security::remove_XSS($_SESSION['view'])."&amp;origin=".Security::remove_XSS($_GET['origin']))."'>".Display::return_icon('calendar_add.gif', get_lang('AgendaAdd'))." ".get_lang('AgendaAdd')."</a>";
-	if (empty ($_SESSION['toolgroup']))
-	{
-		echo get_lang('UserGroupFilter');
-		echo "<form name=\"filter\" style=\"display:inline;\">";
-		show_user_group_filter_form();
-		echo "</form> ";
-	}
-	//echo "<a href='".api_get_self()."?".api_get_cidreq()."&action=importical&amp;view=".(($_SESSION['view']=='month')?"list":Security::remove_XSS($_SESSION['view'])."&amp;origin=".Security::remove_XSS($_GET['origin']))."'>".Display::return_icon('ical_icon.gif', get_lang('ICalFileImport'))." ".get_lang('ICalFileImport')."</a>";
-}
-
-
-
-/**
-* The links that allows the student AND course administrator to show all agenda items and sort up/down
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-function display_student_links()
-{
-	global $show;
-	if ($_SESSION['sort'] == 'DESC')
-	{
-		echo "<a href='".api_get_self()."?".api_get_cidreq()."&amp;sort=asc&amp;toolgroup=".Security::remove_XSS($_GET['toolgroup'])."&amp;origin=".Security::remove_XSS($_GET['origin'])."'>".Display::return_icon('calendar_up.gif',get_lang('AgendaSortChronologicallyUp')).' '.get_lang("AgendaSortChronologicallyUp")."</a> ";
-	}
-	else
-	{
-		echo "<a href='".api_get_self()."?".api_get_cidreq()."&amp;sort=desc&amp;toolgroup=".Security::remove_XSS($_GET['toolgroup'])."&amp;origin=".Security::remove_XSS($_GET['origin'])."'>".Display::return_icon('calendar_down.gif',get_lang('AgendaSortChronologicallyDown')).' '.get_lang("AgendaSortChronologicallyDown")."</a> ";
-	}
-
-	// showing the link to show all items or only those of the current month
-	if ($_SESSION['show']=="showcurrent")
-	{
-		echo "<a href='".api_get_self()."?".api_get_cidreq()."&amp;action=showall&amp;toolgroup=".Security::remove_XSS($_GET['toolgroup'])."&amp;origin=".Security::remove_XSS($_GET['origin'])."'>".Display::return_icon('calendar_select.gif', get_lang("ShowAllEvents")).' '.get_lang("ShowAllEvents")."</a> ";
-	}
-	else
-	{
-		echo "<a href='".api_get_self()."?".api_get_cidreq()."&amp;action=showcurrent&amp;toolgroup=".Security::remove_XSS($_GET['toolgroup'])."&amp;origin=".Security::remove_XSS($_GET['origin'])."'>".Display::return_icon('calendar_month.gif', get_lang("ShowCurrent")).' '.get_lang("ShowCurrent")."</a> ";
-	}
-
-	if ($_SESSION['view'] <> 'month')
-	{
-		echo "<a href=\"".api_get_self()."?action=view&amp;toolgroup=".Security::remove_XSS($_GET['toolgroup'])."&amp;view=month\">".Display::return_icon('calendar_month.gif', get_lang('MonthView'))." ".get_lang('MonthView')."</a> ";
-	}
-	else
-	{
-		echo "\t<a href=\"".api_get_self()."?action=view&amp;toolgroup=".Security::remove_XSS($_GET['toolgroup'])."&amp;view=list\">".Display::return_icon('calendar_select.gif', get_lang('ListView'))." ".get_lang('ListView')."</a> ";
-	}
-}
-
-
-
-/**
-* get all the information of the agenda_item from the database
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @param integer the id of the agenda item we are getting all the information of
-* @return an associative array that contains all the information of the agenda item. The keys are the database fields
-*/
-function get_agenda_item($id)
-{
-	global $TABLEAGENDA;
-    $t_agenda_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT);
-    $id=Database::escape_string($id);
-    $item = array();
-	if(empty($id))
-    {
-        $id=(int)addslashes($_GET['id']);
-    }
-    else
-    {
-    	$id = (int) $id;
-    }
-    if(empty($id)){return $item;}
-	$sql 					= "SELECT * FROM ".$TABLEAGENDA." WHERE id='".$id."'";
-	$result					= Database::query($sql,__FILE__,__LINE__);
-	$entry_to_edit 			= Database::fetch_array($result);
-	$item['title']			= $entry_to_edit["title"];
-	$item['content']		= $entry_to_edit["content"];
-	$item['start_date']		= $entry_to_edit["start_date"];
-	$item['end_date']		= $entry_to_edit["end_date"];
-	$item['to']				= load_edit_users(TOOL_CALENDAR_EVENT, $id);
-	// if the item has been sent to everybody then we show the compact to form
-	if ($item['to']=="everyone")
-	{
-		$_SESSION['allow_individual_calendar']="hide";
-	}
-	else
-	{
-		$_SESSION['allow_individual_calendar']="show";
-	}
-    $item['repeat'] = false;
-    $sql = "SELECT * FROM $t_agenda_repeat WHERE cal_id = $id";
-    $res = Database::query($sql,__FILE__,__LINE__);
-    if(Database::num_rows($res)>0)
-    {
-        //this event is repetitive
-        $row = Database::fetch_array($res);
-        $item['repeat'] = true;
-        $item['repeat_type'] = $row['cal_type'];
-        $item['repeat_end'] = $row['cal_end'];
-        $item['repeat_frequency'] = $row['cal_frequency']; //unused in 1.8.5 RC1 - will be used later to say if once every 2 or 3 weeks, for example
-        $item['repeat_days'] = $row['cal_days']; //unused in 1.8.5 RC1 - will be used later
-    }
-    //TODO - add management of repeat exceptions
-	return $item;
-}
-
-/**
-* This is the function that updates an agenda item. It does 3 things
-* 1. storethe start_date, end_date, title and message in the calendar_event table
-* 2. store the groups/users who this message is meant for in the item_property table
-* 3. modify the attachments (if needed)
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-function store_edited_agenda_item($id_attach,$file_comment)
-{
-	global $_user, $_course;
-
-	// database definitions
-	$TABLE_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
-
-	// STEP 1: editing the calendar_event table
-	// 1.a.  some filtering of the input data
-	$id=(int)$_POST['id'];
-	$title=strip_tags(trim($_POST['title'])); // no html allowed in the title
-	$content=trim($_POST['content']);
-	$start_date=(int)$_POST['fyear']."-".(int)$_POST['fmonth']."-".(int)$_POST['fday']." ".(int)$_POST['fhour'].":".(int)$_POST['fminute'].":00";
-	$end_date=(int)$_POST['end_fyear']."-".(int)$_POST['end_fmonth']."-".(int)$_POST['end_fday']." ".(int)$_POST['end_fhour'].":".(int)$_POST['end_fminute'].":00";
-	$to=$_POST['selectedform'];
-	// 1.b. the actual saving in calendar_event table
-	$edit_result=save_edit_agenda_item($id,$title,$content,$start_date,$end_date);
-
-	if (empty($id_attach)) {
-		add_agenda_attachment_file($file_comment,$id);
-	} else {
-		edit_agenda_attachment_file($file_comment,$id,$id_attach);
-	}
-
-	// step 2: editing the item_propery table (=delete all and add the new destination users/groups)
-	if ($edit_result=true)
-	{
-		// 2.a. delete everything for the users
-		$sql_delete="DELETE FROM ".$TABLE_ITEM_PROPERTY." WHERE ref='$id' AND tool='".TOOL_CALENDAR_EVENT."'";
-
-		$result = Database::query($sql_delete,__FILE__,__LINE__) or die (Database::error());
-		// 2.b. storing the new users/groups
-		if (!is_null($to)) // !is_null($to): when no user is selected we send it to everyone
-		{
-			$send_to=separate_users_groups($to);
-			// storing the selected groups
-			if (is_array($send_to['groups']))
-			{
-				foreach ($send_to['groups'] as $group)
-				{
-					api_item_property_update($_course, TOOL_CALENDAR_EVENT, $id,"AgendaModified", $_user['user_id'], $group,'',$start_date, $end_date);
-				}
-			}
-			// storing the selected users
-			if (is_array($send_to['users']))
-			{
-				foreach ($send_to['users'] as $user)
-				{
-					api_item_property_update($_course, TOOL_CALENDAR_EVENT, $id,"AgendaModified", $_user['user_id'],'',$user, $start_date,$end_date);
-				}
-			}
-		}
-		else // the message is sent to everyone, so we set the group to 0
-		{
-			api_item_property_update($_course, TOOL_CALENDAR_EVENT, $id,"AgendaModified", $_user['user_id'], '','',$start_date,$end_date);
-		}
-
-	} //if ($edit_result=true)
-
-	// step 3: update the attachments (=delete all and add those in the session
-	update_added_resources("Agenda", $id);
-
-	// return the message;
-	Display::display_confirmation_message(get_lang("EditSuccess"));
-
-}
-
-/**
-* This function stores the Agenda Item in the table calendar_event and updates the item_property table also (after an edit)
-* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-function save_edit_agenda_item($id,$title,$content,$start_date,$end_date)
-{
-	$TABLEAGENDA 		= Database::get_course_table(TABLE_AGENDA);
-	$id=Database::escape_string($id);
-	$title=Database::escape_string(Security::remove_XSS($title));
-	$content=stripslashes($content);
-	$content = Database::escape_string(Security::remove_XSS($content,COURSEMANAGERLOWSECURITY));
-	$start_date=Database::escape_string($start_date);
-	$end_date=Database::escape_string($end_date);
-
-	// store the modifications in the table calendar_event
-	$sql = "UPDATE ".$TABLEAGENDA."
-								SET title='".$title."',
-									content='".$content."',
-									start_date='".$start_date."',
-									end_date='".$end_date."'
-								WHERE id='".$id."'";
-	$result = Database::query($sql,__FILE__,__LINE__) or die (Database::error());
-	return true;
-}
-
-/**
-* This is the function that deletes an agenda item.
-* The agenda item is no longer fycically deleted but the visibility in the item_property table is set to 2
-* which means that it is invisible for the student AND course admin. Only the platform administrator can see it.
-* This will in a later stage allow the platform administrator to recover resources that were mistakenly deleted
-* by the course administrator
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @param integer the id of the agenda item wa are deleting
-*/
-function delete_agenda_item($id)
-{
-	global $_course;
-	$id=Database::escape_string($id);
-	if (api_is_allowed_to_edit(false,true)  OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()))
-	{
-		if (!empty($_GET['id']) && isset($_GET['action']) && $_GET['action']=="delete")
-		{
-		    $t_agenda     = Database::get_course_table(TABLE_AGENDA);
-            $t_agenda_r   = Database::get_course_table(TABLE_AGENDA_REPEAT);
-            $id=(int)addslashes($_GET['id']);
-            $sql = "SELECT * FROM $t_agenda_r WHERE cal_id = $id";
-            $res = Database::query($sql,__FILE__,__LINE__);
-            if(Database::num_rows($res)>0)
-            {
-            	$sql_children = "SELECT * FROM $t_agenda WHERE parent_event_id = $id";
-                $res_children = Database::query($sql_children,__FILE__,__LINE__);
-                if(Database::num_rows($res_children)>0)
-                {
-                    while ($row_child = Database::fetch_array($res_children))
-                    {
-                        api_item_property_update($_course,TOOL_CALENDAR_EVENT,$row_child['id'],'delete',api_get_user_id());
-                    }
-                }
-                $sql_del = "DELETE FROM $t_agenda_r WHERE cal_id = $id";
-                $res_del = Database::query($sql_del,__FILE__,__LINE__);
-            }
-			//$sql = "DELETE FROM ".$TABLEAGENDA." WHERE id='$id'";
-			//$sql= "UPDATE ".$TABLE_ITEM_PROPERTY." SET visibility='2' WHERE tool='Agenda' and ref='$id'";
-			//$result = Database::query($sql,__FILE__,__LINE__) or die (Database::error());
-			api_item_property_update($_course,TOOL_CALENDAR_EVENT,$id,'delete',api_get_user_id());
-
-			// delete the resources that were added to this agenda item
-			// 2DO: as we no longer fysically delete the agenda item (to make it possible to 'restore'
-			//		deleted items, we should not delete the added resources either.
-			// delete_added_resource("Agenda", $id); // -> this is no longer needed as the message is not really deleted but only visibility=2 (only platform admin can see it)
-
-			//resetting the $id;
-			$id=null;
-
-			// displaying the result message in the yellow box
-			Display::display_confirmation_message(get_lang("AgendaDeleteSuccess"));
-		}	  // if (isset($id)&&$id&&isset($action)&&$action=="delete")
-	} // if ($is_allowed_to_edit)
-
-}
-/**
-* Makes an agenda item visible or invisible for a student
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @param integer id the id of the agenda item we are changing the visibility of
-*/
-function showhide_agenda_item($id)
-{
-	global $nameTools;
-	/*==================================================
-				SHOW / HIDE A CALENDAR ITEM
-	  ==================================================*/
-	//  and $_GET['isStudentView']<>"false" is added to prevent that the visibility is changed after you do the following:
-	// change visibility -> studentview -> course manager view
-	if ((api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous())) and $_GET['isStudentView']<>"false")
-	{
-		if (isset($_GET['id'])&&$_GET['id']&&isset($_GET['action'])&&$_GET['action']=="showhide")
-		{
-			$id=(int)addslashes($_GET['id']);
-			change_visibility($nameTools,$id);
-			Display::display_confirmation_message(get_lang("VisibilityChanged"));
-		}
-	}
-}
-/**
-* Displays all the agenda items
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @author Yannick Warnier <yannick.warnier@dokeos.com> - cleanup
-*/
-function display_agenda_items()
-{
-	global $TABLEAGENDA;
-	global $TABLE_ITEM_PROPERTY;
-	global $select_month, $select_year;
-	global $DaysShort, $DaysLong, $MonthsLong;
-	global $is_courseAdmin;
-	global $dateFormatLong, $timeNoSecFormat,$charset, $_user, $_course;
-
-	// getting the group memberships
-	$group_memberships=GroupManager::get_group_ids($_course['dbName'],$_user['user_id']);
-
-	// getting the name of the groups
-	$group_names=get_course_groups();
-
-	/*--------------------------------------------------
-			CONSTRUCT THE SQL STATEMENT
-	  --------------------------------------------------*/
-
-    $start = 0;
-    $stop = 0;
-	// this is to make a difference between showing everything (all months) or only the current month)
-	// $show_all_current is a part of the sql statement
-	if ($_SESSION['show']!=="showall")
-	{
-		$show_all_current=" AND MONTH(start_date)=$select_month AND year(start_date)=$select_year";
-        $start = mktime(0,0,0,$select_month,1,$select_year);
-        $stop = 0;
-        if(empty($select_year)){$select_year = date('Y');}
-        if(empty($select_month)){$select_month = date('m');}
-        if($select_month==12)
-        {
-            $stop = mktime(0,0,0,1,1,$select_year+1)-1;
-        }
-        else
-        {
-            $stop = mktime(0,0,0,$select_month+1,1,$select_year)-1;
-        }
-	}
-	else
-	{
-		$show_all_current="";
-        $start = time();
-        $stop = mktime(0,0,0,1,1,2038);//by default, set year to maximum for mktime()
-	}
-
-	// by default we use the id of the current user. The course administrator can see the agenda of other users by using the user / group filter
-	$user_id=$_user['user_id'];
-	if ($_SESSION['user']!==null)
-	{
-		$user_id=intval($_SESSION['user']);
-	}
-	if ($_SESSION['group']!==null)
-	{
-		$group_id=intval($_SESSION['group']);
-	}
-	if ($_SESSION['toolgroup']!==null)
-	{
-		$group_id=intval($_SESSION['toolgroup']);
-	}
-
-    $repeats = array(); //placeholder for repeated events
-	//echo "user:".$_SESSION['user']."group: ".$_SESSION['group'];
-	// A. you are a course admin
-	//if ($is_courseAdmin)
-
-	$session_condition = intval($_SESSION['id_session'])==0 ? '' : ' AND agenda.session_id IN (0,'.intval($_SESSION['id_session']).') ';
-
-
-	if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()))
-	{
-		// A.1. you are a course admin with a USER filter
-		// => see only the messages of this specific user + the messages of the group (s)he is member of.
-		if (!empty($_SESSION['user']))
-		{
-			$group_memberships=GroupManager::get_group_ids($_course['dbName'],$_SESSION['user']);
-
-			$show_user =true;
-			$new_group_memberships=array();
-			foreach($group_memberships as $id)
-			{
-				// did i have access to the same
-				$has_access = GroupManager::user_has_access(api_get_user_id(),$id,GROUP_TOOL_CALENDAR);
-				$result = GroupManager::get_group_properties($id);
+        	if ($end > $now && in_array($type,array('daily','weekly','monthlyByDate','monthlyByDay','monthlyByDayR','yearly'))) {
+        	   $sql = "INSERT INTO $t_agenda_repeat (cal_id, cal_type, cal_end)" .
+                    " VALUES ($last_id,'$type',$end)";
+               $res = Database::query($sql,__FILE__,__LINE__);
+            }
+        }
+    }
+	return $last_id;
+}
 
-				if ($has_access && $result['calendar_state']!='0' )
-				{
-					$new_group_memberships[]=$id;
-				}
-			}
-			$group_memberships = $new_group_memberships;
-
-			if (is_array($group_memberships) && count($group_memberships)>0)
-			{
-				$sql="SELECT
-					agenda.*, toolitemproperties.*
-					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
-					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-					AND	( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id IN (0, ".implode(", ", $group_memberships).") )
-					AND toolitemproperties.visibility='1'
-					$session_condition
-					ORDER BY start_date ".$_SESSION['sort'];
-			}
-			else
-			{
-					$sql="SELECT
-					agenda.*, toolitemproperties.*
-					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
-					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-					AND ( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id='0')
-					AND toolitemproperties.visibility='1'
-					$session_condition
-					ORDER BY start_date ".$_SESSION['sort'];
-			}
-		}
-		// A.2. you are a course admin with a GROUP filter
-		// => see only the messages of this specific group
-		elseif (!empty($_SESSION['group']))
-		{
+/**
+ * Stores the given agenda item as an announcement (unlinked copy)
+ * @param	integer		Agenda item's ID
+ * @return	integer		New announcement item's ID
+ */
+function store_agenda_item_as_announcement($item_id){
+	$table_agenda = Database::get_course_table(TABLE_AGENDA);
+	$table_ann = Database::get_course_table(TABLE_ANNOUNCEMENT);
+	//check params
+	if(empty($item_id) or $item_id != strval(intval($item_id))){return -1;}
+	//get the agenda item
 
-			if (!empty($group_id)) {
-				$result = GroupManager::get_group_properties($group_id);
-				$has_access = GroupManager::user_has_access(api_get_user_id(),$group_id,GROUP_TOOL_CALENDAR);
-				//echo '<pre>';print_R($result);
+	$item_id=Database::escape_string($item_id);
+	$sql = "SELECT * FROM $table_agenda WHERE id = '".$item_id."'";
+	$res = Database::query($sql,__FILE__,__LINE__);
+	if(Database::num_rows($res)>0){
+		$row = Database::fetch_array($res);
+		//we have the agenda event, copy it
+		//get the maximum value for display order in announcement table
+		$sql_max = "SELECT MAX(display_order) FROM $table_ann";
+		$res_max = Database::query($sql_max,__FILE__,__LINE__);
+		$row_max = Database::fetch_array($res_max);
+		$max = $row_max[0]+1;
+		//build the announcement text
+		$content = $row['start_date']." - ".$row['end_date']."\n\n".$row['content'];
+		//insert announcement
 
-				// lastedit
-				if (!$has_access || $result['calendar_state']=='0' )
+		$sql_ins = "INSERT INTO $table_ann (title,content,end_date,display_order) " .
+				"VALUES ('".Security::remove_XSS($row['title'])."','".$content."','".$row['end_date']."','$max')";
+		$res_ins = Database::query($sql_ins,__FILE__,__LINE__);
+		if($res > 0)
+		{
+			$ann_id = Database::get_last_insert_id();
+			//Now also get the list of item_properties rows for this agenda_item (calendar_event)
+			//and copy them into announcement item_properties
+			$table_props = Database::get_course_table(TABLE_ITEM_PROPERTY);
+			$sql_props = "SELECT * FROM $table_props WHERE tool = 'calendar_event' AND ref='$item_id'";
+			$res_props = Database::query($sql_props,__FILE__,__LINE__);
+			if(Database::num_rows($res_props)>0)
+			{
+				while($row_props = Database::fetch_array($res_props))
 				{
-					$group_id=0;
+					//insert into announcement item_property
+					$time = date("Y-m-d H:i:s", time());
+					$sql_ins_props = "INSERT INTO $table_props " .
+							"(tool, insert_user_id, insert_date, " .
+							"lastedit_date, ref, lastedit_type," .
+							"lastedit_user_id, to_group_id, to_user_id, " .
+							"visibility, start_visible, end_visible)" .
+							" VALUES " .
+							"('announcement','".$row_props['insert_user_id']."','".$time."'," .
+							"'$time','$ann_id','AnnouncementAdded'," .
+							"'".$row_props['last_edit_user_id']."','".$row_props['to_group_id']."','".$row_props['to_user_id']."'," .
+							"'".$row_props['visibility']."','".$row_props['start_visible']."','".$row_props['end_visible']."')";
+					$res_ins_props = Database::query($sql_ins_props,__FILE__,__LINE__);
+					if($res_ins_props <= 0){
+						error_log('SQL Error in '.__FILE__.' at line '.__LINE__.': '.$sql_ins_props);
+					}else{
+						//copy was a success
+						return $ann_id;
+					}
 				}
 			}
+		}else{
+			return -1;
+		}
+	}
+	return -1;
+}
 
-			$sql="SELECT
-				agenda.*, toolitemproperties.*
-				FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-				WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
-				AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-				AND ( toolitemproperties.to_group_id=$group_id OR toolitemproperties.to_group_id='0')
-				AND toolitemproperties.visibility='1'
-				$session_condition
-				GROUP BY toolitemproperties.ref
-				ORDER BY start_date ".$_SESSION['sort'];
-		}
-		// A.3 you are a course admin without any group or user filter
-		else
-		{
-			// A.3.a you are a course admin without user or group filter but WITH studentview
-			// => see all the messages of all the users and groups without editing possibilities
-			if ($_GET['isStudentView']=='true')
-			{
-				$sql="SELECT
-					agenda.*, toolitemproperties.*
-					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-					WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
-					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-					AND toolitemproperties.visibility='1'
-					$session_condition
-					GROUP BY toolitemproperties.ref
-					ORDER BY start_date ".$_SESSION['sort'];
-
-			}
-			// A.3.b you are a course admin or a student
-			else
-			{
-				// A.3.b.1 you are a course admin without user or group filter and WITHOUT studentview (= the normal course admin view)
-				// 	=> see all the messages of all the users and groups with editing possibilities
-
-				 if (api_is_course_admin())
-				 {
-					 $sql="SELECT
-						agenda.*, toolitemproperties.*
-						FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-						WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
-						AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-						AND ( toolitemproperties.visibility='0' OR toolitemproperties.visibility='1')
-						$session_condition
-						GROUP BY toolitemproperties.ref
-						ORDER BY start_date ".$_SESSION['sort'];
-				 }
-				 else
-				 {
-				 	// A.3.b.2 you are a student with no group filter possibly showall
-				 	//when showing all the events we do not show the group events
-				 	//todo showing ALL events including the groups events that are available
-
-				 	$sql="SELECT
-						agenda.*, toolitemproperties.*
-						FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-						WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
-						AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-						AND toolitemproperties.visibility='1' AND toolitemproperties.to_group_id='0'
-						$session_condition
-						GROUP BY toolitemproperties.ref
-						ORDER BY start_date ".$_SESSION['sort'];
-
-
-					/*
-				 	if (is_array($group_memberships) && count($group_memberships)>0)
-				 	{
-				 		echo $sql="SELECT
-						agenda.*, toolitemproperties.*
-						FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-						WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
-						AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-						AND toolitemproperties.visibility='1' AND toolitemproperties.to_group_id IN (0, ".implode(", ", $group_memberships).")
-						$session_condition
-						GROUP BY toolitemproperties.ref
-						ORDER BY start_date ".$_SESSION['sort'];
-				 	}
-				 	else
-				 	{
-				 		$sql="SELECT
-						agenda.*, toolitemproperties.*
-						FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-						WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
-						AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-						AND toolitemproperties.visibility='1' AND toolitemproperties.to_group_id='0'
-						$session_condition
-						GROUP BY toolitemproperties.ref
-						ORDER BY start_date ".$_SESSION['sort'];
-				 	}
-				 	*/
-
-				 }
-			}
-		}
-
-	} //if (is_allowed_to_edit() OR( api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()))
-
-	// B. you are a student
-	else
-	{
-		if (is_array($group_memberships) and count($group_memberships)>0)
-		{
-			$sql="SELECT
-				agenda.*, toolitemproperties.*
-				FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-				WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
-				AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-				AND	( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id IN (0, ".implode(", ", $group_memberships).") )
-				AND toolitemproperties.visibility='1'
-				$session_condition
-				ORDER BY start_date ".$_SESSION['sort'];
-		}
-		else
-		{
-			if ($_user['user_id'])
-			{
-				$sql="SELECT
-					agenda.*, toolitemproperties.*
-					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
-					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-					AND ( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id='0')
-					AND toolitemproperties.visibility='1'
-					$session_condition
-					ORDER BY start_date ".$_SESSION['sort'];
-			}
-			else
-			{
-				$sql="SELECT
-					agenda.*, toolitemproperties.*
-					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
-					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-					AND toolitemproperties.to_group_id='0'
-					AND toolitemproperties.visibility='1'
-					$session_condition
-					ORDER BY start_date ".$_SESSION['sort'];
-			}
-		}
-	} // you are a student
-
-	//echo "<pre>".$sql."</pre>";
-	$result=Database::query($sql,__FILE__,__LINE__) or die(Database::error());
-	$number_items=Database::num_rows($result);
-
-	/*--------------------------------------------------
-			DISPLAY: NO ITEMS
-	  --------------------------------------------------*/
-	if ($number_items==0)
-	{
-        echo "<table class=\"data_table\" ><tr><td>".get_lang("NoAgendaItems")."</td></tr></table>";
-	}
-
-	/*--------------------------------------------------
-			DISPLAY: THE ITEMS
-	  --------------------------------------------------*/
-
-    $month_bar="";
-    $event_list="";
-    $counter=0;
-    $export_icon = 'export.png';
-    $export_icon_low = 'export_low_fade.png';
-    $export_icon_high = 'export_high_fade.png';
-
-    while($myrow=Database::fetch_array($result))
-    {
-    	$is_repeated = !empty($myrow['parent_event_id']);
-	    echo '<table class="data_table">',"\n";
-        /*--------------------------------------------------
-        		display: the month bar
-         --------------------------------------------------*/
-        // Make the month bar appear only once.
-        if ($month_bar != date("m",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"])))
-		{
-            $month_bar = date("m",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"]));
-			echo "\t<tr>\n\t\t<td class=\"agenda_month_divider\" colspan=\"3\" valign=\"top\">".
-			api_ucfirst(format_locale_date("%B %Y",strtotime($myrow["start_date"]))).
-			"</td>\n\t</tr>\n";
-		}
-
-        /*--------------------------------------------------
-         display: the icon, title, destinees of the item
-         -------------------------------------------------*/
-    	echo '<tr>';
-
-    	// highlight: if a date in the small calendar is clicked we highlight the relevant items
-    	$db_date=(int)date("d",strtotime($myrow["start_date"])).date("n",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"]));
-    	if ($_GET["day"].$_GET["month"].$_GET["year"] <>$db_date)
-    	{
-    		if ($myrow['visibility']=='0')
-    		{
-    			$style="data_hidden";
-    			$stylenotbold="datanotbold_hidden";
-    			$text_style="text_hidden";
-    		}
-    		else
-    		{
-    			$style="data";
-    			$stylenotbold="datanotbold";
-    			$text_style="text";
-    		}
-
-    	}
-    	else
-    	{
-    		$style="datanow";
-    		$stylenotbold="datanotboldnow";
-    		$text_style="textnow";
-    	}
-
-    	echo "\t\t<th>\n";
-    	// adding an internal anchor
-    	echo "\t\t\t<a name=\"".(int)date("d",strtotime($myrow["start_date"]))."\"></a>";
-    	// the icons. If the message is sent to one or more specific users/groups
-    	// we add the groups icon
-    	// 2do: if it is sent to groups we display the group icon, if it is sent to a user we show the user icon
-    	Display::display_icon('agenda.gif', get_lang('Agenda'));
-    	if ($myrow['to_group_id']!=='0')
-    	{
-    		echo Display::return_icon('group.gif', get_lang('ItemForUserSelection'));
-    	}
-    	echo " ".$myrow['title']."\n";
-    	echo "\t\t</th>\n";
-
-    	// the message has been sent to
-    	echo "\t\t<th>".get_lang("SentTo").": ";
-    	$sent_to=sent_to(TOOL_CALENDAR_EVENT, $myrow["ref"]);
-    	$sent_to_form=sent_to_form($sent_to);
-    	echo $sent_to_form;
-    	echo "</th>";
-
-    	if (!$is_repeated && (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous())))
-    	{
-    		if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $myrow['id'] ) ) )
-			{ // a coach can only delete an element belonging to his session
-	    		echo '<th>'.get_lang('Modify');
-	    		echo '</th></tr>';
-			}
-    	}
-
-        /*--------------------------------------------------
-     			display: the title
-         --------------------------------------------------*/
-    	echo "<tr class='row_odd'>";
-    	echo "\t\t<td>".get_lang("StartTimeWindow").": ";
-    	echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["start_date"])))."&nbsp;&nbsp;&nbsp;";
-    	echo api_ucfirst(strftime($timeNoSecFormat,strtotime($myrow["start_date"])))."";
-    	echo "</td>\n";
-    	echo "\t\t<td>";
-    	if ($myrow["end_date"]<>"0000-00-00 00:00:00")
-    	{
-    		echo get_lang("EndTimeWindow").": ";
-    		echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["end_date"])))."&nbsp;&nbsp;&nbsp;";
-    		echo api_ucfirst(strftime($timeNoSecFormat,strtotime($myrow["end_date"])))."";
-    	}
-    	echo "</td>\n";
-
-    	// attachment list
-	    	$attachment_list=get_attachment($myrow['id']);
-
-        /*--------------------------------------------------
-    	 display: edit delete button (course admin only)
-         --------------------------------------------------*/
-
-
-    	if (!$is_repeated && (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous())))
-    	{
-    		if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $myrow['id'] ) ) )
-			{ // a coach can only delete an element belonging to his session
-				$mylink = api_get_self().'?'.api_get_cidreq().'&amp;origin='.Security::remove_XSS($_GET['origin']).'&amp;id='.$myrow['id'];
-	    		echo '<td align="center">';
-	    		// edit
-    			echo '<a href="'.$mylink.'&amp;action=edit&amp;id_attach='.$attachment_list['id'].'" title="'.get_lang("ModifyCalendarItem").'">';
-	    		echo Display::return_icon('edit.gif', get_lang('ModifyCalendarItem'))."</a>";
-
-    			echo "<a href=\"".$mylink."&amp;action=delete\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."')) return false;\"  title=\"".get_lang("Delete")."\"> ";
-	    		echo Display::return_icon('delete.gif', get_lang('Delete'))."</a>";
-
-    			echo '<a href="'.$mylink.'&amp;action=announce" title="'.get_lang("AddAnnouncement").'">';
-    			echo Display::return_icon('announce_add.gif', get_lang('AddAnnouncement'), array ('style' => 'width:16px; height:16px;'))."</a> ";
-
-	    		if ($myrow['visibility']==1)
-	    		{
-	    			$image_visibility="visible.gif";
-				$text_visibility=get_lang("Hide");
-	    		}
-	    		else
-	    		{
-	    			$image_visibility="invisible.gif";
-				$text_visibility=get_lang("Show");
-	    		}
-    			echo 	'<a href="'.$mylink.'&amp;action=showhide" title="'.$text_visibility.'">',
-    					Display::return_icon($image_visibility, $text_visibility),'</a> ';
-			}
-
-    	if (!$is_repeated && (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous())))
-    	{
-    		if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $myrow['id'] ) ) )
-			{ // a coach can only delete an element belonging to his session
-    			$td_colspan= '<td colspan="3">';
-			}
-			else
-			{
-				$td_colspan= '<td colspan="2">';
-			}
-    	}
-    	else
-    	{
-    		$td_colspan= '<td colspan="2">';
-    	}
-    	$mylink = 'ical_export.php?'.api_get_cidreq().'&amp;type=course&amp;id='.$myrow['id'];
-		//echo '<a class="ical_export" href="'.$mylink.'&amp;class=confidential" title="'.get_lang('ExportiCalConfidential').'">'.Display::return_icon($export_icon_high, get_lang('ExportiCalConfidential')).'</a> ';
-    	//echo '<a class="ical_export" href="'.$mylink.'&amp;class=private" title="'.get_lang('ExportiCalPrivate').'">'.Display::return_icon($export_icon_low, get_lang('ExportiCalPrivate')).'</a> ';
-    	//echo '<a class="ical_export" href="'.$mylink.'&amp;class=public" title="'.get_lang('ExportiCalPublic').'">'.Display::return_icon($export_icon, get_lang('ExportiCalPublic')).'</a> ';
-	    echo '<a href="#" onclick="javascript:win_print=window.open(\'print.php?id='.$myrow['id'].'\',\'popup\',\'left=100,top=100,width=700,height=500,scrollbars=1,resizable=0\'); win_print.focus(); return false;">'.Display::return_icon('print.gif', get_lang('Print')).'</a>&nbsp;';
-    	echo '</td>';
-    	echo '</tr>';
-}
-
-        /*--------------------------------------------------
-     			display: the content
-         --------------------------------------------------*/
-    	$content = $myrow['content'];
-    	$content = make_clickable($content);
-    	$content = text_filter($content);
-    	echo "<tr class='row_even'>";
-    	echo "<td colspan='3'>";
-
-    	echo $content;
-    	// show attachment list
-			if (!empty($attachment_list)) {
-
-				$realname=$attachment_list['path'];
-				$user_filename=$attachment_list['filename'];
-				$full_file_name = 'download.php?file='.$realname;
-				echo Display::return_icon('attachment.gif',get_lang('Attachment'));
-				echo '<a href="'.$full_file_name.'';
-				echo ' "> '.$user_filename.' </a>';
-				echo '<span class="forum_attach_comment" >'.$attachment_list['comment'].'</span>';
-				if (api_is_allowed_to_edit()) {
-					echo '&nbsp;&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;origin='.Security::remove_XSS($_GET['origin']).'&amp;action=delete_attach&amp;id_attach='.$attachment_list['id'].'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset)).'\')) return false;">'.Display::return_icon('delete.gif',get_lang('Delete')).'</a><br />';
-				}
-
-			}
-
-	    echo '</td></tr>';
-
-
-        /*--------------------------------------------------
-     			display: the added resources
-         --------------------------------------------------*/
-    	if (check_added_resources("Agenda", $myrow["id"]))
-    	{
-
-    		echo '<tr>';
-    		echo '<td colspan="3">';
-    		echo "<i>".get_lang("AddedResources")."</i><br/>";
-    		if ($myrow['visibility']==0)
-    		{
-    			$addedresource_style="invisible";
-    		}
-    		display_added_resources("Agenda", $myrow["id"], $addedresource_style);
-    		echo "</td></tr>";
-    	}
-
-
-    	$event_list.=$myrow['id'].',';
-
-    	$counter++;
-        /*--------------------------------------------------
-    	 display: jump-to-top icon
-         --------------------------------------------------*/
-    	echo '<tr>';
-        echo '<td colspan="3">';
-        if($is_repeated){echo get_lang('RepeatedEvent'),' <a href="',api_get_self(),'?',api_get_cidreq(),'&amp;agenda_id=',$myrow['parent_event_id'],'" alt="',get_lang('RepeatedEventViewOriginalEvent'),'">',get_lang('RepeatedEventViewOriginalEvent'),'</a>';}
-    	echo "<a href=\"#top\">".Display::return_icon('top.gif', get_lang('Top'))."</a></td></tr>";
-    	echo "</table><br /><br />";
-    } // end while ($myrow=Database::fetch_array($result))
-
-    if(!empty($event_list))
-    {
-    	$event_list=api_substr($event_list,0,-1);
-    }
-    else
-    {
-    	$event_list='0';
-    }
-
-    echo "<form name=\"event_list_form\"><input type=\"hidden\" name=\"event_list\" value=\"$event_list\" /></form>";
-
-    // closing the layout table
-    echo "</td>",
-    	"</tr>",
-    	"</table>";
-}
-
-/**
- * Show a list with all the attachments according to the post's id
- * @param the post's id
- * @return array with the post info
- * @author Christian Fasanando
- * @version November 2008, dokeos 1.8.6
- */
-
-function get_attachment($agenda_id) {
-	$agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
-	$agenda_id=Database::escape_string($agenda_id);
-	$row=array();
-	$sql = 'SELECT id,path, filename,comment FROM '. $agenda_table_attachment.' WHERE agenda_id = '.(int)$agenda_id.'';
-	$result=Database::query($sql, __FILE__, __LINE__);
-	if (Database::num_rows($result)!=0) {
-		$row=Database::fetch_array($result);
-	}
-	return $row;
-}
-
-/**
-* Displays only 1 agenda item. This is used when an agenda item is added to the learning path.
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-function display_one_agenda_item($agenda_id)
-{
-	global $TABLEAGENDA;
-	global $TABLE_ITEM_PROPERTY;
-	global $select_month, $select_year;
-	global $DaysShort, $DaysLong, $MonthsLong;
-	global $is_courseAdmin;
-	global $dateFormatLong, $timeNoSecFormat, $charset;
-	global $_user;
-	//echo "displaying agenda items";
-
-
-	// getting the name of the groups
-	$group_names=get_course_groups();
-
-	/*--------------------------------------------------
-			CONSTRUCT THE SQL STATEMENT
-	  --------------------------------------------------*/
-	$agenda_id = Database::escape_string($agenda_id);
-
-	$sql="SELECT agenda.*, toolitemproperties.*
-					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-					WHERE agenda.id = toolitemproperties.ref
-					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
-					AND toolitemproperties.visibility='1'
-					AND agenda.id='$agenda_id'";
-	$result=Database::query($sql,__FILE__,__LINE__) or die(Database::error());
-	$number_items=Database::num_rows($result);
-	$myrow=Database::fetch_array($result); // there should be only one item so no need for a while loop
-
-    $sql_rep = "SELECT * FROM $TABLEAGENDA WHERE id = $agenda_id AND parent_event_id IS NOT NULL AND parent_event_id !=0";
-    $res_rep = Database::query($sql_rep,__FILE__,__LINE__);
-    $repeat = false;
-    $repeat_id = 0;
-    if(Database::num_rows($res_rep)>0)
-    {
-        $repeat=true;
-        $row_rep = Database::fetch_array($res_rep);
-        $repeat_id = $row_rep['parent_event_id'];
-    }
-
-	/*--------------------------------------------------
-			DISPLAY: NO ITEMS
-	  --------------------------------------------------*/
-	if ($number_items==0)
-	{
-		echo "<table id=\"data_table\" class=\"data_table\"><tr><td>".get_lang("NoAgendaItems")."</td></tr></table>";
-	}
-
-	/*--------------------------------------------------
-			DISPLAY: THE ITEMS
-	  --------------------------------------------------*/
-	echo "<table id=\"data_table\" class=\"data_table\">\n";
-
-	/*--------------------------------------------------
-	 DISPLAY : the icon, title, destinees of the item
-	  --------------------------------------------------*/
-	echo "\t<tr>\n";
-
-	// highlight: if a date in the small calendar is clicked we highlight the relevant items
-	$db_date=(int)date("d",strtotime($myrow["start_date"])).date("n",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"]));
-	if ($_GET["day"].$_GET["month"].$_GET["year"] <>$db_date)
-	{
-		if ($myrow['visibility']=='0')
-		{
-			$style="data_hidden";
-			$stylenotbold="datanotbold_hidden";
-			$text_style="text_hidden";
-		}
-		else
-		{
-			$style="data";
-			$stylenotbold="datanotbold";
-			$text_style="text";
-		}
-	}
-	else
-	{
-		$style="datanow";
-		$stylenotbold="datanotboldnow";
-		$text_style="textnow";
-	}
-
-
-	echo "\t\t<th>\n";
-
-	// adding an internal anchor
-	echo "\t\t\t<a name=\"".(int)date("d",strtotime($myrow["start_date"]))."\"></a>";
-
-	// the icons. If the message is sent to one or more specific users/groups
-	// we add the groups icon
-	// 2do: if it is sent to groups we display the group icon, if it is sent to a user we show the user icon
-	echo Display::return_icon('agenda.gif');
-	if ($myrow['to_group_id']!=='0')
-	{
-		echo Display::return_icon('group.gif');
-	}
-	echo " ".$myrow['title']."\n";
-	echo "\t\t</th>\n";
-
-	// the message has been sent to
-	echo "\t\t<th>".get_lang("SentTo").": ";
-	$sent_to=sent_to(TOOL_CALENDAR_EVENT, $myrow["ref"]);
-	$sent_to_form=sent_to_form($sent_to);
-	echo $sent_to_form;
-	echo "</th>";
-	if (api_is_allowed_to_edit())	{
-		if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $myrow['id'] ) ) )
-				{ // a coach can only delete an element belonging to his session
-		    		echo '<th>'.get_lang('Modify');
-		    		echo '</th></tr>';
-				}
-	}
-	/*--------------------------------------------------
-	 			DISPLAY: the title
-	  --------------------------------------------------*/
-	echo "\t<tr class='row_odd'>\n";
-	echo "\t\t<td>".get_lang("StartTime").": ";
-	echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["start_date"])))."&nbsp;&nbsp;&nbsp;";
-	echo api_ucfirst(strftime($timeNoSecFormat,strtotime($myrow["start_date"])))."";
-	echo "</td>\n";
-	echo "\t\t<td>".get_lang("EndTime").": ";
-	echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["end_date"])))."&nbsp;&nbsp;&nbsp;";
-	echo api_ucfirst(strftime($timeNoSecFormat,strtotime($myrow["end_date"])))."";
-	echo "</td>\n";
-
-	/*--------------------------------------------------
-		DISPLAY: edit delete button (course admin only)
-	  --------------------------------------------------*/
-	$export_icon = '../img/export.png';
-    $export_icon_low = '../img/export_low_fade.png';
-    $export_icon_high = '../img/export_high_fade.png';
-    if (api_is_allowed_to_edit())	{
-		echo '<td colspan="2">';
-		if (!$repeat && api_is_allowed_to_edit(false,true))	{
-			// edit
-			$mylink = api_get_self()."?".api_get_cidreq()."&amp;origin=".Security::remove_XSS($_GET['origin'])."&amp;id=".$myrow['id'];
-			if (!empty($_GET['agenda_id']))
-			{
-				// rather ugly hack because the id parameter is already set above but below we set it again
-				$mylink .= '&amp;agenda_id='.Security::remove_XSS($_GET['agenda_id']).'&amp;id='.Security::remove_XSS($_GET['agenda_id']);
-			}
-			echo 	"<a href=\"".$mylink."&amp;action=edit\">",
-					Display::return_icon('edit.gif', get_lang('ModifyCalendarItem')), "</a>",
-					"<a href=\"".$mylink."&amp;action=delete\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."')) return false;\">",
-					Display::return_icon('delete.gif', get_lang('Delete')),"</a>";
-			if ($myrow['visibility']==1) {
-				$image_visibility="visible";
-			} else {
-				$image_visibility="invisible";
-			}
-			echo 	'<a href="'.$mylink.'&amp;action=showhide">',Display::return_icon($image_visibility.'.gif', get_lang('Visible')),'</a>';
-		}
-	   	$mylink = 'ical_export.php?'.api_get_cidreq().'&amp;type=course&amp;id='.$myrow['id'];
-	    //echo '<a class="ical_export" href="'.$mylink.'&amp;class=confidential" title="'.get_lang('ExportiCalConfidential').'">'.Display::return_icon($export_icon_high, get_lang('ExportiCalConfidential')).'</a> ';
-	    //echo '<a class="ical_export" href="'.$mylink.'&amp;class=private" title="'.get_lang('ExportiCalPrivate').'">'.Display::return_icon($export_icon_low, get_lang('ExportiCalPrivate')).'</a> ';
-	    //echo '<a class="ical_export" href="'.$mylink.'&amp;class=public" title="'.get_lang('ExportiCalPublic').'">'.Display::return_icon($export_icon, get_lang('ExportiCalPublic')).'</a> ';
-	    echo '<a href="javascript: void(0);" onclick="javascript:win_print=window.open(\'print.php?id='.$myrow['id'].'\',\'popup\',\'left=100,top=100,width=700,height=500,scrollbars=1,resizable=0\'); win_print.focus(); return false;">'.Display::return_icon('print.gif', get_lang('Print')).'</a>&nbsp;';
-		echo "</td></tr>";
-	    if($repeat) {
-	    	echo '<tr>';
-	    	echo '<td colspan="2">',get_lang('RepeatedEvent'),'<a href="',api_get_self(),'?',api_get_cidreq(),'&amp;agenda_id=',$repeat_id,'" alt="',get_lang('RepeatedEventViewOriginalEvent'),'">',get_lang('RepeatedEventViewOriginalEvent'),'</a></td>';
-	        echo '</tr>';
-	    }
-    }
-	/*--------------------------------------------------
-	 			DISPLAY: the content
-	  --------------------------------------------------*/
-
-	$content = $myrow['content'];
-	$content = make_clickable($content);
-	$content = text_filter($content);
-	//echo "\t<tr>\n\t\t<td class=\"".$text_style."\" colspan='2'>";
-	//echo $content;
-	//echo "</td></tr>";
-    echo "<tr class='row_even'>";
-    echo '<td '.(api_is_allowed_to_edit()?'colspan="3"':'colspan="2"'). '>';
-    echo $content;
-    echo '</td></tr>';
-
-	/*--------------------------------------------------
-	 			DISPLAY: the added resources
-	  --------------------------------------------------*/
-	if (check_added_resources("Agenda", $myrow["id"])) {
-		echo "<tr><td colspan='3'>";
-		echo "<i>".get_lang("AddedResources")."</i><br/>";
-		if ($myrow['visibility']==0)
-		{
-			$addedresource_style="invisible";
-		}
-		display_added_resources("Agenda", $myrow["id"], $addedresource_style);
-		echo "</td></tr>";
-	}
-
-	// closing the layout table
-	echo "</td>",
-		"</tr>",
-		"</table>";
-}
-
-
-
-
-/**
-* Show the form for adding a new agenda item. This is the same function that is used whenever we are editing an
-* agenda item. When the id parameter is empty (default behaviour), then we show an empty form, else we are editing and
-* we have to retrieve the information that is in the database and use this information in the forms.
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @param integer id, the id of the agenda item we are editing. By default this is empty which means that we are adding an
-*		 agenda item.
-*/
-function show_add_form($id = '')
-{
-
-	global $MonthsLong;
-	$htmlHeadXtra[] = to_javascript();
-	// the default values for the forms
-	if ($_GET['originalresource'] !== 'no')
-	{
-		$day	= date('d');
-		$month	= date('m');
-		$year	= date('Y');
-		$hours	= 9;
-		$minutes= '00';
-
-		$end_day	= date('d');
-		$end_month	= date('m');
-		$end_year	= date('Y');
-		$end_hours	= 17;
-		$end_minutes= '00';
-        $repeat = false;
-	}
-	else
-	{
-		// we are coming from the resource linker so there might already have been some information in the form.
-		// When we clicked on the button to add resources we stored every form information into a session and now we
-		// are doing the opposite thing: getting the information out of the session and putting it into variables to
-		// display it in the forms.
-		$form_elements=$_SESSION['formelements'];
-		$day=$form_elements['day'];
-		$month=$form_elements['month'];
-		$year=$form_elements['year'];
-		$hours=$form_elements['hour'];
-		$minutes=$form_elements['minutes'];
-		$end_day=$form_elements['end_day'];
-		$end_month=$form_elements['end_month'];
-		$end_year=$form_elements['end_year'];
-		$end_hours=$form_elements['end_hours'];
-		$end_minutes=$form_elements['end_minutes'];
-		$title=$form_elements['title'];
-		$content=$form_elements['content'];
-		$id=$form_elements['id'];
-		$to=$form_elements['to'];
-        $repeat = $form_elements['repeat'];
-	}
-
-	//	switching the send to all/send to groups/send to users
-	if ($_POST['To'])
-	{
-			$day			= $_POST['fday'];
-			$month			= $_POST['fmonth'];
-			$year			= $_POST['fyear'];
-			$hours			= $_POST['fhour'];
-			$minutes		= $_POST['fminute'];
-			$end_day		= $_POST['end_fday'];
-			$end_month		= $_POST['end_fmonth'];
-			$end_year		= $_POST['end_fyear'];
-			$end_hours		= $_POST['end_fhour'];
-			$end_minutes	= $_POST['end_fminute'];
-			$title 			= $_POST['title'];
-			$content		= $_POST['content'];
-			// the invisible fields
-			$action			= $_POST['action'];
-			$id				= $_POST['id'];
-            $repeat         = !empty($_POST['repeat'])?true:false;
-		}
-
-	// if the id is set then we are editing an agenda item
-	if (is_int($id))
-	{
-		//echo "before get_agenda_item".$_SESSION['allow_individual_calendar'];
-		$item_2_edit=get_agenda_item($id);
-		$title	= $item_2_edit['title'];
-		$content= $item_2_edit['content'];
-		// start date
-		list($datepart, $timepart) = split(" ", $item_2_edit['start_date']);
-		list($year, $month, $day) = explode("-", $datepart);
-		list($hours, $minutes, $seconds) = explode(":", $timepart);
-		// end date
-		list($datepart, $timepart) = split(" ", $item_2_edit['end_date']);
-		list($end_year, $end_month, $end_day) = explode("-", $datepart);
-		list($end_hours, $end_minutes, $end_seconds) = explode(":", $timepart);
-		// attachments
-		edit_added_resources("Agenda", $id);
-		$to=$item_2_edit['to'];
-		//echo "<br />after get_agenda_item".$_SESSION['allow_individual_calendar'];
-	}
-	$content=stripslashes($content);
-	$title=stripslashes($title);
-	// we start a completely new item, we do not come from the resource linker
-	if ($_GET['originalresource']!=="no" and $_GET['action']=="add")
-	{
-		$_SESSION["formelements"]=null;
-		unset_session_resources();
-	}
-?>
-
-	<!-- START OF THE FORM  -->
-
-	<form enctype="multipart/form-data"  action="<?php echo api_get_self().'?origin='.$_GET['origin'].'&amp;action='.$_GET['action']; ?>" method="post" name="new_calendar_item">
-	<input type="hidden" name="id" value="<?php if (isset($id)) echo $id; ?>" />
-	<input type="hidden" name="action" value="<?php if (isset($_GET['action'])) echo $_GET['action']; ?>" />
-	<input type="hidden" name="id_attach" value="<?php echo Security::remove_XSS($_REQUEST['id_attach']); ?>" />
-	<input type="hidden" name="sort" value="asc" />
-	<input type="hidden" name="submit_event" value="ok" />
-	<?php
-	// The form title
-	if (isset($id) AND $id<>'')
-	{
-		$form_title = get_lang('ModifyCalendarItem');
-	}
-	else
-	{
-		$form_title = get_lang('AddCalendarItem');
-	}
-	echo '<div class="row"><div class="form_header">'.$form_title.'</div></div>';
-
-	// selecting the users / groups
-	if (isset ($_SESSION['toolgroup']))
-	{
-		echo '<input type="hidden" name="selectedform[0]" value="GROUP:'.intval($_SESSION['toolgroup']).'"/>' ;
-		echo '<input type="hidden" name="To" value="true"/>' ;
-	}
-	else
-	{
-		echo '	<div class="row">
-					<div class="label">
-						<a href="javascript: void(0);" onclick="if(document.getElementById(\'recipient_list\').style.display==\'none\') document.getElementById(\'recipient_list\').style.display=\'block\'; else document.getElementById(\'recipient_list\').style.display=\'none\';">'.Display::return_icon('group.gif', get_lang('SentTo'), array ('align' => 'absmiddle')).' '.get_lang('SentTo').'</a>
-					</div>
-					<div class="formw">';
-		if ((isset($_GET['id'])  && $to=='everyone') || !isset($_GET['id']))
-		{
-					echo get_lang("Everybody").'&nbsp;';
-				}
-				show_to_form($to);
-				if (isset($_GET['id']) && $to!='everyone') {
-					echo '<script>document.getElementById(\'recipient_list\').style.display=\'block\';</script>';
-				}
-		echo '		</div>
-				</div>';
-
-	}
-
-	// start date and time
-	echo 	'<div class="row">
-				<div class="label">
-					'.get_lang('StartDate').'
-				</div>
-				<div class="formw">
-					<div id="err_date" style="display:none;color:red"></div>
-					<div id="err_start_date" style="display:none;color:red"></div>';
-	?>
-					<select name="fday" onchange="javascript:document.new_calendar_item.end_fday.value=this.value;">
-							<?php
-							// small loop for filling all the dates
-							// 2do: the available dates should be those of the selected month => february is from 1 to 28 (or 29) and not to 31
-							echo "\n";
-							foreach (range(1, 31) as $i)
-											{
-											// values have to have double digits
-											$value = ($i <= 9 ? '0'.$i : $i );
-											// the current day is indicated with [] around the date
-											if ($value==$day)
-											{
-												echo "\t\t\t\t <option value=\"".$value."\" selected> ".$i." </option>\n";
-											}
-											else
-											{
-												echo "\t\t\t\t<option value=\"$value\">$i</option>\n";
-											}
-										}
-										 ?>
-					</select>
-					<select name="fmonth" onchange="javascript:document.new_calendar_item.end_fmonth.value=this.value;">
-					<?php
-											echo "\n";
-											for ($i=1; $i<=12; $i++)
-											{
-												// values have to have double digits
-												if ($i<=9)
-												{
-													$value="0".$i;
-												}
-												else
-												{
-													$value=$i;
-												}
-												if ($value==$month)
-												{
-													echo "\t\t\t\t <option value=\"".$value."\" selected>".$MonthsLong[$i-1]."</option>\n";
-												}
-												else
-												{
-													echo "\t\t\t\t <option value=\"".$value."\">".$MonthsLong[$i-1]."</option>\n";
-												}
-											} ?>
-					</select>
-					<select name="fyear" onchange="javascript:document.new_calendar_item.end_fyear.value=this.value;">
-										<option value="<?php echo ($year-1); ?>"><?php echo ($year-1); ?></option>
-											<option value="<?php echo $year; ?>" selected="selected"><?php echo $year; ?></option>
-											<?php
-												echo "\n";
-												for ($i=1; $i<=5; $i++)
-												{
-													$value=$year+$i;
-													echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
-												} ?>
-					</select>
+/**
+* This function separates the users from the groups
+* users have a value USER:XXX (with XXX the dokeos id
+* groups have a value GROUP:YYY (with YYY the group id)
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @return array
+*/
+function separate_users_groups($to)
+{
+	$grouplist = array();
+    $userlist  = array();
+    $send_to = null;
+	if(is_array($to) && count($to)>0)
+    {
+        foreach($to as $to_item)
+    	{
+    	list($type, $id) = explode(':', $to_item);
+    	switch($type)
+    		{
+    		case 'GROUP':
+    			$grouplist[] =$id;
+    			break;
+    		case 'USER':
+    			$userlist[] =$id;
+    			break;
+    		}
+    	}
+        $send_to['groups']=$grouplist;
+        $send_to['users']=$userlist;
+    }
+    return $send_to;
+}
+
+
+
+/**
+* returns all the users and all the groups a specific Agenda item has been sent to
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @return array
+*/
+function sent_to($tool, $id)
+{
+	global $_course;
+	$TABLE_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+
+	$tool=Database::escape_string($tool);
+	$id=Database::escape_string($id);
+
+	$sql="SELECT * FROM $TABLE_ITEM_PROPERTY WHERE tool='".$tool."' AND ref='".$id."'";
+	$result=Database::query($sql,__FILE__,__LINE__);
+	while ($row=Database::fetch_array($result))
+	{
+		// if to_group_id is null then it is sent to a specific user
+		// if to_group_id = 0 then it is sent to everybody
+		if (!is_null($row['to_group_id']) )
+		{
+			$sent_to_group[]=$row['to_group_id'];
+			//echo $row['to_group_id'];
+		}
+		// if to_user_id <> 0 then it is sent to a specific user
+		if ($row['to_user_id']<>0)
+		{
+			$sent_to_user[]=$row['to_user_id'];
+		}
+	}
+	if (isset($sent_to_group))
+	{
+		$sent_to['groups']=$sent_to_group;
+	}
+	if (isset($sent_to_user))
+	{
+		$sent_to['users']=$sent_to_user;
+	}
+	return $sent_to;
+}
+
+
+
+/**
+* constructs the form to display all the groups and users the message has been sent to
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @param  array $sent_to_array: a 2 dimensional array containing the groups and the users
+*				the first level is a distinction between groups and users: $sent_to_array['groups'] and $sent_to_array['users']
+*				$sent_to_array['groups'] (resp. $sent_to_array['users']) is also an array containing all the id's of the
+*				groups (resp. users) who have received this message.
+* @return html
+*/
+function sent_to_form($sent_to_array)
+{
+	// we find all the names of the groups
+	$group_names=get_course_groups();
+
+	count($sent_to_array);
+
+	// we count the number of users and the number of groups
+	if (isset($sent_to_array['users']))
+	{
+		$number_users=count($sent_to_array['users']);
+	}
+	else
+	{
+		$number_users=0;
+	}
+	if (isset($sent_to_array['groups']))
+	{
+		$number_groups=count($sent_to_array['groups']);
+	}
+	else
+	{
+		$number_groups=0;
+	}
+	$total_numbers=$number_users+$number_groups;
+
+	// starting the form if there is more than one user/group
+	if ($total_numbers >1)
+	{
+	$output="<select name=\"sent to\">\n";
+	$output.="<option>".get_lang("SentTo")."</option>";
+	// outputting the name of the groups
+	if (is_array($sent_to_array['groups']))
+		{
+		foreach ($sent_to_array['groups'] as $group_id)
+			{
+			$output.="\t<option value=\"\">G: ".$group_names[$group_id]['name']."</option>\n";
+			}
+		}
+	if (isset($sent_to_array['users']))
+	{
+		if (is_array($sent_to_array['users']))
+			{
+			foreach ($sent_to_array['users'] as $user_id)
+				{
+				$user_info=api_get_user_info($user_id);
+				$output.="\t<option value=\"\">".api_get_person_name($user_info['firstName'], $user_info['lastName'])."</option>\n";
+				}
+			}
+	}
+
+	// ending the form
+	$output.="</select>\n";
+	}
+	else // there is only one user/group
+	{
+		if (is_array($sent_to_array['users']))
+		{
+			$user_info=api_get_user_info($sent_to_array['users'][0]);
+			echo api_get_person_name($user_info['firstName'], $user_info['lastName']);
+		}
+		if (is_array($sent_to_array['groups']) and $sent_to_array['groups'][0]!==0)
+		{
+			$group_id=$sent_to_array['groups'][0];
+			echo $group_names[$group_id]['name'];
+		}
+		if (is_array($sent_to_array['groups']) and $sent_to_array['groups'][0]==0)
+		{
+			echo get_lang("Everybody");
+		}
+		//.$sent_to_array['groups'][0];
+	}
+
+	echo $output;
+}
+
+
+/**
+* This function displays a dropdown list that allows the course administrator do view the calendar items of one specific group
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+function show_group_filter_form()
+{
+	$group_list=get_course_groups();
+
+	echo "<select name=\"select\" onchange=\"javascript: MM_jumpMenu('parent',this,0)\">";
+	echo "<option value=\"agenda.php?group=none\">show all groups</option>";
+	foreach($group_list as $this_group)
+	{
+		// echo "<option value=\"agenda.php?isStudentView=true&amp;group=".$this_group['id']."\">".$this_group['name']."</option>";
+		echo "<option value=\"agenda.php?group=".$this_group['id']."\" ";
+		echo ($this_group['id']==$_SESSION['group'])? " selected":"" ;
+		echo ">".$this_group['name']."</option>";
+	}
+	echo "</select>";
+}
+
+
+
+/**
+* This function displays a dropdown list that allows the course administrator do view the calendar items of one specific group
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+function show_user_filter_form()
+{
+	$user_list=get_course_users();
+
+	echo "<select name=\"select\" onchange=\"javascript: MM_jumpMenu('parent',this,0)\">";
+	echo "<option value=\"agenda.php?user=none\">show all users</option>";
+	foreach($user_list as $this_user)
+		{
+		// echo "<option value=\"agenda.php?isStudentView=true&amp;user=".$this_user['uid']."\">".api_get_person_name($this_user['firstName'], $this_user['lastName'])."</option>";
+		echo "<option value=\"agenda.php?user=".$this_user['uid']."\" ";
+		echo ($this_user['uid']==$_SESSION['user'])? " selected":"" ;
+		echo ">".api_get_person_name($this_user['firstName'], $this_user['lastName'])."</option>";
+		}
+	echo "</select>";
+}
+
+
+
+/**
+* This function displays a dropdown list that allows the course administrator do view the calendar items of one specific group
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+function show_user_group_filter_form()
+{
+	echo "\n<select name=\"select\" onchange=\"javascript: MM_jumpMenu('parent',this,0)\">";
+
+	// Groups
+	$option = "\n\t<optgroup label=\"".get_lang("Groups")."\">";
+	$group_list=get_course_groups();
+	//echo "\n\t<option value=\"agenda.php?user=none\">".get_lang("ShowAll")."</option>";
+
+	$group_available_to_access =array();
+
+	if(!empty($group_list)){
+		foreach($group_list as $this_group) {
+			// echo "<option value=\"agenda.php?isStudentView=true&amp;group=".$this_group['id']."\">".$this_group['name']."</option>";
+			$has_access = GroupManager::user_has_access(api_get_user_id(),$this_group['id'],GROUP_TOOL_CALENDAR);
+			$result = GroupManager::get_group_properties($this_group['id']);
+
+			if ($result['calendar_state']!='0') {
+				$group_available_to_access[]=$this_group['id'];
+			}
+
+			// lastedit
+			if ($has_access || $result['calendar_state']=='1') {
+				$option.= "\n\t\t<option value=\"agenda.php?group=".$this_group['id']."\" ";
+				$option.= ($this_group['id']==$_SESSION['group'])? " selected":"" ;
+				$option.=  ">".$this_group['name']."</option>";
+			}
+		}
+	}
+
+	$all =  "\n\t<option value=\"agenda.php?user=none\">".get_lang("ShowAll")."</option>";
+	$option = $all.$option;
+
+	$option.= "\n\t</optgroup>";
+	echo $option;
+
+	global $_course;
+
+	// Users
+	echo "\n\t<optgroup label=\"".get_lang("Users")."\">";
+	$user_list=get_course_users();
+	foreach($user_list as $this_user) {
+		echo "\n\t\t<option value=\"agenda.php?user=".$this_user['uid']."\" ";
+		echo ($this_user['uid']==$_SESSION['user'])? " selected":"" ;
+		echo ">".api_get_person_name($this_user['firstName'], $this_user['lastName'])."</option>";
+	}
+	echo "\n\t</optgroup>";
+	echo "</select>";
+}
+
+
+
+/**
+* This tools loads all the users and all the groups who have received a specific item (in this case an agenda item)
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+function load_edit_users($tool, $id)
+{
+	global $_course;
+	$tool=Database::escape_string($tool);
+	$id=Database::escape_string($id);
+	$TABLE_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+
+	$sql="SELECT * FROM $TABLE_ITEM_PROPERTY WHERE tool='$tool' AND ref='$id'";
+	$result=Database::query($sql,__FILE__,__LINE__) or die (Database::error());
+	while ($row=Database::fetch_array($result))
+		{
+		$to_group=$row['to_group_id'];
+		switch ($to_group)
+			{
+			// it was send to one specific user
+			case null:
+				$to[]="USER:".$row['to_user_id'];
+				break;
+			// it was sent to everyone
+			case 0:
+				 return "everyone";
+				 exit;
+				break;
+			default:
+				$to[]="GROUP:".$row['to_group_id'];
+			}
+		}
+	return $to;
+}
+
+
+/**
+* This functions swithes the visibility a course resource using the visible field in 'last_tooledit' values: 0 = invisible
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+function change_visibility($tool,$id)
+{
+	global $_course;
+	$TABLE_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+	$tool=Database::escape_string($tool);
+	$id=Database::escape_string($id);
+
+	$sql="SELECT * FROM $TABLE_ITEM_PROPERTY WHERE tool='".TOOL_CALENDAR_EVENT."' AND ref='$id'";
+	$result=Database::query($sql,__FILE__,__LINE__) or die (Database::error());
+	$row=Database::fetch_array($result);
+
+	if ($row['visibility']=='1')
+	{
+		$sql_visibility="UPDATE $TABLE_ITEM_PROPERTY SET visibility='0' WHERE tool='$tool' AND ref='$id'";
+		api_item_property_update($_course,TOOL_CALENDAR_EVENT,$id,"invisible",api_get_user_id());
+	}
+	else
+	{
+		$sql_visibility="UPDATE $TABLE_ITEM_PROPERTY SET visibility='1' WHERE tool='$tool' AND ref='$id'";
+		api_item_property_update($_course,TOOL_CALENDAR_EVENT,$id,"visible",api_get_user_id());
+	}
+}
+
+
+
+/**
+* The links that allows the course administrator to add a new agenda item, to filter on groups or users
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+function display_courseadmin_links() {
+	echo "<a href='".api_get_self()."?".api_get_cidreq()."&action=add&amp;view=".(($_SESSION['view']=='month')?"list":Security::remove_XSS($_SESSION['view'])."&amp;origin=".Security::remove_XSS($_GET['origin']))."'>".Display::return_icon('calendar_add.gif', get_lang('AgendaAdd'))." ".get_lang('AgendaAdd')."</a>";
+	if (empty ($_SESSION['toolgroup']))
+	{
+		echo get_lang('UserGroupFilter');
+		echo "<form name=\"filter\" style=\"display:inline;\">";
+		show_user_group_filter_form();
+		echo "</form> ";
+	}
+	//echo "<a href='".api_get_self()."?".api_get_cidreq()."&action=importical&amp;view=".(($_SESSION['view']=='month')?"list":Security::remove_XSS($_SESSION['view'])."&amp;origin=".Security::remove_XSS($_GET['origin']))."'>".Display::return_icon('ical_icon.gif', get_lang('ICalFileImport'))." ".get_lang('ICalFileImport')."</a>";
+}
+
+
+
+/**
+* The links that allows the student AND course administrator to show all agenda items and sort up/down
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+function display_student_links()
+{
+	global $show;
+	if ($_SESSION['sort'] == 'DESC')
+	{
+		echo "<a href='".api_get_self()."?".api_get_cidreq()."&amp;sort=asc&amp;toolgroup=".Security::remove_XSS($_GET['toolgroup'])."&amp;origin=".Security::remove_XSS($_GET['origin'])."'>".Display::return_icon('calendar_up.gif',get_lang('AgendaSortChronologicallyUp')).' '.get_lang("AgendaSortChronologicallyUp")."</a> ";
+	}
+	else
+	{
+		echo "<a href='".api_get_self()."?".api_get_cidreq()."&amp;sort=desc&amp;toolgroup=".Security::remove_XSS($_GET['toolgroup'])."&amp;origin=".Security::remove_XSS($_GET['origin'])."'>".Display::return_icon('calendar_down.gif',get_lang('AgendaSortChronologicallyDown')).' '.get_lang("AgendaSortChronologicallyDown")."</a> ";
+	}
+
+	// showing the link to show all items or only those of the current month
+	if ($_SESSION['show']=="showcurrent")
+	{
+		echo "<a href='".api_get_self()."?".api_get_cidreq()."&amp;action=showall&amp;toolgroup=".Security::remove_XSS($_GET['toolgroup'])."&amp;origin=".Security::remove_XSS($_GET['origin'])."'>".Display::return_icon('calendar_select.gif', get_lang("ShowAllEvents")).' '.get_lang("ShowAllEvents")."</a> ";
+	}
+	else
+	{
+		echo "<a href='".api_get_self()."?".api_get_cidreq()."&amp;action=showcurrent&amp;toolgroup=".Security::remove_XSS($_GET['toolgroup'])."&amp;origin=".Security::remove_XSS($_GET['origin'])."'>".Display::return_icon('calendar_month.gif', get_lang("ShowCurrent")).' '.get_lang("ShowCurrent")."</a> ";
+	}
+
+	if ($_SESSION['view'] <> 'month')
+	{
+		echo "<a href=\"".api_get_self()."?action=view&amp;toolgroup=".Security::remove_XSS($_GET['toolgroup'])."&amp;view=month\">".Display::return_icon('calendar_month.gif', get_lang('MonthView'))." ".get_lang('MonthView')."</a> ";
+	}
+	else
+	{
+		echo "\t<a href=\"".api_get_self()."?action=view&amp;toolgroup=".Security::remove_XSS($_GET['toolgroup'])."&amp;view=list\">".Display::return_icon('calendar_select.gif', get_lang('ListView'))." ".get_lang('ListView')."</a> ";
+	}
+}
+
+
+
+/**
+* get all the information of the agenda_item from the database
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @param integer the id of the agenda item we are getting all the information of
+* @return an associative array that contains all the information of the agenda item. The keys are the database fields
+*/
+function get_agenda_item($id)
+{
+	global $TABLEAGENDA;
+    $t_agenda_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT);
+    $id=Database::escape_string($id);
+    $item = array();
+	if(empty($id))
+    {
+        $id=(int)addslashes($_GET['id']);
+    }
+    else
+    {
+    	$id = (int) $id;
+    }
+    if(empty($id)){return $item;}
+	$sql 					= "SELECT * FROM ".$TABLEAGENDA." WHERE id='".$id."'";
+	$result					= Database::query($sql,__FILE__,__LINE__);
+	$entry_to_edit 			= Database::fetch_array($result);
+	$item['title']			= $entry_to_edit["title"];
+	$item['content']		= $entry_to_edit["content"];
+	$item['start_date']		= $entry_to_edit["start_date"];
+	$item['end_date']		= $entry_to_edit["end_date"];
+	$item['to']				= load_edit_users(TOOL_CALENDAR_EVENT, $id);
+	// if the item has been sent to everybody then we show the compact to form
+	if ($item['to']=="everyone")
+	{
+		$_SESSION['allow_individual_calendar']="hide";
+	}
+	else
+	{
+		$_SESSION['allow_individual_calendar']="show";
+	}
+    $item['repeat'] = false;
+    $sql = "SELECT * FROM $t_agenda_repeat WHERE cal_id = $id";
+    $res = Database::query($sql,__FILE__,__LINE__);
+    if(Database::num_rows($res)>0)
+    {
+        //this event is repetitive
+        $row = Database::fetch_array($res);
+        $item['repeat'] = true;
+        $item['repeat_type'] = $row['cal_type'];
+        $item['repeat_end'] = $row['cal_end'];
+        $item['repeat_frequency'] = $row['cal_frequency']; //unused in 1.8.5 RC1 - will be used later to say if once every 2 or 3 weeks, for example
+        $item['repeat_days'] = $row['cal_days']; //unused in 1.8.5 RC1 - will be used later
+    }
+    //TODO - add management of repeat exceptions
+	return $item;
+}
+
+/**
+* This is the function that updates an agenda item. It does 3 things
+* 1. storethe start_date, end_date, title and message in the calendar_event table
+* 2. store the groups/users who this message is meant for in the item_property table
+* 3. modify the attachments (if needed)
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+function store_edited_agenda_item($id_attach,$file_comment)
+{
+	global $_user, $_course;
+
+	// database definitions
+	$TABLE_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+
+	// STEP 1: editing the calendar_event table
+	// 1.a.  some filtering of the input data
+	$id=(int)$_POST['id'];
+	$title=strip_tags(trim($_POST['title'])); // no html allowed in the title
+	$content=trim($_POST['content']);
+	$start_date=(int)$_POST['fyear']."-".(int)$_POST['fmonth']."-".(int)$_POST['fday']." ".(int)$_POST['fhour'].":".(int)$_POST['fminute'].":00";
+	$end_date=(int)$_POST['end_fyear']."-".(int)$_POST['end_fmonth']."-".(int)$_POST['end_fday']." ".(int)$_POST['end_fhour'].":".(int)$_POST['end_fminute'].":00";
+	$to=$_POST['selectedform'];
+	// 1.b. the actual saving in calendar_event table
+	$edit_result=save_edit_agenda_item($id,$title,$content,$start_date,$end_date);
+
+	if (empty($id_attach)) {
+		add_agenda_attachment_file($file_comment,$id);
+	} else {
+		edit_agenda_attachment_file($file_comment,$id,$id_attach);
+	}
+
+	// step 2: editing the item_propery table (=delete all and add the new destination users/groups)
+	if ($edit_result=true)
+	{
+		// 2.a. delete everything for the users
+		$sql_delete="DELETE FROM ".$TABLE_ITEM_PROPERTY." WHERE ref='$id' AND tool='".TOOL_CALENDAR_EVENT."'";
+
+		$result = Database::query($sql_delete,__FILE__,__LINE__) or die (Database::error());
+		// 2.b. storing the new users/groups
+		if (!is_null($to)) // !is_null($to): when no user is selected we send it to everyone
+		{
+			$send_to=separate_users_groups($to);
+			// storing the selected groups
+			if (is_array($send_to['groups']))
+			{
+				foreach ($send_to['groups'] as $group)
+				{
+					api_item_property_update($_course, TOOL_CALENDAR_EVENT, $id,"AgendaModified", $_user['user_id'], $group,'',$start_date, $end_date);
+				}
+			}
+			// storing the selected users
+			if (is_array($send_to['users']))
+			{
+				foreach ($send_to['users'] as $user)
+				{
+					api_item_property_update($_course, TOOL_CALENDAR_EVENT, $id,"AgendaModified", $_user['user_id'],'',$user, $start_date,$end_date);
+				}
+			}
+		}
+		else // the message is sent to everyone, so we set the group to 0
+		{
+			api_item_property_update($_course, TOOL_CALENDAR_EVENT, $id,"AgendaModified", $_user['user_id'], '','',$start_date,$end_date);
+		}
+
+	} //if ($edit_result=true)
+
+	// step 3: update the attachments (=delete all and add those in the session
+	update_added_resources("Agenda", $id);
+
+	// return the message;
+	Display::display_confirmation_message(get_lang("EditSuccess"));
+
+}
+
+/**
+* This function stores the Agenda Item in the table calendar_event and updates the item_property table also (after an edit)
+* @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+function save_edit_agenda_item($id,$title,$content,$start_date,$end_date)
+{
+	$TABLEAGENDA 		= Database::get_course_table(TABLE_AGENDA);
+	$id=Database::escape_string($id);
+	$title=Database::escape_string(Security::remove_XSS($title));
+	$content=stripslashes($content);
+	$content = Database::escape_string(Security::remove_XSS($content,COURSEMANAGERLOWSECURITY));
+	$start_date=Database::escape_string($start_date);
+	$end_date=Database::escape_string($end_date);
+
+	// store the modifications in the table calendar_event
+	$sql = "UPDATE ".$TABLEAGENDA."
+								SET title='".$title."',
+									content='".$content."',
+									start_date='".$start_date."',
+									end_date='".$end_date."'
+								WHERE id='".$id."'";
+	$result = Database::query($sql,__FILE__,__LINE__) or die (Database::error());
+	return true;
+}
+
+/**
+* This is the function that deletes an agenda item.
+* The agenda item is no longer fycically deleted but the visibility in the item_property table is set to 2
+* which means that it is invisible for the student AND course admin. Only the platform administrator can see it.
+* This will in a later stage allow the platform administrator to recover resources that were mistakenly deleted
+* by the course administrator
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @param integer the id of the agenda item wa are deleting
+*/
+function delete_agenda_item($id)
+{
+	global $_course;
+	$id=Database::escape_string($id);
+	if (api_is_allowed_to_edit(false,true)  OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()))
+	{
+		if (!empty($_GET['id']) && isset($_GET['action']) && $_GET['action']=="delete")
+		{
+		    $t_agenda     = Database::get_course_table(TABLE_AGENDA);
+            $t_agenda_r   = Database::get_course_table(TABLE_AGENDA_REPEAT);
+            $id=(int)addslashes($_GET['id']);
+            $sql = "SELECT * FROM $t_agenda_r WHERE cal_id = $id";
+            $res = Database::query($sql,__FILE__,__LINE__);
+            if(Database::num_rows($res)>0)
+            {
+            	$sql_children = "SELECT * FROM $t_agenda WHERE parent_event_id = $id";
+                $res_children = Database::query($sql_children,__FILE__,__LINE__);
+                if(Database::num_rows($res_children)>0)
+                {
+                    while ($row_child = Database::fetch_array($res_children))
+                    {
+                        api_item_property_update($_course,TOOL_CALENDAR_EVENT,$row_child['id'],'delete',api_get_user_id());
+                    }
+                }
+                $sql_del = "DELETE FROM $t_agenda_r WHERE cal_id = $id";
+                $res_del = Database::query($sql_del,__FILE__,__LINE__);
+            }
+			//$sql = "DELETE FROM ".$TABLEAGENDA." WHERE id='$id'";
+			//$sql= "UPDATE ".$TABLE_ITEM_PROPERTY." SET visibility='2' WHERE tool='Agenda' and ref='$id'";
+			//$result = Database::query($sql,__FILE__,__LINE__) or die (Database::error());
+			api_item_property_update($_course,TOOL_CALENDAR_EVENT,$id,'delete',api_get_user_id());
+
+			// delete the resources that were added to this agenda item
+			// 2DO: as we no longer fysically delete the agenda item (to make it possible to 'restore'
+			//		deleted items, we should not delete the added resources either.
+			// delete_added_resource("Agenda", $id); // -> this is no longer needed as the message is not really deleted but only visibility=2 (only platform admin can see it)
+
+			//resetting the $id;
+			$id=null;
+
+			// displaying the result message in the yellow box
+			Display::display_confirmation_message(get_lang("AgendaDeleteSuccess"));
+		}	  // if (isset($id)&&$id&&isset($action)&&$action=="delete")
+	} // if ($is_allowed_to_edit)
+
+}
+/**
+* Makes an agenda item visible or invisible for a student
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @param integer id the id of the agenda item we are changing the visibility of
+*/
+function showhide_agenda_item($id)
+{
+	global $nameTools;
+	/*==================================================
+				SHOW / HIDE A CALENDAR ITEM
+	  ==================================================*/
+	//  and $_GET['isStudentView']<>"false" is added to prevent that the visibility is changed after you do the following:
+	// change visibility -> studentview -> course manager view
+	if ((api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous())) and $_GET['isStudentView']<>"false")
+	{
+		if (isset($_GET['id'])&&$_GET['id']&&isset($_GET['action'])&&$_GET['action']=="showhide")
+		{
+			$id=(int)addslashes($_GET['id']);
+			change_visibility($nameTools,$id);
+			Display::display_confirmation_message(get_lang("VisibilityChanged"));
+		}
+	}
+}
+/**
+* Displays all the agenda items
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @author Yannick Warnier <yannick.warnier@dokeos.com> - cleanup
+*/
+function display_agenda_items()
+{
+	global $TABLEAGENDA;
+	global $TABLE_ITEM_PROPERTY;
+	global $select_month, $select_year;
+	global $DaysShort, $DaysLong, $MonthsLong;
+	global $is_courseAdmin;
+	global $dateFormatLong, $timeNoSecFormat,$charset, $_user, $_course;
+
+	// getting the group memberships
+	$group_memberships=GroupManager::get_group_ids($_course['dbName'],$_user['user_id']);
+
+	// getting the name of the groups
+	$group_names=get_course_groups();
+
+	/*--------------------------------------------------
+			CONSTRUCT THE SQL STATEMENT
+	  --------------------------------------------------*/
+
+    $start = 0;
+    $stop = 0;
+	// this is to make a difference between showing everything (all months) or only the current month)
+	// $show_all_current is a part of the sql statement
+	if ($_SESSION['show']!=="showall")
+	{
+		$show_all_current=" AND MONTH(start_date)=$select_month AND year(start_date)=$select_year";
+        $start = mktime(0,0,0,$select_month,1,$select_year);
+        $stop = 0;
+        if(empty($select_year)){$select_year = date('Y');}
+        if(empty($select_month)){$select_month = date('m');}
+        if($select_month==12)
+        {
+            $stop = mktime(0,0,0,1,1,$select_year+1)-1;
+        }
+        else
+        {
+            $stop = mktime(0,0,0,$select_month+1,1,$select_year)-1;
+        }
+	}
+	else
+	{
+		$show_all_current="";
+        $start = time();
+        $stop = mktime(0,0,0,1,1,2038);//by default, set year to maximum for mktime()
+	}
+
+	// by default we use the id of the current user. The course administrator can see the agenda of other users by using the user / group filter
+	$user_id=$_user['user_id'];
+	if ($_SESSION['user']!==null)
+	{
+		$user_id=intval($_SESSION['user']);
+	}
+	if ($_SESSION['group']!==null)
+	{
+		$group_id=intval($_SESSION['group']);
+	}
+	if ($_SESSION['toolgroup']!==null)
+	{
+		$group_id=intval($_SESSION['toolgroup']);
+	}
+
+    $repeats = array(); //placeholder for repeated events
+	//echo "user:".$_SESSION['user']."group: ".$_SESSION['group'];
+	// A. you are a course admin
+	//if ($is_courseAdmin)
+
+	$session_condition = intval($_SESSION['id_session'])==0 ? '' : ' AND agenda.session_id IN (0,'.intval($_SESSION['id_session']).') ';
+
+
+	if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()))
+	{
+		// A.1. you are a course admin with a USER filter
+		// => see only the messages of this specific user + the messages of the group (s)he is member of.
+		if (!empty($_SESSION['user']))
+		{
+			$group_memberships=GroupManager::get_group_ids($_course['dbName'],$_SESSION['user']);
+
+			$show_user =true;
+			$new_group_memberships=array();
+			foreach($group_memberships as $id)
+			{
+				// did i have access to the same
+				$has_access = GroupManager::user_has_access(api_get_user_id(),$id,GROUP_TOOL_CALENDAR);
+				$result = GroupManager::get_group_properties($id);
+
+				if ($has_access && $result['calendar_state']!='0' )
+				{
+					$new_group_memberships[]=$id;
+				}
+			}
+			$group_memberships = $new_group_memberships;
+
+			if (is_array($group_memberships) && count($group_memberships)>0)
+			{
+				$sql="SELECT
+					agenda.*, toolitemproperties.*
+					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
+					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+					AND	( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id IN (0, ".implode(", ", $group_memberships).") )
+					AND toolitemproperties.visibility='1'
+					$session_condition
+					ORDER BY start_date ".$_SESSION['sort'];
+			}
+			else
+			{
+					$sql="SELECT
+					agenda.*, toolitemproperties.*
+					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
+					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+					AND ( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id='0')
+					AND toolitemproperties.visibility='1'
+					$session_condition
+					ORDER BY start_date ".$_SESSION['sort'];
+			}
+		}
+		// A.2. you are a course admin with a GROUP filter
+		// => see only the messages of this specific group
+		elseif (!empty($_SESSION['group']))
+		{
+
+			if (!empty($group_id)) {
+				$result = GroupManager::get_group_properties($group_id);
+				$has_access = GroupManager::user_has_access(api_get_user_id(),$group_id,GROUP_TOOL_CALENDAR);
+				//echo '<pre>';print_R($result);
+
+				// lastedit
+				if (!$has_access || $result['calendar_state']=='0' )
+				{
+					$group_id=0;
+				}
+			}
+
+			$sql="SELECT
+				agenda.*, toolitemproperties.*
+				FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+				WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
+				AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+				AND ( toolitemproperties.to_group_id=$group_id OR toolitemproperties.to_group_id='0')
+				AND toolitemproperties.visibility='1'
+				$session_condition
+				GROUP BY toolitemproperties.ref
+				ORDER BY start_date ".$_SESSION['sort'];
+		}
+		// A.3 you are a course admin without any group or user filter
+		else
+		{
+			// A.3.a you are a course admin without user or group filter but WITH studentview
+			// => see all the messages of all the users and groups without editing possibilities
+			if ($_GET['isStudentView']=='true')
+			{
+				$sql="SELECT
+					agenda.*, toolitemproperties.*
+					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+					WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
+					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+					AND toolitemproperties.visibility='1'
+					$session_condition
+					GROUP BY toolitemproperties.ref
+					ORDER BY start_date ".$_SESSION['sort'];
+
+			}
+			// A.3.b you are a course admin or a student
+			else
+			{
+				// A.3.b.1 you are a course admin without user or group filter and WITHOUT studentview (= the normal course admin view)
+				// 	=> see all the messages of all the users and groups with editing possibilities
+
+				 if (api_is_course_admin())
+				 {
+					 $sql="SELECT
+						agenda.*, toolitemproperties.*
+						FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+						WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
+						AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+						AND ( toolitemproperties.visibility='0' OR toolitemproperties.visibility='1')
+						$session_condition
+						GROUP BY toolitemproperties.ref
+						ORDER BY start_date ".$_SESSION['sort'];
+				 }
+				 else
+				 {
+				 	// A.3.b.2 you are a student with no group filter possibly showall
+				 	//when showing all the events we do not show the group events
+				 	//todo showing ALL events including the groups events that are available
+
+				 	$sql="SELECT
+						agenda.*, toolitemproperties.*
+						FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+						WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
+						AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+						AND toolitemproperties.visibility='1' AND toolitemproperties.to_group_id='0'
+						$session_condition
+						GROUP BY toolitemproperties.ref
+						ORDER BY start_date ".$_SESSION['sort'];
+
+
+					/*
+				 	if (is_array($group_memberships) && count($group_memberships)>0)
+				 	{
+				 		echo $sql="SELECT
+						agenda.*, toolitemproperties.*
+						FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+						WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
+						AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+						AND toolitemproperties.visibility='1' AND toolitemproperties.to_group_id IN (0, ".implode(", ", $group_memberships).")
+						$session_condition
+						GROUP BY toolitemproperties.ref
+						ORDER BY start_date ".$_SESSION['sort'];
+				 	}
+				 	else
+				 	{
+				 		$sql="SELECT
+						agenda.*, toolitemproperties.*
+						FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+						WHERE agenda.id = toolitemproperties.ref  ".$show_all_current."
+						AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+						AND toolitemproperties.visibility='1' AND toolitemproperties.to_group_id='0'
+						$session_condition
+						GROUP BY toolitemproperties.ref
+						ORDER BY start_date ".$_SESSION['sort'];
+				 	}
+				 	*/
+
+				 }
+			}
+		}
+
+	} //if (is_allowed_to_edit() OR( api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()))
+
+	// B. you are a student
+	else
+	{
+		if (is_array($group_memberships) and count($group_memberships)>0)
+		{
+			$sql="SELECT
+				agenda.*, toolitemproperties.*
+				FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+				WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
+				AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+				AND	( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id IN (0, ".implode(", ", $group_memberships).") )
+				AND toolitemproperties.visibility='1'
+				$session_condition
+				ORDER BY start_date ".$_SESSION['sort'];
+		}
+		else
+		{
+			if ($_user['user_id'])
+			{
+				$sql="SELECT
+					agenda.*, toolitemproperties.*
+					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
+					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+					AND ( toolitemproperties.to_user_id=$user_id OR toolitemproperties.to_group_id='0')
+					AND toolitemproperties.visibility='1'
+					$session_condition
+					ORDER BY start_date ".$_SESSION['sort'];
+			}
+			else
+			{
+				$sql="SELECT
+					agenda.*, toolitemproperties.*
+					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+					WHERE agenda.id = toolitemproperties.ref   ".$show_all_current."
+					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+					AND toolitemproperties.to_group_id='0'
+					AND toolitemproperties.visibility='1'
+					$session_condition
+					ORDER BY start_date ".$_SESSION['sort'];
+			}
+		}
+	} // you are a student
+
+	//echo "<pre>".$sql."</pre>";
+	$result=Database::query($sql,__FILE__,__LINE__) or die(Database::error());
+	$number_items=Database::num_rows($result);
+
+	/*--------------------------------------------------
+			DISPLAY: NO ITEMS
+	  --------------------------------------------------*/
+	if ($number_items==0)
+	{
+        echo "<table class=\"data_table\" ><tr><td>".get_lang("NoAgendaItems")."</td></tr></table>";
+	}
+
+	/*--------------------------------------------------
+			DISPLAY: THE ITEMS
+	  --------------------------------------------------*/
+
+    $month_bar="";
+    $event_list="";
+    $counter=0;
+    $export_icon = 'export.png';
+    $export_icon_low = 'export_low_fade.png';
+    $export_icon_high = 'export_high_fade.png';
+
+    while($myrow=Database::fetch_array($result))
+    {
+    	$is_repeated = !empty($myrow['parent_event_id']);
+	    echo '<table class="data_table">',"\n";
+        /*--------------------------------------------------
+        		display: the month bar
+         --------------------------------------------------*/
+        // Make the month bar appear only once.
+        if ($month_bar != date("m",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"])))
+		{
+            $month_bar = date("m",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"]));
+			echo "\t<tr>\n\t\t<td class=\"agenda_month_divider\" colspan=\"3\" valign=\"top\">".
+			api_ucfirst(format_locale_date("%B %Y",strtotime($myrow["start_date"]))).
+			"</td>\n\t</tr>\n";
+		}
+
+        /*--------------------------------------------------
+         display: the icon, title, destinees of the item
+         -------------------------------------------------*/
+    	echo '<tr>';
+
+    	// highlight: if a date in the small calendar is clicked we highlight the relevant items
+    	$db_date=(int)date("d",strtotime($myrow["start_date"])).date("n",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"]));
+    	if ($_GET["day"].$_GET["month"].$_GET["year"] <>$db_date)
+    	{
+    		if ($myrow['visibility']=='0')
+    		{
+    			$style="data_hidden";
+    			$stylenotbold="datanotbold_hidden";
+    			$text_style="text_hidden";
+    		}
+    		else
+    		{
+    			$style="data";
+    			$stylenotbold="datanotbold";
+    			$text_style="text";
+    		}
+
+    	}
+    	else
+    	{
+    		$style="datanow";
+    		$stylenotbold="datanotboldnow";
+    		$text_style="textnow";
+    	}
+
+    	echo "\t\t<th>\n";
+    	// adding an internal anchor
+    	echo "\t\t\t<a name=\"".(int)date("d",strtotime($myrow["start_date"]))."\"></a>";
+    	// the icons. If the message is sent to one or more specific users/groups
+    	// we add the groups icon
+    	// 2do: if it is sent to groups we display the group icon, if it is sent to a user we show the user icon
+    	Display::display_icon('agenda.gif', get_lang('Agenda'));
+    	if ($myrow['to_group_id']!=='0')
+    	{
+    		echo Display::return_icon('group.gif', get_lang('ItemForUserSelection'));
+    	}
+    	echo " ".$myrow['title']."\n";
+    	echo "\t\t</th>\n";
+
+    	// the message has been sent to
+    	echo "\t\t<th>".get_lang("SentTo").": ";
+    	$sent_to=sent_to(TOOL_CALENDAR_EVENT, $myrow["ref"]);
+    	$sent_to_form=sent_to_form($sent_to);
+    	echo $sent_to_form;
+    	echo "</th>";
+
+    	if (!$is_repeated && (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous())))
+    	{
+    		if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $myrow['id'] ) ) )
+			{ // a coach can only delete an element belonging to his session
+	    		echo '<th>'.get_lang('Modify');
+	    		echo '</th></tr>';
+			}
+    	}
+
+        /*--------------------------------------------------
+     			display: the title
+         --------------------------------------------------*/
+    	echo "<tr class='row_odd'>";
+    	echo "\t\t<td>".get_lang("StartTimeWindow").": ";
+    	echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["start_date"])))."&nbsp;&nbsp;&nbsp;";
+    	echo api_ucfirst(strftime($timeNoSecFormat,strtotime($myrow["start_date"])))."";
+    	echo "</td>\n";
+    	echo "\t\t<td>";
+    	if ($myrow["end_date"]<>"0000-00-00 00:00:00")
+    	{
+    		echo get_lang("EndTimeWindow").": ";
+    		echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["end_date"])))."&nbsp;&nbsp;&nbsp;";
+    		echo api_ucfirst(strftime($timeNoSecFormat,strtotime($myrow["end_date"])))."";
+    	}
+    	echo "</td>\n";
+
+    	// attachment list
+	    	$attachment_list=get_attachment($myrow['id']);
+
+        /*--------------------------------------------------
+    	 display: edit delete button (course admin only)
+         --------------------------------------------------*/
+
+
+    	if (!$is_repeated && (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous())))
+    	{
+    		if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $myrow['id'] ) ) )
+			{ // a coach can only delete an element belonging to his session
+				$mylink = api_get_self().'?'.api_get_cidreq().'&amp;origin='.Security::remove_XSS($_GET['origin']).'&amp;id='.$myrow['id'];
+	    		echo '<td align="center">';
+	    		// edit
+    			echo '<a href="'.$mylink.'&amp;action=edit&amp;id_attach='.$attachment_list['id'].'" title="'.get_lang("ModifyCalendarItem").'">';
+	    		echo Display::return_icon('edit.gif', get_lang('ModifyCalendarItem'))."</a>";
+
+    			echo "<a href=\"".$mylink."&amp;action=delete\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."')) return false;\"  title=\"".get_lang("Delete")."\"> ";
+	    		echo Display::return_icon('delete.gif', get_lang('Delete'))."</a>";
+
+    			echo '<a href="'.$mylink.'&amp;action=announce" title="'.get_lang("AddAnnouncement").'">';
+    			echo Display::return_icon('announce_add.gif', get_lang('AddAnnouncement'), array ('style' => 'width:16px; height:16px;'))."</a> ";
+
+	    		if ($myrow['visibility']==1)
+	    		{
+	    			$image_visibility="visible.gif";
+				$text_visibility=get_lang("Hide");
+	    		}
+	    		else
+	    		{
+	    			$image_visibility="invisible.gif";
+				$text_visibility=get_lang("Show");
+	    		}
+    			echo 	'<a href="'.$mylink.'&amp;action=showhide" title="'.$text_visibility.'">',
+    					Display::return_icon($image_visibility, $text_visibility),'</a> ';
+			}
+
+    	if (!$is_repeated && (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous())))
+    	{
+    		if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $myrow['id'] ) ) )
+			{ // a coach can only delete an element belonging to his session
+    			$td_colspan= '<td colspan="3">';
+			}
+			else
+			{
+				$td_colspan= '<td colspan="2">';
+			}
+    	}
+    	else
+    	{
+    		$td_colspan= '<td colspan="2">';
+    	}
+    	$mylink = 'ical_export.php?'.api_get_cidreq().'&amp;type=course&amp;id='.$myrow['id'];
+		//echo '<a class="ical_export" href="'.$mylink.'&amp;class=confidential" title="'.get_lang('ExportiCalConfidential').'">'.Display::return_icon($export_icon_high, get_lang('ExportiCalConfidential')).'</a> ';
+    	//echo '<a class="ical_export" href="'.$mylink.'&amp;class=private" title="'.get_lang('ExportiCalPrivate').'">'.Display::return_icon($export_icon_low, get_lang('ExportiCalPrivate')).'</a> ';
+    	//echo '<a class="ical_export" href="'.$mylink.'&amp;class=public" title="'.get_lang('ExportiCalPublic').'">'.Display::return_icon($export_icon, get_lang('ExportiCalPublic')).'</a> ';
+	    echo '<a href="#" onclick="javascript:win_print=window.open(\'print.php?id='.$myrow['id'].'\',\'popup\',\'left=100,top=100,width=700,height=500,scrollbars=1,resizable=0\'); win_print.focus(); return false;">'.Display::return_icon('print.gif', get_lang('Print')).'</a>&nbsp;';
+    	echo '</td>';
+    	echo '</tr>';
+}
+
+        /*--------------------------------------------------
+     			display: the content
+         --------------------------------------------------*/
+    	$content = $myrow['content'];
+    	$content = make_clickable($content);
+    	$content = text_filter($content);
+    	echo "<tr class='row_even'>";
+    	echo "<td colspan='3'>";
+
+    	echo $content;
+    	// show attachment list
+			if (!empty($attachment_list)) {
+
+				$realname=$attachment_list['path'];
+				$user_filename=$attachment_list['filename'];
+				$full_file_name = 'download.php?file='.$realname;
+				echo Display::return_icon('attachment.gif',get_lang('Attachment'));
+				echo '<a href="'.$full_file_name.'';
+				echo ' "> '.$user_filename.' </a>';
+				echo '<span class="forum_attach_comment" >'.$attachment_list['comment'].'</span>';
+				if (api_is_allowed_to_edit()) {
+					echo '&nbsp;&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;origin='.Security::remove_XSS($_GET['origin']).'&amp;action=delete_attach&amp;id_attach='.$attachment_list['id'].'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset)).'\')) return false;">'.Display::return_icon('delete.gif',get_lang('Delete')).'</a><br />';
+				}
+
+			}
+
+	    echo '</td></tr>';
+
+
+        /*--------------------------------------------------
+     			display: the added resources
+         --------------------------------------------------*/
+    	if (check_added_resources("Agenda", $myrow["id"]))
+    	{
+
+    		echo '<tr>';
+    		echo '<td colspan="3">';
+    		echo "<i>".get_lang("AddedResources")."</i><br/>";
+    		if ($myrow['visibility']==0)
+    		{
+    			$addedresource_style="invisible";
+    		}
+    		display_added_resources("Agenda", $myrow["id"], $addedresource_style);
+    		echo "</td></tr>";
+    	}
+
+
+    	$event_list.=$myrow['id'].',';
+
+    	$counter++;
+        /*--------------------------------------------------
+    	 display: jump-to-top icon
+         --------------------------------------------------*/
+    	echo '<tr>';
+        echo '<td colspan="3">';
+        if($is_repeated){echo get_lang('RepeatedEvent'),' <a href="',api_get_self(),'?',api_get_cidreq(),'&amp;agenda_id=',$myrow['parent_event_id'],'" alt="',get_lang('RepeatedEventViewOriginalEvent'),'">',get_lang('RepeatedEventViewOriginalEvent'),'</a>';}
+    	echo "<a href=\"#top\">".Display::return_icon('top.gif', get_lang('Top'))."</a></td></tr>";
+    	echo "</table><br /><br />";
+    } // end while ($myrow=Database::fetch_array($result))
+
+    if(!empty($event_list))
+    {
+    	$event_list=api_substr($event_list,0,-1);
+    }
+    else
+    {
+    	$event_list='0';
+    }
+
+    echo "<form name=\"event_list_form\"><input type=\"hidden\" name=\"event_list\" value=\"$event_list\" /></form>";
+
+    // closing the layout table
+    echo "</td>",
+    	"</tr>",
+    	"</table>";
+}
+
+/**
+ * Show a list with all the attachments according to the post's id
+ * @param the post's id
+ * @return array with the post info
+ * @author Christian Fasanando
+ * @version November 2008, dokeos 1.8.6
+ */
+
+function get_attachment($agenda_id) {
+	$agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
+	$agenda_id=Database::escape_string($agenda_id);
+	$row=array();
+	$sql = 'SELECT id,path, filename,comment FROM '. $agenda_table_attachment.' WHERE agenda_id = '.(int)$agenda_id.'';
+	$result=Database::query($sql, __FILE__, __LINE__);
+	if (Database::num_rows($result)!=0) {
+		$row=Database::fetch_array($result);
+	}
+	return $row;
+}
+
+/**
+* Displays only 1 agenda item. This is used when an agenda item is added to the learning path.
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+function display_one_agenda_item($agenda_id)
+{
+	global $TABLEAGENDA;
+	global $TABLE_ITEM_PROPERTY;
+	global $select_month, $select_year;
+	global $DaysShort, $DaysLong, $MonthsLong;
+	global $is_courseAdmin;
+	global $dateFormatLong, $timeNoSecFormat, $charset;
+	global $_user;
+	//echo "displaying agenda items";
+
+
+	// getting the name of the groups
+	$group_names=get_course_groups();
+
+	/*--------------------------------------------------
+			CONSTRUCT THE SQL STATEMENT
+	  --------------------------------------------------*/
+	$agenda_id = Database::escape_string($agenda_id);
+
+	$sql="SELECT agenda.*, toolitemproperties.*
+					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
+					WHERE agenda.id = toolitemproperties.ref
+					AND toolitemproperties.tool='".TOOL_CALENDAR_EVENT."'
+					AND toolitemproperties.visibility='1'
+					AND agenda.id='$agenda_id'";
+	$result=Database::query($sql,__FILE__,__LINE__) or die(Database::error());
+	$number_items=Database::num_rows($result);
+	$myrow=Database::fetch_array($result); // there should be only one item so no need for a while loop
+
+    $sql_rep = "SELECT * FROM $TABLEAGENDA WHERE id = $agenda_id AND parent_event_id IS NOT NULL AND parent_event_id !=0";
+    $res_rep = Database::query($sql_rep,__FILE__,__LINE__);
+    $repeat = false;
+    $repeat_id = 0;
+    if(Database::num_rows($res_rep)>0)
+    {
+        $repeat=true;
+        $row_rep = Database::fetch_array($res_rep);
+        $repeat_id = $row_rep['parent_event_id'];
+    }
+
+	/*--------------------------------------------------
+			DISPLAY: NO ITEMS
+	  --------------------------------------------------*/
+	if ($number_items==0)
+	{
+		echo "<table id=\"data_table\" class=\"data_table\"><tr><td>".get_lang("NoAgendaItems")."</td></tr></table>";
+	}
+
+	/*--------------------------------------------------
+			DISPLAY: THE ITEMS
+	  --------------------------------------------------*/
+	echo "<table id=\"data_table\" class=\"data_table\">\n";
+
+	/*--------------------------------------------------
+	 DISPLAY : the icon, title, destinees of the item
+	  --------------------------------------------------*/
+	echo "\t<tr>\n";
+
+	// highlight: if a date in the small calendar is clicked we highlight the relevant items
+	$db_date=(int)date("d",strtotime($myrow["start_date"])).date("n",strtotime($myrow["start_date"])).date("Y",strtotime($myrow["start_date"]));
+	if ($_GET["day"].$_GET["month"].$_GET["year"] <>$db_date)
+	{
+		if ($myrow['visibility']=='0')
+		{
+			$style="data_hidden";
+			$stylenotbold="datanotbold_hidden";
+			$text_style="text_hidden";
+		}
+		else
+		{
+			$style="data";
+			$stylenotbold="datanotbold";
+			$text_style="text";
+		}
+	}
+	else
+	{
+		$style="datanow";
+		$stylenotbold="datanotboldnow";
+		$text_style="textnow";
+	}
+
+
+	echo "\t\t<th>\n";
+
+	// adding an internal anchor
+	echo "\t\t\t<a name=\"".(int)date("d",strtotime($myrow["start_date"]))."\"></a>";
+
+	// the icons. If the message is sent to one or more specific users/groups
+	// we add the groups icon
+	// 2do: if it is sent to groups we display the group icon, if it is sent to a user we show the user icon
+	echo Display::return_icon('agenda.gif');
+	if ($myrow['to_group_id']!=='0')
+	{
+		echo Display::return_icon('group.gif');
+	}
+	echo " ".$myrow['title']."\n";
+	echo "\t\t</th>\n";
+
+	// the message has been sent to
+	echo "\t\t<th>".get_lang("SentTo").": ";
+	$sent_to=sent_to(TOOL_CALENDAR_EVENT, $myrow["ref"]);
+	$sent_to_form=sent_to_form($sent_to);
+	echo $sent_to_form;
+	echo "</th>";
+	if (api_is_allowed_to_edit())	{
+		if( ! (api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $myrow['id'] ) ) )
+				{ // a coach can only delete an element belonging to his session
+		    		echo '<th>'.get_lang('Modify');
+		    		echo '</th></tr>';
+				}
+	}
+	/*--------------------------------------------------
+	 			DISPLAY: the title
+	  --------------------------------------------------*/
+	echo "\t<tr class='row_odd'>\n";
+	echo "\t\t<td>".get_lang("StartTime").": ";
+	echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["start_date"])))."&nbsp;&nbsp;&nbsp;";
+	echo api_ucfirst(strftime($timeNoSecFormat,strtotime($myrow["start_date"])))."";
+	echo "</td>\n";
+	echo "\t\t<td>".get_lang("EndTime").": ";
+	echo api_ucfirst(format_locale_date($dateFormatLong,strtotime($myrow["end_date"])))."&nbsp;&nbsp;&nbsp;";
+	echo api_ucfirst(strftime($timeNoSecFormat,strtotime($myrow["end_date"])))."";
+	echo "</td>\n";
+
+	/*--------------------------------------------------
+		DISPLAY: edit delete button (course admin only)
+	  --------------------------------------------------*/
+	$export_icon = '../img/export.png';
+    $export_icon_low = '../img/export_low_fade.png';
+    $export_icon_high = '../img/export_high_fade.png';
+    if (api_is_allowed_to_edit())	{
+		echo '<td colspan="2">';
+		if (!$repeat && api_is_allowed_to_edit(false,true))	{
+			// edit
+			$mylink = api_get_self()."?".api_get_cidreq()."&amp;origin=".Security::remove_XSS($_GET['origin'])."&amp;id=".$myrow['id'];
+			if (!empty($_GET['agenda_id']))
+			{
+				// rather ugly hack because the id parameter is already set above but below we set it again
+				$mylink .= '&amp;agenda_id='.Security::remove_XSS($_GET['agenda_id']).'&amp;id='.Security::remove_XSS($_GET['agenda_id']);
+			}
+			echo 	"<a href=\"".$mylink."&amp;action=edit\">",
+					Display::return_icon('edit.gif', get_lang('ModifyCalendarItem')), "</a>",
+					"<a href=\"".$mylink."&amp;action=delete\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."')) return false;\">",
+					Display::return_icon('delete.gif', get_lang('Delete')),"</a>";
+			if ($myrow['visibility']==1) {
+				$image_visibility="visible";
+			} else {
+				$image_visibility="invisible";
+			}
+			echo 	'<a href="'.$mylink.'&amp;action=showhide">',Display::return_icon($image_visibility.'.gif', get_lang('Visible')),'</a>';
+		}
+	   	$mylink = 'ical_export.php?'.api_get_cidreq().'&amp;type=course&amp;id='.$myrow['id'];
+	    //echo '<a class="ical_export" href="'.$mylink.'&amp;class=confidential" title="'.get_lang('ExportiCalConfidential').'">'.Display::return_icon($export_icon_high, get_lang('ExportiCalConfidential')).'</a> ';
+	    //echo '<a class="ical_export" href="'.$mylink.'&amp;class=private" title="'.get_lang('ExportiCalPrivate').'">'.Display::return_icon($export_icon_low, get_lang('ExportiCalPrivate')).'</a> ';
+	    //echo '<a class="ical_export" href="'.$mylink.'&amp;class=public" title="'.get_lang('ExportiCalPublic').'">'.Display::return_icon($export_icon, get_lang('ExportiCalPublic')).'</a> ';
+	    echo '<a href="javascript: void(0);" onclick="javascript:win_print=window.open(\'print.php?id='.$myrow['id'].'\',\'popup\',\'left=100,top=100,width=700,height=500,scrollbars=1,resizable=0\'); win_print.focus(); return false;">'.Display::return_icon('print.gif', get_lang('Print')).'</a>&nbsp;';
+		echo "</td></tr>";
+	    if($repeat) {
+	    	echo '<tr>';
+	    	echo '<td colspan="2">',get_lang('RepeatedEvent'),'<a href="',api_get_self(),'?',api_get_cidreq(),'&amp;agenda_id=',$repeat_id,'" alt="',get_lang('RepeatedEventViewOriginalEvent'),'">',get_lang('RepeatedEventViewOriginalEvent'),'</a></td>';
+	        echo '</tr>';
+	    }
+    }
+	/*--------------------------------------------------
+	 			DISPLAY: the content
+	  --------------------------------------------------*/
+
+	$content = $myrow['content'];
+	$content = make_clickable($content);
+	$content = text_filter($content);
+	//echo "\t<tr>\n\t\t<td class=\"".$text_style."\" colspan='2'>";
+	//echo $content;
+	//echo "</td></tr>";
+    echo "<tr class='row_even'>";
+    echo '<td '.(api_is_allowed_to_edit()?'colspan="3"':'colspan="2"'). '>';
+    echo $content;
+    echo '</td></tr>';
+
+	/*--------------------------------------------------
+	 			DISPLAY: the added resources
+	  --------------------------------------------------*/
+	if (check_added_resources("Agenda", $myrow["id"])) {
+		echo "<tr><td colspan='3'>";
+		echo "<i>".get_lang("AddedResources")."</i><br/>";
+		if ($myrow['visibility']==0)
+		{
+			$addedresource_style="invisible";
+		}
+		display_added_resources("Agenda", $myrow["id"], $addedresource_style);
+		echo "</td></tr>";
+	}
+
+	// closing the layout table
+	echo "</td>",
+		"</tr>",
+		"</table>";
+}
+
+
+
+
+/**
+* Show the form for adding a new agenda item. This is the same function that is used whenever we are editing an
+* agenda item. When the id parameter is empty (default behaviour), then we show an empty form, else we are editing and
+* we have to retrieve the information that is in the database and use this information in the forms.
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @param integer id, the id of the agenda item we are editing. By default this is empty which means that we are adding an
+*		 agenda item.
+*/
+function show_add_form($id = '')
+{
+
+	global $MonthsLong;
+	$htmlHeadXtra[] = to_javascript();
+	// the default values for the forms
+	if ($_GET['originalresource'] !== 'no')
+	{
+		$day	= date('d');
+		$month	= date('m');
+		$year	= date('Y');
+		$hours	= 9;
+		$minutes= '00';
+
+		$end_day	= date('d');
+		$end_month	= date('m');
+		$end_year	= date('Y');
+		$end_hours	= 17;
+		$end_minutes= '00';
+        $repeat = false;
+	}
+	else
+	{
+		// we are coming from the resource linker so there might already have been some information in the form.
+		// When we clicked on the button to add resources we stored every form information into a session and now we
+		// are doing the opposite thing: getting the information out of the session and putting it into variables to
+		// display it in the forms.
+		$form_elements=$_SESSION['formelements'];
+		$day=$form_elements['day'];
+		$month=$form_elements['month'];
+		$year=$form_elements['year'];
+		$hours=$form_elements['hour'];
+		$minutes=$form_elements['minutes'];
+		$end_day=$form_elements['end_day'];
+		$end_month=$form_elements['end_month'];
+		$end_year=$form_elements['end_year'];
+		$end_hours=$form_elements['end_hours'];
+		$end_minutes=$form_elements['end_minutes'];
+		$title=$form_elements['title'];
+		$content=$form_elements['content'];
+		$id=$form_elements['id'];
+		$to=$form_elements['to'];
+        $repeat = $form_elements['repeat'];
+	}
+
+	//	switching the send to all/send to groups/send to users
+	if ($_POST['To'])
+	{
+			$day			= $_POST['fday'];
+			$month			= $_POST['fmonth'];
+			$year			= $_POST['fyear'];
+			$hours			= $_POST['fhour'];
+			$minutes		= $_POST['fminute'];
+			$end_day		= $_POST['end_fday'];
+			$end_month		= $_POST['end_fmonth'];
+			$end_year		= $_POST['end_fyear'];
+			$end_hours		= $_POST['end_fhour'];
+			$end_minutes	= $_POST['end_fminute'];
+			$title 			= $_POST['title'];
+			$content		= $_POST['content'];
+			// the invisible fields
+			$action			= $_POST['action'];
+			$id				= $_POST['id'];
+            $repeat         = !empty($_POST['repeat'])?true:false;
+		}
+
+	// if the id is set then we are editing an agenda item
+	if (is_int($id))
+	{
+		//echo "before get_agenda_item".$_SESSION['allow_individual_calendar'];
+		$item_2_edit=get_agenda_item($id);
+		$title	= $item_2_edit['title'];
+		$content= $item_2_edit['content'];
+		// start date
+		list($datepart, $timepart) = split(" ", $item_2_edit['start_date']);
+		list($year, $month, $day) = explode("-", $datepart);
+		list($hours, $minutes, $seconds) = explode(":", $timepart);
+		// end date
+		list($datepart, $timepart) = split(" ", $item_2_edit['end_date']);
+		list($end_year, $end_month, $end_day) = explode("-", $datepart);
+		list($end_hours, $end_minutes, $end_seconds) = explode(":", $timepart);
+		// attachments
+		edit_added_resources("Agenda", $id);
+		$to=$item_2_edit['to'];
+		//echo "<br />after get_agenda_item".$_SESSION['allow_individual_calendar'];
+	}
+	$content=stripslashes($content);
+	$title=stripslashes($title);
+	// we start a completely new item, we do not come from the resource linker
+	if ($_GET['originalresource']!=="no" and $_GET['action']=="add")
+	{
+		$_SESSION["formelements"]=null;
+		unset_session_resources();
+	}
+?>
+
+	<!-- START OF THE FORM  -->
+
+	<form enctype="multipart/form-data"  action="<?php echo api_get_self().'?origin='.$_GET['origin'].'&amp;action='.$_GET['action']; ?>" method="post" name="new_calendar_item">
+	<input type="hidden" name="id" value="<?php if (isset($id)) echo $id; ?>" />
+	<input type="hidden" name="action" value="<?php if (isset($_GET['action'])) echo $_GET['action']; ?>" />
+	<input type="hidden" name="id_attach" value="<?php echo Security::remove_XSS($_REQUEST['id_attach']); ?>" />
+	<input type="hidden" name="sort" value="asc" />
+	<input type="hidden" name="submit_event" value="ok" />
+	<?php
+	// The form title
+	if (isset($id) AND $id<>'')
+	{
+		$form_title = get_lang('ModifyCalendarItem');
+	}
+	else
+	{
+		$form_title = get_lang('AddCalendarItem');
+	}
+	echo '<div class="row"><div class="form_header">'.$form_title.'</div></div>';
+
+	// selecting the users / groups
+	if (isset ($_SESSION['toolgroup']))
+	{
+		echo '<input type="hidden" name="selectedform[0]" value="GROUP:'.intval($_SESSION['toolgroup']).'"/>' ;
+		echo '<input type="hidden" name="To" value="true"/>' ;
+	}
+	else
+	{
+		echo '	<div class="row">
+					<div class="label">
+						<a href="javascript: void(0);" onclick="if(document.getElementById(\'recipient_list\').style.display==\'none\') document.getElementById(\'recipient_list\').style.display=\'block\'; else document.getElementById(\'recipient_list\').style.display=\'none\';">'.Display::return_icon('group.gif', get_lang('SentTo'), array ('align' => 'absmiddle')).' '.get_lang('SentTo').'</a>
+					</div>
+					<div class="formw">';
+		if ((isset($_GET['id'])  && $to=='everyone') || !isset($_GET['id']))
+		{
+					echo get_lang("Everybody").'&nbsp;';
+				}
+				show_to_form($to);
+				if (isset($_GET['id']) && $to!='everyone') {
+					echo '<script>document.getElementById(\'recipient_list\').style.display=\'block\';</script>';
+				}
+		echo '		</div>
+				</div>';
+
+	}
+
+	// start date and time
+	echo 	'<div class="row">
+				<div class="label">
+					'.get_lang('StartDate').'
+				</div>
+				<div class="formw">
+					<div id="err_date" style="display:none;color:red"></div>
+					<div id="err_start_date" style="display:none;color:red"></div>';
+	?>
+					<select name="fday" onchange="javascript:document.new_calendar_item.end_fday.value=this.value;">
+							<?php
+							// small loop for filling all the dates
+							// 2do: the available dates should be those of the selected month => february is from 1 to 28 (or 29) and not to 31
+							echo "\n";
+							foreach (range(1, 31) as $i)
+											{
+											// values have to have double digits
+											$value = ($i <= 9 ? '0'.$i : $i );
+											// the current day is indicated with [] around the date
+											if ($value==$day)
+											{
+												echo "\t\t\t\t <option value=\"".$value."\" selected> ".$i." </option>\n";
+											}
+											else
+											{
+												echo "\t\t\t\t<option value=\"$value\">$i</option>\n";
+											}
+										}
+										 ?>
+					</select>
+					<select name="fmonth" onchange="javascript:document.new_calendar_item.end_fmonth.value=this.value;">
+					<?php
+											echo "\n";
+											for ($i=1; $i<=12; $i++)
+											{
+												// values have to have double digits
+												if ($i<=9)
+												{
+													$value="0".$i;
+												}
+												else
+												{
+													$value=$i;
+												}
+												if ($value==$month)
+												{
+													echo "\t\t\t\t <option value=\"".$value."\" selected>".$MonthsLong[$i-1]."</option>\n";
+												}
+												else
+												{
+													echo "\t\t\t\t <option value=\"".$value."\">".$MonthsLong[$i-1]."</option>\n";
+												}
+											} ?>
+					</select>
+					<select name="fyear" onchange="javascript:document.new_calendar_item.end_fyear.value=this.value;">
+										<option value="<?php echo ($year-1); ?>"><?php echo ($year-1); ?></option>
+											<option value="<?php echo $year; ?>" selected="selected"><?php echo $year; ?></option>
+											<?php
+												echo "\n";
+												for ($i=1; $i<=5; $i++)
+												{
+													$value=$year+$i;
+													echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
+												} ?>
+					</select>
 					<a href="javascript:openCalendar('new_calendar_item', 'f')"><?php Display::display_icon('calendar_select.gif', get_lang('Select'), array ('style' => 'vertical-align: middle;')); ?></a>
-					&nbsp;<?php echo get_lang('StartTime').": \n"; ?>&nbsp;
-						<select name="fhour" onchange="javascript:document.new_calendar_item.end_fhour.value=this.value;">
-							<!-- <option value="--">--</option> -->
-							<?php
-								echo "\n";
-								foreach (range(0, 23) as $i)
-								{
-									// values have to have double digits
-									$value = ($i <= 9 ? '0'.$i : $i );
-									// the current hour is indicated with [] around the hour
-									if ($hours==$value)
-									{
-										echo "\t\t\t\t<option value=\"".$value."\" selected> ".$value." </option>\n";
-									}
-									else
-									{
-										echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
-									}
-								} ?>
-						</select>
-
-						<select name="fminute" onchange="javascript:document.new_calendar_item.end_fminute.value=this.value;">
-							<!-- <option value="<?php echo $minutes ?>"><?php echo $minutes; ?></option> -->
-							<!-- <option value="--">--</option> -->
-							<?php
-								foreach (range(0, 59) as $i)
-								{
-									// values have to have double digits
-									$value = ($i <= 9 ? '0'.$i : $i );
-									echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
-								} ?>
-						</select>
+					&nbsp;<?php echo get_lang('StartTime').": \n"; ?>&nbsp;
+						<select name="fhour" onchange="javascript:document.new_calendar_item.end_fhour.value=this.value;">
+							<!-- <option value="--">--</option> -->
+							<?php
+								echo "\n";
+								foreach (range(0, 23) as $i)
+								{
+									// values have to have double digits
+									$value = ($i <= 9 ? '0'.$i : $i );
+									// the current hour is indicated with [] around the hour
+									if ($hours==$value)
+									{
+										echo "\t\t\t\t<option value=\"".$value."\" selected> ".$value." </option>\n";
+									}
+									else
+									{
+										echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
+									}
+								} ?>
+						</select>
+
+						<select name="fminute" onchange="javascript:document.new_calendar_item.end_fminute.value=this.value;">
+							<!-- <option value="<?php echo $minutes ?>"><?php echo $minutes; ?></option> -->
+							<!-- <option value="--">--</option> -->
+							<?php
+								foreach (range(0, 59) as $i)
+								{
+									// values have to have double digits
+									$value = ($i <= 9 ? '0'.$i : $i );
+									echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
+								} ?>
+						</select>
 	<?php
-	echo 	'	</div>
-			</div>';
-
-	// end date and time
-	echo 	'<div class="row">
-				<div class="label">
-					'.get_lang('EndDate').'
-				</div>
-				<div class="formw">
+	echo 	'	</div>
+			</div>';
+
+	// end date and time
+	echo 	'<div class="row">
+				<div class="label">
+					'.get_lang('EndDate').'
+				</div>
+				<div class="formw">
 					<div id="err_end_date" style="display:none;color:red"></div>';
-	?>
-						<select name="end_fday">
-							<?php
-								// small loop for filling all the dates
-								// 2do: the available dates should be those of the selected month => february is from 1 to 28 (or 29) and not to 31
-								echo "\n";
-								foreach (range(1, 31) as $i)
-								{
-									// values have to have double digits
-									$value = ($i <= 9 ? '0'.$i : $i );
-									// the current day is indicated with [] around the date
-									if ($value==$end_day)
-										{ echo "\t\t\t\t <option value=\"".$value."\" selected> ".$i." </option>\n";}
-									else
-										{ echo "\t\t\t\t <option value=\"".$value."\">".$i."</option>\n"; }
-									}?>
-						</select>
-							<!-- month: january -> december -->
-						<select name="end_fmonth">
-								<?php
-								echo "\n";
-								foreach (range(1, 12) as $i)
-								{
-									// values have to have double digits
-									$value = ($i <= 9 ? '0'.$i : $i );
-									if ($value==$end_month)
-										{ echo "\t\t\t\t <option value=\"".$value."\" selected>".$MonthsLong[$i-1]."</option>\n"; }
-									else
-										{ echo "\t\t\t\t <option value=\"".$value."\">".$MonthsLong[$i-1]."</option>\n"; }
-									}?>
+	?>
+						<select name="end_fday">
+							<?php
+								// small loop for filling all the dates
+								// 2do: the available dates should be those of the selected month => february is from 1 to 28 (or 29) and not to 31
+								echo "\n";
+								foreach (range(1, 31) as $i)
+								{
+									// values have to have double digits
+									$value = ($i <= 9 ? '0'.$i : $i );
+									// the current day is indicated with [] around the date
+									if ($value==$end_day)
+										{ echo "\t\t\t\t <option value=\"".$value."\" selected> ".$i." </option>\n";}
+									else
+										{ echo "\t\t\t\t <option value=\"".$value."\">".$i."</option>\n"; }
+									}?>
+						</select>
+							<!-- month: january -> december -->
+						<select name="end_fmonth">
+								<?php
+								echo "\n";
+								foreach (range(1, 12) as $i)
+								{
+									// values have to have double digits
+									$value = ($i <= 9 ? '0'.$i : $i );
+									if ($value==$end_month)
+										{ echo "\t\t\t\t <option value=\"".$value."\" selected>".$MonthsLong[$i-1]."</option>\n"; }
+									else
+										{ echo "\t\t\t\t <option value=\"".$value."\">".$MonthsLong[$i-1]."</option>\n"; }
+									}?>
+						</select>
+						<select name="end_fyear">
+								<option value="<?php echo ($end_year-1) ?>"><?php echo ($end_year-1) ?></option>
+								<option value="<?php echo $end_year ?>" selected> <?php echo $end_year ?> </option>
+								<?php
+								echo "\n";
+								for ($i=1; $i<=5; $i++)
+								{
+									$value=$end_year+$i;
+									echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
+								} ?>
+						</select>
+					<a href="javascript:openCalendar('new_calendar_item', 'end_f')"><?php Display::display_icon('calendar_select.gif', get_lang('Select'), array ('style' => 'vertical-align: middle;')); ?></a>
+					&nbsp;<?php echo get_lang('EndTime').": \n"; ?>&nbsp;
+
+						<select name="end_fhour">
+							<!-- <option value="--">--</option> -->
+							<?php
+								echo "\n";
+								foreach (range(0, 23) as $i)
+								{
+									// values have to have double digits
+									$value = ($i <= 9 ? '0'.$i : $i );
+									// the current hour is indicated with [] around the hour
+									if ($end_hours==$value)
+										{ echo "\t\t\t\t<option value=\"".$value."\" selected> ".$value." </option>\n"; }
+									else
+										{ echo "\t\t\t\t<option value=\"".$value."\"> ".$value." </option>\n"; }
+								} ?>
+						</select>
+
+						<select name="end_fminute">
+							<!-- <option value="<?php echo $end_minutes; ?>"><?php echo $end_minutes; ?></option> -->
+							<!-- <option value="--">--</option> -->
+							<?php
+								foreach (range(0, 59) as $i)
+								{
+									// values have to have double digits
+									$value = ($i <= 9 ? '0'.$i : $i );
+									echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
+								} ?>
 						</select>
-						<select name="end_fyear">
-								<option value="<?php echo ($end_year-1) ?>"><?php echo ($end_year-1) ?></option>
-								<option value="<?php echo $end_year ?>" selected> <?php echo $end_year ?> </option>
-								<?php
-								echo "\n";
-								for ($i=1; $i<=5; $i++)
-								{
-									$value=$end_year+$i;
-									echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
-								} ?>
-						</select>
-					<a href="javascript:openCalendar('new_calendar_item', 'end_f')"><?php Display::display_icon('calendar_select.gif', get_lang('Select'), array ('style' => 'vertical-align: middle;')); ?></a>
-					&nbsp;<?php echo get_lang('EndTime').": \n"; ?>&nbsp;
-
-						<select name="end_fhour">
-							<!-- <option value="--">--</option> -->
-							<?php
-								echo "\n";
-								foreach (range(0, 23) as $i)
-								{
-									// values have to have double digits
-									$value = ($i <= 9 ? '0'.$i : $i );
-									// the current hour is indicated with [] around the hour
-									if ($end_hours==$value)
-										{ echo "\t\t\t\t<option value=\"".$value."\" selected> ".$value." </option>\n"; }
-									else
-										{ echo "\t\t\t\t<option value=\"".$value."\"> ".$value." </option>\n"; }
-								} ?>
-						</select>
-
-						<select name="end_fminute">
-							<!-- <option value="<?php echo $end_minutes; ?>"><?php echo $end_minutes; ?></option> -->
-							<!-- <option value="--">--</option> -->
-							<?php
-								foreach (range(0, 59) as $i)
-								{
-									// values have to have double digits
-									$value = ($i <= 9 ? '0'.$i : $i );
-									echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
-								} ?>
-						</select>
 	<?php
-	echo 	'	</div>
-			</div>';
-
-	// the title of the agenda item
-	echo 	' 	<div class="row">
-					<div class="label">
-						<span class="form_required">*</span>'.get_lang('ItemTitle').'
-					</div>
-					<div class="formw">
+	echo 	'	</div>
+			</div>';
+
+	// the title of the agenda item
+	echo 	' 	<div class="row">
+					<div class="label">
+						<span class="form_required">*</span>'.get_lang('ItemTitle').'
+					</div>
+					<div class="formw">
 	<div id="err_title" style="display:none;color:red"></div>
-						<input type="text" size="60" name="title" value="';
-						if (isset($title)) echo $title;
-	echo				'" />
-					</div>
-				</div>';
-
-
-	// the main area of the agenda item: the wysiwyg editor
-	echo '	<div class="row">
-				<div class="label">
-					<span class="form_required">*</span>'.get_lang('Description').'
-				</div>
-				<div class="formw">';
-			require_once(api_get_path(LIBRARY_PATH) . "/fckeditor/fckeditor.php");
-
-			$oFCKeditor = new FCKeditor('content') ;
-
-			$oFCKeditor->Width		= '100%';
-			$oFCKeditor->Height		= '200';
-
-			if(!api_is_allowed_to_edit())
-			{
-				$oFCKeditor->ToolbarSet = 'AgendaStudent';
-			}
-			else
-			{
-				$oFCKeditor->ToolbarSet = 'Agenda';
-			}
-			$oFCKeditor->Value		= $content;
-
-			$return =	$oFCKeditor->CreateHtml();
-
-			echo $return;
-	echo '		</div>
-			</div>';
-
+						<input type="text" size="60" name="title" value="';
+						if (isset($title)) echo $title;
+	echo				'" />
+					</div>
+				</div>';
+
+
+	// the main area of the agenda item: the wysiwyg editor
+	echo '	<div class="row">
+				<div class="label">
+					<span class="form_required">*</span>'.get_lang('Description').'
+				</div>
+				<div class="formw">';
+			require_once(api_get_path(LIBRARY_PATH) . "/fckeditor/fckeditor.php");
+
+			$oFCKeditor = new FCKeditor('content') ;
+
+			$oFCKeditor->Width		= '100%';
+			$oFCKeditor->Height		= '200';
+
+			if(!api_is_allowed_to_edit())
+			{
+				$oFCKeditor->ToolbarSet = 'AgendaStudent';
+			}
+			else
+			{
+				$oFCKeditor->ToolbarSet = 'Agenda';
+			}
+			$oFCKeditor->Value		= $content;
+
+			$return =	$oFCKeditor->CreateHtml();
+
+			echo $return;
+	echo '		</div>
+			</div>';
+
 	// the added resources
-	/*echo '	<div class="row">
-				<div class="label">
-					'.get_lang('AddedResources').'
-				</div>
-				<div class="formw">';
-			if ($_SESSION['allow_individual_calendar']=='show')
-				show_addresource_button('onclick="selectAll(this.form.elements[6],true)"');
-			else
-				show_addresource_button();
-			$form_elements=$_SESSION['formelements'];
-	   echo display_resources(0);
-	   $test=$_SESSION['addedresource'];
-	echo '		</div>
-			</div>';
-			*/
-
-	// File attachment
-	echo '	<div class="row">
-				<div class="label">
-					<a href="javascript://" onclick="return plus_attachment();"><span id="plus"><img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang('AddAnAttachment').'</span></a>
-				</div>
-				<div class="formw">
-					<table id="options" style="display: none;">
-					<tr>
-						<td colspan="2">
-					        <label for="file_name">'.get_lang('FileName').'&nbsp;</label>
-					        <input type="file" name="user_upload"/>
-					    </td>
-					 </tr>
-					 <tr>
-					    <td colspan="2">
-					    	<label for="comment">'.get_lang('FileComment').'</label><br />
-					    	<textarea name="file_comment" rows ="4" cols = "34" ></textarea>
-					    </td>
-				    </tr>
-			    </table>
-			 </div>
-			</div>';
-
-
-	// Repeating the calendar item
-    if(empty($id)) //only show repeat fields when adding, not for editing an calendar item
-    {
-	echo '	<div class="row">
-				<div class="label">
-					<a href="javascript://" onclick="return plus_repeated_event();"><span id="plus2"><img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang('RepeatEvent').'</span></a>
-				</div>
-				<div class="formw">';
-?>
-					<table id="options2" style="display: none;">
-					<tr>
-							<td><label for="repeat"><?php echo get_lang('RepeatEvent');?></label></td>
-							<td><input type="checkbox" name="repeat" <?php echo ($repeat?'checked="checked"':'');?>/></td>
-			    </tr>
-			    <tr>
-							<td><label for="repeat_type"><?php echo get_lang('RepeatType');?></label></td>
-							<td>
-			        <select name="repeat_type">
-			          <option value="daily"><?php echo get_lang('RepeatDaily');?></option>
-			          <option value="weekly"><?php echo get_lang('RepeatWeekly');?></option>
-			          <option value="monthlyByDate"><?php echo get_lang('RepeatMonthlyByDate');?></option>
-			          <!--option value="monthlyByDay"><?php echo get_lang('RepeatMonthlyByDay');?></option>
-			          <option value="monthlyByDayR"><?php echo get_lang('RepeatMonthlyByDayR');?></option-->
-			          <option value="yearly"><?php echo get_lang('RepeatYearly');?></option>
-			        </select>
-			      </td>
-			    </tr>
-			    <tr>
-							<td><label for="repeat_end_day"><?php echo get_lang('RepeatEnd');?></label></td>
-			            	<td>
-			            <select name="repeat_end_day">
-			                <?php
-			                    // small loop for filling all the dates
-			                    // 2do: the available dates should be those of the selected month => february is from 1 to 28 (or 29) and not to 31
-			                    echo "\n";
-			                    foreach (range(1, 31) as $i)
-			                    {
-			                        // values have to have double digits
-			                        $value = ($i <= 9 ? '0'.$i : $i );
-			                        // the current day is indicated with [] around the date
-			                        if ($value==$end_day)
-			                            { echo "\t\t\t\t <option value=\"".$value."\" selected> ".$i." </option>\n";}
-			                        else
-			                            { echo "\t\t\t\t <option value=\"".$value."\">".$i."</option>\n"; }
-			                        }?>
-			                </select>
-
-			                <!-- month: january -> december -->
-			                <select name="repeat_end_month">
-			                    <?php
-			                    echo "\n";
-			                    foreach (range(1, 12) as $i)
-			                    {
-			                        // values have to have double digits
-			                        $value = ($i <= 9 ? '0'.$i : $i );
-			                        if ($value==$end_month+1)
-			                            { echo "\t\t\t\t ",'<option value="',$value,'" selected="selected">',$MonthsLong[$i-1],"</option>\n"; }
-			                        else
-			                            { echo "\t\t\t\t ",'<option value="',$value,'">',$MonthsLong[$i-1],"</option>\n"; }
-			                        }?>
-			                </select>
-
-			                <select name="repeat_end_year">
-			                    <option value="<?php echo ($end_year-1) ?>"><?php echo ($end_year-1) ?></option>
-			                    <option value="<?php echo $end_year ?>" selected> <?php echo $end_year ?> </option>
-			                    <?php
-			                    echo "\n";
-			                    for ($i=1; $i<=5; $i++)
-			                    {
-			                        $value=$end_year+$i;
-			                        echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
-			                    } ?>
-			            </select>
-			            		<a href="javascript:openCalendar('new_calendar_item', 'repeat_end_')"><?php Display::display_icon('calendar_select.gif', get_lang('Select'), array ('style' => 'vertical-align: middle;')); ?></a>
-								    </td>
-				    </tr>
-			    </table>
-<?php
-	echo '		</div>
-			</div>';
-    }//only show repeat fields if adding, not if editing
-
-
-    // the submit button for storing the calendar item
-    echo '		<div class="row">
-					<div class="label">
-			 </div>
-					<div class="formw">';
-		if(isset($_GET['id'])) {
-		$class='save';
-			$text=get_lang('ModifyEvent');
-		} else {
-		$class='add';
+	/*echo '	<div class="row">
+				<div class="label">
+					'.get_lang('AddedResources').'
+				</div>
+				<div class="formw">';
+			if ($_SESSION['allow_individual_calendar']=='show')
+				show_addresource_button('onclick="selectAll(this.form.elements[6],true)"');
+			else
+				show_addresource_button();
+			$form_elements=$_SESSION['formelements'];
+	   echo display_resources(0);
+	   $test=$_SESSION['addedresource'];
+	echo '		</div>
+			</div>';
+			*/
+
+	// File attachment
+	echo '	<div class="row">
+				<div class="label">
+					<a href="javascript://" onclick="return plus_attachment();"><span id="plus"><img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang('AddAnAttachment').'</span></a>
+				</div>
+				<div class="formw">
+					<table id="options" style="display: none;">
+					<tr>
+						<td colspan="2">
+					        <label for="file_name">'.get_lang('FileName').'&nbsp;</label>
+					        <input type="file" name="user_upload"/>
+					    </td>
+					 </tr>
+					 <tr>
+					    <td colspan="2">
+					    	<label for="comment">'.get_lang('FileComment').'</label><br />
+					    	<textarea name="file_comment" rows ="4" cols = "34" ></textarea>
+					    </td>
+				    </tr>
+			    </table>
+			 </div>
+			</div>';
+
+
+	// Repeating the calendar item
+    if(empty($id)) //only show repeat fields when adding, not for editing an calendar item
+    {
+	echo '	<div class="row">
+				<div class="label">
+					<a href="javascript://" onclick="return plus_repeated_event();"><span id="plus2"><img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang('RepeatEvent').'</span></a>
+				</div>
+				<div class="formw">';
+?>
+					<table id="options2" style="display: none;">
+					<tr>
+							<td><label for="repeat"><?php echo get_lang('RepeatEvent');?></label></td>
+							<td><input type="checkbox" name="repeat" <?php echo ($repeat?'checked="checked"':'');?>/></td>
+			    </tr>
+			    <tr>
+							<td><label for="repeat_type"><?php echo get_lang('RepeatType');?></label></td>
+							<td>
+			        <select name="repeat_type">
+			          <option value="daily"><?php echo get_lang('RepeatDaily');?></option>
+			          <option value="weekly"><?php echo get_lang('RepeatWeekly');?></option>
+			          <option value="monthlyByDate"><?php echo get_lang('RepeatMonthlyByDate');?></option>
+			          <!--option value="monthlyByDay"><?php echo get_lang('RepeatMonthlyByDay');?></option>
+			          <option value="monthlyByDayR"><?php echo get_lang('RepeatMonthlyByDayR');?></option-->
+			          <option value="yearly"><?php echo get_lang('RepeatYearly');?></option>
+			        </select>
+			      </td>
+			    </tr>
+			    <tr>
+							<td><label for="repeat_end_day"><?php echo get_lang('RepeatEnd');?></label></td>
+			            	<td>
+			            <select name="repeat_end_day">
+			                <?php
+			                    // small loop for filling all the dates
+			                    // 2do: the available dates should be those of the selected month => february is from 1 to 28 (or 29) and not to 31
+			                    echo "\n";
+			                    foreach (range(1, 31) as $i)
+			                    {
+			                        // values have to have double digits
+			                        $value = ($i <= 9 ? '0'.$i : $i );
+			                        // the current day is indicated with [] around the date
+			                        if ($value==$end_day)
+			                            { echo "\t\t\t\t <option value=\"".$value."\" selected> ".$i." </option>\n";}
+			                        else
+			                            { echo "\t\t\t\t <option value=\"".$value."\">".$i."</option>\n"; }
+			                        }?>
+			                </select>
+
+			                <!-- month: january -> december -->
+			                <select name="repeat_end_month">
+			                    <?php
+			                    echo "\n";
+			                    foreach (range(1, 12) as $i)
+			                    {
+			                        // values have to have double digits
+			                        $value = ($i <= 9 ? '0'.$i : $i );
+			                        if ($value==$end_month+1)
+			                            { echo "\t\t\t\t ",'<option value="',$value,'" selected="selected">',$MonthsLong[$i-1],"</option>\n"; }
+			                        else
+			                            { echo "\t\t\t\t ",'<option value="',$value,'">',$MonthsLong[$i-1],"</option>\n"; }
+			                        }?>
+			                </select>
+
+			                <select name="repeat_end_year">
+			                    <option value="<?php echo ($end_year-1) ?>"><?php echo ($end_year-1) ?></option>
+			                    <option value="<?php echo $end_year ?>" selected> <?php echo $end_year ?> </option>
+			                    <?php
+			                    echo "\n";
+			                    for ($i=1; $i<=5; $i++)
+			                    {
+			                        $value=$end_year+$i;
+			                        echo "\t\t\t\t<option value=\"$value\">$value</option>\n";
+			                    } ?>
+			            </select>
+			            		<a href="javascript:openCalendar('new_calendar_item', 'repeat_end_')"><?php Display::display_icon('calendar_select.gif', get_lang('Select'), array ('style' => 'vertical-align: middle;')); ?></a>
+								    </td>
+				    </tr>
+			    </table>
+<?php
+	echo '		</div>
+			</div>';
+    }//only show repeat fields if adding, not if editing
+
+
+    // the submit button for storing the calendar item
+    echo '		<div class="row">
+					<div class="label">
+			 </div>
+					<div class="formw">';
+		if(isset($_GET['id'])) {
+		$class='save';
+			$text=get_lang('ModifyEvent');
+		} else {
+		$class='add';
 			$text=get_lang('AgendaAdd');
-		}
-	echo '<button class="'.$class.'" type="button" name="name" onclick="selectAll(document.getElementById(\'selected_form\'),true)">'.$text.'</button>';
-	echo '			</div>
-				</div>';
-		?>
-	</form>
-<?php
-}
-
-function get_agendaitems($month, $year)
-{
-	global $_user;
-	global $_configuration;
-
-	$items = array ();
-	$month = Database::escape_string($month);
+		}
+	echo '<button class="'.$class.'" type="button" name="name" onclick="selectAll(document.getElementById(\'selected_form\'),true)">'.$text.'</button>';
+	echo '			</div>
+				</div>';
+		?>
+	</form>
+<?php
+}
+
+function get_agendaitems($month, $year)
+{
+	global $_user;
+	global $_configuration;
+
+	$items = array ();
+	$month = Database::escape_string($month);
 	$year = Database::escape_string($year);
 
-	//databases of the courses
-	$TABLEAGENDA 		= Database :: get_course_table(TABLE_AGENDA);
-	$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-
-	$group_memberships = GroupManager :: get_group_ids(Database::get_current_course_database(), $_user['user_id']);
-	// if the user is administrator of that course we show all the agenda items
-	if (api_is_allowed_to_edit(false,true)) {
-		//echo "course admin";
-
-		$sqlquery = "SELECT
-						DISTINCT agenda.*, item_property.*
-						FROM ".$TABLEAGENDA." agenda,
-							 ".$TABLE_ITEMPROPERTY." item_property
-						WHERE agenda.id = item_property.ref
-						AND MONTH(agenda.start_date)='".$month."'
-						AND YEAR(agenda.start_date)='".$year."'
-						AND item_property.tool='".TOOL_CALENDAR_EVENT."'
-						AND item_property.visibility='1'
-						GROUP BY agenda.id
-						ORDER BY start_date ";
-	}
-	// if the user is not an administrator of that course
-	else
-	{
-		//echo "GEEN course admin";
-		if (is_array($group_memberships) && count($group_memberships)>0)
-		{
-			$sqlquery = "SELECT
-							agenda.*, item_property.*
-							FROM ".$TABLEAGENDA." agenda,
-								".$TABLE_ITEMPROPERTY." item_property
-							WHERE agenda.id = item_property.ref
-							AND MONTH(agenda.start_date)='".$month."'
-							AND YEAR(agenda.start_date)='".$year."'
-							AND item_property.tool='".TOOL_CALENDAR_EVENT."'
-							AND	( item_property.to_user_id='".$_user['user_id']."' OR item_property.to_group_id IN (0, ".implode(", ", $group_memberships).") )
-							AND item_property.visibility='1'
-							ORDER BY start_date ";
-		}
-		else
-		{
-			$sqlquery = "SELECT
-							agenda.*, item_property.*
-							FROM ".$TABLEAGENDA." agenda,
-							".$TABLE_ITEMPROPERTY." item_property
-							WHERE agenda.id = item_property.ref
-							AND MONTH(agenda.start_date)='".$month."'
-							AND YEAR(agenda.start_date)='".$year."'
-							AND item_property.tool='".TOOL_CALENDAR_EVENT."'
-							AND ( item_property.to_user_id='".$_user['user_id']."' OR item_property.to_group_id='0')
-							AND item_property.visibility='1'
-							ORDER BY start_date ";
-		}
-	}
-
-	$mycourse = api_get_course_info();
-    $result = Database::query($sqlquery, __FILE__, __LINE__);
-    global $_configuration;
-   	$root_url = $_configuration['root_web'];
-	if ($_configuration['multiple_access_urls']==true) {
+	//databases of the courses
+	$TABLEAGENDA 		= Database :: get_course_table(TABLE_AGENDA);
+	$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
+
+	$group_memberships = GroupManager :: get_group_ids(Database::get_current_course_database(), $_user['user_id']);
+	// if the user is administrator of that course we show all the agenda items
+	if (api_is_allowed_to_edit(false,true)) {
+		//echo "course admin";
+
+		$sqlquery = "SELECT
+						DISTINCT agenda.*, item_property.*
+						FROM ".$TABLEAGENDA." agenda,
+							 ".$TABLE_ITEMPROPERTY." item_property
+						WHERE agenda.id = item_property.ref
+						AND MONTH(agenda.start_date)='".$month."'
+						AND YEAR(agenda.start_date)='".$year."'
+						AND item_property.tool='".TOOL_CALENDAR_EVENT."'
+						AND item_property.visibility='1'
+						GROUP BY agenda.id
+						ORDER BY start_date ";
+	}
+	// if the user is not an administrator of that course
+	else
+	{
+		//echo "GEEN course admin";
+		if (is_array($group_memberships) && count($group_memberships)>0)
+		{
+			$sqlquery = "SELECT
+							agenda.*, item_property.*
+							FROM ".$TABLEAGENDA." agenda,
+								".$TABLE_ITEMPROPERTY." item_property
+							WHERE agenda.id = item_property.ref
+							AND MONTH(agenda.start_date)='".$month."'
+							AND YEAR(agenda.start_date)='".$year."'
+							AND item_property.tool='".TOOL_CALENDAR_EVENT."'
+							AND	( item_property.to_user_id='".$_user['user_id']."' OR item_property.to_group_id IN (0, ".implode(", ", $group_memberships).") )
+							AND item_property.visibility='1'
+							ORDER BY start_date ";
+		}
+		else
+		{
+			$sqlquery = "SELECT
+							agenda.*, item_property.*
+							FROM ".$TABLEAGENDA." agenda,
+							".$TABLE_ITEMPROPERTY." item_property
+							WHERE agenda.id = item_property.ref
+							AND MONTH(agenda.start_date)='".$month."'
+							AND YEAR(agenda.start_date)='".$year."'
+							AND item_property.tool='".TOOL_CALENDAR_EVENT."'
+							AND ( item_property.to_user_id='".$_user['user_id']."' OR item_property.to_group_id='0')
+							AND item_property.visibility='1'
+							ORDER BY start_date ";
+		}
+	}
+
+	$mycourse = api_get_course_info();
+    $result = Database::query($sqlquery, __FILE__, __LINE__);
+    global $_configuration;
+   	$root_url = $_configuration['root_web'];
+	if ($_configuration['multiple_access_urls']==true) {
 		$access_url_id = api_get_current_access_url_id();
-		if ($access_url_id != -1 ){
+		if ($access_url_id != -1 ){
 			$url = api_get_access_url($access_url_id);
-			$root_url = $url['url'];
+			$root_url = $url['url'];
 		}
-	}
-
-	while ($item = Database::fetch_array($result))
-	{
-		$agendaday = date('j',strtotime($item['start_date']));
-		$time= date('H:i',strtotime($item['start_date']));
-		$URL = $root_url.'main/calendar/agenda.php?cidReq='.$mycourse['id']."&amp;day=$agendaday&amp;month=$month&amp;year=$year#$agendaday"; // RH  //Patrick Cool: to highlight the relevant agenda item
-		$items[$agendaday][$item['start_time']] .= '<i>'.$time.'</i> <a href="'.$URL.'" title="'.$mycourse['name'].'">'.$mycourse['official_code'].'</a> '.$item['title'].'<br />';
-	}
-
-	// sorting by hour for every day
-	$agendaitems = array ();
-	while (list ($agendaday, $tmpitems) = each($items))
-	{
-		sort($tmpitems);
-		while (list ($key, $val) = each($tmpitems))
-		{
-			$agendaitems[$agendaday] .= $val;
-		}
-	}
-	return $agendaitems;
-}
-
-function display_upcoming_events()
-{
-	echo '<b>'.get_lang('UpcomingEvent').'</b><br />';
-	$number_of_items_to_show = (int)api_get_setting('number_of_upcoming_events');
-
-	//databases of the courses
-	$TABLEAGENDA 		= Database :: get_course_table(TABLE_AGENDA);
-	$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-    $mycourse = api_get_course_info();
-    $myuser = api_get_user_info();
-
-	$group_memberships = GroupManager :: get_group_ids($mycourse['dbName'], $myuser['user_id']);
-	// if the user is administrator of that course we show all the agenda items
-	if (api_is_allowed_to_edit(false,true))
-	{
-		//echo "course admin";
-		$sqlquery = "SELECT
-						DISTINCT agenda.*, item_property.*
-						FROM ".$TABLEAGENDA." agenda,
-							 ".$TABLE_ITEMPROPERTY." item_property
-						WHERE agenda.id = item_property.ref
-						AND item_property.tool='".TOOL_CALENDAR_EVENT."'
-						AND item_property.visibility='1'
-						AND agenda.start_date > NOW()
-						GROUP BY agenda.id
-						ORDER BY start_date ";
-	}
-	// if the user is not an administrator of that course
-	else
-	{
-		//echo "GEEN course admin";
-		if (is_array($group_memberships) and count($group_memberships)>0)
-		{
-			$sqlquery = "SELECT
-							agenda.*, item_property.*
-							FROM ".$TABLEAGENDA." agenda,
-								".$TABLE_ITEMPROPERTY." item_property
-							WHERE agenda.id = item_property.ref
-							AND item_property.tool='".TOOL_CALENDAR_EVENT."'
-							AND	( item_property.to_user_id='".$myuser['user_id']."' OR item_property.to_group_id IN (0, ".implode(", ", $group_memberships).") )
-							AND item_property.visibility='1'
-							AND agenda.start_date > NOW()
-							ORDER BY start_date ";
-		}
-		else
-		{
-			$sqlquery = "SELECT
-							agenda.*, item_property.*
-							FROM ".$TABLEAGENDA." agenda,
-							".$TABLE_ITEMPROPERTY." item_property
-							WHERE agenda.id = item_property.ref
-							AND item_property.tool='".TOOL_CALENDAR_EVENT."'
-							AND ( item_property.to_user_id='".$myuser['user_id']."' OR item_property.to_group_id='0')
-							AND item_property.visibility='1'
-							AND agenda.start_date > NOW()
-							ORDER BY start_date ";
-		}
-	}
-	$result = Database::query($sqlquery, __FILE__, __LINE__);
-	$counter = 0;
-	while ($item = Database::fetch_array($result,'ASSOC'))
-	{
-		if ($counter < $number_of_items_to_show)
-		{
-			echo $item['start_date'],' - ',$item['title'],'<br />';
-			$counter++;
-		}
-	}
-}
-/**
- * This function calculates the startdate of the week (monday)
- * and the enddate of the week (sunday)
- * and returns it as an array
- */
-function calculate_start_end_of_week($week_number, $year)
-{
-	// determine the start and end date
-	// step 1: we calculate a timestamp for a day in this week
-	$random_day_in_week = mktime(0, 0, 0, 1, 1, $year) + ($week_number-1) * (7 * 24 * 60 * 60); // we calculate a random day in this week
-	// step 2: we which day this is (0=sunday, 1=monday, ...)
-	$number_day_in_week = date('w', $random_day_in_week);
-	// step 3: we calculate the timestamp of the monday of the week we are in
-	$start_timestamp = $random_day_in_week - (($number_day_in_week -1) * 24 * 60 * 60);
-	// step 4: we calculate the timestamp of the sunday of the week we are in
-	$end_timestamp = $random_day_in_week + ((7 - $number_day_in_week +1) * 24 * 60 * 60) - 3600;
-	// step 5: calculating the start_day, end_day, start_month, end_month, start_year, end_year
-	$start_day = date('j', $start_timestamp);
-	$start_month = date('n', $start_timestamp);
-	$start_year = date('Y', $start_timestamp);
-	$end_day = date('j', $end_timestamp);
-	$end_month = date('n', $end_timestamp);
-	$end_year = date('Y', $end_timestamp);
-	$start_end_array['start']['day'] = $start_day;
-	$start_end_array['start']['month'] = $start_month;
-	$start_end_array['start']['year'] = $start_year;
-	$start_end_array['end']['day'] = $end_day;
-	$start_end_array['end']['month'] = $end_month;
-	$start_end_array['end']['year'] = $end_year;
-	return $start_end_array;
-}
-/**
- * Show the mini calendar of the given month
- */
-function display_daycalendar($agendaitems, $day, $month, $year, $weekdaynames, $monthName)
-{
-	global $DaysShort, $DaysLong, $course_path;
-	global $MonthsLong;
-	global $query;
-
-	// timestamp of today
-	$today = mktime();
-	$nextday = $today + (24 * 60 * 60);
-	$previousday = $today - (24 * 60 * 60);
-	// the week number of the year
-	$week_number = date("W", $today);
-	// if we moved to the next / previous day we have to recalculate the $today variable
-	if ($_GET['day'])
-	{
-		$today = mktime(0, 0, 0, $month, $day, $year);
-		$nextday = $today + (24 * 60 * 60);
-		$previousday = $today - (24 * 60 * 60);
-		$week_number = date("W", $today);
-	}
-	// calculating the start date of the week
-	// the date of the monday of this week is the timestamp of today minus
-	// number of days that have already passed this week * 24 hours * 60 minutes * 60 seconds
-	$current_day = date("j", $today); // Day of the month without leading zeros (1 to 31) of today
-	$day_of_the_week = date("w", $today); // Numeric representation of the day of the week	0 (for Sunday) through 6 (for Saturday) of today
-	//$timestamp_first_date_of_week=$today-(($day_of_the_week-1)*24*60*60); // timestamp of the monday of this week
-	//$timestamp_last_date_of_week=$today+((7-$day_of_the_week)*24*60*60); // timestamp of the sunday of this week
-	// we are loading all the calendar items of all the courses for today
-	echo "<table class=\"data_table\">\n";
-	// the forward and backwards url
-	$backwardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=day&amp;day=".date("j", $previousday)."&amp;month=".date("n", $previousday)."&amp;year=".date("Y", $previousday);
-	$forewardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=day&amp;day=".date("j", $nextday)."&amp;month=".date("n", $nextday)."&amp;year=".date("Y", $nextday);
-	// The title row containing the day
-	echo "<tr>\n", "<th width=\"10%\"><a href=\"", $backwardsURL, "\">&#171;</a></th>\n", "<th>";
-	echo $DaysLong[$day_of_the_week]." ".date("j", $today)." ".$MonthsLong[date("n", $today) - 1]." ".date("Y", $today);
-	echo "</th>";
-	echo "<th width=\"10%\"><a href=\"", $forewardsURL, "\">&#187;</a></th>\n";
-	echo "</tr>\n";
-	// the rows for each half an hour
-	for ($i = 10; $i < 48; $i ++)
-	{
-		if ($i % 2 == 0)
-		{
-			$class = "class=\"row_even\"";
-		}
-		else
-		{
-			$class = "class=\"row_odd\"";
-		}
-		echo "<tr $class>\n";
-		echo "\t";
-		if ($i % 2 == 0)
-		{
-			echo ("<td valign=\"top\" width=\"75\">". (($i) / 2)." ".get_lang("HourShort")." 00</td>\n");
-		}
-		else
-		{
-			echo ("<td valign=\"top\" width=\"75\">". ((($i) / 2) - (1 / 2))." ".get_lang("HourShort")." 30</td>\n");
-		}
-		echo "\t<td $class valign=\"top\" colspan=\"2\">\n";
-		if (is_array($agendaitems[$i]))
-		{
-			foreach ($agendaitems[$i] as $key => $value)
-			{
-				echo $value;
-			}
-		}
-		else
-		{
-			echo $agendaitems[$i];
-		}
-		echo "\t</td>\n";
-		echo "</tr>\n";
-	}
-	echo "</table>\n";
-}
-/**
- *	Display the weekly view of the calendar
- */
-function display_weekcalendar($agendaitems, $month, $year, $weekdaynames, $monthName)
-{
-	global $DaysShort,$course_path;
-	global $MonthsLong;
-	// timestamp of today
-	$today = time();
-	$day_of_the_week = date("w", $today);
-	$thisday_of_the_week = date("w", $today);
-	// the week number of the year
-	$week_number = date("W", $today);
-	$thisweek_number = $week_number;
-	// if we moved to the next / previous week we have to recalculate the $today variable
-	if ($_GET['week'])
-	{
-		$today = mktime(0, 0, 0, 1, 1, $year);
-		$today = $today + (((int)$_GET['week']-1) * (7 * 24 * 60 * 60));
-		$week_number = date("W", $today);
-	}
-	// calculating the start date of the week
-	// the date of the monday of this week is the timestamp of today minus
-	// number of days that have already passed this week * 24 hours * 60 minutes * 60 seconds
-	$current_day = date("j", $today); // Day of the month without leading zeros (1 to 31) of today
-	$day_of_the_week = date("w", $today); // Numeric representation of the day of the week	0 (for Sunday) through 6 (for Saturday) of today
-	$timestamp_first_date_of_week = $today - (($day_of_the_week -1) * 24 * 60 * 60); // timestamp of the monday of this week
-	$timestamp_last_date_of_week = $today + ((7 - $day_of_the_week) * 24 * 60 * 60); // timestamp of the sunday of this week
-	$backwardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=week&amp;week=". ($week_number -1);
-	$forewardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=week&amp;week=". ($week_number +1);
-	echo "<table class=\"data_table\">\n";
-	// The title row containing the the week information (week of the year (startdate of week - enddate of week)
-	echo "<tr>\n";
-	echo "<th width=\"10%\"><a href=\"", $backwardsURL, "\">&#171;</a></th>\n";
-	echo "<th colspan=\"5\">".get_lang("Week")." ".$week_number;
-	echo " (".$DaysShort['1']." ".date("j", $timestamp_first_date_of_week)." ".$MonthsLong[date("n", $timestamp_first_date_of_week) - 1]." ".date("Y", $timestamp_first_date_of_week)." - ".$DaysShort['0']." ".date("j", $timestamp_last_date_of_week)." ".$MonthsLong[date("n", $timestamp_last_date_of_week) - 1]." ".date("Y", $timestamp_last_date_of_week).')';
-	echo "</th>";
-	echo "<th width=\"10%\"><a href=\"", $forewardsURL, "\">&#187;</a></th>\n", "</tr>\n";
-	// The second row containing the short names of the days of the week
-	echo "<tr>\n";
-	// this is the Day of the month without leading zeros (1 to 31) of the monday of this week
-	$tmp_timestamp = $timestamp_first_date_of_week;
-	for ($ii = 1; $ii < 8; $ii ++)
-	{
-		$is_today = ($ii == $thisday_of_the_week AND (!isset($_GET['week']) OR $_GET['week']==$thisweek_number));
-		echo "\t<td class=\"weekdays\">";
-		if ($is_today)
-		{
-			echo "<font color=#CC3300>";
-		}
-		echo $DaysShort[$ii % 7]." ".date("j", $tmp_timestamp)." ".$MonthsLong[date("n", $tmp_timestamp) - 1];
-		if ($is_today)
-		{
-			echo "</font>";
-		}
-		echo "</td>\n";
-		// we 24 hours * 60 minutes * 60 seconds to the $tmp_timestamp
-		$array_tmp_timestamp[] = $tmp_timestamp;
-		$tmp_timestamp = $tmp_timestamp + (24 * 60 * 60);
-	}
-	echo "</tr>\n";
-	// the table cells containing all the entries for that day
-	echo "<tr>\n";
-	$counter = 0;
-	foreach ($array_tmp_timestamp as $key => $value)
-	{
-		if ($counter < 5)
-		{
-			$class = "class=\"days_week\"";
-		}
-		else
-		{
-			$class = "class=\"days_weekend\"";
-		}
-		if ($counter == $thisday_of_the_week -1 AND (!isset($_GET['week']) OR $_GET['week']==$thisweek_number))
-		{
-			$class = "class=\"days_today\"";
-		}
-		echo "\t<td ".$class.">";
-		echo "<span class=\"agendaitem\">".$agendaitems[date('j', $value)]."&nbsp;</span> ";
-		echo "</td>\n";
-		$counter ++;
-	}
-	echo "</tr>\n";
-	echo "</table>\n";
-}
-/**
- * Show the monthcalender of the given month
- */
-function get_day_agendaitems($courses_dbs, $month, $year, $day)
-{
-	global $_user;
-	global $_configuration;
-	global $setting_agenda_link;
-
-	$items = array ();
-
-	// get agenda-items for every course
-	//$query=Database::query($sql_select_courses);
-	foreach ($courses_dbs as $key => $array_course_info)
-	{
-		//databases of the courses
-		$TABLEAGENDA = Database :: get_course_table(TABLE_AGENDA, $array_course_info['db']);
-		$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $array_course_info['db']);
-
-		// getting all the groups of the user for the current course
-		$group_memberships = GroupManager :: get_group_ids($array_course_info['db'], $_user['user_id']);
-		// if the user is administrator of that course we show all the agenda items
-		if ($array_course_info['status'] == '1')
-		{
-			//echo "course admin";
-			$sqlquery = "SELECT
-							DISTINCT agenda.*, item_property.*
-							FROM ".$TABLEAGENDA." agenda,
-								".$TABLE_ITEMPROPERTY." item_property
-							WHERE agenda.id = item_property.ref
-							AND DAYOFMONTH(start_date)='".$day."' AND MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
-							AND item_property.tool='".TOOL_CALENDAR_EVENT."'
-							AND item_property.visibility='1'
-							GROUP BY agenda.id
-							ORDER BY start_date ";
-		}
-		// if the user is not an administrator of that course
-		else
-		{
-			//echo "GEEN course admin";
-			if (is_array($group_memberships) && count($group_memberships)>0)
-			{
-				$sqlquery = "SELECT
-								agenda.*, item_property.*
-								FROM ".$TABLEAGENDA." agenda,
-									".$TABLE_ITEMPROPERTY." item_property
-								WHERE agenda.id = item_property.ref
-								AND DAYOFMONTH(start_date)='".$day."' AND MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
-								AND item_property.tool='".TOOL_CALENDAR_EVENT."'
-								AND	( item_property.to_user_id='".$_user['user_id']."' OR `item_property`.`to_group_id` IN (0, ".implode(", ", $group_memberships).") )
-								AND item_property.visibility='1'
-								ORDER BY start_date ";
-			}
-			else
-			{
-				$sqlquery = "SELECT
-								agenda.*, item_property.*
-								FROM ".$TABLEAGENDA." agenda,
-									".$TABLE_ITEMPROPERTY." item_property
-								WHERE agenda.id = item_property.ref
-								AND DAYOFMONTH(start_date)='".$day."' AND MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
-								AND item_property.tool='".TOOL_CALENDAR_EVENT."'
-								AND ( item_property.to_user_id='".$_user['user_id']."' OR item_property.to_group_id='0')
-								AND item_property.visibility='1'
-								ORDER BY start_date ";
-			}
-		}
-		//$sqlquery = "SELECT * FROM $agendadb WHERE DAYOFMONTH(day)='$day' AND month(day)='$month' AND year(day)='$year'";
-		//echo "abc";
-		//echo $sqlquery;
-		$result = Database::query($sqlquery, __FILE__, __LINE__);
-		//echo Database::num_rows($result);
-		while ($item = Database::fetch_array($result))
-		{
-			// in the display_daycalendar function we use $i (ranging from 0 to 47) for each halfhour
-			// we want to know for each agenda item for this day to wich halfhour it must be assigned
-			list ($datepart, $timepart) = split(" ", $item['start_date']);
-			list ($year, $month, $day) = explode("-", $datepart);
-			list ($hours, $minutes, $seconds) = explode(":", $timepart);
-
-			$halfhour = 2 * $hours;
-			if ($minutes >= '30')
-			{
-				$halfhour = $halfhour +1;
-			}
-
-			if ($setting_agenda_link == 'coursecode')
-			{
-				$title=$array_course_info['title'];
-				$agenda_link = cut($title,14,true);
-			}
-			else
-			{
-				$agenda_link = Display::return_icon('course_home.gif');
-			}
-
-			//$URL = $_configuration['root_web'].$mycours["dir"]."/";
-			$URL = $_configuration['root_web'].'main/calendar/agenda.php?cidReq='.urlencode($array_course_info["code"])."&amp;day=$day&amp;month=$month&amp;year=$year#$day"; // RH  //Patrick Cool: to highlight the relevant agenda item
-			$items[$halfhour][] .= "<i>".$hours.":".$minutes."</i> <a href=\"$URL\" title=\"".$array_course_info['name']."\">".$agenda_link."</a>  ".$item['title']."<br />";
-		}
-	}
-	// sorting by hour for every day
-	/*$agendaitems = array();
-	while (list($agendaday, $tmpitems) = each($items))
-	{
-		sort($tmpitems);
-		while (list($key,$val) = each($tmpitems))
-		{
-			$agendaitems[$agendaday].=$val;
-		}
-	}*/
-	$agendaitems = $items;
-	//print_r($agendaitems);
-	return $agendaitems;
-}
-/**
- * Return agenda items of the week
- */
-function get_week_agendaitems($courses_dbs, $month, $year, $week = '')
-{
-	global $TABLEAGENDA, $TABLE_ITEMPROPERTY;
-	global $_user;
-	global $_configuration;
-	global $setting_agenda_link;
-
-	$items = array ();
-	// The default value of the week
-	if ($week == '')
-	{
-		$week_number = date("W", time());
-	}
-	else
-	{
-		$week_number = $week;
-	}
-	$start_end = calculate_start_end_of_week($week_number, $year);
-	$start_filter = $start_end['start']['year']."-".$start_end['start']['month']."-".$start_end['start']['day'];
-	$end_filter = $start_end['end']['year']."-".$start_end['end']['month']."-".$start_end['end']['day'];
-	// get agenda-items for every course
-	foreach ($courses_dbs as $key => $array_course_info)
-	{
-		//databases of the courses
-		$TABLEAGENDA = Database :: get_course_table(TABLE_AGENDA, $array_course_info["db"]);
-		$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $array_course_info["db"]);
-
-		// getting all the groups of the user for the current course
-		$group_memberships = GroupManager :: get_group_ids($array_course_info["db"], $_user['user_id']);
-
-		// if the user is administrator of that course we show all the agenda items
-		if ($array_course_info['status'] == '1')
-		{
-			//echo "course admin";
-			$sqlquery = "SELECT
-							DISTINCT a.*, i.*
-							FROM ".$TABLEAGENDA." a,
-								".$TABLE_ITEMPROPERTY." i
-							WHERE a.id = i.ref
-							AND a.start_date>='".$start_filter."' AND a.start_date<='".$end_filter."'
-							AND i.tool='".TOOL_CALENDAR_EVENT."'
-							AND i.visibility='1'
-							GROUP BY a.id
-							ORDER BY a.start_date";
-		}
-		// if the user is not an administrator of that course
-		else
-		{
-			//echo "GEEN course admin";
-			if (is_array($group_memberships) && count($group_memberships)>0)
-			{
-				$sqlquery = "SELECT
-									a.*, i.*
-									FROM ".$TABLEAGENDA." a,
-										 ".$TABLE_ITEMPROPERTY." i
-									WHERE a.id = i.`ref`
-									AND a.start_date>='".$start_filter."' AND a.start_date<='".$end_filter."'
-									AND i.tool='".TOOL_CALENDAR_EVENT."'
-									AND	( i.to_user_id='".$_user['user_id']."' OR i.to_group_id IN (0, ".implode(", ", $group_memberships).") )
-									AND i.visibility='1'
-									ORDER BY a.start_date";
-			}
-			else
-			{
-				$sqlquery = "SELECT
-									a.*, i.*
-									FROM ".$TABLEAGENDA." a,
-										 ".$TABLE_ITEMPROPERTY." i
-									WHERE a.id = i.ref
-									AND a.start_date>='".$start_filter."' AND a.start_date<='".$end_filter."'
-									AND i.tool='".TOOL_CALENDAR_EVENT."'
-									AND ( i.to_user_id='".$_user['user_id']."' OR i.to_group_id='0')
-									AND i.visibility='1'
-									ORDER BY a.start_date";
-			}
-		}
-		//echo "<pre>".$sqlquery."</pre>";
-		// $sqlquery = "SELECT * FROM $agendadb WHERE (DAYOFMONTH(day)>='$start_day' AND DAYOFMONTH(day)<='$end_day')
-		//				AND (MONTH(day)>='$start_month' AND MONTH(day)<='$end_month')
-		//				AND (YEAR(day)>='$start_year' AND YEAR(day)<='$end_year')";
-		$result = Database::query($sqlquery, __FILE__, __LINE__);
-		while ($item = Database::fetch_array($result))
-		{
-			$agendaday = date("j",strtotime($item['start_date']));
-			$time= date("H:i",strtotime($item['start_date']));
-
-			if ($setting_agenda_link == 'coursecode')
-			{
-				$title=$array_course_info['title'];
-				$agenda_link = cut($title, 14, true);
-			}
-			else
-			{
-				$agenda_link = Display::return_icon('course_home.gif');
-			}
-
-			$URL = $_configuration['root_web']."main/calendar/agenda.php?cidReq=".urlencode($array_course_info["code"])."&amp;day=$agendaday&amp;month=$month&amp;year=$year#$agendaday"; // RH  //Patrick Cool: to highlight the relevant agenda item
-			//Display the events in agenda
-			$items[$agendaday][$item['start_date']] .= "<i>$time</i> <a href=\"$URL\" title=\"".$array_course_info["name"]."\">".$agenda_link."</a>";
-			$items[$agendaday][$item['start_date']] .= "<div>".$item['title']."</div><br>";
-
-		}
-	}
-	// sorting by hour for every day
-	$agendaitems = array ();
-	while (list ($agendaday, $tmpitems) = each($items))
-	{
-		sort($tmpitems);
-		while (list ($key, $val) = each($tmpitems))
-		{
-			$agendaitems[$agendaday] .= $val;
-		}
-	}
-	//print_r($agendaitems);
-	return $agendaitems;
-}
-/**
- * Get repeated events of a course between two dates (timespan of a day).
- * Returns an array containing the events
- * @param   string  Course info array (as returned by api_get_course_info())
- * @param	int		UNIX timestamp of span start. Defaults 0, later transformed into today's start
- * @param	int		UNIX timestamp. Defaults to 0, later transformed into today's end
- * @param   array   A set of parameters to alter the SQL query
- * @return	array	[int] => [course_id,parent_event_id,start_date,end_date,title,description]
- */
-function get_repeated_events_day_view($course_info,$start=0,$end=0,$params)
-{
-	$events = array();
-	//initialise all values
-	$y=0;
-	$m=0;
-	$d=0;
-    //block $end if higher than 2038 -- PHP doesn't go past that
-    if($end>2145934800){$end = 2145934800;}
-	if($start == 0 or $end == 0)
-	{
-		$y=date('Y');
-		$m=date('m');
-		$d=date('j');
-	}
-	if($start==0)
-	{
-		$start = mktime(0,0,0,$m,$d,$y);
-	}
-	$db_start = date('Y-m-d H:i:s',$start);
-	if($end==0)
-	{
-		$end = mktime(23,59,59,$m,$d,$y);
-	}
-	//$db_end = date('Y-m-d H:i:s',$end);
-
-	$t_cal = Database::get_course_table(TABLE_AGENDA,$course_info['dbName']);
-	$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
-    $t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
-	$sql = "SELECT c.id, c.title, c.content, " .
-			" UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
-			" cr.cal_type, cr.cal_end " .
-			" FROM $t_cal c, $t_cal_repeat cr, $t_ip as item_property " .
-			" WHERE cr.cal_end >= $start " .
-			" AND cr.cal_id = c.id " .
-            " AND item_property.ref = c.id ".
-            " AND item_property.tool = '".TOOL_CALENDAR_EVENT."' ".
-			" AND c.start_date <= '$db_start' "
-            .(!empty($params['conditions'])?$params['conditions']:'')
-            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
-            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
-	$res = Database::query($sql,__FILE__,__LINE__);
-	if(Database::num_rows($res)>0)
-	{
-		while($row = Database::fetch_array($res))
-		{
-			$orig_start = $row['orig_start'];
-			$orig_end = $row['orig_end'];
-			$repeat_type = $row['cal_type'];
-			switch($repeat_type)
-			{
-				case 'daily':
-					//we are in the daily view, so if this element is repeated daily and
-					//the repetition is still active today (which is a condition of the SQL query)
-					//then the event happens today. Just build today's timestamp for start and end
-					$time_orig_h = date('H',$orig_start);
-					$time_orig_m = date('i',$orig_start);
-					$time_orig_s = date('s',$orig_start);
-					$int_time = (($time_orig_h*60)+$time_orig_m)*60+$time_orig_s; //time in seconds since 00:00:00
-					$span = $orig_end - $orig_start; //total seconds between start and stop of original event
-					$current_start =$start + $int_time; //unixtimestamp start of today's event
-					$current_stop = $start+$int_time+$span; //unixtimestamp stop of today's event
-					$events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
-					break;
-				case 'weekly':
-					$time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/W/j/N/G/i/s',$end);
-					list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig))) && ($dw_orig == $dw_now))
-					{ //if the event is after the original (at least one week) and the day of the week is the same
-					  $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				case 'monthlyByDate':
-					$time_orig = date('Y/n/j/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/j/G/i/s',$end);
-					list($y_now,$m_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig))) && ($d_orig == $d_now))
-					{
-					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				case 'monthlyByDayR':
-					//not implemented yet
-					break;
-				case 'monthlyByDay':
-					//not implemented yet
-					break;
-				case 'yearly':
-					$time_orig = date('Y/n/j/z/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/j/z/G/i/s',$end);
-					list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					if(($y_now>$y_orig) && ($dy_orig == $dy_now))
-					{
-					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				default:
-					break;
-			}
-		}
-	}
-	return $events;
-}
-/**
- * Get repeated events of a course between two dates (timespan of a week).
- * Returns an array containing the events
- * @param	string	Course info array (as returned by api_get_course_info())
- * @param	int		UNIX timestamp of span start. Defaults 0, later transformed into today's start
- * @param	int		UNIX timestamp. Defaults to 0, later transformed into today's end
- * @param   array   A set of parameters to alter the SQL query
- * @return	array	[int] => [course_id,parent_event_id,start_date,end_date,title,description]
- */
-function get_repeated_events_week_view($course_info,$start=0,$end=0,$params)
-{
-	$events = array();
-    //block $end if higher than 2038 -- PHP doesn't go past that
-    if($end>2145934800){$end = 2145934800;}
-	//initialise all values
-	$y=0;
-	$m=0;
-	$d=0;
-	if($start == 0 or $end == 0)
-	{
-		$time = time();
-		$dw = date('w',$time);
-		$week_start = $time - (($dw-1)*86400);
-		$y = date('Y',$week_start);
-		$m = date('m',$week_start);
-		$d = date('j',$week_start);
-		$w = date('W',$week_start);
-	}
-	if($start==0)
-	{
-		$start = mktime(0,0,0,$m,$d,$y);
-	}
-	$db_start = date('Y-m-d H:i:s',$start);
-	if($end==0)
-	{
-		$end = $start+(86400*7)-1; //start of week, more 7 days, minus 1 second to get back to the previoyus day
-	}
-	//$db_end = date('Y-m-d H:i:s',$end);
-
-	$t_cal = Database::get_course_table(TABLE_AGENDA,$course_info['dbName']);
-	$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
-    $t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
-    $sql = "SELECT c.id, c.title, c.content, " .
-            " UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
-            " cr.cal_type, cr.cal_end " .
-            " FROM $t_cal c, $t_cal_repeat cr, $t_ip as item_property " .
-            " WHERE cr.cal_end >= $start " .
-            " AND cr.cal_id = c.id " .
-            " AND item_property.ref = c.id ".
-            " AND item_property.tool = '".TOOL_CALENDAR_EVENT."' ".
-            " AND c.start_date <= '$db_start' "
-            .(!empty($params['conditions'])?$params['conditions']:'')
-            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
-            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
-	$res = Database::query($sql,__FILE__,__LINE__);
-	if(Database::num_rows($res)>0)
-	{
-		while($row = Database::fetch_array($res))
-		{
-			$orig_start = $row['orig_start'];
-			$orig_end = $row['orig_end'];
-			$repeat_type = $row['cal_type'];
-			switch($repeat_type)
-			{
-				case 'daily':
-					$time_orig_h = date('H',$orig_start);
-					$time_orig_m = date('i',$orig_start);
-					$time_orig_s = date('s',$orig_start);
-					$int_time = (($time_orig_h*60)+$time_orig_m)*60+$time_orig_s; //time in seconds since 00:00:00
-					$span = $orig_end - $orig_start; //total seconds between start and stop of original event
-					for($i=0;$i<7;$i++)
-					{
-						$current_start = $start + ($i*86400) + $int_time; //unixtimestamp start of today's event
-						$current_stop = $start + ($i*86400) + $int_time + $span; //unixtimestamp stop of today's event
-						$events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
-					}
-					break;
-				case 'weekly':
-					$time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/W/j/N/G/i/s',$end);
-					list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig))))
-					{ //if the event is after the original (at least one week) and the day of the week is the same
-					  $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				case 'monthlyByDate':
-					$time_orig = date('Y/n/W/j/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$w_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/W/j/G/i/s',$end);
-					list($y_now,$m_now,$w_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
-					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig))) && ($start<$event_repetition_time && $event_repetition_time<$end))
-					{ //if the event is after the original (at least one month) and the original event's day is between the first day of the week and the last day of the week
-					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				case 'monthlyByDayR':
-					//not implemented yet
-					break;
-				case 'monthlyByDay':
-					//not implemented yet
-					break;
-				case 'yearly':
-					$time_orig = date('Y/n/j/z/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/j/z/G/i/s',$end);
-					list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
-					if((($y_now>$y_orig) && ($start<$event_repetition_time && $event_repetition_time<$end)))
-					{
-					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				default:
-					break;
-			}
-		}
-	}
-	return $events;
-}
-/**
- * Get repeated events of a course between two dates (timespan of a month).
- * Returns an array containing the events
- * @param   string  Course info array (as returned by api_get_course_info())
- * @param	int		UNIX timestamp of span start. Defaults 0, later transformed into today's start
- * @param	int		UNIX timestamp. Defaults to 0, later transformed into today's end
- * @param   array   A set of parameters to alter the SQL query
- * @return	array	[int] => [course_id,parent_event_id,start_date,end_date,title,description]
- */
-function get_repeated_events_month_view($course_info,$start=0,$end=0,$params)
-{
-	$events = array();
-    //block $end if higher than 2038 -- PHP doesn't go past that
-    if($end>2145934800){$end = 2145934800;}
-	//initialise all values
-	$y=0;
-	$m=0;
-	$d=0;
-	if($start == 0 or $end == 0)
-	{
-		$time = time();
-		$y = date('Y');
-		$m = date('m');
-	}
-	if($start==0)
-	{
-		$start = mktime(0,0,0,$m,1,$y);
-	}
-	$db_start = date('Y-m-d H:i:s',$start);
-	if($end==0)
-	{
-		if($m==12)
-		{
-			$end = mktime(0,0,0,1,1,$y+1)-1; //start of next month, minus 1 second to get back to the previoyus day
-		}
-		else
-		{
-			$end = mktime(0,0,0,$m+1,1,$y)-1;
-		}
-	}
-	//$db_end = date('Y-m-d H:i:s',$end);
-
-	$t_cal = Database::get_course_table(TABLE_AGENDA,$course_info['dbName']);
-	$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
-    $t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
-    $sql = "SELECT c.id, c.title, c.content, " .
-            " UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
-            " cr.cal_type, cr.cal_end " .
-            " FROM $t_cal c, $t_cal_repeat cr, $t_ip as item_property " .
-            " WHERE cr.cal_end >= $start " .
-            " AND cr.cal_id = c.id " .
-            " AND item_property.ref = c.id ".
-            " AND item_property.tool = '".TOOL_CALENDAR_EVENT."' ".
-            " AND c.start_date <= '$db_start' "
-            .(!empty($params['conditions'])?$params['conditions']:'')
-            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
-            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
-	$res = Database::query($sql,__FILE__,__LINE__);
-	if(Database::num_rows($res)>0)
-	{
-		while($row = Database::fetch_array($res))
-		{
-			$orig_start = $row['orig_start'];
-			$orig_end = $row['orig_end'];
-			$repeat_type = $row['cal_type'];
-			switch($repeat_type)
-			{
-				case 'daily':
-					$time_orig_h = date('H',$orig_start);
-					$time_orig_m = date('i',$orig_start);
-					$time_orig_s = date('s',$orig_start);
-					$month_last_day = date('d',$end);
-					$int_time = (($time_orig_h*60)+$time_orig_m)*60+$time_orig_s; //time in seconds since 00:00:00
-					$span = $orig_end - $orig_start; //total seconds between start and stop of original event
-					for($i=0;$i<$month_last_day;$i++)
-					{
-						$current_start = $start + ($i*86400) + $int_time; //unixtimestamp start of today's event
-						$current_stop = $start + ($i*86400) + $int_time + $span; //unixtimestamp stop of today's event
-						$events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
-					}
-					break;
-				case 'weekly':
-					//A weekly repeated event is very difficult to catch in a month view,
-					//because weeks start before or at the same time as the first day of the month
-					//The same can be said for the end of the month.
-					// The idea is thus to get all possible events by enlarging the scope of
-					// the month to get complete weeks covering the complete month, and then take out
-					// the events that start before the 1st ($start) or after the last day of the month ($end)
-					$time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-                    $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
-                    list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-
-					$time_now = date('Y/n/W/j/N/G/i/s',$end);
-					list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-
-					$month_first_week = date('W',$start);
-					$month_last_week = date('W',$end);
-
-					if(($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig)))
-					{ //if the event is after the original (at least one week) and the day of the week is the same
-						for($i=$month_first_week;$i<=$month_last_week;$i++)
-						{
-						  //the "day of the week" of repetition is the same as the $dw_orig,
-                          //so to get the "day of the month" from the "day of the week", we have
-                          //to get the first "day of the week" for this week and add the number
-                          //of days (in seconds) to reach the $dw_orig
-                          //example: the first week spans between the 28th of April (Monday) to the
-                          // 4th of May (Sunday). The event occurs on the 2nd day of each week.
-                          // This means the event occurs on 29/4, 6/5, 13/5, 20/5 and 27/5.
-                          // We want to get all of these, and then reject 29/4 because it is out
-                          // of the month itself.
-
-                          //First, to get the start time of the first day of the month view (even if
-                          // the day is from the past month), we get the month start date (1/5) and
-                          // see which day of the week it is, and subtract the number of days necessary
-                          // to get back to the first day of the week.
-                          $month_first_day_weekday = date('N',$start);
-                          $first_week_start = $start - (($month_first_day_weekday-1)*86400);
-
-                          //Second, we add the week day of the original event, so that we have an
-                          // absolute time that represents the first repetition of the event in
-                          // our 4- or 5-weeks timespan
-                          $first_event_repeat_start = $first_week_start + (($dw_orig-1)*86400) + ($h_orig*3600) + ($n_orig*60) + $s_orig;
-
-                          //Third, we start looping through the repetitions and see if they are between
-                          // $start and $end
-					      for($i = $first_event_repeat_start; $i<=$end; $i+=604800)
-                          {
-                          	if($start<$i && $i<$end)
-                            {
-                               list($y_repeat,$m_repeat,$d_repeat,$h_repeat,$n_repeat,$s_repeat) = split('/',date('Y/m/j/H/i/s',$i));
-                               $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-                            }
-                          }
-						}
-					}
-					break;
-				case 'monthlyByDate':
-					$time_orig = date('Y/n/W/j/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$w_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/W/j/G/i/s',$end);
-					list($y_now,$m_now,$w_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
-					if(($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig)))
-					{ //if the event is after the original (at least one month) and the original event's day is between the first day of the week and the last day of the week
-					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				case 'monthlyByDayR':
-					//not implemented yet
-					break;
-				case 'monthlyByDay':
-					//not implemented yet
-					break;
-				case 'yearly':
-					$time_orig = date('Y/n/j/z/G/i/s',$orig_start);
-					list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-					$time_now = date('Y/n/j/z/G/i/s',$end);
-					list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
-					if((($y_now>$y_orig) && ($start<$event_repetition_time && $event_repetition_time<$end)))
-					{
-					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-					  list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-					}
-					break;
-				default:
-					break;
-			}
-		}
-	}
-	return $events;
-}
-/**
- * Get repeated events of a course between two dates (1 year timespan). Used for the list display.
- * This is virtually unlimited but by default it shortens to 100 years from now (even a birthday shouldn't be useful more than this time - except for turtles)
- * Returns an array containing the events
- * @param   string  Course info array (as returned by api_get_course_info())
- * @param   int     UNIX timestamp of span start. Defaults 0, later transformed into today's start
- * @param   int     UNIX timestamp. Defaults to 0, later transformed into today's end
- * @param   array   A set of parameters to alter the SQL query
- * @return  array   [int] => [course_id,parent_event_id,start_date,end_date,title,description]
- */
-function get_repeated_events_list_view($course_info,$start=0,$end=0,$params)
-{
-    $events = array();
-    //block $end if higher than 2038 -- PHP doesn't go past that
-    if($end>2145934800){$end = 2145934800;}
-    //initialise all values
-    $y=0;
-    $m=0;
-    $d=0;
-    if(empty($start) or empty($end))
-    {
-        $time = time();
-        $y = date('Y');
-        $m = date('m');
-    }
-    if(empty($start))
-    {
-        $start = mktime(0, 0, 0, $m, 1, $y);
-    }
-    $db_start = date('Y-m-d H:i:s', $start);
-    if(empty($end))
-    {
-        $end = mktime(0, 0, 0, 1, 1, 2037);
-    }
-    //$db_end = date('Y-m-d H:i:s',$end);
-
-    $t_cal = Database::get_course_table(TABLE_AGENDA,$course_info['dbName']);
-    $t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
-    $t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
-    $sql = "SELECT c.id, c.title, c.content, " .
-            " UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
-            " cr.cal_type, cr.cal_end " .
-            " FROM $t_cal c, $t_cal_repeat cr, $t_ip as item_property " .
-            " WHERE cr.cal_end >= $start " .
-            " AND cr.cal_id = c.id " .
-            " AND item_property.ref = c.id ".
-            " AND item_property.tool = '".TOOL_CALENDAR_EVENT."' ".
-            " AND c.start_date <= '$db_start' "
-            .(!empty($params['conditions'])?$params['conditions']:'')
-            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
-            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
-    $res = Database::query($sql,__FILE__,__LINE__);
-    if(Database::num_rows($res)>0)
-    {
-        while($row = Database::fetch_array($res))
-        {
-            $orig_start = $row['orig_start'];
-            $orig_end = $row['orig_end'];
-            $repeat_type = $row['cal_type'];
-            $repeat_end = $row['cal_end'];
-            switch($repeat_type)
-            {
-                case 'daily':
-                    $time_orig_h = date('H',$orig_start);
-                    $time_orig_m = date('i',$orig_start);
-                    $time_orig_s = date('s',$orig_start);
-                    $span = $orig_end - $orig_start; //total seconds between start and stop of original event
-                    for($i=$orig_start+86400;($i<$end && $i<=$repeat_end);$i+=86400)
-                    {
-                        $current_start = $i; //unixtimestamp start of today's event
-                        $current_stop = $i + $span; //unixtimestamp stop of today's event
-                        $events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
-                    }
-                    break;
-                case 'weekly':
-                    //A weekly repeated event is very difficult to catch in a month view,
-                    // because weeks start before or at the same time as the first day of the month
-                    //The same can be said for the end of the month.
-                    // The idea is thus to get all possible events by enlarging the scope of
-                    // the month to get complete weeks covering the complete month, and then take out
-                    // the events that start before the 1st ($start) or after the last day of the month ($end)
-                    $time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
-                    list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-                    $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
-                    list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-
-                    $time_now = date('Y/n/W/j/N/G/i/s',$end);
-                    list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-                    if($w_now==52)
-                    {
-                        ++$y_now;
-                        $w_now=1;
-                    }
-                    else
-                    {
-                        ++$w_now;
-                    }
-                    $month_first_week = date('W',$start);
-                    $total_weeks = ((date('Y',$end)-$y_orig)-1)*52;
-                    $month_last_week = $month_first_week + $total_weeks;
-
-                    if(($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig)))
-                    { //if the event is after the original (at least one week) and the day of the week is the same
-                        //for($i=$month_first_week;($i<=$month_last_week && $i<1000);$i++)
-                        //{
-
-
-                          /*
-                           The "day of the week" of repetition is the same as the $dw_orig,
-                           so to get the "day of the month" from the "day of the week", we have
-                           to get the first "day of the week" for this week and add the number
-                           of days (in seconds) to reach the $dw_orig
-                          example: the first week spans between the 28th of April (Monday) to the
-                           4th of May (Sunday). The event occurs on the 2nd day of each week.
-                           This means the event occurs on 29/4, 6/5, 13/5, 20/5 and 27/5.
-                           We want to get all of these, and then reject 29/4 because it is out
-                           of the month itself.
-                          First, to get the start time of the first day of the month view (even if
-                           the day is from the past month), we get the month start date (1/5) and
-                           see which day of the week it is, and subtract the number of days necessary
-                           to get back to the first day of the week.
-                          */
-                          $month_first_day_weekday = date('N',$start);
-                          $first_week_start = $start - (($month_first_day_weekday-1)*86400);
-
-                          //Second, we add the week day of the original event, so that we have an
-                          // absolute time that represents the first repetition of the event in
-                          // our 4- or 5-weeks timespan
-                          $first_event_repeat_start = $first_week_start + (($dw_orig-1)*86400) + ($h_orig*3600) + ($n_orig*60) + $s_orig;
-
-                          //Third, we start looping through the repetitions and see if they are between
-                          // $start and $end
-                          for($i = $first_event_repeat_start; ($i<=$end && $i<=$repeat_end); $i+=604800)
-                          {
-                            if($start<$i && $i<=$end && $i<=$repeat_end)
-                            {
-                               list($y_repeat,$m_repeat,$d_repeat,$h_repeat,$n_repeat,$s_repeat) = split('/',date('Y/m/j/H/i/s',$i));
-                               $new_start_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
-                               $new_stop_time = mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now);
-                               $events[] = array($course_info['id'], $row['id'], $new_start_time, $new_stop_time, $row['title'], $row['content']);
-                            }
-                            $time_now = date('Y/n/W/j/N/G/i/s',$i+604800);
-                            list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-                          }
-                        //}
-                    }
-                    break;
-                case 'monthlyByDate':
-                    $time_orig = date('Y/n/W/j/G/i/s',$orig_start);
-                    list($y_orig,$m_orig,$w_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-
-                    $time_now = date('Y/n/W/j/G/i/s',$start);
-                    list($y_now,$m_now,$w_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-                    //make sure we are one month ahead (to avoid being the same month as the original event)
-                    if($m_now==12)
-                    {
-                        ++$y_now;
-                        $m_now = 1;
-                    }
-                    else
-                    {
-                        ++$m_now;
-                    }
-
-                    $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-                    list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-
-                    $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
-                    $diff = $orig_end - $orig_start;
-                    while((($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig))) && ($event_repetition_time < $end) && ($event_repetition_time < $repeat_end))
-                    { //if the event is after the original (at least one month) and the original event's day is between the first day of the week and the last day of the week
-                      $new_start_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
-                      $new_stop_time = mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now);
-                      $events[] = array($course_info['id'],$row['id'],$new_start_time,$new_stop_time,$row['title'],$row['content']);
-                      if($m_now==12)
-                      {
-                      	++$y_now;
-                        $m_now = 1;
-                      }
-                      else
-                      {
-                        ++$m_now;
-                      }
-                      $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
-                    }
-                    break;
-                case 'monthlyByDayR':
-                    //not implemented yet
-                    break;
-                case 'monthlyByDay':
-                    //not implemented yet
-                    break;
-                case 'yearly':
-                    $time_orig = date('Y/n/j/z/G/i/s',$orig_start);
-                    list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-                    $time_now = date('Y/n/j/z/G/i/s',$end);
-                    list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-                    $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
-                    while((($y_now>$y_orig) && ($start<$event_repetition_time && $event_repetition_time<$end && $event_repetition_time<$repeat_end)))
-                    {
-                      $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
-                      list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
-                      $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
-                      ++$y_now;
-                      $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
-                    }
-                    break;
-                default:
-                    break;
-            }
-        }
-    }
-    return $events;
-}
-/**
- * Tells if an agenda item is repeated
- * @param   string  Course database
- * @param   int     The agenda item
- * @return  boolean True if repeated, false otherwise
- */
-function is_repeated_event($id,$course=null)
-{
-	if(empty($course))
-    {
-    	$course_info = api_get_course_info();
-        $course = $course_info['dbName'];
-    }
-    $id = (int) $id;
-	$t_agenda_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course);
-    $sql = "SELECT * FROM $t_agenda_repeat WHERE cal_id = $id";
-    $res = Database::query($sql,__FILE__,__LINE__);
-    if(Database::num_rows($res)>0)
-    {
-    	return true;
-    }
-    return false;
-}
-/**
- * Adds x weeks to a UNIX timestamp
- * @param   int     The timestamp
- * @param   int     The number of weeks to add
- * @return  int     The new timestamp
- */
-function add_week($timestamp,$num=1)
-{
-    return $timestamp + $num*604800;
-}
-/**
- * Adds x months to a UNIX timestamp
- * @param   int     The timestamp
- * @param   int     The number of years to add
- * @return  int     The new timestamp
- */
-function add_month($timestamp,$num=1)
-{
-	list($y, $m, $d, $h, $n, $s) = split('/',date('Y/m/d/h/i/s',$timestamp));
-    if($m+$num>12)
-    {
-    	$y += floor($num/12);
-        $m += $num%12;
-    }
-    else
-    {
-        $m += $num;
-    }
-    return mktime($h, $n, $s, $m, $d, $y);
-}
-/**
- * Adds x years to a UNIX timestamp
- * @param   int     The timestamp
- * @param   int     The number of years to add
- * @return  int     The new timestamp
- */
-function add_year($timestamp,$num=1)
-{
-    list($y, $m, $d, $h, $n, $s) = split('/',date('Y/m/d/h/i/s',$timestamp));
-    return mktime($h, $n, $s, $m, $d, $y+$num);
-}
-/**
- * Adds an agenda item in the database. Similar to store_new_agenda_item() except it takes parameters
- * @param   array   Course info
- * @param   string  Event title
- * @param   string  Event content/description
- * @param   string  Start date
- * @param   string  End date
- * @param   array   List of groups to which this event is added
- * @param   int     Parent id (optional)
- * @return  int     The new item's DB ID
- */
-function agenda_add_item($course_info, $title, $content, $db_start_date, $db_end_date,$to=array(), $parent_id=null,$file_comment='')
-{
-	global $_course;
-    $user_id    = api_get_user_id();
-
-    // database table definitions
-    $t_agenda   = Database::get_course_table(TABLE_AGENDA,$course_info['dbName']);
-    $agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
-    $item_property 				=	Database::get_course_table(TABLE_ITEM_PROPERTY);
-
-    // some filtering of the input data
-    $content=stripslashes($content);
-	$title=Database::escape_string(Security::remove_XSS($title));
+	}
+
+	while ($item = Database::fetch_array($result))
+	{
+		$agendaday = date('j',strtotime($item['start_date']));
+		$time= date('H:i',strtotime($item['start_date']));
+		$URL = $root_url.'main/calendar/agenda.php?cidReq='.$mycourse['id']."&amp;day=$agendaday&amp;month=$month&amp;year=$year#$agendaday"; // RH  //Patrick Cool: to highlight the relevant agenda item
+		$items[$agendaday][$item['start_time']] .= '<i>'.$time.'</i> <a href="'.$URL.'" title="'.$mycourse['name'].'">'.$mycourse['official_code'].'</a> '.$item['title'].'<br />';
+	}
+
+	// sorting by hour for every day
+	$agendaitems = array ();
+	while (list ($agendaday, $tmpitems) = each($items))
+	{
+		sort($tmpitems);
+		while (list ($key, $val) = each($tmpitems))
+		{
+			$agendaitems[$agendaday] .= $val;
+		}
+	}
+	return $agendaitems;
+}
+
+function display_upcoming_events()
+{
+	echo '<b>'.get_lang('UpcomingEvent').'</b><br />';
+	$number_of_items_to_show = (int)api_get_setting('number_of_upcoming_events');
+
+	//databases of the courses
+	$TABLEAGENDA 		= Database :: get_course_table(TABLE_AGENDA);
+	$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
+    $mycourse = api_get_course_info();
+    $myuser = api_get_user_info();
+
+	$group_memberships = GroupManager :: get_group_ids($mycourse['dbName'], $myuser['user_id']);
+	// if the user is administrator of that course we show all the agenda items
+	if (api_is_allowed_to_edit(false,true))
+	{
+		//echo "course admin";
+		$sqlquery = "SELECT
+						DISTINCT agenda.*, item_property.*
+						FROM ".$TABLEAGENDA." agenda,
+							 ".$TABLE_ITEMPROPERTY." item_property
+						WHERE agenda.id = item_property.ref
+						AND item_property.tool='".TOOL_CALENDAR_EVENT."'
+						AND item_property.visibility='1'
+						AND agenda.start_date > NOW()
+						GROUP BY agenda.id
+						ORDER BY start_date ";
+	}
+	// if the user is not an administrator of that course
+	else
+	{
+		//echo "GEEN course admin";
+		if (is_array($group_memberships) and count($group_memberships)>0)
+		{
+			$sqlquery = "SELECT
+							agenda.*, item_property.*
+							FROM ".$TABLEAGENDA." agenda,
+								".$TABLE_ITEMPROPERTY." item_property
+							WHERE agenda.id = item_property.ref
+							AND item_property.tool='".TOOL_CALENDAR_EVENT."'
+							AND	( item_property.to_user_id='".$myuser['user_id']."' OR item_property.to_group_id IN (0, ".implode(", ", $group_memberships).") )
+							AND item_property.visibility='1'
+							AND agenda.start_date > NOW()
+							ORDER BY start_date ";
+		}
+		else
+		{
+			$sqlquery = "SELECT
+							agenda.*, item_property.*
+							FROM ".$TABLEAGENDA." agenda,
+							".$TABLE_ITEMPROPERTY." item_property
+							WHERE agenda.id = item_property.ref
+							AND item_property.tool='".TOOL_CALENDAR_EVENT."'
+							AND ( item_property.to_user_id='".$myuser['user_id']."' OR item_property.to_group_id='0')
+							AND item_property.visibility='1'
+							AND agenda.start_date > NOW()
+							ORDER BY start_date ";
+		}
+	}
+	$result = Database::query($sqlquery, __FILE__, __LINE__);
+	$counter = 0;
+	while ($item = Database::fetch_array($result,'ASSOC'))
+	{
+		if ($counter < $number_of_items_to_show)
+		{
+			echo $item['start_date'],' - ',$item['title'],'<br />';
+			$counter++;
+		}
+	}
+}
+/**
+ * This function calculates the startdate of the week (monday)
+ * and the enddate of the week (sunday)
+ * and returns it as an array
+ */
+function calculate_start_end_of_week($week_number, $year)
+{
+	// determine the start and end date
+	// step 1: we calculate a timestamp for a day in this week
+	$random_day_in_week = mktime(0, 0, 0, 1, 1, $year) + ($week_number-1) * (7 * 24 * 60 * 60); // we calculate a random day in this week
+	// step 2: we which day this is (0=sunday, 1=monday, ...)
+	$number_day_in_week = date('w', $random_day_in_week);
+	// step 3: we calculate the timestamp of the monday of the week we are in
+	$start_timestamp = $random_day_in_week - (($number_day_in_week -1) * 24 * 60 * 60);
+	// step 4: we calculate the timestamp of the sunday of the week we are in
+	$end_timestamp = $random_day_in_week + ((7 - $number_day_in_week +1) * 24 * 60 * 60) - 3600;
+	// step 5: calculating the start_day, end_day, start_month, end_month, start_year, end_year
+	$start_day = date('j', $start_timestamp);
+	$start_month = date('n', $start_timestamp);
+	$start_year = date('Y', $start_timestamp);
+	$end_day = date('j', $end_timestamp);
+	$end_month = date('n', $end_timestamp);
+	$end_year = date('Y', $end_timestamp);
+	$start_end_array['start']['day'] = $start_day;
+	$start_end_array['start']['month'] = $start_month;
+	$start_end_array['start']['year'] = $start_year;
+	$start_end_array['end']['day'] = $end_day;
+	$start_end_array['end']['month'] = $end_month;
+	$start_end_array['end']['year'] = $end_year;
+	return $start_end_array;
+}
+/**
+ * Show the mini calendar of the given month
+ */
+function display_daycalendar($agendaitems, $day, $month, $year, $weekdaynames, $monthName)
+{
+	global $DaysShort, $DaysLong, $course_path;
+	global $MonthsLong;
+	global $query;
+
+	// timestamp of today
+	$today = mktime();
+	$nextday = $today + (24 * 60 * 60);
+	$previousday = $today - (24 * 60 * 60);
+	// the week number of the year
+	$week_number = date("W", $today);
+	// if we moved to the next / previous day we have to recalculate the $today variable
+	if ($_GET['day'])
+	{
+		$today = mktime(0, 0, 0, $month, $day, $year);
+		$nextday = $today + (24 * 60 * 60);
+		$previousday = $today - (24 * 60 * 60);
+		$week_number = date("W", $today);
+	}
+	// calculating the start date of the week
+	// the date of the monday of this week is the timestamp of today minus
+	// number of days that have already passed this week * 24 hours * 60 minutes * 60 seconds
+	$current_day = date("j", $today); // Day of the month without leading zeros (1 to 31) of today
+	$day_of_the_week = date("w", $today); // Numeric representation of the day of the week	0 (for Sunday) through 6 (for Saturday) of today
+	//$timestamp_first_date_of_week=$today-(($day_of_the_week-1)*24*60*60); // timestamp of the monday of this week
+	//$timestamp_last_date_of_week=$today+((7-$day_of_the_week)*24*60*60); // timestamp of the sunday of this week
+	// we are loading all the calendar items of all the courses for today
+	echo "<table class=\"data_table\">\n";
+	// the forward and backwards url
+	$backwardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=day&amp;day=".date("j", $previousday)."&amp;month=".date("n", $previousday)."&amp;year=".date("Y", $previousday);
+	$forewardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=day&amp;day=".date("j", $nextday)."&amp;month=".date("n", $nextday)."&amp;year=".date("Y", $nextday);
+	// The title row containing the day
+	echo "<tr>\n", "<th width=\"10%\"><a href=\"", $backwardsURL, "\">&#171;</a></th>\n", "<th>";
+	echo $DaysLong[$day_of_the_week]." ".date("j", $today)." ".$MonthsLong[date("n", $today) - 1]." ".date("Y", $today);
+	echo "</th>";
+	echo "<th width=\"10%\"><a href=\"", $forewardsURL, "\">&#187;</a></th>\n";
+	echo "</tr>\n";
+	// the rows for each half an hour
+	for ($i = 10; $i < 48; $i ++)
+	{
+		if ($i % 2 == 0)
+		{
+			$class = "class=\"row_even\"";
+		}
+		else
+		{
+			$class = "class=\"row_odd\"";
+		}
+		echo "<tr $class>\n";
+		echo "\t";
+		if ($i % 2 == 0)
+		{
+			echo ("<td valign=\"top\" width=\"75\">". (($i) / 2)." ".get_lang("HourShort")." 00</td>\n");
+		}
+		else
+		{
+			echo ("<td valign=\"top\" width=\"75\">". ((($i) / 2) - (1 / 2))." ".get_lang("HourShort")." 30</td>\n");
+		}
+		echo "\t<td $class valign=\"top\" colspan=\"2\">\n";
+		if (is_array($agendaitems[$i]))
+		{
+			foreach ($agendaitems[$i] as $key => $value)
+			{
+				echo $value;
+			}
+		}
+		else
+		{
+			echo $agendaitems[$i];
+		}
+		echo "\t</td>\n";
+		echo "</tr>\n";
+	}
+	echo "</table>\n";
+}
+/**
+ *	Display the weekly view of the calendar
+ */
+function display_weekcalendar($agendaitems, $month, $year, $weekdaynames, $monthName)
+{
+	global $DaysShort,$course_path;
+	global $MonthsLong;
+	// timestamp of today
+	$today = time();
+	$day_of_the_week = date("w", $today);
+	$thisday_of_the_week = date("w", $today);
+	// the week number of the year
+	$week_number = date("W", $today);
+	$thisweek_number = $week_number;
+	// if we moved to the next / previous week we have to recalculate the $today variable
+	if ($_GET['week'])
+	{
+		$today = mktime(0, 0, 0, 1, 1, $year);
+		$today = $today + (((int)$_GET['week']-1) * (7 * 24 * 60 * 60));
+		$week_number = date("W", $today);
+	}
+	// calculating the start date of the week
+	// the date of the monday of this week is the timestamp of today minus
+	// number of days that have already passed this week * 24 hours * 60 minutes * 60 seconds
+	$current_day = date("j", $today); // Day of the month without leading zeros (1 to 31) of today
+	$day_of_the_week = date("w", $today); // Numeric representation of the day of the week	0 (for Sunday) through 6 (for Saturday) of today
+	$timestamp_first_date_of_week = $today - (($day_of_the_week -1) * 24 * 60 * 60); // timestamp of the monday of this week
+	$timestamp_last_date_of_week = $today + ((7 - $day_of_the_week) * 24 * 60 * 60); // timestamp of the sunday of this week
+	$backwardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=week&amp;week=". ($week_number -1);
+	$forewardsURL = api_get_self()."?coursePath=".urlencode($course_path)."&amp;courseCode=".Security::remove_XSS($_GET['courseCode'])."&amp;action=view&amp;view=week&amp;week=". ($week_number +1);
+	echo "<table class=\"data_table\">\n";
+	// The title row containing the the week information (week of the year (startdate of week - enddate of week)
+	echo "<tr>\n";
+	echo "<th width=\"10%\"><a href=\"", $backwardsURL, "\">&#171;</a></th>\n";
+	echo "<th colspan=\"5\">".get_lang("Week")." ".$week_number;
+	echo " (".$DaysShort['1']." ".date("j", $timestamp_first_date_of_week)." ".$MonthsLong[date("n", $timestamp_first_date_of_week) - 1]." ".date("Y", $timestamp_first_date_of_week)." - ".$DaysShort['0']." ".date("j", $timestamp_last_date_of_week)." ".$MonthsLong[date("n", $timestamp_last_date_of_week) - 1]." ".date("Y", $timestamp_last_date_of_week).')';
+	echo "</th>";
+	echo "<th width=\"10%\"><a href=\"", $forewardsURL, "\">&#187;</a></th>\n", "</tr>\n";
+	// The second row containing the short names of the days of the week
+	echo "<tr>\n";
+	// this is the Day of the month without leading zeros (1 to 31) of the monday of this week
+	$tmp_timestamp = $timestamp_first_date_of_week;
+	for ($ii = 1; $ii < 8; $ii ++)
+	{
+		$is_today = ($ii == $thisday_of_the_week AND (!isset($_GET['week']) OR $_GET['week']==$thisweek_number));
+		echo "\t<td class=\"weekdays\">";
+		if ($is_today)
+		{
+			echo "<font color=#CC3300>";
+		}
+		echo $DaysShort[$ii % 7]." ".date("j", $tmp_timestamp)." ".$MonthsLong[date("n", $tmp_timestamp) - 1];
+		if ($is_today)
+		{
+			echo "</font>";
+		}
+		echo "</td>\n";
+		// we 24 hours * 60 minutes * 60 seconds to the $tmp_timestamp
+		$array_tmp_timestamp[] = $tmp_timestamp;
+		$tmp_timestamp = $tmp_timestamp + (24 * 60 * 60);
+	}
+	echo "</tr>\n";
+	// the table cells containing all the entries for that day
+	echo "<tr>\n";
+	$counter = 0;
+	foreach ($array_tmp_timestamp as $key => $value)
+	{
+		if ($counter < 5)
+		{
+			$class = "class=\"days_week\"";
+		}
+		else
+		{
+			$class = "class=\"days_weekend\"";
+		}
+		if ($counter == $thisday_of_the_week -1 AND (!isset($_GET['week']) OR $_GET['week']==$thisweek_number))
+		{
+			$class = "class=\"days_today\"";
+		}
+		echo "\t<td ".$class.">";
+		echo "<span class=\"agendaitem\">".$agendaitems[date('j', $value)]."&nbsp;</span> ";
+		echo "</td>\n";
+		$counter ++;
+	}
+	echo "</tr>\n";
+	echo "</table>\n";
+}
+/**
+ * Show the monthcalender of the given month
+ */
+function get_day_agendaitems($courses_dbs, $month, $year, $day)
+{
+	global $_user;
+	global $_configuration;
+	global $setting_agenda_link;
+
+	$items = array ();
+
+	// get agenda-items for every course
+	//$query=Database::query($sql_select_courses);
+	foreach ($courses_dbs as $key => $array_course_info)
+	{
+		//databases of the courses
+		$TABLEAGENDA = Database :: get_course_table(TABLE_AGENDA, $array_course_info['db']);
+		$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $array_course_info['db']);
+
+		// getting all the groups of the user for the current course
+		$group_memberships = GroupManager :: get_group_ids($array_course_info['db'], $_user['user_id']);
+		// if the user is administrator of that course we show all the agenda items
+		if ($array_course_info['status'] == '1')
+		{
+			//echo "course admin";
+			$sqlquery = "SELECT
+							DISTINCT agenda.*, item_property.*
+							FROM ".$TABLEAGENDA." agenda,
+								".$TABLE_ITEMPROPERTY." item_property
+							WHERE agenda.id = item_property.ref
+							AND DAYOFMONTH(start_date)='".$day."' AND MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
+							AND item_property.tool='".TOOL_CALENDAR_EVENT."'
+							AND item_property.visibility='1'
+							GROUP BY agenda.id
+							ORDER BY start_date ";
+		}
+		// if the user is not an administrator of that course
+		else
+		{
+			//echo "GEEN course admin";
+			if (is_array($group_memberships) && count($group_memberships)>0)
+			{
+				$sqlquery = "SELECT
+								agenda.*, item_property.*
+								FROM ".$TABLEAGENDA." agenda,
+									".$TABLE_ITEMPROPERTY." item_property
+								WHERE agenda.id = item_property.ref
+								AND DAYOFMONTH(start_date)='".$day."' AND MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
+								AND item_property.tool='".TOOL_CALENDAR_EVENT."'
+								AND	( item_property.to_user_id='".$_user['user_id']."' OR `item_property`.`to_group_id` IN (0, ".implode(", ", $group_memberships).") )
+								AND item_property.visibility='1'
+								ORDER BY start_date ";
+			}
+			else
+			{
+				$sqlquery = "SELECT
+								agenda.*, item_property.*
+								FROM ".$TABLEAGENDA." agenda,
+									".$TABLE_ITEMPROPERTY." item_property
+								WHERE agenda.id = item_property.ref
+								AND DAYOFMONTH(start_date)='".$day."' AND MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
+								AND item_property.tool='".TOOL_CALENDAR_EVENT."'
+								AND ( item_property.to_user_id='".$_user['user_id']."' OR item_property.to_group_id='0')
+								AND item_property.visibility='1'
+								ORDER BY start_date ";
+			}
+		}
+		//$sqlquery = "SELECT * FROM $agendadb WHERE DAYOFMONTH(day)='$day' AND month(day)='$month' AND year(day)='$year'";
+		//echo "abc";
+		//echo $sqlquery;
+		$result = Database::query($sqlquery, __FILE__, __LINE__);
+		//echo Database::num_rows($result);
+		while ($item = Database::fetch_array($result))
+		{
+			// in the display_daycalendar function we use $i (ranging from 0 to 47) for each halfhour
+			// we want to know for each agenda item for this day to wich halfhour it must be assigned
+			list ($datepart, $timepart) = split(" ", $item['start_date']);
+			list ($year, $month, $day) = explode("-", $datepart);
+			list ($hours, $minutes, $seconds) = explode(":", $timepart);
+
+			$halfhour = 2 * $hours;
+			if ($minutes >= '30')
+			{
+				$halfhour = $halfhour +1;
+			}
+
+			if ($setting_agenda_link == 'coursecode')
+			{
+				$title=$array_course_info['title'];
+				$agenda_link = cut($title,14,true);
+			}
+			else
+			{
+				$agenda_link = Display::return_icon('course_home.gif');
+			}
+
+			//$URL = $_configuration['root_web'].$mycours["dir"]."/";
+			$URL = $_configuration['root_web'].'main/calendar/agenda.php?cidReq='.urlencode($array_course_info["code"])."&amp;day=$day&amp;month=$month&amp;year=$year#$day"; // RH  //Patrick Cool: to highlight the relevant agenda item
+			$items[$halfhour][] .= "<i>".$hours.":".$minutes."</i> <a href=\"$URL\" title=\"".$array_course_info['name']."\">".$agenda_link."</a>  ".$item['title']."<br />";
+		}
+	}
+	// sorting by hour for every day
+	/*$agendaitems = array();
+	while (list($agendaday, $tmpitems) = each($items))
+	{
+		sort($tmpitems);
+		while (list($key,$val) = each($tmpitems))
+		{
+			$agendaitems[$agendaday].=$val;
+		}
+	}*/
+	$agendaitems = $items;
+	//print_r($agendaitems);
+	return $agendaitems;
+}
+/**
+ * Return agenda items of the week
+ */
+function get_week_agendaitems($courses_dbs, $month, $year, $week = '')
+{
+	global $TABLEAGENDA, $TABLE_ITEMPROPERTY;
+	global $_user;
+	global $_configuration;
+	global $setting_agenda_link;
+
+	$items = array ();
+	// The default value of the week
+	if ($week == '')
+	{
+		$week_number = date("W", time());
+	}
+	else
+	{
+		$week_number = $week;
+	}
+	$start_end = calculate_start_end_of_week($week_number, $year);
+	$start_filter = $start_end['start']['year']."-".$start_end['start']['month']."-".$start_end['start']['day'];
+	$end_filter = $start_end['end']['year']."-".$start_end['end']['month']."-".$start_end['end']['day'];
+	// get agenda-items for every course
+	foreach ($courses_dbs as $key => $array_course_info)
+	{
+		//databases of the courses
+		$TABLEAGENDA = Database :: get_course_table(TABLE_AGENDA, $array_course_info["db"]);
+		$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $array_course_info["db"]);
+
+		// getting all the groups of the user for the current course
+		$group_memberships = GroupManager :: get_group_ids($array_course_info["db"], $_user['user_id']);
+
+		// if the user is administrator of that course we show all the agenda items
+		if ($array_course_info['status'] == '1')
+		{
+			//echo "course admin";
+			$sqlquery = "SELECT
+							DISTINCT a.*, i.*
+							FROM ".$TABLEAGENDA." a,
+								".$TABLE_ITEMPROPERTY." i
+							WHERE a.id = i.ref
+							AND a.start_date>='".$start_filter."' AND a.start_date<='".$end_filter."'
+							AND i.tool='".TOOL_CALENDAR_EVENT."'
+							AND i.visibility='1'
+							GROUP BY a.id
+							ORDER BY a.start_date";
+		}
+		// if the user is not an administrator of that course
+		else
+		{
+			//echo "GEEN course admin";
+			if (is_array($group_memberships) && count($group_memberships)>0)
+			{
+				$sqlquery = "SELECT
+									a.*, i.*
+									FROM ".$TABLEAGENDA." a,
+										 ".$TABLE_ITEMPROPERTY." i
+									WHERE a.id = i.`ref`
+									AND a.start_date>='".$start_filter."' AND a.start_date<='".$end_filter."'
+									AND i.tool='".TOOL_CALENDAR_EVENT."'
+									AND	( i.to_user_id='".$_user['user_id']."' OR i.to_group_id IN (0, ".implode(", ", $group_memberships).") )
+									AND i.visibility='1'
+									ORDER BY a.start_date";
+			}
+			else
+			{
+				$sqlquery = "SELECT
+									a.*, i.*
+									FROM ".$TABLEAGENDA." a,
+										 ".$TABLE_ITEMPROPERTY." i
+									WHERE a.id = i.ref
+									AND a.start_date>='".$start_filter."' AND a.start_date<='".$end_filter."'
+									AND i.tool='".TOOL_CALENDAR_EVENT."'
+									AND ( i.to_user_id='".$_user['user_id']."' OR i.to_group_id='0')
+									AND i.visibility='1'
+									ORDER BY a.start_date";
+			}
+		}
+		//echo "<pre>".$sqlquery."</pre>";
+		// $sqlquery = "SELECT * FROM $agendadb WHERE (DAYOFMONTH(day)>='$start_day' AND DAYOFMONTH(day)<='$end_day')
+		//				AND (MONTH(day)>='$start_month' AND MONTH(day)<='$end_month')
+		//				AND (YEAR(day)>='$start_year' AND YEAR(day)<='$end_year')";
+		$result = Database::query($sqlquery, __FILE__, __LINE__);
+		while ($item = Database::fetch_array($result))
+		{
+			$agendaday = date("j",strtotime($item['start_date']));
+			$time= date("H:i",strtotime($item['start_date']));
+
+			if ($setting_agenda_link == 'coursecode')
+			{
+				$title=$array_course_info['title'];
+				$agenda_link = cut($title, 14, true);
+			}
+			else
+			{
+				$agenda_link = Display::return_icon('course_home.gif');
+			}
+
+			$URL = $_configuration['root_web']."main/calendar/agenda.php?cidReq=".urlencode($array_course_info["code"])."&amp;day=$agendaday&amp;month=$month&amp;year=$year#$agendaday"; // RH  //Patrick Cool: to highlight the relevant agenda item
+			//Display the events in agenda
+			$items[$agendaday][$item['start_date']] .= "<i>$time</i> <a href=\"$URL\" title=\"".$array_course_info["name"]."\">".$agenda_link."</a>";
+			$items[$agendaday][$item['start_date']] .= "<div>".$item['title']."</div><br>";
+
+		}
+	}
+	// sorting by hour for every day
+	$agendaitems = array ();
+	while (list ($agendaday, $tmpitems) = each($items))
+	{
+		sort($tmpitems);
+		while (list ($key, $val) = each($tmpitems))
+		{
+			$agendaitems[$agendaday] .= $val;
+		}
+	}
+	//print_r($agendaitems);
+	return $agendaitems;
+}
+/**
+ * Get repeated events of a course between two dates (timespan of a day).
+ * Returns an array containing the events
+ * @param   string  Course info array (as returned by api_get_course_info())
+ * @param	int		UNIX timestamp of span start. Defaults 0, later transformed into today's start
+ * @param	int		UNIX timestamp. Defaults to 0, later transformed into today's end
+ * @param   array   A set of parameters to alter the SQL query
+ * @return	array	[int] => [course_id,parent_event_id,start_date,end_date,title,description]
+ */
+function get_repeated_events_day_view($course_info,$start=0,$end=0,$params)
+{
+	$events = array();
+	//initialise all values
+	$y=0;
+	$m=0;
+	$d=0;
+    //block $end if higher than 2038 -- PHP doesn't go past that
+    if($end>2145934800){$end = 2145934800;}
+	if($start == 0 or $end == 0)
+	{
+		$y=date('Y');
+		$m=date('m');
+		$d=date('j');
+	}
+	if($start==0)
+	{
+		$start = mktime(0,0,0,$m,$d,$y);
+	}
+	$db_start = date('Y-m-d H:i:s',$start);
+	if($end==0)
+	{
+		$end = mktime(23,59,59,$m,$d,$y);
+	}
+	//$db_end = date('Y-m-d H:i:s',$end);
+
+	$t_cal = Database::get_course_table(TABLE_AGENDA,$course_info['dbName']);
+	$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
+    $t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
+	$sql = "SELECT c.id, c.title, c.content, " .
+			" UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
+			" cr.cal_type, cr.cal_end " .
+			" FROM $t_cal c, $t_cal_repeat cr, $t_ip as item_property " .
+			" WHERE cr.cal_end >= $start " .
+			" AND cr.cal_id = c.id " .
+            " AND item_property.ref = c.id ".
+            " AND item_property.tool = '".TOOL_CALENDAR_EVENT."' ".
+			" AND c.start_date <= '$db_start' "
+            .(!empty($params['conditions'])?$params['conditions']:'')
+            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
+            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
+	$res = Database::query($sql,__FILE__,__LINE__);
+	if(Database::num_rows($res)>0)
+	{
+		while($row = Database::fetch_array($res))
+		{
+			$orig_start = $row['orig_start'];
+			$orig_end = $row['orig_end'];
+			$repeat_type = $row['cal_type'];
+			switch($repeat_type)
+			{
+				case 'daily':
+					//we are in the daily view, so if this element is repeated daily and
+					//the repetition is still active today (which is a condition of the SQL query)
+					//then the event happens today. Just build today's timestamp for start and end
+					$time_orig_h = date('H',$orig_start);
+					$time_orig_m = date('i',$orig_start);
+					$time_orig_s = date('s',$orig_start);
+					$int_time = (($time_orig_h*60)+$time_orig_m)*60+$time_orig_s; //time in seconds since 00:00:00
+					$span = $orig_end - $orig_start; //total seconds between start and stop of original event
+					$current_start =$start + $int_time; //unixtimestamp start of today's event
+					$current_stop = $start+$int_time+$span; //unixtimestamp stop of today's event
+					$events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
+					break;
+				case 'weekly':
+					$time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/W/j/N/G/i/s',$end);
+					list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig))) && ($dw_orig == $dw_now))
+					{ //if the event is after the original (at least one week) and the day of the week is the same
+					  $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				case 'monthlyByDate':
+					$time_orig = date('Y/n/j/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/j/G/i/s',$end);
+					list($y_now,$m_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig))) && ($d_orig == $d_now))
+					{
+					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				case 'monthlyByDayR':
+					//not implemented yet
+					break;
+				case 'monthlyByDay':
+					//not implemented yet
+					break;
+				case 'yearly':
+					$time_orig = date('Y/n/j/z/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/j/z/G/i/s',$end);
+					list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					if(($y_now>$y_orig) && ($dy_orig == $dy_now))
+					{
+					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				default:
+					break;
+			}
+		}
+	}
+	return $events;
+}
+/**
+ * Get repeated events of a course between two dates (timespan of a week).
+ * Returns an array containing the events
+ * @param	string	Course info array (as returned by api_get_course_info())
+ * @param	int		UNIX timestamp of span start. Defaults 0, later transformed into today's start
+ * @param	int		UNIX timestamp. Defaults to 0, later transformed into today's end
+ * @param   array   A set of parameters to alter the SQL query
+ * @return	array	[int] => [course_id,parent_event_id,start_date,end_date,title,description]
+ */
+function get_repeated_events_week_view($course_info,$start=0,$end=0,$params)
+{
+	$events = array();
+    //block $end if higher than 2038 -- PHP doesn't go past that
+    if($end>2145934800){$end = 2145934800;}
+	//initialise all values
+	$y=0;
+	$m=0;
+	$d=0;
+	if($start == 0 or $end == 0)
+	{
+		$time = time();
+		$dw = date('w',$time);
+		$week_start = $time - (($dw-1)*86400);
+		$y = date('Y',$week_start);
+		$m = date('m',$week_start);
+		$d = date('j',$week_start);
+		$w = date('W',$week_start);
+	}
+	if($start==0)
+	{
+		$start = mktime(0,0,0,$m,$d,$y);
+	}
+	$db_start = date('Y-m-d H:i:s',$start);
+	if($end==0)
+	{
+		$end = $start+(86400*7)-1; //start of week, more 7 days, minus 1 second to get back to the previoyus day
+	}
+	//$db_end = date('Y-m-d H:i:s',$end);
+
+	$t_cal = Database::get_course_table(TABLE_AGENDA,$course_info['dbName']);
+	$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
+    $t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
+    $sql = "SELECT c.id, c.title, c.content, " .
+            " UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
+            " cr.cal_type, cr.cal_end " .
+            " FROM $t_cal c, $t_cal_repeat cr, $t_ip as item_property " .
+            " WHERE cr.cal_end >= $start " .
+            " AND cr.cal_id = c.id " .
+            " AND item_property.ref = c.id ".
+            " AND item_property.tool = '".TOOL_CALENDAR_EVENT."' ".
+            " AND c.start_date <= '$db_start' "
+            .(!empty($params['conditions'])?$params['conditions']:'')
+            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
+            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
+	$res = Database::query($sql,__FILE__,__LINE__);
+	if(Database::num_rows($res)>0)
+	{
+		while($row = Database::fetch_array($res))
+		{
+			$orig_start = $row['orig_start'];
+			$orig_end = $row['orig_end'];
+			$repeat_type = $row['cal_type'];
+			switch($repeat_type)
+			{
+				case 'daily':
+					$time_orig_h = date('H',$orig_start);
+					$time_orig_m = date('i',$orig_start);
+					$time_orig_s = date('s',$orig_start);
+					$int_time = (($time_orig_h*60)+$time_orig_m)*60+$time_orig_s; //time in seconds since 00:00:00
+					$span = $orig_end - $orig_start; //total seconds between start and stop of original event
+					for($i=0;$i<7;$i++)
+					{
+						$current_start = $start + ($i*86400) + $int_time; //unixtimestamp start of today's event
+						$current_stop = $start + ($i*86400) + $int_time + $span; //unixtimestamp stop of today's event
+						$events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
+					}
+					break;
+				case 'weekly':
+					$time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/W/j/N/G/i/s',$end);
+					list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig))))
+					{ //if the event is after the original (at least one week) and the day of the week is the same
+					  $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				case 'monthlyByDate':
+					$time_orig = date('Y/n/W/j/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$w_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/W/j/G/i/s',$end);
+					list($y_now,$m_now,$w_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
+					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig))) && ($start<$event_repetition_time && $event_repetition_time<$end))
+					{ //if the event is after the original (at least one month) and the original event's day is between the first day of the week and the last day of the week
+					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				case 'monthlyByDayR':
+					//not implemented yet
+					break;
+				case 'monthlyByDay':
+					//not implemented yet
+					break;
+				case 'yearly':
+					$time_orig = date('Y/n/j/z/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/j/z/G/i/s',$end);
+					list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
+					if((($y_now>$y_orig) && ($start<$event_repetition_time && $event_repetition_time<$end)))
+					{
+					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				default:
+					break;
+			}
+		}
+	}
+	return $events;
+}
+/**
+ * Get repeated events of a course between two dates (timespan of a month).
+ * Returns an array containing the events
+ * @param   string  Course info array (as returned by api_get_course_info())
+ * @param	int		UNIX timestamp of span start. Defaults 0, later transformed into today's start
+ * @param	int		UNIX timestamp. Defaults to 0, later transformed into today's end
+ * @param   array   A set of parameters to alter the SQL query
+ * @return	array	[int] => [course_id,parent_event_id,start_date,end_date,title,description]
+ */
+function get_repeated_events_month_view($course_info,$start=0,$end=0,$params)
+{
+	$events = array();
+    //block $end if higher than 2038 -- PHP doesn't go past that
+    if($end>2145934800){$end = 2145934800;}
+	//initialise all values
+	$y=0;
+	$m=0;
+	$d=0;
+	if($start == 0 or $end == 0)
+	{
+		$time = time();
+		$y = date('Y');
+		$m = date('m');
+	}
+	if($start==0)
+	{
+		$start = mktime(0,0,0,$m,1,$y);
+	}
+	$db_start = date('Y-m-d H:i:s',$start);
+	if($end==0)
+	{
+		if($m==12)
+		{
+			$end = mktime(0,0,0,1,1,$y+1)-1; //start of next month, minus 1 second to get back to the previoyus day
+		}
+		else
+		{
+			$end = mktime(0,0,0,$m+1,1,$y)-1;
+		}
+	}
+	//$db_end = date('Y-m-d H:i:s',$end);
+
+	$t_cal = Database::get_course_table(TABLE_AGENDA,$course_info['dbName']);
+	$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
+    $t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
+    $sql = "SELECT c.id, c.title, c.content, " .
+            " UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
+            " cr.cal_type, cr.cal_end " .
+            " FROM $t_cal c, $t_cal_repeat cr, $t_ip as item_property " .
+            " WHERE cr.cal_end >= $start " .
+            " AND cr.cal_id = c.id " .
+            " AND item_property.ref = c.id ".
+            " AND item_property.tool = '".TOOL_CALENDAR_EVENT."' ".
+            " AND c.start_date <= '$db_start' "
+            .(!empty($params['conditions'])?$params['conditions']:'')
+            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
+            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
+	$res = Database::query($sql,__FILE__,__LINE__);
+	if(Database::num_rows($res)>0)
+	{
+		while($row = Database::fetch_array($res))
+		{
+			$orig_start = $row['orig_start'];
+			$orig_end = $row['orig_end'];
+			$repeat_type = $row['cal_type'];
+			switch($repeat_type)
+			{
+				case 'daily':
+					$time_orig_h = date('H',$orig_start);
+					$time_orig_m = date('i',$orig_start);
+					$time_orig_s = date('s',$orig_start);
+					$month_last_day = date('d',$end);
+					$int_time = (($time_orig_h*60)+$time_orig_m)*60+$time_orig_s; //time in seconds since 00:00:00
+					$span = $orig_end - $orig_start; //total seconds between start and stop of original event
+					for($i=0;$i<$month_last_day;$i++)
+					{
+						$current_start = $start + ($i*86400) + $int_time; //unixtimestamp start of today's event
+						$current_stop = $start + ($i*86400) + $int_time + $span; //unixtimestamp stop of today's event
+						$events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
+					}
+					break;
+				case 'weekly':
+					//A weekly repeated event is very difficult to catch in a month view,
+					//because weeks start before or at the same time as the first day of the month
+					//The same can be said for the end of the month.
+					// The idea is thus to get all possible events by enlarging the scope of
+					// the month to get complete weeks covering the complete month, and then take out
+					// the events that start before the 1st ($start) or after the last day of the month ($end)
+					$time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+                    $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
+                    list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+
+					$time_now = date('Y/n/W/j/N/G/i/s',$end);
+					list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+
+					$month_first_week = date('W',$start);
+					$month_last_week = date('W',$end);
+
+					if(($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig)))
+					{ //if the event is after the original (at least one week) and the day of the week is the same
+						for($i=$month_first_week;$i<=$month_last_week;$i++)
+						{
+						  //the "day of the week" of repetition is the same as the $dw_orig,
+                          //so to get the "day of the month" from the "day of the week", we have
+                          //to get the first "day of the week" for this week and add the number
+                          //of days (in seconds) to reach the $dw_orig
+                          //example: the first week spans between the 28th of April (Monday) to the
+                          // 4th of May (Sunday). The event occurs on the 2nd day of each week.
+                          // This means the event occurs on 29/4, 6/5, 13/5, 20/5 and 27/5.
+                          // We want to get all of these, and then reject 29/4 because it is out
+                          // of the month itself.
+
+                          //First, to get the start time of the first day of the month view (even if
+                          // the day is from the past month), we get the month start date (1/5) and
+                          // see which day of the week it is, and subtract the number of days necessary
+                          // to get back to the first day of the week.
+                          $month_first_day_weekday = date('N',$start);
+                          $first_week_start = $start - (($month_first_day_weekday-1)*86400);
+
+                          //Second, we add the week day of the original event, so that we have an
+                          // absolute time that represents the first repetition of the event in
+                          // our 4- or 5-weeks timespan
+                          $first_event_repeat_start = $first_week_start + (($dw_orig-1)*86400) + ($h_orig*3600) + ($n_orig*60) + $s_orig;
+
+                          //Third, we start looping through the repetitions and see if they are between
+                          // $start and $end
+					      for($i = $first_event_repeat_start; $i<=$end; $i+=604800)
+                          {
+                          	if($start<$i && $i<$end)
+                            {
+                               list($y_repeat,$m_repeat,$d_repeat,$h_repeat,$n_repeat,$s_repeat) = split('/',date('Y/m/j/H/i/s',$i));
+                               $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+                            }
+                          }
+						}
+					}
+					break;
+				case 'monthlyByDate':
+					$time_orig = date('Y/n/W/j/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$w_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/W/j/G/i/s',$end);
+					list($y_now,$m_now,$w_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
+					if(($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig)))
+					{ //if the event is after the original (at least one month) and the original event's day is between the first day of the week and the last day of the week
+					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				case 'monthlyByDayR':
+					//not implemented yet
+					break;
+				case 'monthlyByDay':
+					//not implemented yet
+					break;
+				case 'yearly':
+					$time_orig = date('Y/n/j/z/G/i/s',$orig_start);
+					list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+					$time_now = date('Y/n/j/z/G/i/s',$end);
+					list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
+					if((($y_now>$y_orig) && ($start<$event_repetition_time && $event_repetition_time<$end)))
+					{
+					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+					  list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+					  $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+					}
+					break;
+				default:
+					break;
+			}
+		}
+	}
+	return $events;
+}
+/**
+ * Get repeated events of a course between two dates (1 year timespan). Used for the list display.
+ * This is virtually unlimited but by default it shortens to 100 years from now (even a birthday shouldn't be useful more than this time - except for turtles)
+ * Returns an array containing the events
+ * @param   string  Course info array (as returned by api_get_course_info())
+ * @param   int     UNIX timestamp of span start. Defaults 0, later transformed into today's start
+ * @param   int     UNIX timestamp. Defaults to 0, later transformed into today's end
+ * @param   array   A set of parameters to alter the SQL query
+ * @return  array   [int] => [course_id,parent_event_id,start_date,end_date,title,description]
+ */
+function get_repeated_events_list_view($course_info,$start=0,$end=0,$params)
+{
+    $events = array();
+    //block $end if higher than 2038 -- PHP doesn't go past that
+    if($end>2145934800){$end = 2145934800;}
+    //initialise all values
+    $y=0;
+    $m=0;
+    $d=0;
+    if(empty($start) or empty($end))
+    {
+        $time = time();
+        $y = date('Y');
+        $m = date('m');
+    }
+    if(empty($start))
+    {
+        $start = mktime(0, 0, 0, $m, 1, $y);
+    }
+    $db_start = date('Y-m-d H:i:s', $start);
+    if(empty($end))
+    {
+        $end = mktime(0, 0, 0, 1, 1, 2037);
+    }
+    //$db_end = date('Y-m-d H:i:s',$end);
+
+    $t_cal = Database::get_course_table(TABLE_AGENDA,$course_info['dbName']);
+    $t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
+    $t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
+    $sql = "SELECT c.id, c.title, c.content, " .
+            " UNIX_TIMESTAMP(c.start_date) as orig_start, UNIX_TIMESTAMP(c.end_date) as orig_end, " .
+            " cr.cal_type, cr.cal_end " .
+            " FROM $t_cal c, $t_cal_repeat cr, $t_ip as item_property " .
+            " WHERE cr.cal_end >= $start " .
+            " AND cr.cal_id = c.id " .
+            " AND item_property.ref = c.id ".
+            " AND item_property.tool = '".TOOL_CALENDAR_EVENT."' ".
+            " AND c.start_date <= '$db_start' "
+            .(!empty($params['conditions'])?$params['conditions']:'')
+            .(!empty($params['groupby'])?' GROUP BY '.$params['groupby']:'')
+            .(!empty($params['orderby'])?' ORDER BY '.$params['orderby']:'');
+    $res = Database::query($sql,__FILE__,__LINE__);
+    if(Database::num_rows($res)>0)
+    {
+        while($row = Database::fetch_array($res))
+        {
+            $orig_start = $row['orig_start'];
+            $orig_end = $row['orig_end'];
+            $repeat_type = $row['cal_type'];
+            $repeat_end = $row['cal_end'];
+            switch($repeat_type)
+            {
+                case 'daily':
+                    $time_orig_h = date('H',$orig_start);
+                    $time_orig_m = date('i',$orig_start);
+                    $time_orig_s = date('s',$orig_start);
+                    $span = $orig_end - $orig_start; //total seconds between start and stop of original event
+                    for($i=$orig_start+86400;($i<$end && $i<=$repeat_end);$i+=86400)
+                    {
+                        $current_start = $i; //unixtimestamp start of today's event
+                        $current_stop = $i + $span; //unixtimestamp stop of today's event
+                        $events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
+                    }
+                    break;
+                case 'weekly':
+                    //A weekly repeated event is very difficult to catch in a month view,
+                    // because weeks start before or at the same time as the first day of the month
+                    //The same can be said for the end of the month.
+                    // The idea is thus to get all possible events by enlarging the scope of
+                    // the month to get complete weeks covering the complete month, and then take out
+                    // the events that start before the 1st ($start) or after the last day of the month ($end)
+                    $time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
+                    list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+                    $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
+                    list($y_orig_e,$m_orig_e,$w_orig_e,$d_orig_e,$dw_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+
+                    $time_now = date('Y/n/W/j/N/G/i/s',$end);
+                    list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+                    if($w_now==52)
+                    {
+                        ++$y_now;
+                        $w_now=1;
+                    }
+                    else
+                    {
+                        ++$w_now;
+                    }
+                    $month_first_week = date('W',$start);
+                    $total_weeks = ((date('Y',$end)-$y_orig)-1)*52;
+                    $month_last_week = $month_first_week + $total_weeks;
+
+                    if(($y_now>$y_orig) OR (($y_now == $y_orig) && ($w_now>$w_orig)))
+                    { //if the event is after the original (at least one week) and the day of the week is the same
+                        //for($i=$month_first_week;($i<=$month_last_week && $i<1000);$i++)
+                        //{
+
+
+                          /*
+                           The "day of the week" of repetition is the same as the $dw_orig,
+                           so to get the "day of the month" from the "day of the week", we have
+                           to get the first "day of the week" for this week and add the number
+                           of days (in seconds) to reach the $dw_orig
+                          example: the first week spans between the 28th of April (Monday) to the
+                           4th of May (Sunday). The event occurs on the 2nd day of each week.
+                           This means the event occurs on 29/4, 6/5, 13/5, 20/5 and 27/5.
+                           We want to get all of these, and then reject 29/4 because it is out
+                           of the month itself.
+                          First, to get the start time of the first day of the month view (even if
+                           the day is from the past month), we get the month start date (1/5) and
+                           see which day of the week it is, and subtract the number of days necessary
+                           to get back to the first day of the week.
+                          */
+                          $month_first_day_weekday = date('N',$start);
+                          $first_week_start = $start - (($month_first_day_weekday-1)*86400);
+
+                          //Second, we add the week day of the original event, so that we have an
+                          // absolute time that represents the first repetition of the event in
+                          // our 4- or 5-weeks timespan
+                          $first_event_repeat_start = $first_week_start + (($dw_orig-1)*86400) + ($h_orig*3600) + ($n_orig*60) + $s_orig;
+
+                          //Third, we start looping through the repetitions and see if they are between
+                          // $start and $end
+                          for($i = $first_event_repeat_start; ($i<=$end && $i<=$repeat_end); $i+=604800)
+                          {
+                            if($start<$i && $i<=$end && $i<=$repeat_end)
+                            {
+                               list($y_repeat,$m_repeat,$d_repeat,$h_repeat,$n_repeat,$s_repeat) = split('/',date('Y/m/j/H/i/s',$i));
+                               $new_start_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
+                               $new_stop_time = mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now);
+                               $events[] = array($course_info['id'], $row['id'], $new_start_time, $new_stop_time, $row['title'], $row['content']);
+                            }
+                            $time_now = date('Y/n/W/j/N/G/i/s',$i+604800);
+                            list($y_now,$m_now,$w_now,$d_now,$dw_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+                          }
+                        //}
+                    }
+                    break;
+                case 'monthlyByDate':
+                    $time_orig = date('Y/n/W/j/G/i/s',$orig_start);
+                    list($y_orig,$m_orig,$w_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+
+                    $time_now = date('Y/n/W/j/G/i/s',$start);
+                    list($y_now,$m_now,$w_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+                    //make sure we are one month ahead (to avoid being the same month as the original event)
+                    if($m_now==12)
+                    {
+                        ++$y_now;
+                        $m_now = 1;
+                    }
+                    else
+                    {
+                        ++$m_now;
+                    }
+
+                    $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+                    list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+
+                    $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
+                    $diff = $orig_end - $orig_start;
+                    while((($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig))) && ($event_repetition_time < $end) && ($event_repetition_time < $repeat_end))
+                    { //if the event is after the original (at least one month) and the original event's day is between the first day of the week and the last day of the week
+                      $new_start_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
+                      $new_stop_time = mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now);
+                      $events[] = array($course_info['id'],$row['id'],$new_start_time,$new_stop_time,$row['title'],$row['content']);
+                      if($m_now==12)
+                      {
+                      	++$y_now;
+                        $m_now = 1;
+                      }
+                      else
+                      {
+                        ++$m_now;
+                      }
+                      $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
+                    }
+                    break;
+                case 'monthlyByDayR':
+                    //not implemented yet
+                    break;
+                case 'monthlyByDay':
+                    //not implemented yet
+                    break;
+                case 'yearly':
+                    $time_orig = date('Y/n/j/z/G/i/s',$orig_start);
+                    list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
+                    $time_now = date('Y/n/j/z/G/i/s',$end);
+                    list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
+                    $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
+                    while((($y_now>$y_orig) && ($start<$event_repetition_time && $event_repetition_time<$end && $event_repetition_time<$repeat_end)))
+                    {
+                      $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
+                      list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
+                      $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
+                      ++$y_now;
+                      $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
+                    }
+                    break;
+                default:
+                    break;
+            }
+        }
+    }
+    return $events;
+}
+/**
+ * Tells if an agenda item is repeated
+ * @param   string  Course database
+ * @param   int     The agenda item
+ * @return  boolean True if repeated, false otherwise
+ */
+function is_repeated_event($id,$course=null)
+{
+	if(empty($course))
+    {
+    	$course_info = api_get_course_info();
+        $course = $course_info['dbName'];
+    }
+    $id = (int) $id;
+	$t_agenda_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course);
+    $sql = "SELECT * FROM $t_agenda_repeat WHERE cal_id = $id";
+    $res = Database::query($sql,__FILE__,__LINE__);
+    if(Database::num_rows($res)>0)
+    {
+    	return true;
+    }
+    return false;
+}
+/**
+ * Adds x weeks to a UNIX timestamp
+ * @param   int     The timestamp
+ * @param   int     The number of weeks to add
+ * @return  int     The new timestamp
+ */
+function add_week($timestamp,$num=1)
+{
+    return $timestamp + $num*604800;
+}
+/**
+ * Adds x months to a UNIX timestamp
+ * @param   int     The timestamp
+ * @param   int     The number of years to add
+ * @return  int     The new timestamp
+ */
+function add_month($timestamp,$num=1)
+{
+	list($y, $m, $d, $h, $n, $s) = split('/',date('Y/m/d/h/i/s',$timestamp));
+    if($m+$num>12)
+    {
+    	$y += floor($num/12);
+        $m += $num%12;
+    }
+    else
+    {
+        $m += $num;
+    }
+    return mktime($h, $n, $s, $m, $d, $y);
+}
+/**
+ * Adds x years to a UNIX timestamp
+ * @param   int     The timestamp
+ * @param   int     The number of years to add
+ * @return  int     The new timestamp
+ */
+function add_year($timestamp,$num=1)
+{
+    list($y, $m, $d, $h, $n, $s) = split('/',date('Y/m/d/h/i/s',$timestamp));
+    return mktime($h, $n, $s, $m, $d, $y+$num);
+}
+/**
+ * Adds an agenda item in the database. Similar to store_new_agenda_item() except it takes parameters
+ * @param   array   Course info
+ * @param   string  Event title
+ * @param   string  Event content/description
+ * @param   string  Start date
+ * @param   string  End date
+ * @param   array   List of groups to which this event is added
+ * @param   int     Parent id (optional)
+ * @return  int     The new item's DB ID
+ */
+function agenda_add_item($course_info, $title, $content, $db_start_date, $db_end_date,$to=array(), $parent_id=null,$file_comment='')
+{
+	global $_course;
+    $user_id    = api_get_user_id();
+
+    // database table definitions
+    $t_agenda   = Database::get_course_table(TABLE_AGENDA,$course_info['dbName']);
+    $agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
+    $item_property 				=	Database::get_course_table(TABLE_ITEM_PROPERTY);
+
+    // some filtering of the input data
+    $content=stripslashes($content);
+	$title=Database::escape_string(Security::remove_XSS($title));
 	$content = Database::escape_string(Security::remove_XSS($content,COURSEMANAGERLOWSECURITY));
-    $start_date = Database::escape_string($db_start_date);
-    $end_date   = Database::escape_string($db_end_date);
-    isset($_SESSION['id_session'])?$id_session=intval($_SESSION['id_session']):$id_session=null;
-    // store in the table calendar_event
-
-    // check if exists in calendar_event table and if it is not deleted!
+    $start_date = Database::escape_string($db_start_date);
+    $end_date   = Database::escape_string($db_end_date);
+    isset($_SESSION['id_session'])?$id_session=intval($_SESSION['id_session']):$id_session=null;
+    // store in the table calendar_event
+
+    // check if exists in calendar_event table and if it is not deleted!
     $sql = "SELECT * FROM $t_agenda agenda, $item_property item_property
     			WHERE agenda.title='$title'
     			AND agenda.content = '$content'
-    			AND agenda.start_date = '$start_date'
+    			AND agenda.start_date = '$start_date'
     			AND agenda.end_date = '$end_date' ".(!empty($parent_id)? "
     			AND agenda.parent_event_id = '$parent_id'":"")."
-    			AND agenda.session_id = '$id_session'
-    			AND item_property.tool = '".TOOL_CALENDAR_EVENT."'
-    			AND item_property.ref = agenda.id
+    			AND agenda.session_id = '$id_session'
+    			AND item_property.tool = '".TOOL_CALENDAR_EVENT."'
+    			AND item_property.ref = agenda.id
     			AND item_property.visibility <> 2
-    			";
-    $result = Database::query($sql,__FILE__,__LINE__);
-    $count = Database::num_rows($result);
-    if ($count > 0) {
-    	return false;
-    }
-
-    $sql = "INSERT INTO ".$t_agenda."
-                            (title,content, start_date, end_date".(!empty($parent_id)?',parent_event_id':'').", session_id)
-                            VALUES
-                            ('".$title."','".$content."', '".$start_date."','".$end_date."'".(!empty($parent_id)?','.((int)$parent_id):'').", '".$id_session."')";
-
-    $result = Database::query($sql,__FILE__,__LINE__) or die (Database::error());
-    $last_id=Database::insert_id();
-
-    // add a attachment file in agenda
-
-    add_agenda_attachment_file($file_comment,$last_id);
-
-    // store in last_tooledit (first the groups, then the users
-    $done = false;
-    if ((!is_null($to))or (!empty($_SESSION['toolgroup']))) // !is_null($to): when no user is selected we send it to everyone
-    {
-        $send_to=separate_users_groups($to);
-        // storing the selected groups
-        if (is_array($send_to['groups']))
-        {
-            foreach ($send_to['groups'] as $group)
-            {
-                api_item_property_update($course_info, TOOL_CALENDAR_EVENT, $last_id, "AgendaAdded", $user_id, $group,0,$start_date, $end_date);
-                $done = true;
-            }
-        }
-        // storing the selected users
-        if (is_array($send_to['users']))
-        {
-            foreach ($send_to['users'] as $user)
-            {
-                api_item_property_update($course_info, TOOL_CALENDAR_EVENT, $last_id, "AgendaAdded", $user_id,0,$user, $start_date,$end_date);
-                $done = true;
-            }
-        }
-    }
-
-    if(!$done) // the message is sent to everyone, so we set the group to 0
-    {
-        api_item_property_update($course_info, TOOL_CALENDAR_EVENT, $last_id, "AgendaAdded", $user_id,0,0, $start_date,$end_date);
-    }
-    // storing the resources
-    if (!empty($_SESSION['source_type']) && !empty($last_id)) {
-    store_resources($_SESSION['source_type'],$last_id);
-    }
-    return $last_id;
-}
-
-/**
- * This function delete a attachment file by id
- * @param integer attachment file Id
- *
- */
-function delete_attachment_file($id_attach) {
-
-	global $_course;
-	$agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
-	$id_attach=Database::escape_string($id_attach);
-
-	$sql="DELETE FROM $agenda_table_attachment WHERE id = ".(int)$id_attach;
-	$result=Database::query($sql, __LINE__, __FILE__);
-	$last_id_file=Database::insert_id();
-	// update item_property
-	api_item_property_update($_course, 'calendar_event_attachment', $id_attach ,'AgendaAttachmentDeleted', api_get_user_id());
+    			";
+    $result = Database::query($sql,__FILE__,__LINE__);
+    $count = Database::num_rows($result);
+    if ($count > 0) {
+    	return false;
+    }
+
+    $sql = "INSERT INTO ".$t_agenda."
+                            (title,content, start_date, end_date".(!empty($parent_id)?',parent_event_id':'').", session_id)
+                            VALUES
+                            ('".$title."','".$content."', '".$start_date."','".$end_date."'".(!empty($parent_id)?','.((int)$parent_id):'').", '".$id_session."')";
+
+    $result = Database::query($sql,__FILE__,__LINE__) or die (Database::error());
+    $last_id=Database::insert_id();
+
+    // add a attachment file in agenda
+
+    add_agenda_attachment_file($file_comment,$last_id);
+
+    // store in last_tooledit (first the groups, then the users
+    $done = false;
+    if ((!is_null($to))or (!empty($_SESSION['toolgroup']))) // !is_null($to): when no user is selected we send it to everyone
+    {
+        $send_to=separate_users_groups($to);
+        // storing the selected groups
+        if (is_array($send_to['groups']))
+        {
+            foreach ($send_to['groups'] as $group)
+            {
+                api_item_property_update($course_info, TOOL_CALENDAR_EVENT, $last_id, "AgendaAdded", $user_id, $group,0,$start_date, $end_date);
+                $done = true;
+            }
+        }
+        // storing the selected users
+        if (is_array($send_to['users']))
+        {
+            foreach ($send_to['users'] as $user)
+            {
+                api_item_property_update($course_info, TOOL_CALENDAR_EVENT, $last_id, "AgendaAdded", $user_id,0,$user, $start_date,$end_date);
+                $done = true;
+            }
+        }
+    }
+
+    if(!$done) // the message is sent to everyone, so we set the group to 0
+    {
+        api_item_property_update($course_info, TOOL_CALENDAR_EVENT, $last_id, "AgendaAdded", $user_id,0,0, $start_date,$end_date);
+    }
+    // storing the resources
+    if (!empty($_SESSION['source_type']) && !empty($last_id)) {
+    store_resources($_SESSION['source_type'],$last_id);
+    }
+    return $last_id;
+}
+
+/**
+ * This function delete a attachment file by id
+ * @param integer attachment file Id
+ *
+ */
+function delete_attachment_file($id_attach) {
+
+	global $_course;
+	$agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
+	$id_attach=Database::escape_string($id_attach);
+
+	$sql="DELETE FROM $agenda_table_attachment WHERE id = ".(int)$id_attach;
+	$result=Database::query($sql, __LINE__, __FILE__);
+	$last_id_file=Database::insert_id();
+	// update item_property
+	api_item_property_update($_course, 'calendar_event_attachment', $id_attach ,'AgendaAttachmentDeleted', api_get_user_id());
 	if (!empty($result)) {
-	Display::display_confirmation_message(get_lang("AttachmentFileDeleteSuccess"));
-	}
-}
-
-/**
- * This function add a attachment file into agenda
- * @param string  a comment about file
- * @param int last id from calendar table
- *
- */
-function add_agenda_attachment_file($file_comment,$last_id) {
-
-	global $_course;
-	$agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
-	// Storing the attachments
-
-    if(!empty($_FILES['user_upload']['name'])) {
-		$upload_ok = process_uploaded_file($_FILES['user_upload']);
-	}
-
-	if (!empty($upload_ok)) {
-			$courseDir   = $_course['path'].'/upload/calendar';
-			$sys_course_path = api_get_path(SYS_COURSE_PATH);
-			$updir = $sys_course_path.$courseDir;
-
-			// Try to add an extension to the file if it hasn't one
-			$new_file_name = add_ext_on_mime(stripslashes($_FILES['user_upload']['name']), $_FILES['user_upload']['type']);
-			// user's file name
-			$file_name =$_FILES['user_upload']['name'];
-
-			if (!filter_extension($new_file_name))  {
-				Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
-			} else {
-				$new_file_name = uniqid('');
-				$new_path=$updir.'/'.$new_file_name;
-				$result= @move_uploaded_file($_FILES['user_upload']['tmp_name'], $new_path);
-				$safe_file_comment= Database::escape_string($file_comment);
-				$safe_file_name = Database::escape_string($file_name);
-				$safe_new_file_name = Database::escape_string($new_file_name);
-				// Storing the attachments if any
-				if ($result) {
-					$sql='INSERT INTO '.$agenda_table_attachment.'(filename,comment, path,agenda_id,size) '.
-						 "VALUES ( '".$safe_file_name."', '".$safe_file_comment."', '".$safe_new_file_name."' , '".$last_id."', '".$_FILES['user_upload']['size']."' )";
-					$result=Database::query($sql, __LINE__, __FILE__);
-					$message.=' / '.get_lang('FileUploadSucces').'<br />';
-
-					$last_id_file=Database::insert_id();
-					api_item_property_update($_course, 'calendar_event_attachment', $last_id_file ,'AgendaAttachmentAdded', api_get_user_id());
-
-				}
-			}
-		}
-}
-/**
- * This function edit a attachment file into agenda
- * @param string  a comment about file
- * @param int Agenda Id
- *  @param int attachment file Id
- */
-function edit_agenda_attachment_file($file_comment,$agenda_id,$id_attach) {
-
-	global $_course;
-	$agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
-	// Storing the attachments
-
-    if(!empty($_FILES['user_upload']['name'])) {
-		$upload_ok = process_uploaded_file($_FILES['user_upload']);
-	}
-
-	if (!empty($upload_ok)) {
-			$courseDir   = $_course['path'].'/upload/calendar';
-			$sys_course_path = api_get_path(SYS_COURSE_PATH);
-			$updir = $sys_course_path.$courseDir;
-
-			// Try to add an extension to the file if it hasn't one
-			$new_file_name = add_ext_on_mime(stripslashes($_FILES['user_upload']['name']), $_FILES['user_upload']['type']);
-			// user's file name
-			$file_name =$_FILES['user_upload']['name'];
-
-			if (!filter_extension($new_file_name))  {
-				Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
-			} else {
-				$new_file_name = uniqid('');
-				$new_path=$updir.'/'.$new_file_name;
-				$result= @move_uploaded_file($_FILES['user_upload']['tmp_name'], $new_path);
-				$safe_file_comment= Database::escape_string($file_comment);
-				$safe_file_name = Database::escape_string($file_name);
-				$safe_new_file_name = Database::escape_string($new_file_name);
-				$safe_agenda_id = (int)$agenda_id;
-				$safe_id_attach = (int)$id_attach;
-				// Storing the attachments if any
-				if ($result) {
-					$sql="UPDATE $agenda_table_attachment SET filename = '$safe_file_name', comment = '$safe_file_comment', path = '$safe_new_file_name', agenda_id = '$safe_agenda_id', size ='".$_FILES['user_upload']['size']."'
-						   WHERE id = '$safe_id_attach'";
-					$result=Database::query($sql, __LINE__, __FILE__);
-
-					api_item_property_update($_course, 'calendar_event_attachment', $safe_id_attach ,'AgendaAttachmentUpdated', api_get_user_id());
-
-				}
-			}
-		}
-}
-
-/**
- * Adds a repetitive item to the database
- * @param   array   Course info
- * @param   int     The original event's id
- * @param   string  Type of repetition
- * @param   int     Timestamp of end of repetition (repeating until that date)
- * @param   array   Original event's destination (users list)
- * @param 	string  a comment about a attachment file into agenda
- * @return  boolean False if error, True otherwise
- */
-function agenda_add_repeat_item($course_info,$orig_id,$type,$end,$orig_dest,$file_comment='')
-{
-	$t_agenda   = Database::get_course_table(TABLE_AGENDA,$course_info['dbName']);
-    $t_agenda_r = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
-    //$sql = "SELECT title, content, UNIX_TIMESTAMP(start_date) as sd, UNIX_TIMESTAMP(end_date) as ed FROM $t_agenda WHERE id = $orig_id";
-    $sql = 'SELECT title, content, start_date as sd, end_date as ed FROM '. $t_agenda.' WHERE id ="'.Database::escape_string($orig_id).'" ';
-    $res = Database::query($sql,__FILE__,__LINE__);
-    if(Database::num_rows($res)!==1){return false;}
-    $row = Database::fetch_array($res);
-    //$orig_start = $row['sd'];
-    $orig_start = mktime(substr($row['sd'],11,2),substr($row['sd'],14,2),substr($row['sd'],17,2),substr($row['sd'],5,2),substr($row['sd'],8,2),substr($row['sd'],0,4));
-    //$orig_end   = $row['ed'];
-    $orig_end   = mktime(substr($row['ed'],11,2),substr($row['ed'],14,2),substr($row['ed'],17,2),substr($row['ed'],5,2),substr($row['ed'],8,2),substr($row['ed'],0,4));
-    $diff = $orig_end - $orig_start;
-    $orig_title = $row['title'];
-    $orig_content = $row['content'];
-    $now = time();
-    $type = Database::escape_string($type);
-    $end = (int) $end;
-    if(1<=$end && $end<=500)
-    {
-    	//we assume that, with this type of value, the user actually gives a count of repetitions
-        //and that he wants us to calculate the end date with that (particularly in case of imports from ical)
-        switch($type)
-        {
-            case 'daily':
-                $end = $orig_start + (86400*$end);
-                break;
-            case 'weekly':
-                $end = add_week($orig_start,$end);
-                break;
-            case 'monthlyByDate':
-                $end = add_month($orig_start,$end);
-                break;
-            case 'monthlyByDay':
-                //TODO
-                break;
-            case 'monthlyByDayR':
-                //TODO
-                break;
-            case 'yearly':
-                $end = add_year($orig_start,$end);
-                break;
-        }
-    }
-    if($end > $now
-        && in_array($type,array('daily','weekly','monthlyByDate','monthlyByDay','monthlyByDayR','yearly')))
-    {
-       $sql = "INSERT INTO $t_agenda_r (cal_id, cal_type, cal_end)" .
-            " VALUES ($orig_id,'$type',$end)";
-       $res = Database::query($sql,__FILE__,__LINE__);
-        switch($type)
-        {
-            case 'daily':
-                for($i = $orig_start + 86400; ($i <= $end); $i += 86400)
-                {
-                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $i), date('Y-m-d H:i:s', $i+$diff), $orig_dest, $orig_id,$file_comment);
-                }
-                break;
-            case 'weekly':
-                for($i = $orig_start + 604800; ($i <= $end); $i += 604800)
-                {
-                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $i), date('Y-m-d H:i:s', $i+$diff), $orig_dest, $orig_id,$file_comment);
-                }
-                break;
-            case 'monthlyByDate':
-                $next_start = add_month($orig_start);
-                while($next_start <= $end)
-                {
-                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $next_start), date('Y-m-d H:i:s', $next_start+$diff), $orig_dest, $orig_id,$file_comment);
-                    $next_start = add_month($next_start);
-                }
-                break;
-            case 'monthlyByDay':
-                //not yet implemented
-                break;
-            case 'monthlyByDayR':
-                //not yet implemented
-                break;
-            case 'yearly':
-                $next_start = add_year($orig_start);
-                while($next_start <= $end)
-                {
-                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $next_start), date('Y-m-d H:i:s', $next_start+$diff), $orig_dest, $orig_id,$file_comment);
-                    $next_start = add_year($next_start);
-                }
-                break;
-        }
-    }
-	return true;
-}
-/**
- * Import an iCal file into the database
- * @param   array   Course info
- * @return  boolean True on success, false otherwise
- */
-function agenda_import_ical($course_info,$file) {
-	require_once(api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
-    $charset = api_get_setting('platform_charset');
-    $filepath = api_get_path(SYS_ARCHIVE_PATH).$file['name'];
-    if(!@move_uploaded_file($file['tmp_name'],$filepath))
-    {
-    	error_log('Problem moving uploaded file: '.$file['error'].' in '.__FILE__.' line '.__LINE__);
-    	return false;
-    }
-    require_once (api_get_path(LIBRARY_PATH).'icalcreator/iCalcreator.class.php');
-    $ical = new vcalendar();
-    $ical->setConfig( 'directory', dirname($filepath) );
-    $ical->setConfig( 'filename', basename($filepath) );
-    $ical->parse();
-    //we need to recover: summary, description, dtstart, dtend, organizer, attendee, location (=course name),
-    // rrule
-    $ve = $ical->getComponent(0);
-    //print_r($ve);
-    $ttitle = $ve->getProperty('summary');
-    $title = api_convert_encoding($ttitle,$charset,'UTF-8');
-    $tdesc = $ve->getProperty('description');
-    $desc = api_convert_encoding($tdesc,$charset,'UTF-8');
-    $ts = $ve->getProperty('dtstart');
-    $start_date = $ts['year'].'-'.$ts['month'].'-'.$ts['day'].' '.$ts['hour'].':'.$ts['min'].':'.$ts['sec'];
-    $ts = $ve->getProperty('dtend');
-    $end_date = $ts['year'].'-'.$ts['month'].'-'.$ts['day'].' '.$ts['hour'].':'.$ts['min'].':'.$ts['sec'];
-    //echo $start_date.' - '.$end_date;
-    $organizer = $ve->getProperty('organizer');
-    $attendee = $ve->getProperty('attendee');
-    $course_name = $ve->getProperty('location');
-    //insert the event in our database
-    $id = agenda_add_item($course_info,$title,$desc,$start_date,$end_date,$_POST['selectedform']);
-
-    $repeat = $ve->getProperty('rrule');
-    if(is_array($repeat) && !empty($repeat['FREQ']))
-    {
-    	$trans = array('DAILY'=>'daily','WEEKLY'=>'weekly','MONTHLY'=>'monthlyByDate','YEARLY'=>'yearly');
-        $freq = $trans[$repeat['FREQ']];
-        $interval = $repeat['INTERVAL'];
-        if(isset($repeat['UNTIL']) && is_array($repeat['UNTIL']))
-        {
-            $until = mktime(23,59,59,$repeat['UNTIL']['month'],$repeat['UNTIL']['day'],$repeat['UNTIL']['year']);
-            $res = agenda_add_repeat_item($course_info,$id,$freq,$until,$_POST['selectedform']);
-        }
-        //TODO: deal with count
-        if(!empty($repeat['COUNT']))
-        {
-            $count = $repeat['COUNT'];
-            $res = agenda_add_repeat_item($course_info,$id,$freq,$count,$_POST['selectedform']);
-        }
-    }
-    return true;
-}
-/**
- * This function retrieves one personal agenda item returns it.
- * @param	array	The array containing existing events. We add to this array.
- * @param	int		Day
- * @param	int		Month
- * @param	int		Year (4 digits)
- * @param	int		Week number
- * @param	string	Type of view (month_view, week_view, day_view)
- * @return 	array	The results of the database query, or null if not found
+	Display::display_confirmation_message(get_lang("AttachmentFileDeleteSuccess"));
+	}
+}
+
+/**
+ * This function add a attachment file into agenda
+ * @param string  a comment about file
+ * @param int last id from calendar table
+ *
+ */
+function add_agenda_attachment_file($file_comment,$last_id) {
+
+	global $_course;
+	$agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
+	// Storing the attachments
+
+    if(!empty($_FILES['user_upload']['name'])) {
+		$upload_ok = process_uploaded_file($_FILES['user_upload']);
+	}
+
+	if (!empty($upload_ok)) {
+			$courseDir   = $_course['path'].'/upload/calendar';
+			$sys_course_path = api_get_path(SYS_COURSE_PATH);
+			$updir = $sys_course_path.$courseDir;
+
+			// Try to add an extension to the file if it hasn't one
+			$new_file_name = add_ext_on_mime(stripslashes($_FILES['user_upload']['name']), $_FILES['user_upload']['type']);
+			// user's file name
+			$file_name =$_FILES['user_upload']['name'];
+
+			if (!filter_extension($new_file_name))  {
+				Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
+			} else {
+				$new_file_name = uniqid('');
+				$new_path=$updir.'/'.$new_file_name;
+				$result= @move_uploaded_file($_FILES['user_upload']['tmp_name'], $new_path);
+				$safe_file_comment= Database::escape_string($file_comment);
+				$safe_file_name = Database::escape_string($file_name);
+				$safe_new_file_name = Database::escape_string($new_file_name);
+				// Storing the attachments if any
+				if ($result) {
+					$sql='INSERT INTO '.$agenda_table_attachment.'(filename,comment, path,agenda_id,size) '.
+						 "VALUES ( '".$safe_file_name."', '".$safe_file_comment."', '".$safe_new_file_name."' , '".$last_id."', '".$_FILES['user_upload']['size']."' )";
+					$result=Database::query($sql, __LINE__, __FILE__);
+					$message.=' / '.get_lang('FileUploadSucces').'<br />';
+
+					$last_id_file=Database::insert_id();
+					api_item_property_update($_course, 'calendar_event_attachment', $last_id_file ,'AgendaAttachmentAdded', api_get_user_id());
+
+				}
+			}
+		}
+}
+/**
+ * This function edit a attachment file into agenda
+ * @param string  a comment about file
+ * @param int Agenda Id
+ *  @param int attachment file Id
+ */
+function edit_agenda_attachment_file($file_comment,$agenda_id,$id_attach) {
+
+	global $_course;
+	$agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
+	// Storing the attachments
+
+    if(!empty($_FILES['user_upload']['name'])) {
+		$upload_ok = process_uploaded_file($_FILES['user_upload']);
+	}
+
+	if (!empty($upload_ok)) {
+			$courseDir   = $_course['path'].'/upload/calendar';
+			$sys_course_path = api_get_path(SYS_COURSE_PATH);
+			$updir = $sys_course_path.$courseDir;
+
+			// Try to add an extension to the file if it hasn't one
+			$new_file_name = add_ext_on_mime(stripslashes($_FILES['user_upload']['name']), $_FILES['user_upload']['type']);
+			// user's file name
+			$file_name =$_FILES['user_upload']['name'];
+
+			if (!filter_extension($new_file_name))  {
+				Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
+			} else {
+				$new_file_name = uniqid('');
+				$new_path=$updir.'/'.$new_file_name;
+				$result= @move_uploaded_file($_FILES['user_upload']['tmp_name'], $new_path);
+				$safe_file_comment= Database::escape_string($file_comment);
+				$safe_file_name = Database::escape_string($file_name);
+				$safe_new_file_name = Database::escape_string($new_file_name);
+				$safe_agenda_id = (int)$agenda_id;
+				$safe_id_attach = (int)$id_attach;
+				// Storing the attachments if any
+				if ($result) {
+					$sql="UPDATE $agenda_table_attachment SET filename = '$safe_file_name', comment = '$safe_file_comment', path = '$safe_new_file_name', agenda_id = '$safe_agenda_id', size ='".$_FILES['user_upload']['size']."'
+						   WHERE id = '$safe_id_attach'";
+					$result=Database::query($sql, __LINE__, __FILE__);
+
+					api_item_property_update($_course, 'calendar_event_attachment', $safe_id_attach ,'AgendaAttachmentUpdated', api_get_user_id());
+
+				}
+			}
+		}
+}
+
+/**
+ * Adds a repetitive item to the database
+ * @param   array   Course info
+ * @param   int     The original event's id
+ * @param   string  Type of repetition
+ * @param   int     Timestamp of end of repetition (repeating until that date)
+ * @param   array   Original event's destination (users list)
+ * @param 	string  a comment about a attachment file into agenda
+ * @return  boolean False if error, True otherwise
+ */
+function agenda_add_repeat_item($course_info,$orig_id,$type,$end,$orig_dest,$file_comment='')
+{
+	$t_agenda   = Database::get_course_table(TABLE_AGENDA,$course_info['dbName']);
+    $t_agenda_r = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
+    //$sql = "SELECT title, content, UNIX_TIMESTAMP(start_date) as sd, UNIX_TIMESTAMP(end_date) as ed FROM $t_agenda WHERE id = $orig_id";
+    $sql = 'SELECT title, content, start_date as sd, end_date as ed FROM '. $t_agenda.' WHERE id ="'.Database::escape_string($orig_id).'" ';
+    $res = Database::query($sql,__FILE__,__LINE__);
+    if(Database::num_rows($res)!==1){return false;}
+    $row = Database::fetch_array($res);
+    //$orig_start = $row['sd'];
+    $orig_start = mktime(substr($row['sd'],11,2),substr($row['sd'],14,2),substr($row['sd'],17,2),substr($row['sd'],5,2),substr($row['sd'],8,2),substr($row['sd'],0,4));
+    //$orig_end   = $row['ed'];
+    $orig_end   = mktime(substr($row['ed'],11,2),substr($row['ed'],14,2),substr($row['ed'],17,2),substr($row['ed'],5,2),substr($row['ed'],8,2),substr($row['ed'],0,4));
+    $diff = $orig_end - $orig_start;
+    $orig_title = $row['title'];
+    $orig_content = $row['content'];
+    $now = time();
+    $type = Database::escape_string($type);
+    $end = (int) $end;
+    if(1<=$end && $end<=500)
+    {
+    	//we assume that, with this type of value, the user actually gives a count of repetitions
+        //and that he wants us to calculate the end date with that (particularly in case of imports from ical)
+        switch($type)
+        {
+            case 'daily':
+                $end = $orig_start + (86400*$end);
+                break;
+            case 'weekly':
+                $end = add_week($orig_start,$end);
+                break;
+            case 'monthlyByDate':
+                $end = add_month($orig_start,$end);
+                break;
+            case 'monthlyByDay':
+                //TODO
+                break;
+            case 'monthlyByDayR':
+                //TODO
+                break;
+            case 'yearly':
+                $end = add_year($orig_start,$end);
+                break;
+        }
+    }
+    if($end > $now
+        && in_array($type,array('daily','weekly','monthlyByDate','monthlyByDay','monthlyByDayR','yearly')))
+    {
+       $sql = "INSERT INTO $t_agenda_r (cal_id, cal_type, cal_end)" .
+            " VALUES ($orig_id,'$type',$end)";
+       $res = Database::query($sql,__FILE__,__LINE__);
+        switch($type)
+        {
+            case 'daily':
+                for($i = $orig_start + 86400; ($i <= $end); $i += 86400)
+                {
+                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $i), date('Y-m-d H:i:s', $i+$diff), $orig_dest, $orig_id,$file_comment);
+                }
+                break;
+            case 'weekly':
+                for($i = $orig_start + 604800; ($i <= $end); $i += 604800)
+                {
+                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $i), date('Y-m-d H:i:s', $i+$diff), $orig_dest, $orig_id,$file_comment);
+                }
+                break;
+            case 'monthlyByDate':
+                $next_start = add_month($orig_start);
+                while($next_start <= $end)
+                {
+                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $next_start), date('Y-m-d H:i:s', $next_start+$diff), $orig_dest, $orig_id,$file_comment);
+                    $next_start = add_month($next_start);
+                }
+                break;
+            case 'monthlyByDay':
+                //not yet implemented
+                break;
+            case 'monthlyByDayR':
+                //not yet implemented
+                break;
+            case 'yearly':
+                $next_start = add_year($orig_start);
+                while($next_start <= $end)
+                {
+                    $res = agenda_add_item($course_info, $orig_title, $orig_content, date('Y-m-d H:i:s', $next_start), date('Y-m-d H:i:s', $next_start+$diff), $orig_dest, $orig_id,$file_comment);
+                    $next_start = add_year($next_start);
+                }
+                break;
+        }
+    }
+	return true;
+}
+/**
+ * Import an iCal file into the database
+ * @param   array   Course info
+ * @return  boolean True on success, false otherwise
+ */
+function agenda_import_ical($course_info,$file) {
+	require_once(api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
+    $charset = api_get_setting('platform_charset');
+    $filepath = api_get_path(SYS_ARCHIVE_PATH).$file['name'];
+    if(!@move_uploaded_file($file['tmp_name'],$filepath))
+    {
+    	error_log('Problem moving uploaded file: '.$file['error'].' in '.__FILE__.' line '.__LINE__);
+    	return false;
+    }
+    require_once (api_get_path(LIBRARY_PATH).'icalcreator/iCalcreator.class.php');
+    $ical = new vcalendar();
+    $ical->setConfig( 'directory', dirname($filepath) );
+    $ical->setConfig( 'filename', basename($filepath) );
+    $ical->parse();
+    //we need to recover: summary, description, dtstart, dtend, organizer, attendee, location (=course name),
+    // rrule
+    $ve = $ical->getComponent(0);
+    //print_r($ve);
+    $ttitle = $ve->getProperty('summary');
+    $title = api_convert_encoding($ttitle,$charset,'UTF-8');
+    $tdesc = $ve->getProperty('description');
+    $desc = api_convert_encoding($tdesc,$charset,'UTF-8');
+    $ts = $ve->getProperty('dtstart');
+    $start_date = $ts['year'].'-'.$ts['month'].'-'.$ts['day'].' '.$ts['hour'].':'.$ts['min'].':'.$ts['sec'];
+    $ts = $ve->getProperty('dtend');
+    $end_date = $ts['year'].'-'.$ts['month'].'-'.$ts['day'].' '.$ts['hour'].':'.$ts['min'].':'.$ts['sec'];
+    //echo $start_date.' - '.$end_date;
+    $organizer = $ve->getProperty('organizer');
+    $attendee = $ve->getProperty('attendee');
+    $course_name = $ve->getProperty('location');
+    //insert the event in our database
+    $id = agenda_add_item($course_info,$title,$desc,$start_date,$end_date,$_POST['selectedform']);
+
+    $repeat = $ve->getProperty('rrule');
+    if(is_array($repeat) && !empty($repeat['FREQ']))
+    {
+    	$trans = array('DAILY'=>'daily','WEEKLY'=>'weekly','MONTHLY'=>'monthlyByDate','YEARLY'=>'yearly');
+        $freq = $trans[$repeat['FREQ']];
+        $interval = $repeat['INTERVAL'];
+        if(isset($repeat['UNTIL']) && is_array($repeat['UNTIL']))
+        {
+            $until = mktime(23,59,59,$repeat['UNTIL']['month'],$repeat['UNTIL']['day'],$repeat['UNTIL']['year']);
+            $res = agenda_add_repeat_item($course_info,$id,$freq,$until,$_POST['selectedform']);
+        }
+        //TODO: deal with count
+        if(!empty($repeat['COUNT']))
+        {
+            $count = $repeat['COUNT'];
+            $res = agenda_add_repeat_item($course_info,$id,$freq,$count,$_POST['selectedform']);
+        }
+    }
+    return true;
+}
+/**
+ * This function retrieves one personal agenda item returns it.
+ * @param	array	The array containing existing events. We add to this array.
+ * @param	int		Day
+ * @param	int		Month
+ * @param	int		Year (4 digits)
+ * @param	int		Week number
+ * @param	string	Type of view (month_view, week_view, day_view)
+ * @return 	array	The results of the database query, or null if not found
  */
-function get_global_agenda_items($agendaitems, $day = "", $month = "", $year = "", $week = "", $type)
-{
-	$tbl_global_agenda= Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-	global $_user;
-	global $_configuration;
-	$month=Database::escape_string($month);
-	$year=Database::escape_string($year);
-	$week=Database::escape_string($week);
-	$day=Database::escape_string($day);
-	// 1. creating the SQL statement for getting the personal agenda items in MONTH view
-	if ($type == "month_view" or $type == "") // we are in month view
-	{
-		$sql = "SELECT * FROM ".$tbl_global_agenda." WHERE MONTH(start_date)='".$month."' AND YEAR(start_date) = '".$year."'  ORDER BY start_date ASC";
-	}
-	// 2. creating the SQL statement for getting the personal agenda items in WEEK view
-	if ($type == "week_view") // we are in week view
-	{
-		$start_end_day_of_week = calculate_start_end_of_week($week, $year);
-		$start_day = $start_end_day_of_week['start']['day'];
-		$start_month = $start_end_day_of_week['start']['month'];
-		$start_year = $start_end_day_of_week['start']['year'];
-		$end_day = $start_end_day_of_week['end']['day'];
-		$end_month = $start_end_day_of_week['end']['month'];
-		$end_year = $start_end_day_of_week['end']['year'];
-		// in sql statements you have to use year-month-day for date calculations
-		$start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
-		$end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
-		$sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."'";
-	}
-	// 3. creating the SQL statement for getting the personal agenda items in DAY view
-	if ($type == "day_view") // we are in day view
-	{
-		// we could use mysql date() function but this is only available from 4.1 and higher
-		$start_filter = $year."-".$month."-".$day." 00:00:00";
-		$end_filter = $year."-".$month."-".$day." 23:59:59";
-		$sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."'";
-	}
-	$result = Database::query($sql, __FILE__, __LINE__);
-	while ($item = Database::fetch_array($result))
-	{
-		// we break the date field in the database into a date and a time part
-		$agenda_db_date = explode(" ", $item['start_date']);
-		$date = $agenda_db_date[0];
-		$time = $agenda_db_date[1];
-		// we divide the date part into a day, a month and a year
-		$agendadate = explode("-", $date);
-		$year = intval($agendadate[0]);
-		$month = intval($agendadate[1]);
-		$day = intval($agendadate[2]);
-		// we divide the time part into hour, minutes, seconds
-		$agendatime = explode(":", $time);
-		$hour = $agendatime[0];
-		$minute = $agendatime[1];
-		$second = $agendatime[2];
-		// if the student has specified a course we a add a link to that course
-		if ($item['course'] <> "")
-		{
-			$url = $_configuration['root_web']."main/admin/agenda.php?cidReq=".urlencode($item['course'])."&amp;day=$day&amp;month=$month&amp;year=$year#$day"; // RH  //Patrick Cool: to highlight the relevant agenda item
-			$course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
-		}
-		else
-		{
-			$course_link = "";
-		}
-		// Creating the array that will be returned. If we have week or month view we have an array with the date as the key
-		// if we have a day_view we use a half hour as index => key 33 = 16h30
-		if ($type !== "day_view") // This is the array construction for the WEEK or MONTH view
-		{
-			//Display the Agenda global in the tab agenda (administrator)
-			$agendaitems[$day] .= "".get_lang('StartTimeWindow')."&nbsp;<i>$hour:$minute</i>&nbsp;-&nbsp;";
-			$agendaitems[$day] .= "<b>".get_lang('GlobalEvent')."</b>";
-			$agendaitems[$day] .= "<div>".$item['title']."</div><br>";
-		} else {
-			// this is the array construction for the DAY view
-			$halfhour = 2 * $agendatime['0'];
-			if ($agendatime['1'] >= '30') {
-				$halfhour = $halfhour +1;
-			}
-			//$agendaitems[$halfhour] .= "<div><i>$hour:$minute</i> <b>".get_lang('Evento Global'). ":  </b><a href=\"myagenda.php?action=view&amp;view=personal&amp;day=$day&amp;month=$month&amp;year=$year&amp;id=".$item['id']."#".$item['id']."\" class=\"personal_agenda\">".$item['title']."</a></div>";
-			if (!is_array($agendaitems[$halfhour]))
+function get_global_agenda_items($agendaitems, $day = "", $month = "", $year = "", $week = "", $type)
+{
+	$tbl_global_agenda= Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+	global $_user;
+	global $_configuration;
+	$month=Database::escape_string($month);
+	$year=Database::escape_string($year);
+	$week=Database::escape_string($week);
+	$day=Database::escape_string($day);
+	// 1. creating the SQL statement for getting the personal agenda items in MONTH view
+	if ($type == "month_view" or $type == "") // we are in month view
+	{
+		$sql = "SELECT * FROM ".$tbl_global_agenda." WHERE MONTH(start_date)='".$month."' AND YEAR(start_date) = '".$year."'  ORDER BY start_date ASC";
+	}
+	// 2. creating the SQL statement for getting the personal agenda items in WEEK view
+	if ($type == "week_view") // we are in week view
+	{
+		$start_end_day_of_week = calculate_start_end_of_week($week, $year);
+		$start_day = $start_end_day_of_week['start']['day'];
+		$start_month = $start_end_day_of_week['start']['month'];
+		$start_year = $start_end_day_of_week['start']['year'];
+		$end_day = $start_end_day_of_week['end']['day'];
+		$end_month = $start_end_day_of_week['end']['month'];
+		$end_year = $start_end_day_of_week['end']['year'];
+		// in sql statements you have to use year-month-day for date calculations
+		$start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
+		$end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
+		$sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."'";
+	}
+	// 3. creating the SQL statement for getting the personal agenda items in DAY view
+	if ($type == "day_view") // we are in day view
+	{
+		// we could use mysql date() function but this is only available from 4.1 and higher
+		$start_filter = $year."-".$month."-".$day." 00:00:00";
+		$end_filter = $year."-".$month."-".$day." 23:59:59";
+		$sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."'";
+	}
+	$result = Database::query($sql, __FILE__, __LINE__);
+	while ($item = Database::fetch_array($result))
+	{
+		// we break the date field in the database into a date and a time part
+		$agenda_db_date = explode(" ", $item['start_date']);
+		$date = $agenda_db_date[0];
+		$time = $agenda_db_date[1];
+		// we divide the date part into a day, a month and a year
+		$agendadate = explode("-", $date);
+		$year = intval($agendadate[0]);
+		$month = intval($agendadate[1]);
+		$day = intval($agendadate[2]);
+		// we divide the time part into hour, minutes, seconds
+		$agendatime = explode(":", $time);
+		$hour = $agendatime[0];
+		$minute = $agendatime[1];
+		$second = $agendatime[2];
+		// if the student has specified a course we a add a link to that course
+		if ($item['course'] <> "")
+		{
+			$url = $_configuration['root_web']."main/admin/agenda.php?cidReq=".urlencode($item['course'])."&amp;day=$day&amp;month=$month&amp;year=$year#$day"; // RH  //Patrick Cool: to highlight the relevant agenda item
+			$course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
+		}
+		else
+		{
+			$course_link = "";
+		}
+		// Creating the array that will be returned. If we have week or month view we have an array with the date as the key
+		// if we have a day_view we use a half hour as index => key 33 = 16h30
+		if ($type !== "day_view") // This is the array construction for the WEEK or MONTH view
+		{
+			//Display the Agenda global in the tab agenda (administrator)
+			$agendaitems[$day] .= "".get_lang('StartTimeWindow')."&nbsp;<i>$hour:$minute</i>&nbsp;-&nbsp;";
+			$agendaitems[$day] .= "<b>".get_lang('GlobalEvent')."</b>";
+			$agendaitems[$day] .= "<div>".$item['title']."</div><br>";
+		} else {
+			// this is the array construction for the DAY view
+			$halfhour = 2 * $agendatime['0'];
+			if ($agendatime['1'] >= '30') {
+				$halfhour = $halfhour +1;
+			}
+			//$agendaitems[$halfhour] .= "<div><i>$hour:$minute</i> <b>".get_lang('Evento Global'). ":  </b><a href=\"myagenda.php?action=view&amp;view=personal&amp;day=$day&amp;month=$month&amp;year=$year&amp;id=".$item['id']."#".$item['id']."\" class=\"personal_agenda\">".$item['title']."</a></div>";
+			if (!is_array($agendaitems[$halfhour]))
 	        	$content = $agendaitems[$halfhour];
-			$agendaitems[$halfhour] = $content."<div><i>$hour:$minute</i> <b>".get_lang('GlobalEvent'). ":  </b>".$item['title']."</div>";
-		}
-	}
-	//print_r($agendaitems);
-	return $agendaitems;
-}
-
-function display_ical_import_form()
-{
-	echo '<div class="row"><div class="form_header">'.get_lang('ICalFileImport').'</div></div>';
-	echo '<form enctype="multipart/form-data"  action="'.api_get_self().'?origin='.Security::remove_XSS($_GET['origin']).'&amp;action='.Security::remove_XSS($_GET['action']).'" method="post" name="frm_import_ical">';
-	echo '<div class="row">
-				<div class="label">
-					<span class="form_required">*</span> '.get_lang('ICalFileImport').'
-				</div>
-				<div class="formw"><input type="file" name="ical_import"/>
-				</div>
-			</div>';
-	echo '<div class="row">
-				<div class="label">
-				</div>
-				<div class="formw">
-					<button class="save" type="submit" name="ical_submit" value="'.get_lang('Import').'">'.get_lang('Import').'</button>
-				</div>
+			$agendaitems[$halfhour] = $content."<div><i>$hour:$minute</i> <b>".get_lang('GlobalEvent'). ":  </b>".$item['title']."</div>";
+		}
+	}
+	//print_r($agendaitems);
+	return $agendaitems;
+}
+
+function display_ical_import_form()
+{
+	echo '<div class="row"><div class="form_header">'.get_lang('ICalFileImport').'</div></div>';
+	echo '<form enctype="multipart/form-data"  action="'.api_get_self().'?origin='.Security::remove_XSS($_GET['origin']).'&amp;action='.Security::remove_XSS($_GET['action']).'" method="post" name="frm_import_ical">';
+	echo '<div class="row">
+				<div class="label">
+					<span class="form_required">*</span> '.get_lang('ICalFileImport').'
+				</div>
+				<div class="formw"><input type="file" name="ical_import"/>
+				</div>
 			</div>';
-	echo '</form>';
-}
+	echo '<div class="row">
+				<div class="label">
+				</div>
+				<div class="formw">
+					<button class="save" type="submit" name="ical_submit" value="'.get_lang('Import').'">'.get_lang('Import').'</button>
+				</div>
+			</div>';
+	echo '</form>';
+}

+ 45 - 45
main/chat/chat_banner.php

@@ -1,46 +1,46 @@
-<?php // $Id: chat_banner.php,v 1.3 2005/06/06 13:01:23 olivierb78 Exp $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004 Dokeos S.A.
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Olivier Brouckaert
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	Dokeos banner
-*
-*	@author Olivier Brouckaert
-*	@package dokeos.chat
-==============================================================================
-*/
-
-$language_file = array ('chat');
-
-include('../inc/global.inc.php');
-
-
-$interbreadcrumb[] = array ("url" => "chat.php", "name" => get_lang("Chat"));
-$noPHP_SELF=true;
-$shortBanner=false;
-
-Display::display_header(null,"Chat");
-?>
-
-</body>
+<?php // $Id: chat_banner.php,v 1.3 2005/06/06 13:01:23 olivierb78 Exp $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004 Dokeos S.A.
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Olivier Brouckaert
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	Dokeos banner
+*
+*	@author Olivier Brouckaert
+*	@package dokeos.chat
+==============================================================================
+*/
+
+$language_file = array ('chat');
+
+include('../inc/global.inc.php');
+
+
+$interbreadcrumb[] = array ("url" => "chat.php", "name" => get_lang("Chat"));
+$noPHP_SELF=true;
+$shortBanner=false;
+
+Display::display_header(null,"Chat");
+?>
+
+</body>
 </html>

+ 147 - 147
main/chat/chat_chat.php

@@ -1,161 +1,161 @@
-<?php // $Id: chat_chat.php,v 1.10 2005/05/18 13:58:10 bvanderkimpen Exp $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004 Dokeos S.A.
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Olivier Brouckaert
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	Chat frame that shows the message list
-*
-*	@author Olivier Brouckaert
-*	@package dokeos.chat
-==============================================================================
-*/
-
-define('FRAME','chat');
-
-$language_file = array ('chat');
-require('../inc/global.inc.php');
-include(api_get_path(LIBRARY_PATH).'document.lib.php');
-include (api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
-//$course=api_get_course_id();
-
-$course=$_GET['cidReq'];
-
+<?php // $Id: chat_chat.php,v 1.10 2005/05/18 13:58:10 bvanderkimpen Exp $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004 Dokeos S.A.
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Olivier Brouckaert
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	Chat frame that shows the message list
+*
+*	@author Olivier Brouckaert
+*	@package dokeos.chat
+==============================================================================
+*/
+
+define('FRAME','chat');
+
+$language_file = array ('chat');
+require('../inc/global.inc.php');
+include(api_get_path(LIBRARY_PATH).'document.lib.php');
+include (api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
+//$course=api_get_course_id();
+
+$course=$_GET['cidReq'];
+
 // if we have the session set up
-if (!empty($course))
+if (!empty($course))
 {
-	$reset=$_GET['reset']?true:false;
-	$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
-	$query="SELECT username FROM $tbl_user WHERE user_id='".$_user['user_id']."'";
-	$result=Database::query($query,__FILE__,__LINE__);
+	$reset=$_GET['reset']?true:false;
+	$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
+	$query="SELECT username FROM $tbl_user WHERE user_id='".$_user['user_id']."'";
+	$result=Database::query($query,__FILE__,__LINE__);
 
-	list($pseudoUser)=Database::fetch_row($result);
+	list($pseudoUser)=Database::fetch_row($result);
 
-	$isAllowed=(empty($pseudoUser) || !$_cid)?false:true;
-	$isMaster=$is_courseAdmin?true:false;
+	$isAllowed=(empty($pseudoUser) || !$_cid)?false:true;
+	$isMaster=$is_courseAdmin?true:false;
 
 
-	$dateNow=date('Y-m-d');
+	$dateNow=date('Y-m-d');
 
-	$documentPath=api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
-	$chatPath=$documentPath.'chat_files/';
-	$TABLEITEMPROPERTY= Database::get_course_table(TABLE_ITEM_PROPERTY);
+	$documentPath=api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
+	$chatPath=$documentPath.'chat_files/';
+	$TABLEITEMPROPERTY= Database::get_course_table(TABLE_ITEM_PROPERTY);
 
-	if(!is_dir($chatPath))
-	{
-		if(is_file($chatPath))
-		{
-			@unlink($chatPath);
-		}
+	if(!is_dir($chatPath))
+	{
+		if(is_file($chatPath))
+		{
+			@unlink($chatPath);
+		}
 
-		if (!api_is_anonymous()) {
-			$perm = api_get_setting('permissions_for_new_directories');
-			$perm = octdec(!empty($perm)?$perm:'0770');
-			@mkdir($chatPath,$perm);
+		if (!api_is_anonymous()) {
+			$perm = api_get_setting('permissions_for_new_directories');
+			$perm = octdec(!empty($perm)?$perm:'0770');
+			@mkdir($chatPath,$perm);
 			@chmod($chatPath,$perm);
-			$doc_id=add_document($_course,'/chat_files','folder',0,'chat_files');
-			Database::query("INSERT INTO ".$TABLEITEMPROPERTY . " (tool,insert_user_id,insert_te,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ('document',1,NOW(),NOW(),$doc_id,'DocumentAdded',1,0,NULL,0)");
-		}
-	}
-
-	if(!file_exists($chatPath.'messages-'.$dateNow.'.log.html'))
-	{
-		@fclose(fopen($chatPath.'messages-'.$dateNow.'.log.html','w'));
-		if (!api_is_anonymous()) {
-			$doc_id=add_document($_course,'/chat_files/messages-'.$dateNow.'.log.html','file',0,'messages-'.$dateNow.'.log.html');
-			api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id']);
-			item_property_update_on_folder($_course,'/chat_files', $_user['user_id']);
-		}
-	}
-
-	if($reset && $isMaster)
-	{
-		$i=1;
-
-		while(file_exists($chatPath.'messages-'.$dateNow.'-'.$i.'.log.html'))
-		{
-			$i++;
-		}
-
-		@rename($chatPath.'messages-'.$dateNow.'.log.html',$chatPath.'messages-'.$dateNow.'-'.$i.'.log.html');
-
-		@fclose(fopen($chatPath.'messages-'.$dateNow.'.log.html','w'));
-
-		$doc_id=add_document($_course,'/chat_files/messages-'.$dateNow.'-'.$i.'.log.html','file',filesize($chatPath.'messages-'.$dateNow.'-'.$i.'.log.html'),'messages-'.$dateNow.'-'.$i.'.log.html');
-
-		api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id']);
-		item_property_update_on_folder($_course,'/chat_files', $_user['user_id']);
-
-		$doc_id = DocumentManager::get_document_id($_course,'/chat_files/messages-'.$dateNow.'.log.html');
-
-		update_existing_document($_course, $doc_id,0);
-	}
-
-	$content=file($chatPath.'messages-'.$dateNow.'.log.html');
-	$nbr_lines=sizeof($content);
-	$remove=$nbr_lines-100;
-
-	if($remove < 0)
-	{
-		$remove=0;
-	}
-
-	array_splice($content,0,$remove);
-	include('header_frame.inc.php');
-
-	if ($_GET["origin"]=='whoisonline') {  //the caller
-		$content[0]=get_lang('CallSent').'<br>'.$content[0];
-	}
-	if ($_GET["origin"]=='whoisonlinejoin') {   //the joiner (we have to delete the chat request to him when he joins the chat)
-		$track_user_table = Database::get_main_table(TABLE_MAIN_USER);
-		$sql="update $track_user_table set chatcall_user_id = '', chatcall_date = '', chatcall_text='' where (user_id = ".$_user['user_id'].")";
-		$result=Database::query($sql,__FILE__,__LINE__);
-	}
-
-	echo '<div style="margin-left: 5px;">';
-	foreach($content as $thisLine)
-	{
-		echo strip_tags(api_html_entity_decode($thisLine),'<br> <span> <b> <i> <img> <font>');
-	}
-	echo '</div>';
-
-	?>
-
-	<a name="bottom" style="text-decoration:none;">&nbsp;</a>
-
-	<?php
-	if($isMaster || $is_courseCoach)
-	{
+			$doc_id=add_document($_course,'/chat_files','folder',0,'chat_files');
+			Database::query("INSERT INTO ".$TABLEITEMPROPERTY . " (tool,insert_user_id,insert_te,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ('document',1,NOW(),NOW(),$doc_id,'DocumentAdded',1,0,NULL,0)");
+		}
+	}
+
+	if(!file_exists($chatPath.'messages-'.$dateNow.'.log.html'))
+	{
+		@fclose(fopen($chatPath.'messages-'.$dateNow.'.log.html','w'));
+		if (!api_is_anonymous()) {
+			$doc_id=add_document($_course,'/chat_files/messages-'.$dateNow.'.log.html','file',0,'messages-'.$dateNow.'.log.html');
+			api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id']);
+			item_property_update_on_folder($_course,'/chat_files', $_user['user_id']);
+		}
+	}
+
+	if($reset && $isMaster)
+	{
+		$i=1;
+
+		while(file_exists($chatPath.'messages-'.$dateNow.'-'.$i.'.log.html'))
+		{
+			$i++;
+		}
+
+		@rename($chatPath.'messages-'.$dateNow.'.log.html',$chatPath.'messages-'.$dateNow.'-'.$i.'.log.html');
+
+		@fclose(fopen($chatPath.'messages-'.$dateNow.'.log.html','w'));
+
+		$doc_id=add_document($_course,'/chat_files/messages-'.$dateNow.'-'.$i.'.log.html','file',filesize($chatPath.'messages-'.$dateNow.'-'.$i.'.log.html'),'messages-'.$dateNow.'-'.$i.'.log.html');
+
+		api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id']);
+		item_property_update_on_folder($_course,'/chat_files', $_user['user_id']);
+
+		$doc_id = DocumentManager::get_document_id($_course,'/chat_files/messages-'.$dateNow.'.log.html');
+
+		update_existing_document($_course, $doc_id,0);
+	}
+
+	$content=file($chatPath.'messages-'.$dateNow.'.log.html');
+	$nbr_lines=sizeof($content);
+	$remove=$nbr_lines-100;
+
+	if($remove < 0)
+	{
+		$remove=0;
+	}
+
+	array_splice($content,0,$remove);
+	include('header_frame.inc.php');
+
+	if ($_GET["origin"]=='whoisonline') {  //the caller
+		$content[0]=get_lang('CallSent').'<br>'.$content[0];
+	}
+	if ($_GET["origin"]=='whoisonlinejoin') {   //the joiner (we have to delete the chat request to him when he joins the chat)
+		$track_user_table = Database::get_main_table(TABLE_MAIN_USER);
+		$sql="update $track_user_table set chatcall_user_id = '', chatcall_date = '', chatcall_text='' where (user_id = ".$_user['user_id'].")";
+		$result=Database::query($sql,__FILE__,__LINE__);
+	}
+
+	echo '<div style="margin-left: 5px;">';
+	foreach($content as $thisLine)
+	{
+		echo strip_tags(api_html_entity_decode($thisLine),'<br> <span> <b> <i> <img> <font>');
+	}
+	echo '</div>';
+
+	?>
+
+	<a name="bottom" style="text-decoration:none;">&nbsp;</a>
+
+	<?php
+	if($isMaster || $is_courseCoach)
+	{
 		$rand=mt_rand(1,1000);
-		echo '<div style="margin-left: 5px;">';
-		echo '<a href="'.api_get_self().'?rand='.$rand.'&reset=1&cidReq='.$_GET['cidReq'].'#bottom" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang('ConfirmReset'),ENT_QUOTES,$charset)).'\')) return false;">'.Display::return_icon('delete.gif', get_lang('ClearList')).' '.get_lang('ClearList').'</a>';
-		echo '</div>';
-	}
-}
-else
+		echo '<div style="margin-left: 5px;">';
+		echo '<a href="'.api_get_self().'?rand='.$rand.'&reset=1&cidReq='.$_GET['cidReq'].'#bottom" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang('ConfirmReset'),ENT_QUOTES,$charset)).'\')) return false;">'.Display::return_icon('delete.gif', get_lang('ClearList')).' '.get_lang('ClearList').'</a>';
+		echo '</div>';
+	}
+}
+else
 {
-	include('header_frame.inc.php');
+	include('header_frame.inc.php');
 	$message=get_lang('CloseOtherSession');
 	Display :: display_error_message($message);
-}
-include('footer_frame.inc.php');
-?>
+}
+include('footer_frame.inc.php');
+?>

+ 39 - 39
main/chat/chat_footer.php

@@ -1,27 +1,27 @@
-<?php
-require ('../inc/global.inc.php');
-
-define('FRAME','footer');
-
-echo '<html><head><style>';
-
-/*
+<?php
+require ('../inc/global.inc.php');
+
+define('FRAME','footer');
+
+echo '<html><head><style>';
+
+/*
  * Choose CSS style (platform's, user's, or course's)
- */
-
-$platform_theme = api_get_setting('stylesheets'); 	// plataform's css
-$my_style=$platform_theme;
+ */
+
+$platform_theme = api_get_setting('stylesheets'); 	// plataform's css
+$my_style=$platform_theme;
 if(api_get_setting('user_selected_theme') == 'true')
 {
-	$useri = api_get_user_info();
-	$user_theme = $useri['theme'];
-	if(!empty($user_theme) && $user_theme != $my_style)
-	{
-		$my_style = $user_theme;					// user's css
-	}
-}
-
-$mycourseid = api_get_course_id();
+	$useri = api_get_user_info();
+	$user_theme = $useri['theme'];
+	if(!empty($user_theme) && $user_theme != $my_style)
+	{
+		$my_style = $user_theme;					// user's css
+	}
+}
+
+$mycourseid = api_get_course_id();
 if (!empty($mycourseid) && $mycourseid != -1)
 {
 	if (api_get_setting('allow_course_theme') == 'true')
@@ -29,25 +29,25 @@ if (!empty($mycourseid) && $mycourseid != -1)
 		$mycoursetheme=api_get_course_setting('course_theme');
 		if (!empty($mycoursetheme) && $mycoursetheme!=-1)
 		{
-			if(!empty($mycoursetheme) && $mycoursetheme != $my_style)
+			if(!empty($mycoursetheme) && $mycoursetheme != $my_style)
 			{
-				$my_style = $mycoursetheme;		// course's css
+				$my_style = $mycoursetheme;		// course's css
 			}
 		}
 
-	}
-}
-
-echo '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/default.css'.'";';
-
-echo '</style></head><body><br>';
-
-/*
-==============================================================================
-	FOOTER
-==============================================================================
-*/
-
-Display::display_footer();
-
-?>
+	}
+}
+
+echo '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/default.css'.'";';
+
+echo '</style></head><body><br>';
+
+/*
+==============================================================================
+	FOOTER
+==============================================================================
+*/
+
+Display::display_footer();
+
+?>

+ 125 - 125
main/chat/chat_hidden.php

@@ -1,126 +1,126 @@
-<?php // $Id: chat_hidden.php,v 1.8 2005/05/01 11:49:16 darkden81 Exp $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004 Dokeos S.A.
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Olivier Brouckaert
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	Hidden frame that refreshes the visible frames when a modification occurs
-*
-*	@author Olivier Brouckaert
-*	@package dokeos.chat
-==============================================================================
-*/
-
-define('FRAME','hidden');
-
-$language_file = array ('chat');
-
-require('../inc/global.inc.php');
-include_once '../inc/lib/course.lib.php';
-require_once 'chat_functions.lib.php';
-//$tbl_user=$mainDbName."`.`user";
-//$tbl_chat_connected=$_course['dbNameGlu'].'chat_connected';
-$tbl_user 		= Database::get_main_table(TABLE_MAIN_USER);
-$tbl_chat_connected 	= Database::get_course_chat_connected_table();
-
-$query="SELECT username FROM $tbl_user WHERE user_id='".$_user['user_id']."'";
-$result=Database::query($query,__FILE__,__LINE__);
-
-list($pseudoUser)=Database::fetch_row($result);
-
-$isAllowed=(empty($pseudoUser) || !$_cid)?false:true;
-$isMaster=$is_courseAdmin?true:false;
-
-/*if(!$isAllowed)
-{
-	exit();
-}*/
-
-$dateNow=date('Y-m-d');
-
-$documentPath=api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
-$chatPath=$documentPath.'chat_files/';
-
-$chat_size_old=intval($_POST['chat_size_old']);
-$chat_size_new=filesize($chatPath.'messages-'.$dateNow.'.log.html');
-
-$sql="SELECT user_id FROM $tbl_chat_connected WHERE user_id='".$_user['user_id']."'";
-$result=Database::query($sql);
-
-//The user_id exists so we must do an UPDATE and not a INSERT
-$current_time=date('Y-m-d H:i:s');
-if (Database::num_rows($result)==0) {
-	$query="INSERT INTO $tbl_chat_connected(user_id,last_connection) VALUES('".$_user['user_id']."','".$current_time."')";
-} else {
-	$query="UPDATE $tbl_chat_connected set last_connection='".$current_time."' WHERE user_id='".$_user['user_id']."'";
-}
-
-Database::query($query,__FILE__,__LINE__);
-
-$query="SELECT COUNT(user_id) FROM $tbl_chat_connected WHERE last_connection>'".date('Y-m-d H:i:s',time()-60*5)."'";
-$result=Database::query($query,__FILE__,__LINE__);
-
-$connected_old=intval($_POST['connected_old']);
-list($connected_new) = Database::fetch_row($result);
-/*disconnected user of chat*/
-disconnect_user_of_chat ();
-include("header_frame.inc.php");
-
-//navigation menu
-if(api_get_setting('show_navigation_menu') != 'false')
-{
-   $course_id = api_get_course_id();
-   if ( !empty($course_id) && ($course_id != -1) )
-   {
-   		if( api_get_setting('show_navigation_menu') != 'icons')
-		{
-	    	echo '</div> <!-- end #center -->';
-    		echo '</div> <!-- end #centerwrap -->';
-		}
-      	require_once(api_get_path(INCLUDE_PATH).'tool_navigation_menu.inc.php');
-      	show_navigation_menu();
-   }
-}
-?>
-
-<form name="formHidden" method="post" action="<?php echo api_get_self().'?cidReq='.$_GET['cidReq']; ?>">
-<input type="hidden" name="chat_size_old" value="<?php echo $chat_size_new; ?>">
-<input type="hidden" name="connected_old" value="<?php echo $connected_new; ?>">
-</form>
-
-<?php
-
-if ($_SESSION["origin"] == 'whoisonline') {  //check if our target has denied our request or not
-	$talk_to=$_SESSION["target"];
-	$track_user_table = Database::get_main_table(TABLE_MAIN_USER);
-	$sql="select chatcall_text from $track_user_table where ( user_id = $talk_to )";
-	$result=Database::query($sql,__FILE__,__LINE__);
-	$row=mysql_fetch_array($result);
-	if ($row['chatcall_text'] == 'DENIED') {
+<?php // $Id: chat_hidden.php,v 1.8 2005/05/01 11:49:16 darkden81 Exp $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004 Dokeos S.A.
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Olivier Brouckaert
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	Hidden frame that refreshes the visible frames when a modification occurs
+*
+*	@author Olivier Brouckaert
+*	@package dokeos.chat
+==============================================================================
+*/
+
+define('FRAME','hidden');
+
+$language_file = array ('chat');
+
+require('../inc/global.inc.php');
+include_once '../inc/lib/course.lib.php';
+require_once 'chat_functions.lib.php';
+//$tbl_user=$mainDbName."`.`user";
+//$tbl_chat_connected=$_course['dbNameGlu'].'chat_connected';
+$tbl_user 		= Database::get_main_table(TABLE_MAIN_USER);
+$tbl_chat_connected 	= Database::get_course_chat_connected_table();
+
+$query="SELECT username FROM $tbl_user WHERE user_id='".$_user['user_id']."'";
+$result=Database::query($query,__FILE__,__LINE__);
+
+list($pseudoUser)=Database::fetch_row($result);
+
+$isAllowed=(empty($pseudoUser) || !$_cid)?false:true;
+$isMaster=$is_courseAdmin?true:false;
+
+/*if(!$isAllowed)
+{
+	exit();
+}*/
+
+$dateNow=date('Y-m-d');
+
+$documentPath=api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
+$chatPath=$documentPath.'chat_files/';
+
+$chat_size_old=intval($_POST['chat_size_old']);
+$chat_size_new=filesize($chatPath.'messages-'.$dateNow.'.log.html');
+
+$sql="SELECT user_id FROM $tbl_chat_connected WHERE user_id='".$_user['user_id']."'";
+$result=Database::query($sql);
+
+//The user_id exists so we must do an UPDATE and not a INSERT
+$current_time=date('Y-m-d H:i:s');
+if (Database::num_rows($result)==0) {
+	$query="INSERT INTO $tbl_chat_connected(user_id,last_connection) VALUES('".$_user['user_id']."','".$current_time."')";
+} else {
+	$query="UPDATE $tbl_chat_connected set last_connection='".$current_time."' WHERE user_id='".$_user['user_id']."'";
+}
+
+Database::query($query,__FILE__,__LINE__);
+
+$query="SELECT COUNT(user_id) FROM $tbl_chat_connected WHERE last_connection>'".date('Y-m-d H:i:s',time()-60*5)."'";
+$result=Database::query($query,__FILE__,__LINE__);
+
+$connected_old=intval($_POST['connected_old']);
+list($connected_new) = Database::fetch_row($result);
+/*disconnected user of chat*/
+disconnect_user_of_chat ();
+include("header_frame.inc.php");
+
+//navigation menu
+if(api_get_setting('show_navigation_menu') != 'false')
+{
+   $course_id = api_get_course_id();
+   if ( !empty($course_id) && ($course_id != -1) )
+   {
+   		if( api_get_setting('show_navigation_menu') != 'icons')
+		{
+	    	echo '</div> <!-- end #center -->';
+    		echo '</div> <!-- end #centerwrap -->';
+		}
+      	require_once(api_get_path(INCLUDE_PATH).'tool_navigation_menu.inc.php');
+      	show_navigation_menu();
+   }
+}
+?>
+
+<form name="formHidden" method="post" action="<?php echo api_get_self().'?cidReq='.$_GET['cidReq']; ?>">
+<input type="hidden" name="chat_size_old" value="<?php echo $chat_size_new; ?>">
+<input type="hidden" name="connected_old" value="<?php echo $connected_new; ?>">
+</form>
+
+<?php
+
+if ($_SESSION["origin"] == 'whoisonline') {  //check if our target has denied our request or not
+	$talk_to=$_SESSION["target"];
+	$track_user_table = Database::get_main_table(TABLE_MAIN_USER);
+	$sql="select chatcall_text from $track_user_table where ( user_id = $talk_to )";
+	$result=Database::query($sql,__FILE__,__LINE__);
+	$row=mysql_fetch_array($result);
+	if ($row['chatcall_text'] == 'DENIED') {
 		echo "<script language=javascript> alert('".get_lang('ChatDenied')."'); </script>";
-		$sql="update $track_user_table set chatcall_user_id = '', chatcall_date = '', chatcall_text='' where (user_id = $talk_to)";
-		$result=Database::query($sql,__FILE__,__LINE__);
-	}
-}
-
-include('footer_frame.inc.php');
-?>
+		$sql="update $track_user_table set chatcall_user_id = '', chatcall_date = '', chatcall_text='' where (user_id = $talk_to)";
+		$result=Database::query($sql,__FILE__,__LINE__);
+	}
+}
+
+include('footer_frame.inc.php');
+?>

+ 268 - 268
main/chat/chat_message.php

@@ -1,286 +1,286 @@
-<?php // $Id: chat_message.php,v 1.11 2005/05/18 13:58:20 bvanderkimpen Exp $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004 Dokeos S.A.
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Olivier Brouckaert
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	Allows to type the messages that will be displayed on chat_chat.php
-*
-*	@author Olivier Brouckaert
-*	@package dokeos.chat
-==============================================================================
-*/
-
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
-*/
-
-define('FRAME','message');
-
-$language_file = array ('chat');
-
-require('../inc/global.inc.php');
-
-$course=api_get_course_id();
-
-/////
-// Juan Carlos Ra�a insert smileys and self-closing window
-////
-?>
-<script language="javascript" type="text/javascript">
+<?php // $Id: chat_message.php,v 1.11 2005/05/18 13:58:20 bvanderkimpen Exp $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004 Dokeos S.A.
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Olivier Brouckaert
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	Allows to type the messages that will be displayed on chat_chat.php
+*
+*	@author Olivier Brouckaert
+*	@package dokeos.chat
+==============================================================================
+*/
+
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
+*/
+
+define('FRAME','message');
+
+$language_file = array ('chat');
+
+require('../inc/global.inc.php');
+
+$course=api_get_course_id();
+
+/////
+// Juan Carlos Ra�a insert smileys and self-closing window
+////
+?>
+<script language="javascript" type="text/javascript">
 function insert_smile(text) {
-	if (text.createTextRange) {
-    text.smile = document.selection.createRange().duplicate();
-   	}
-}
-
-function insert(text) {
-	var chat = document.formMessage.message;
+	if (text.createTextRange) {
+    text.smile = document.selection.createRange().duplicate();
+   	}
+}
+
+function insert(text) {
+	var chat = document.formMessage.message;
    	if (chat.createTextRange && chat.smile) {
     	var smile = chat.smile;
-    	smile.text = smile.text.charAt(smile.text.length - 1) == ' ' ? text + ' ' : text;
-   	}
-   	else chat.value += text;
-   	chat.focus(smile)
-}
-
-function close_chat_window() {
-	var chat_window = top.window.self;
-	chat_window.opener = top.window.self;
-	chat_window.top.close();
-}
-
-
-</script>
-
-<?php
-
-// mode open in a new window: close the window when there isn't an user login
-
-if(empty($_user['user_id']))
+    	smile.text = smile.text.charAt(smile.text.length - 1) == ' ' ? text + ' ' : text;
+   	}
+   	else chat.value += text;
+   	chat.focus(smile)
+}
+
+function close_chat_window() {
+	var chat_window = top.window.self;
+	chat_window.opener = top.window.self;
+	chat_window.top.close();
+}
+
+
+</script>
+
+<?php
+
+// mode open in a new window: close the window when there isn't an user login
+
+if(empty($_user['user_id']))
 {
 	echo '<script languaje="javascript"> close_chat_window() </script>';
-}
-else
-{
-	api_protect_course_script();
-}
-
+}
+else
+{
+	api_protect_course_script();
+}
+
 // if we have the session set up
-if (!empty($course) && !empty($_user['user_id']))
-{
-	include_once(api_get_path(LIBRARY_PATH).'document.lib.php');
-	include_once(api_get_path(LIBRARY_PATH).'text.lib.php');
-	include_once (api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
-
-	/*
-	-----------------------------------------------------------
-		Constants and variables
-	-----------------------------------------------------------
-	*/
-	$tbl_user	= Database::get_main_table(TABLE_MAIN_USER);
-	$sent = $_REQUEST['sent'];
-
-	/*
-	==============================================================================
-			MAIN CODE
-	==============================================================================
-	*/
-	$query="SELECT lastname, firstname, username FROM $tbl_user WHERE user_id='".$_user['user_id']."'";
-	$result=Database::query($query,__FILE__,__LINE__);
-
-	list($pseudoUser)=Database::fetch_row($result);
-
-	$isAllowed=(empty($pseudoUser) || !$_cid)?false:true;
-	$isMaster=$is_courseAdmin?true:false;
-
-	$firstname=Database::result($result,0,'firstname');
-	$lastname=Database::result($result,0,'lastname');
-
-	$dateNow=date('Y-m-d');
-
-	$documentPath=api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
-	$chatPath=$documentPath.'chat_files/';
-	$TABLEITEMPROPERTY= Database::get_course_table(TABLE_ITEM_PROPERTY);
-
-	if(!is_dir($chatPath)) {
-		if(is_file($chatPath)) {
-			@unlink($chatPath);
-		}
+if (!empty($course) && !empty($_user['user_id']))
+{
+	include_once(api_get_path(LIBRARY_PATH).'document.lib.php');
+	include_once(api_get_path(LIBRARY_PATH).'text.lib.php');
+	include_once (api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
+
+	/*
+	-----------------------------------------------------------
+		Constants and variables
+	-----------------------------------------------------------
+	*/
+	$tbl_user	= Database::get_main_table(TABLE_MAIN_USER);
+	$sent = $_REQUEST['sent'];
+
+	/*
+	==============================================================================
+			MAIN CODE
+	==============================================================================
+	*/
+	$query="SELECT lastname, firstname, username FROM $tbl_user WHERE user_id='".$_user['user_id']."'";
+	$result=Database::query($query,__FILE__,__LINE__);
+
+	list($pseudoUser)=Database::fetch_row($result);
+
+	$isAllowed=(empty($pseudoUser) || !$_cid)?false:true;
+	$isMaster=$is_courseAdmin?true:false;
+
+	$firstname=Database::result($result,0,'firstname');
+	$lastname=Database::result($result,0,'lastname');
+
+	$dateNow=date('Y-m-d');
+
+	$documentPath=api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
+	$chatPath=$documentPath.'chat_files/';
+	$TABLEITEMPROPERTY= Database::get_course_table(TABLE_ITEM_PROPERTY);
+
+	if(!is_dir($chatPath)) {
+		if(is_file($chatPath)) {
+			@unlink($chatPath);
+		}
 		if (!api_is_anonymous()) {
-			$perm = api_get_setting('permissions_for_new_directories');
-			$perm = octdec(!empty($perm)?$perm:'0770');
-			@mkdir($chatPath,$perm);
+			$perm = api_get_setting('permissions_for_new_directories');
+			$perm = octdec(!empty($perm)?$perm:'0770');
+			@mkdir($chatPath,$perm);
 			@chmod($chatPath,$perm);
-			$doc_id=add_document($_course,'/chat_files','folder',0,'chat_files');
-			$sql_insert = "INSERT INTO ".$TABLEITEMPROPERTY . " (tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ('document',1,NOW(),NOW(),$doc_id,'DocumentAdded',1,0,NULL,0)";
-			Database::query($sql_insert ,__FILE__,__LINE__);
+			$doc_id=add_document($_course,'/chat_files','folder',0,'chat_files');
+			$sql_insert = "INSERT INTO ".$TABLEITEMPROPERTY . " (tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ('document',1,NOW(),NOW(),$doc_id,'DocumentAdded',1,0,NULL,0)";
+			Database::query($sql_insert ,__FILE__,__LINE__);
 		}
-	}
+	}
 
 	include('header_frame.inc.php');
-	$chat_size=0;
-
-	//define emoticons
-	$emoticon_text1=':-)';
-	$emoticon_img1= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_smile.gif" alt="'.get_lang('Smile').'" title="'.get_lang('Smile').'" />';
-	$emoticon_text2=':-D';
-	$emoticon_img2= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_biggrin.gif" alt="'.get_lang('BigGrin').'" title="'.get_lang('BigGrin').'" />';
-	$emoticon_text3=';-)';
-	$emoticon_img3= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_wink.gif" alt="'.get_lang('Wink').'" title="'.get_lang('Wink').'" />';
-	$emoticon_text4=':-P';
+	$chat_size=0;
+
+	//define emoticons
+	$emoticon_text1=':-)';
+	$emoticon_img1= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_smile.gif" alt="'.get_lang('Smile').'" title="'.get_lang('Smile').'" />';
+	$emoticon_text2=':-D';
+	$emoticon_img2= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_biggrin.gif" alt="'.get_lang('BigGrin').'" title="'.get_lang('BigGrin').'" />';
+	$emoticon_text3=';-)';
+	$emoticon_img3= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_wink.gif" alt="'.get_lang('Wink').'" title="'.get_lang('Wink').'" />';
+	$emoticon_text4=':-P';
 	$emoticon_img4= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_razz.gif" alt="'.get_lang('Avid').'" title="'.get_lang('Avid').'" />';
-	$emoticon_text5='8-)';
-	$emoticon_img5= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_cool.gif" alt="'.get_lang('Cool').'" title="'.get_lang('Cool').'" />';
-	$emoticon_text6=':-o)';
-	$emoticon_img6= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_surprised.gif" alt="'.get_lang('Surprised').'" title="'.get_lang('Surprised').'" />';
-	$emoticon_text7='=;';
-	$emoticon_img7= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_hand.gif" alt="'.get_lang('Hand').'" title="'.get_lang('Hand').'" />';
-	$emoticon_text8='=8-o';
-	$emoticon_img8= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_eek.gif" alt="'.get_lang('Amazing').'" title="'.get_lang('Amazing').'" />';
-	$emoticon_text9=':-|)';
+	$emoticon_text5='8-)';
+	$emoticon_img5= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_cool.gif" alt="'.get_lang('Cool').'" title="'.get_lang('Cool').'" />';
+	$emoticon_text6=':-o)';
+	$emoticon_img6= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_surprised.gif" alt="'.get_lang('Surprised').'" title="'.get_lang('Surprised').'" />';
+	$emoticon_text7='=;';
+	$emoticon_img7= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_hand.gif" alt="'.get_lang('Hand').'" title="'.get_lang('Hand').'" />';
+	$emoticon_text8='=8-o';
+	$emoticon_img8= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_eek.gif" alt="'.get_lang('Amazing').'" title="'.get_lang('Amazing').'" />';
+	$emoticon_text9=':-|)';
 	$emoticon_img9= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_neutral.gif" alt="'.get_lang('Neutral').'" title="'.get_lang('Neutral').'" />';
-	$emoticon_text8=':-k';
-	$emoticon_img8= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_think.gif" alt="'.get_lang('Think').'" title="'.get_lang('Think').'" />';
-	$emoticon_text11=':-?';
-	$emoticon_img11= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_confused.gif" alt="'.get_lang('Confused').'" title="'.get_lang('Confused').'" />';
-	$emoticon_text12=':-8';
+	$emoticon_text8=':-k';
+	$emoticon_img8= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_think.gif" alt="'.get_lang('Think').'" title="'.get_lang('Think').'" />';
+	$emoticon_text11=':-?';
+	$emoticon_img11= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_confused.gif" alt="'.get_lang('Confused').'" title="'.get_lang('Confused').'" />';
+	$emoticon_text12=':-8';
 	$emoticon_img12= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_redface.gif" alt="'.get_lang('Redface').'" title="'.get_lang('Redface').'" />';
-	$emoticon_text13=':-=';
-	$emoticon_img13= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_shhh.gif" alt="'.get_lang('Silence').'" title="'.get_lang('Silence').'" />';
-	$emoticon_text14=':-#)';
+	$emoticon_text13=':-=';
+	$emoticon_img13= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_shhh.gif" alt="'.get_lang('Silence').'" title="'.get_lang('Silence').'" />';
+	$emoticon_text14=':-#)';
 	$emoticon_img14= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_silenced.gif" alt="'.get_lang('Silenced').'" title="'.get_lang('Silenced').'" />';
-	$emoticon_text15=':-(';
-	$emoticon_img15= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_sad.gif" alt="'.get_lang('Sad').'" title="'.get_lang('Sad').'" />';
-	$emoticon_text16=':-[8';
-	$emoticon_img16= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_angry.gif" alt="'.get_lang('Angry').'" title="'.get_lang('Angry').'" />';
-	$emoticon_text17='--)';
-	$emoticon_img17= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_arrow.gif" alt="'.get_lang('Arrow').'" title="'.get_lang('Arrow').'" />';
-	$emoticon_text18=':!:';
+	$emoticon_text15=':-(';
+	$emoticon_img15= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_sad.gif" alt="'.get_lang('Sad').'" title="'.get_lang('Sad').'" />';
+	$emoticon_text16=':-[8';
+	$emoticon_img16= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_angry.gif" alt="'.get_lang('Angry').'" title="'.get_lang('Angry').'" />';
+	$emoticon_text17='--)';
+	$emoticon_img17= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_arrow.gif" alt="'.get_lang('Arrow').'" title="'.get_lang('Arrow').'" />';
+	$emoticon_text18=':!:';
 	$emoticon_img18= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_exclaim.gif" alt="'.get_lang('Exclamation').'" title="'.get_lang('Exclamation').'" />';
-	$emoticon_text19=':?:';
-	$emoticon_img19= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_question.gif" alt="'.get_lang('Question').'" title="'.get_lang('Question').'" />';
-	$emoticon_text20='0-';
+	$emoticon_text19=':?:';
+	$emoticon_img19= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_question.gif" alt="'.get_lang('Question').'" title="'.get_lang('Question').'" />';
+	$emoticon_text20='0-';
 	$emoticon_img20= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_idea.gif" alt="'.get_lang('Idea').'" title="'.get_lang('Idea').'" />';
-  //
-	$emoticon_text201='*';
-	$emoticon_img201= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/waiting.gif" alt="'.get_lang('AskPermissionSpeak').'" title="'.get_lang('AskPermissionSpeak').'" />';
-	$emoticon_text202=':speak:';
+  //
+	$emoticon_text201='*';
+	$emoticon_img201= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/waiting.gif" alt="'.get_lang('AskPermissionSpeak').'" title="'.get_lang('AskPermissionSpeak').'" />';
+	$emoticon_text202=':speak:';
 	$emoticon_img202= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/flag_green_small.gif" alt="'.get_lang('GiveTheFloorTo').'" title="'.get_lang('GiveTheFloorTo').'" />';
-	$emoticon_text203=':pause:';
+	$emoticon_text203=':pause:';
 	$emoticon_img203= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/flag_yellow_small.gif" alt="'.get_lang('Pause').'" title="'.get_lang('Pause').'" />';
-	$emoticon_text204=':stop:';
+	$emoticon_text204=':stop:';
 	$emoticon_img204= '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/flag_red_small.gif" alt="'.get_lang('Stop').'" title="'.get_lang('Stop').'" />';
 
-	if($sent)
-	{
-		$message=trim(htmlspecialchars(stripslashes($_POST['message']),ENT_QUOTES,$charset));
-		$message=str_replace($emoticon_text1, $emoticon_img1, $message);
-		$message=str_replace($emoticon_text2, $emoticon_img2, $message);
-		$message=str_replace($emoticon_text3, $emoticon_img3, $message);
-		$message=str_replace($emoticon_text4, $emoticon_img4, $message);
-		$message=str_replace($emoticon_text5, $emoticon_img5, $message);
-		$message=str_replace($emoticon_text6, $emoticon_img6, $message);
-		$message=str_replace($emoticon_text7, $emoticon_img7, $message);
-		$message=str_replace($emoticon_text8, $emoticon_img8, $message);
-		$message=str_replace($emoticon_text9, $emoticon_img9, $message);
-		$message=str_replace($emoticon_text10, $emoticon_img10, $message);
-		$message=str_replace($emoticon_text11, $emoticon_img11, $message);
-		$message=str_replace($emoticon_text12, $emoticon_img12, $message);
-		$message=str_replace($emoticon_text13, $emoticon_img13, $message);
-		$message=str_replace($emoticon_text14, $emoticon_img14, $message);
-		$message=str_replace($emoticon_text15, $emoticon_img15, $message);
-		$message=str_replace($emoticon_text16, $emoticon_img16, $message);
-		$message=str_replace($emoticon_text17, $emoticon_img17, $message);
-		$message=str_replace($emoticon_text18, $emoticon_img18, $message);
- 		$message=str_replace($emoticon_text19, $emoticon_img19, $message);
-		$message=str_replace($emoticon_text20, $emoticon_img20, $message);
-		//
-		$message=str_replace($emoticon_text201, $emoticon_img201, $message);
-		$message=str_replace($emoticon_text202, $emoticon_img202, $message);
-		$message=str_replace($emoticon_text203, $emoticon_img203, $message);
-		$message=str_replace($emoticon_text204, $emoticon_img204, $message);
-
+	if($sent)
+	{
+		$message=trim(htmlspecialchars(stripslashes($_POST['message']),ENT_QUOTES,$charset));
+		$message=str_replace($emoticon_text1, $emoticon_img1, $message);
+		$message=str_replace($emoticon_text2, $emoticon_img2, $message);
+		$message=str_replace($emoticon_text3, $emoticon_img3, $message);
+		$message=str_replace($emoticon_text4, $emoticon_img4, $message);
+		$message=str_replace($emoticon_text5, $emoticon_img5, $message);
+		$message=str_replace($emoticon_text6, $emoticon_img6, $message);
+		$message=str_replace($emoticon_text7, $emoticon_img7, $message);
+		$message=str_replace($emoticon_text8, $emoticon_img8, $message);
+		$message=str_replace($emoticon_text9, $emoticon_img9, $message);
+		$message=str_replace($emoticon_text10, $emoticon_img10, $message);
+		$message=str_replace($emoticon_text11, $emoticon_img11, $message);
+		$message=str_replace($emoticon_text12, $emoticon_img12, $message);
+		$message=str_replace($emoticon_text13, $emoticon_img13, $message);
+		$message=str_replace($emoticon_text14, $emoticon_img14, $message);
+		$message=str_replace($emoticon_text15, $emoticon_img15, $message);
+		$message=str_replace($emoticon_text16, $emoticon_img16, $message);
+		$message=str_replace($emoticon_text17, $emoticon_img17, $message);
+		$message=str_replace($emoticon_text18, $emoticon_img18, $message);
+ 		$message=str_replace($emoticon_text19, $emoticon_img19, $message);
+		$message=str_replace($emoticon_text20, $emoticon_img20, $message);
+		//
+		$message=str_replace($emoticon_text201, $emoticon_img201, $message);
+		$message=str_replace($emoticon_text202, $emoticon_img202, $message);
+		$message=str_replace($emoticon_text203, $emoticon_img203, $message);
+		$message=str_replace($emoticon_text204, $emoticon_img204, $message);
+
 
 
 
 		$timeNow=date('d/m/y H:i:s');
 		if (!api_is_anonymous()) {
-			if(!empty($message))
-			{
-				$message=make_clickable($message);
-
-				if(!file_exists($chatPath.'messages-'.$dateNow.'.log.html'))
-				{
-					$doc_id=add_document($_course,'/chat_files/messages-'.$dateNow.'.log.html','file',0,'messages-'.$dateNow.'.log.html');
-
-					api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id']);
-					item_property_update_on_folder($_course,'/chat_files', $_user['user_id']);
-				}
-				else
-				{
-					$doc_id = DocumentManager::get_document_id($_course,'/chat_files/messages-'.$dateNow.'.log.html');
-				}
-
-				$fp=fopen($chatPath.'messages-'.$dateNow.'.log.html','a');
-
-				if($isMaster)
-				{
+			if(!empty($message))
+			{
+				$message=make_clickable($message);
+
+				if(!file_exists($chatPath.'messages-'.$dateNow.'.log.html'))
+				{
+					$doc_id=add_document($_course,'/chat_files/messages-'.$dateNow.'.log.html','file',0,'messages-'.$dateNow.'.log.html');
+
+					api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id']);
+					item_property_update_on_folder($_course,'/chat_files', $_user['user_id']);
+				}
+				else
+				{
+					$doc_id = DocumentManager::get_document_id($_course,'/chat_files/messages-'.$dateNow.'.log.html');
+				}
+
+				$fp=fopen($chatPath.'messages-'.$dateNow.'.log.html','a');
+
+				if($isMaster)
+				{
 					$photo= '<img src="'.api_get_path(WEB_IMG_PATH).'teachers.gif" alt="'.get_lang('Teacher').'"  width="11" height="11" align="top"  title="'.get_lang('Teacher').'"  />';
 					fputs($fp,'<span style="color:#999; font-size: smaller;">['.$timeNow.']</span>'.$photo.' <span id="chat_login_name"><b>'.api_get_person_name($firstname, $lastname).'</b></span> : <i>'.$message.'</i><br>'."\n");
 
-				}
-				else
-				{
-					$photo= '<img src="'.api_get_path(WEB_IMG_PATH).'students.gif" alt="'.get_lang('Student').'"  width="11" height="11" align="top"  title="'.get_lang('Student').'"  />';
-					 fputs($fp,'<span style="color:#999; font-size: smaller;">['.$timeNow.']</span>'.$photo.' <b>'.api_get_person_name($firstname, $lastname).'</b> : <i>'.$message.'</i><br>'."\n");
-				}
-
-				fclose($fp);
-
-				$chat_size=filesize($chatPath.'messages-'.$dateNow.'.log.html');
-
-				update_existing_document($_course, $doc_id,$chat_size);
-				item_property_update_on_folder($_course,'/chat_files', $_user['user_id']);
-			}
-		}
-	}
-	?>
-	<form name="formMessage" method="post" action="<?php echo api_get_self().'?'.api_get_cidreq(); ?>" onsubmit="javascript:if(document.formMessage.message.value == '') { alert('<?php echo addslashes(api_htmlentities(get_lang('TypeMessage'),ENT_QUOTES,$charset)); ?>'); document.formMessage.message.focus(); return false; }" autocomplete="off">
-	<input type="hidden" name="sent" value="1">
-	<table border="0" cellpadding="5" cellspacing="0" width="100%">
-	<tr>
-        <td width="320" valign="middle">
-        <textarea name="message" style="width: 320px; height: 35px" onkeydown="send_message(event);" onclick="javascript:insert_smile(this);"></textarea>
-        </td>
-        <td>
-        <input type="submit" value="<?php echo get_lang("Send"); ?>" class="background_submit">
-        </td>
-	</tr>
-    <tr>
-        <td>
-        <?php
+				}
+				else
+				{
+					$photo= '<img src="'.api_get_path(WEB_IMG_PATH).'students.gif" alt="'.get_lang('Student').'"  width="11" height="11" align="top"  title="'.get_lang('Student').'"  />';
+					 fputs($fp,'<span style="color:#999; font-size: smaller;">['.$timeNow.']</span>'.$photo.' <b>'.api_get_person_name($firstname, $lastname).'</b> : <i>'.$message.'</i><br>'."\n");
+				}
+
+				fclose($fp);
+
+				$chat_size=filesize($chatPath.'messages-'.$dateNow.'.log.html');
+
+				update_existing_document($_course, $doc_id,$chat_size);
+				item_property_update_on_folder($_course,'/chat_files', $_user['user_id']);
+			}
+		}
+	}
+	?>
+	<form name="formMessage" method="post" action="<?php echo api_get_self().'?'.api_get_cidreq(); ?>" onsubmit="javascript:if(document.formMessage.message.value == '') { alert('<?php echo addslashes(api_htmlentities(get_lang('TypeMessage'),ENT_QUOTES,$charset)); ?>'); document.formMessage.message.focus(); return false; }" autocomplete="off">
+	<input type="hidden" name="sent" value="1">
+	<table border="0" cellpadding="5" cellspacing="0" width="100%">
+	<tr>
+        <td width="320" valign="middle">
+        <textarea name="message" style="width: 320px; height: 35px" onkeydown="send_message(event);" onclick="javascript:insert_smile(this);"></textarea>
+        </td>
+        <td>
+        <input type="submit" value="<?php echo get_lang("Send"); ?>" class="background_submit">
+        </td>
+	</tr>
+    <tr>
+        <td>
+        <?php
 		echo  "<a href=\"javascript:insert('".$emoticon_text1."')\">".$emoticon_img1."</a>";
 		echo  "<a href=\"javascript:insert('".$emoticon_text2."')\">".$emoticon_img2."</a>";
 		echo  "<a href=\"javascript:insert('".$emoticon_text3."')\">".$emoticon_img3."</a>";
@@ -300,22 +300,22 @@ if (!empty($course) && !empty($_user['user_id']))
 		echo  "<a href=\"javascript:insert('".$emoticon_text17."')\">".$emoticon_img17."</a>";
 		echo  "<a href=\"javascript:insert('".$emoticon_text18."')\">".$emoticon_img18."</a>";
 		echo  "<a href=\"javascript:insert('".$emoticon_text19."')\">".$emoticon_img19."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text20."')\">".$emoticon_img20."</a>";
-		?>
-        </td>
-        <td>
-        <?php
+		echo  "<a href=\"javascript:insert('".$emoticon_text20."')\">".$emoticon_img20."</a>";
+		?>
+        </td>
+        <td>
+        <?php
 		echo  "<a href=\"javascript:insert('".$emoticon_text201."')\">".$emoticon_img201."</a>";
 		echo  "<a href=\"javascript:insert('".$emoticon_text202."')\">".$emoticon_img202."</a>";
 		echo  "<a href=\"javascript:insert('".$emoticon_text203."')\">".$emoticon_img203."</a>";
 		echo  "<a href=\"javascript:insert('".$emoticon_text204."')\">".$emoticon_img204."</a>";
-		?>
-        </td>
-    </tr>
-	</table>
-    </form>
+		?>
+        </td>
+    </tr>
+	</table>
+    </form>
 <?php
-
-}
-include('footer_frame.inc.php');
-?>
+
+}
+include('footer_frame.inc.php');
+?>

+ 119 - 119
main/chat/chat_whoisonline.php

@@ -1,134 +1,134 @@
-<?php // $Id: chat_whoisonline.php,v 1.12.2.1 2005/09/02 08:18:31 pcool Exp $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2008 Dokeos SPRL
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Olivier Brouckaert
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt"
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	Shows the list of connected users
-*
-*	@author Olivier Brouckaert
-*	@package dokeos.chat
-==============================================================================
-*/
-
-define('FRAME','online');
-$language_file = array ('chat');
-
-include('../inc/global.inc.php');
-include('../inc/lib/course.lib.php');
-include('../inc/lib/usermanager.lib.php');
-
-$course=api_get_course_id();
-
-if (!empty($course))
-{
-	$showPic=intval($_GET['showPic']);
-	$tbl_course_user	= Database::get_main_table(TABLE_MAIN_COURSE_USER);
-	$tbl_session_course_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-	$tbl_session	= Database::get_main_table(TABLE_MAIN_SESSION);
-	$tbl_session_course	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-	$tbl_user		= Database::get_main_table(TABLE_MAIN_USER);
-	$tbl_chat_connected	= Database::get_course_table(CHAT_CONNECTED_TABLE,$_course['dbName']);
-
-	$query="SELECT username FROM $tbl_user WHERE user_id='".$_user['user_id']."'";
-	$result=Database::query($query,__FILE__,__LINE__);
-
-	list($pseudoUser)=Database::fetch_array($result);
-
-	$isAllowed=(empty($pseudoUser) || !$_cid)?false:true;
-	$isMaster=$is_courseAdmin?true:false;
+<?php // $Id: chat_whoisonline.php,v 1.12.2.1 2005/09/02 08:18:31 pcool Exp $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2008 Dokeos SPRL
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Olivier Brouckaert
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt"
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	Shows the list of connected users
+*
+*	@author Olivier Brouckaert
+*	@package dokeos.chat
+==============================================================================
+*/
+
+define('FRAME','online');
+$language_file = array ('chat');
+
+include('../inc/global.inc.php');
+include('../inc/lib/course.lib.php');
+include('../inc/lib/usermanager.lib.php');
+
+$course=api_get_course_id();
+
+if (!empty($course))
+{
+	$showPic=intval($_GET['showPic']);
+	$tbl_course_user	= Database::get_main_table(TABLE_MAIN_COURSE_USER);
+	$tbl_session_course_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+	$tbl_session	= Database::get_main_table(TABLE_MAIN_SESSION);
+	$tbl_session_course	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+	$tbl_user		= Database::get_main_table(TABLE_MAIN_USER);
+	$tbl_chat_connected	= Database::get_course_table(CHAT_CONNECTED_TABLE,$_course['dbName']);
+
+	$query="SELECT username FROM $tbl_user WHERE user_id='".$_user['user_id']."'";
+	$result=Database::query($query,__FILE__,__LINE__);
+
+	list($pseudoUser)=Database::fetch_array($result);
+
+	$isAllowed=(empty($pseudoUser) || !$_cid)?false:true;
+	$isMaster=$is_courseAdmin?true:false;
 
 	$date_inter=date('Y-m-d H:i:s',time()-120);
 
 	$Users = array();
 
-	if(!isset($_SESSION['id_session']))
-	{
-		$query="SELECT DISTINCT t1.user_id,username,firstname,lastname,picture_uri,t3.status FROM $tbl_user t1,$tbl_chat_connected t2,$tbl_course_user t3 WHERE t1.user_id=t2.user_id AND t3.user_id=t2.user_id AND t3.course_code = '".$_course['sysCode']."' AND t2.last_connection>'".$date_inter."' ORDER BY username";
-		$result=Database::query($query,__FILE__,__LINE__);
-		$Users=Database::store_result($result);
-	}
-	else
-	{
-		// select learners
-		$query="SELECT DISTINCT t1.user_id,username,firstname,lastname,picture_uri FROM $tbl_user t1,$tbl_chat_connected t2,$tbl_session_course_user t3 WHERE t1.user_id=t2.user_id AND t3.id_user=t2.user_id AND t3.id_session = '".$_SESSION['id_session']."' AND t3.course_code = '".$_course['sysCode']."' AND t2.last_connection>'".$date_inter."' ORDER BY username";
-		$result=Database::query($query,__FILE__,__LINE__);
-		while($learner = Database::fetch_array($result))
-		{
-			$Users[$learner['user_id']] = $learner;
-		}
-
-		// select session coach
-		$query="SELECT DISTINCT t1.user_id,username,firstname,lastname,picture_uri FROM $tbl_user t1,$tbl_chat_connected t2,$tbl_session t3 WHERE t1.user_id=t2.user_id AND t3.id_coach=t2.user_id AND t3.id = '".$_SESSION['id_session']."' AND t2.last_connection>'".$date_inter."' ORDER BY username";
-		$result=Database::query($query,__FILE__,__LINE__);
-		if($coach = Database::fetch_array($result))
-			$Users[$coach['user_id']] = $coach;
-
-		// select session course coach
-		$query="SELECT DISTINCT t1.user_id,username,firstname,lastname,picture_uri FROM $tbl_user t1,$tbl_chat_connected t2,$tbl_session_course t3 WHERE t1.user_id=t2.user_id AND t3.id_coach=t2.user_id AND t3.id_session = '".$_SESSION['id_session']."' AND t3.course_code = '".$_course['sysCode']."' AND t2.last_connection>'".$date_inter."' ORDER BY username";
-		$result=Database::query($query,__FILE__,__LINE__);
-		if($coach = Database::fetch_array($result))
-			$Users[$coach['user_id']] = $coach;
-
-	}
+	if(!isset($_SESSION['id_session']))
+	{
+		$query="SELECT DISTINCT t1.user_id,username,firstname,lastname,picture_uri,t3.status FROM $tbl_user t1,$tbl_chat_connected t2,$tbl_course_user t3 WHERE t1.user_id=t2.user_id AND t3.user_id=t2.user_id AND t3.course_code = '".$_course['sysCode']."' AND t2.last_connection>'".$date_inter."' ORDER BY username";
+		$result=Database::query($query,__FILE__,__LINE__);
+		$Users=Database::store_result($result);
+	}
+	else
+	{
+		// select learners
+		$query="SELECT DISTINCT t1.user_id,username,firstname,lastname,picture_uri FROM $tbl_user t1,$tbl_chat_connected t2,$tbl_session_course_user t3 WHERE t1.user_id=t2.user_id AND t3.id_user=t2.user_id AND t3.id_session = '".$_SESSION['id_session']."' AND t3.course_code = '".$_course['sysCode']."' AND t2.last_connection>'".$date_inter."' ORDER BY username";
+		$result=Database::query($query,__FILE__,__LINE__);
+		while($learner = Database::fetch_array($result))
+		{
+			$Users[$learner['user_id']] = $learner;
+		}
+
+		// select session coach
+		$query="SELECT DISTINCT t1.user_id,username,firstname,lastname,picture_uri FROM $tbl_user t1,$tbl_chat_connected t2,$tbl_session t3 WHERE t1.user_id=t2.user_id AND t3.id_coach=t2.user_id AND t3.id = '".$_SESSION['id_session']."' AND t2.last_connection>'".$date_inter."' ORDER BY username";
+		$result=Database::query($query,__FILE__,__LINE__);
+		if($coach = Database::fetch_array($result))
+			$Users[$coach['user_id']] = $coach;
+
+		// select session course coach
+		$query="SELECT DISTINCT t1.user_id,username,firstname,lastname,picture_uri FROM $tbl_user t1,$tbl_chat_connected t2,$tbl_session_course t3 WHERE t1.user_id=t2.user_id AND t3.id_coach=t2.user_id AND t3.id_session = '".$_SESSION['id_session']."' AND t3.course_code = '".$_course['sysCode']."' AND t2.last_connection>'".$date_inter."' ORDER BY username";
+		$result=Database::query($query,__FILE__,__LINE__);
+		if($coach = Database::fetch_array($result))
+			$Users[$coach['user_id']] = $coach;
+
+	}
 
 
 	$user_id=$enreg['user_id'];
-	include('header_frame.inc.php');
-	?>
-	<table border="0" cellpadding="0" cellspacing="0" width="100%" class="data_table">
-	<tr><th colspan="2"><?php echo get_lang("Connected"); ?></th></tr>
-	<?php
-	foreach($Users as $enreg)
+	include('header_frame.inc.php');
+	?>
+	<table border="0" cellpadding="0" cellspacing="0" width="100%" class="data_table">
+	<tr><th colspan="2"><?php echo get_lang("Connected"); ?></th></tr>
+	<?php
+	foreach($Users as $enreg)
 	{
-		if(!isset($_SESSION['id_session']))
-		{
-			$status=$enreg['status'];
-		}
-		else
-		{
-			if(CourseManager::is_course_teacher($enreg['user_id'],$_SESSION['_course']['id'])) $status=1; else $status=5;
-		}
-
-	$user_image=UserManager::get_user_picture_path_by_id($enreg['user_id'],'web',false,true);
-	$file_url=$user_image['dir'].$user_image['file'];
+		if(!isset($_SESSION['id_session']))
+		{
+			$status=$enreg['status'];
+		}
+		else
+		{
+			if(CourseManager::is_course_teacher($enreg['user_id'],$_SESSION['_course']['id'])) $status=1; else $status=5;
+		}
+
+	$user_image=UserManager::get_user_picture_path_by_id($enreg['user_id'],'web',false,true);
+	$file_url=$user_image['dir'].$user_image['file'];
 
 	?>
     <tr>
-	  <td width="1%" valign="top"><img src="<?php echo $file_url;?>" border="0" width="22" alt="" /></td>
-	  <td width="99%"><?php if($status == 1) echo Display::return_icon('teachers.gif', get_lang('Teacher'),array('height' => '11')).' '; else echo Display::return_icon('students.gif', get_lang('Student'), array('height' => '11'));?><a <?php if($status == 1) echo 'class="master"';// ?> name="user_<?php echo $enreg['user_id']; ?>" href="<?php echo api_get_self(); ?>?<?php echo api_get_cidreq();?>&showPic=<?php if($showPic == $enreg['user_id']) echo '0'; else echo $enreg['user_id']; ?>#user_<?php echo $enreg['user_id']; ?>"><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']); ?></a></td>
-	</tr>
-	<?php
-
-	if($showPic == $enreg['user_id']): ?>
-	<tr>
-	  <td colspan="2" align="center"><img src="<?php echo $file_url;?>" border="0" width="100" alt="" /></td>
-	</tr>
-	<?php endif; ?>
-	<?php
-	}
-	unset($Users);
+	  <td width="1%" valign="top"><img src="<?php echo $file_url;?>" border="0" width="22" alt="" /></td>
+	  <td width="99%"><?php if($status == 1) echo Display::return_icon('teachers.gif', get_lang('Teacher'),array('height' => '11')).' '; else echo Display::return_icon('students.gif', get_lang('Student'), array('height' => '11'));?><a <?php if($status == 1) echo 'class="master"';// ?> name="user_<?php echo $enreg['user_id']; ?>" href="<?php echo api_get_self(); ?>?<?php echo api_get_cidreq();?>&showPic=<?php if($showPic == $enreg['user_id']) echo '0'; else echo $enreg['user_id']; ?>#user_<?php echo $enreg['user_id']; ?>"><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']); ?></a></td>
+	</tr>
+	<?php
+
+	if($showPic == $enreg['user_id']): ?>
+	<tr>
+	  <td colspan="2" align="center"><img src="<?php echo $file_url;?>" border="0" width="100" alt="" /></td>
+	</tr>
+	<?php endif; ?>
+	<?php
+	}
+	unset($Users);
 	?>
 	</table>
 	<?php
-	}
-	include('footer_frame.inc.php');
-?>
+	}
+	include('footer_frame.inc.php');
+?>

+ 34 - 34
main/chat/footer_frame.inc.php

@@ -1,35 +1,35 @@
-<?php // $Id: footer_frame.inc.php,v 1.1 2005/03/03 10:15:20 olivierb78 Exp $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004 Dokeos S.A.
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Olivier Brouckaert
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	Footer of each frame of the Chat tool
-*
-*	@author Olivier Brouckaert
-*	@package dokeos.chat
-==============================================================================
-*/
-?>
-
-</body>
+<?php // $Id: footer_frame.inc.php,v 1.1 2005/03/03 10:15:20 olivierb78 Exp $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004 Dokeos S.A.
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Olivier Brouckaert
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	Footer of each frame of the Chat tool
+*
+*	@author Olivier Brouckaert
+*	@package dokeos.chat
+==============================================================================
+*/
+?>
+
+</body>
 </html>

+ 147 - 147
main/chat/header_frame.inc.php

@@ -1,72 +1,72 @@
-<?php // $Id: header_frame.inc.php,v 1.2 2005/05/01 11:49:16 darkden81 Exp $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004 Dokeos S.A.
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Olivier Brouckaert
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	Header of each frame of the Chat tool
-*
-*	@author Olivier Brouckaert
-*   @modified by Denes Nagy
-*	@package dokeos.chat
-==============================================================================
-*/
-
-if(!defined('FRAME'))
-{
-	exit();
-}
-
-$bodyXtra='';
-
-if(FRAME == 'hidden')
-{
-	$bodyXtra='onload="javascript:updateChat(); updateConnected(); setTimeout(\'submitHiddenForm();\',5000);"';
+<?php // $Id: header_frame.inc.php,v 1.2 2005/05/01 11:49:16 darkden81 Exp $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004 Dokeos S.A.
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Olivier Brouckaert
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	Header of each frame of the Chat tool
+*
+*	@author Olivier Brouckaert
+*   @modified by Denes Nagy
+*	@package dokeos.chat
+==============================================================================
+*/
+
+if(!defined('FRAME'))
+{
+	exit();
+}
+
+$bodyXtra='';
+
+if(FRAME == 'hidden')
+{
+	$bodyXtra='onload="javascript:updateChat(); updateConnected(); setTimeout(\'submitHiddenForm();\',5000);"';
     // change timeout to change refresh time of the chat window
-}
-elseif(FRAME == 'message')
-{
-	$bodyXtra='onload="javascript:eventMessage();"';
-}
-
-
-/*
+}
+elseif(FRAME == 'message')
+{
+	$bodyXtra='onload="javascript:eventMessage();"';
+}
+
+
+/*
  * Choose CSS style (platform's, user's, or course's)
- */
-
-$platform_theme = api_get_setting('stylesheets'); 	// plataform's css
-$my_style=$platform_theme;
+ */
+
+$platform_theme = api_get_setting('stylesheets'); 	// plataform's css
+$my_style=$platform_theme;
 if(api_get_setting('user_selected_theme') == 'true')
 {
-	$useri = api_get_user_info();
-	$user_theme = $useri['theme'];
-	if(!empty($user_theme) && $user_theme != $my_style)
-	{
-		$my_style = $user_theme;					// user's css
-	}
-}
-
-$mycourseid = api_get_course_id();
-
+	$useri = api_get_user_info();
+	$user_theme = $useri['theme'];
+	if(!empty($user_theme) && $user_theme != $my_style)
+	{
+		$my_style = $user_theme;					// user's css
+	}
+}
+
+$mycourseid = api_get_course_id();
+
 if (!empty($mycourseid) && $mycourseid != -1)
 {
 	if (api_get_setting('allow_course_theme') == 'true')
@@ -74,91 +74,91 @@ if (!empty($mycourseid) && $mycourseid != -1)
 		$mycoursetheme=api_get_course_setting('course_theme');
 		if (!empty($mycoursetheme) && $mycoursetheme!=-1)
 		{
-			if(!empty($mycoursetheme) && $mycoursetheme != $my_style)
+			if(!empty($mycoursetheme) && $mycoursetheme != $my_style)
 			{
-				$my_style = $mycoursetheme;		// course's css
+				$my_style = $mycoursetheme;		// course's css
 			}
 		}
 
-	}
-}
-
-if (empty($mycourseid))
-{
-	// if it is not set $mycourse id we reload the chat_message window in order to hide the
-	// textarea to submit a message
-	echo '<script type="text/javascript" language="javascript">';
-	echo "parent.chat_message.location.href='chat_whoisonline.php?".api_get_cidreq()."';";
-	echo '</script>';
-}
-?><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<html>
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=<?php echo $charset;?>">
-<title>Chat</title>
-<link rel="stylesheet" type="text/css" href="../css/<?php echo $my_style; ?>/default.css">
-<style>
-	a{
-		font-size: 12px;
-	}
-
-	.background_submit{
-		background: url(../img/chat_little.gif) 2px 2px no-repeat;
-		padding: 2px 1px 1px 20px;
-	}
-	TH{
-		font-size: 12px;
-	}
-</style>
-
-<script type="text/javascript" language="javascript">
-<!--
-function updateChat()
-{
-	if('<?php echo $chat_size_old; ?>' != '<?php echo $chat_size_new; ?>')
-	{
+	}
+}
+
+if (empty($mycourseid))
+{
+	// if it is not set $mycourse id we reload the chat_message window in order to hide the
+	// textarea to submit a message
+	echo '<script type="text/javascript" language="javascript">';
+	echo "parent.chat_message.location.href='chat_whoisonline.php?".api_get_cidreq()."';";
+	echo '</script>';
+}
+?><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=<?php echo $charset;?>">
+<title>Chat</title>
+<link rel="stylesheet" type="text/css" href="../css/<?php echo $my_style; ?>/default.css">
+<style>
+	a{
+		font-size: 12px;
+	}
+
+	.background_submit{
+		background: url(../img/chat_little.gif) 2px 2px no-repeat;
+		padding: 2px 1px 1px 20px;
+	}
+	TH{
+		font-size: 12px;
+	}
+</style>
+
+<script type="text/javascript" language="javascript">
+<!--
+function updateChat()
+{
+	if('<?php echo $chat_size_old; ?>' != '<?php echo $chat_size_new; ?>')
+	{
 		parent.chat_chat.location.href='chat_chat.php?size=<?php echo $chat_size_new.'&cidReq='.$_GET['cidReq']; ?>#bottom';
-	}
-}
-
-function updateConnected()
-{
-	if('<?php echo $connected_old; ?>' != '<?php echo $connected_new; ?>')
-	{
-		parent.chat_whoisonline.location.href='chat_whoisonline.php?size=<?php echo $connected_new; ?>';
-	}
-}
-
-function submitHiddenForm()
-{
-	document.formHidden.submit();
-}
-
-function eventMessage()
-{
-	<?php if($chat_size): ?>
-	parent.chat_hidden.document.formHidden.chat_size_old.value='<?php echo $chat_size; ?>';
-	parent.chat_chat.location.href='chat_chat.php?size=<?php echo $chat_size.'&cidReq='.$_GET['cidReq']; ?>#bottom';
-	<?php endif; ?>
-
-	document.formMessage.message.focus();
-}
-
-function send_message(evenement){
-
-    for (prop in evenement)
-    {
-    	if(prop == 'which') touche = evenement.which; else touche = evenement.keyCode;
-    }
-
-    if (touche == 13)
-    {
-    	document.formMessage.submit();
-    }
-}
-
-//-->
-</script>
-
-</head>
+	}
+}
+
+function updateConnected()
+{
+	if('<?php echo $connected_old; ?>' != '<?php echo $connected_new; ?>')
+	{
+		parent.chat_whoisonline.location.href='chat_whoisonline.php?size=<?php echo $connected_new; ?>';
+	}
+}
+
+function submitHiddenForm()
+{
+	document.formHidden.submit();
+}
+
+function eventMessage()
+{
+	<?php if($chat_size): ?>
+	parent.chat_hidden.document.formHidden.chat_size_old.value='<?php echo $chat_size; ?>';
+	parent.chat_chat.location.href='chat_chat.php?size=<?php echo $chat_size.'&cidReq='.$_GET['cidReq']; ?>#bottom';
+	<?php endif; ?>
+
+	document.formMessage.message.focus();
+}
+
+function send_message(evenement){
+
+    for (prop in evenement)
+    {
+    	if(prop == 'which') touche = evenement.which; else touche = evenement.keyCode;
+    }
+
+    if (touche == 13)
+    {
+    	document.formMessage.submit();
+    }
+}
+
+//-->
+</script>
+
+</head>
 <body <?php echo $bodyXtra; ?> >

+ 11 - 11
main/conference/index.php

@@ -1,12 +1,12 @@
-<?php
-/* See license terms in /dokeos_license.txt */
-/**
- * Generates the HTML page containing the iframe that loads the videoconference's Flash plugin
- */
-include("../inc/global.inc.php");
-api_protect_course_script();
-$_SESSION["roomType"] = $_GET['type'];
-?>
-<span align="center">
-<iframe frameborder="0" scrolling="no" width="100%" height="100%" src="videoconference.php"></iframe>
+<?php
+/* See license terms in /dokeos_license.txt */
+/**
+ * Generates the HTML page containing the iframe that loads the videoconference's Flash plugin
+ */
+include("../inc/global.inc.php");
+api_protect_course_script();
+$_SESSION["roomType"] = $_GET['type'];
+?>
+<span align="center">
+<iframe frameborder="0" scrolling="no" width="100%" height="100%" src="videoconference.php"></iframe>
 </span>

+ 456 - 456
main/course_home/2column.php

@@ -1,460 +1,460 @@
-<?php // $Id: 2column.php,v 1.5 2006/08/10 14:34:54 pcool Exp $
-
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2005 Dokeos S.A.
-	Copyright (c) 2003 Ghent University
-	Copyright (c) 2001 Universite Catholique de Louvain
-	Copyright (c) various contributors
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*                  HOME PAGE FOR EACH COURSE
-*
-*	This page, included in every course's index.php is the home
-*	page. To make administration simple, the teacher edits his
-*	course from the home page. Only the login detects that the
-*	visitor is allowed to activate, deactivate home page links,
-*	access to the teachers tools (statistics, edit forums...).
-*
-*	@package dokeos.course_home
-==============================================================================
-*/
-
-/*
-==============================================================================
-		FUNCTIONS
-==============================================================================
-*/
-
-/**
- * Displays the tools of a certain category.
- *
- * @return void
- * @param string $course_tool_category	contains the category of tools to display:
- * "Public", "PublicButHide", "courseAdmin", "claroAdmin"
- */
-function show_tools($course_tool_category)
-{
-	global $charset;
-	$web_code_path = api_get_path(WEB_CODE_PATH);
-	$course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
-
-	switch ($course_tool_category)
-	{
-		case TOOL_PUBLIC:
-
-				$result = Database::query("SELECT * FROM $course_tool_table WHERE visibility=1 ORDER BY id",__FILE__,__LINE__);
-				$colLink ="##003399";
-				break;
-
-		case TOOL_PUBLIC_BUT_HIDDEN:
-
-				$result = Database::query("SELECT * FROM $course_tool_table WHERE visibility=0 AND admin=0 ORDER BY id",__FILE__,__LINE__);
-				$colLink ="##808080";
-				break;
-
-		case TOOL_COURSE_ADMIN:
-
-				$result = Database::query("SELECT * FROM $course_tool_table WHERE admin=1 AND visibility != 2 ORDER BY id",__FILE__,__LINE__);
-				$colLink ="##003399";
-				break;
-
-		case TOOL_PLATFORM_ADMIN:
-
-				$result = Database::query("SELECT * FROM $course_tool_table WHERE visibility = 2 ORDER BY id",__FILE__,__LINE__);
-				$colLink ="##003399";
-	}
-
-	$i=0;
-
-	// grabbing all the tools from $course_tool_table
-	while ($temp_row = mysql_fetch_array($result))
-	{
-		if($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN && $temp_row['image'] != 'scormbuilder.gif')
-		{
-			$temp_row['image']=str_replace('.gif','_na.gif',$temp_row['image']);
-		}
-		$all_tools_list[]=$temp_row;
-	}
-
-	// grabbing all the links that have the property on_homepage set to 1
-	$course_link_table = Database::get_course_table(TABLE_LINK);
-	$course_item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
-	switch ($course_tool_category)
-	{
-		case TOOL_PUBLIC:
-			$sql_links="SELECT tl.*, tip.visibility
-					FROM $course_link_table tl
-					LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
-					WHERE tl.on_homepage='1' AND tip.visibility = 1";
-			break;
-		case TOOL_PUBLIC_BUT_HIDDEN:
-			$sql_links="SELECT tl.*, tip.visibility
-				FROM $course_link_table tl
-				LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
-				WHERE tl.on_homepage='1' AND tip.visibility = 0";
-			break;
-		default:
-			$sql_links = null;
-			break;
-	}
-	if( $sql_links != null )
-	{
-		$properties = array();
-		$result_links=Database::query($sql_links,__FILE__,__LINE__);
-		while ($links_row=mysql_fetch_array($result_links))
-		{
-			unset($properties);
-			$properties['name']=$links_row['title'];
-			$properties['link']=$links_row['url'];
-			$properties['visibility']=$links_row['visibility'];
-			$properties['image']=($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN)?"external_na.gif":"external.gif";
-			$properties['adminlink']=api_get_path(WEB_CODE_PATH)."link/link.php?action=editlink&id=".$links_row['id'];
-			$all_tools_list[]=$properties;
-		}
-	}
-
-	if (isset($all_tools_list))
-	{
-		$lnk = array();
-		foreach ($all_tools_list as $toolsRow)
-		{
-			if (api_get_session_id()!=0 && in_array($toolsRow['name'],array('course_maintenance','course_setting'))) {
-				continue;
-			}
-
-			if (!($i%2))
-			{
-				echo	"<tr valign=\"top\">\n";
-			}
-
-			// NOTE : table contains only the image file name, not full path
-			if(!stristr($toolsRow['link'],'http://') && !stristr($toolsRow['link'],'https://') && !stristr($toolsRow['link'],'ftp://'))
-			{
-				$toolsRow['link']=$web_code_path.$toolsRow['link'];
-			}
-			if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN)
-			{
-			    $class="class=\"invisible\"";
-			}
-			$qm_or_amp = ((strpos($toolsRow['link'],'?')===FALSE)?'?':'&amp;');
-
-			$toolsRow['link'] = $toolsRow['link'];
-			echo	'<td width="50%" height="30">';
-
-			if(strpos($toolsRow['name'],'visio_')!==false)
-			{
-				echo '<a  '.$class.' href="javascript: void(0);" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']).(($toolsRow['image']=="external.gif" || $toolsRow['image']=="external_na.gif") ? '' : $qm_or_amp.api_get_cidreq()) . '\',\'window_visio'.$_SESSION['_cid'].'\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '">';
-			}
-
-			else if(strpos($toolsRow['name'],'chat')!==false && api_get_course_setting('allow_open_chat_window')==true)
+<?php // $Id: 2column.php,v 1.5 2006/08/10 14:34:54 pcool Exp $
+
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2005 Dokeos S.A.
+	Copyright (c) 2003 Ghent University
+	Copyright (c) 2001 Universite Catholique de Louvain
+	Copyright (c) various contributors
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*                  HOME PAGE FOR EACH COURSE
+*
+*	This page, included in every course's index.php is the home
+*	page. To make administration simple, the teacher edits his
+*	course from the home page. Only the login detects that the
+*	visitor is allowed to activate, deactivate home page links,
+*	access to the teachers tools (statistics, edit forums...).
+*
+*	@package dokeos.course_home
+==============================================================================
+*/
+
+/*
+==============================================================================
+		FUNCTIONS
+==============================================================================
+*/
+
+/**
+ * Displays the tools of a certain category.
+ *
+ * @return void
+ * @param string $course_tool_category	contains the category of tools to display:
+ * "Public", "PublicButHide", "courseAdmin", "claroAdmin"
+ */
+function show_tools($course_tool_category)
+{
+	global $charset;
+	$web_code_path = api_get_path(WEB_CODE_PATH);
+	$course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
+
+	switch ($course_tool_category)
+	{
+		case TOOL_PUBLIC:
+
+				$result = Database::query("SELECT * FROM $course_tool_table WHERE visibility=1 ORDER BY id",__FILE__,__LINE__);
+				$colLink ="##003399";
+				break;
+
+		case TOOL_PUBLIC_BUT_HIDDEN:
+
+				$result = Database::query("SELECT * FROM $course_tool_table WHERE visibility=0 AND admin=0 ORDER BY id",__FILE__,__LINE__);
+				$colLink ="##808080";
+				break;
+
+		case TOOL_COURSE_ADMIN:
+
+				$result = Database::query("SELECT * FROM $course_tool_table WHERE admin=1 AND visibility != 2 ORDER BY id",__FILE__,__LINE__);
+				$colLink ="##003399";
+				break;
+
+		case TOOL_PLATFORM_ADMIN:
+
+				$result = Database::query("SELECT * FROM $course_tool_table WHERE visibility = 2 ORDER BY id",__FILE__,__LINE__);
+				$colLink ="##003399";
+	}
+
+	$i=0;
+
+	// grabbing all the tools from $course_tool_table
+	while ($temp_row = mysql_fetch_array($result))
+	{
+		if($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN && $temp_row['image'] != 'scormbuilder.gif')
+		{
+			$temp_row['image']=str_replace('.gif','_na.gif',$temp_row['image']);
+		}
+		$all_tools_list[]=$temp_row;
+	}
+
+	// grabbing all the links that have the property on_homepage set to 1
+	$course_link_table = Database::get_course_table(TABLE_LINK);
+	$course_item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
+	switch ($course_tool_category)
+	{
+		case TOOL_PUBLIC:
+			$sql_links="SELECT tl.*, tip.visibility
+					FROM $course_link_table tl
+					LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
+					WHERE tl.on_homepage='1' AND tip.visibility = 1";
+			break;
+		case TOOL_PUBLIC_BUT_HIDDEN:
+			$sql_links="SELECT tl.*, tip.visibility
+				FROM $course_link_table tl
+				LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
+				WHERE tl.on_homepage='1' AND tip.visibility = 0";
+			break;
+		default:
+			$sql_links = null;
+			break;
+	}
+	if( $sql_links != null )
+	{
+		$properties = array();
+		$result_links=Database::query($sql_links,__FILE__,__LINE__);
+		while ($links_row=mysql_fetch_array($result_links))
+		{
+			unset($properties);
+			$properties['name']=$links_row['title'];
+			$properties['link']=$links_row['url'];
+			$properties['visibility']=$links_row['visibility'];
+			$properties['image']=($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN)?"external_na.gif":"external.gif";
+			$properties['adminlink']=api_get_path(WEB_CODE_PATH)."link/link.php?action=editlink&id=".$links_row['id'];
+			$all_tools_list[]=$properties;
+		}
+	}
+
+	if (isset($all_tools_list))
+	{
+		$lnk = array();
+		foreach ($all_tools_list as $toolsRow)
+		{
+			if (api_get_session_id()!=0 && in_array($toolsRow['name'],array('course_maintenance','course_setting'))) {
+				continue;
+			}
+
+			if (!($i%2))
+			{
+				echo	"<tr valign=\"top\">\n";
+			}
+
+			// NOTE : table contains only the image file name, not full path
+			if(!stristr($toolsRow['link'],'http://') && !stristr($toolsRow['link'],'https://') && !stristr($toolsRow['link'],'ftp://'))
+			{
+				$toolsRow['link']=$web_code_path.$toolsRow['link'];
+			}
+			if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN)
+			{
+			    $class="class=\"invisible\"";
+			}
+			$qm_or_amp = ((strpos($toolsRow['link'],'?')===FALSE)?'?':'&amp;');
+
+			$toolsRow['link'] = $toolsRow['link'];
+			echo	'<td width="50%" height="30">';
+
+			if(strpos($toolsRow['name'],'visio_')!==false)
+			{
+				echo '<a  '.$class.' href="javascript: void(0);" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']).(($toolsRow['image']=="external.gif" || $toolsRow['image']=="external_na.gif") ? '' : $qm_or_amp.api_get_cidreq()) . '\',\'window_visio'.$_SESSION['_cid'].'\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '">';
+			}
+
+			else if(strpos($toolsRow['name'],'chat')!==false && api_get_course_setting('allow_open_chat_window')==true)
 			{
-				/*
-				echo  '<a href="#" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']) .(($toolsRow['image']=="external.gif" || $toolsRow['image']=="external_na.gif") ? '' : $qm_or_amp.api_get_cidreq()). '\',\'window_chat'.$_SESSION['_cid'].'\',config=\'height=\'+380+\', width=\'+625+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '"'.$class.'>';
-				*/
-				echo  '<a href="javascript: void(0);" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']).$qm_or_amp.api_get_cidreq() . '\',\'window_chat'.$_SESSION['_cid'].'\',config=\'height=\'+380+\', width=\'+625+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '"'.$class.'>';
+				/*
+				echo  '<a href="#" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']) .(($toolsRow['image']=="external.gif" || $toolsRow['image']=="external_na.gif") ? '' : $qm_or_amp.api_get_cidreq()). '\',\'window_chat'.$_SESSION['_cid'].'\',config=\'height=\'+380+\', width=\'+625+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '"'.$class.'>';
+				*/
+				echo  '<a href="javascript: void(0);" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']).$qm_or_amp.api_get_cidreq() . '\',\'window_chat'.$_SESSION['_cid'].'\',config=\'height=\'+380+\', width=\'+625+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '"'.$class.'>';
 			}
 			else
-			{
+			{
 				echo	'<a href="'. htmlspecialchars($toolsRow['link']).(($toolsRow['image']=="external.gif" || $toolsRow['image']=="external_na.gif") ? '' : $qm_or_amp.api_get_cidreq()).'" target="' , $toolsRow['target'], '" '.$class.'>';
-			}
-
-			/*
-			echo Display::return_icon($toolsRow['image'], get_lang(ucfirst($toolsRow['name']))),'&nbsp;', ($toolsRow['image']=="external.gif" || $toolsRow['image']=="external_na.gif" || $toolsRow['image']=="scormbuilder.gif" || $toolsRow['image']=="blog.gif") ? htmlspecialchars( $toolsRow['name'],ENT_QUOTES,$charset) : get_lang(ucfirst($toolsRow['name'])),'</a>';
-			*/
-			if ($toolsRow['image'] == 'file_html.gif' || $toolsRow['image'] == 'file_html_na.gif'
-				|| $toolsRow['image'] == 'scormbuilder.gif' || $toolsRow['image'] == 'scormbuilder_na.gif'
-				|| $toolsRow['image'] == 'blog.gif' || $toolsRow['image'] == 'blog_na.gif'
-				|| $toolsRow['image'] == 'external.gif' || $toolsRow['image'] == 'external_na.gif')
-			{
-				$tool_name = htmlspecialchars($toolsRow['name'], ENT_QUOTES, $charset);
-			}
-			else
-			{
-				$tool_name = get_lang(ucfirst($toolsRow['name']));
-			}
-			echo Display::return_icon($toolsRow['image'], $tool_name),'&nbsp;', $tool_name,'</a>';
-
-			// This part displays the links to hide or remove a tool.
-			// These links are only visible by the course manager.
-			unset($lnk);
-			if (api_is_allowed_to_edit())
-			{
-				if ($toolsRow["visibility"] == '1')
-				{
-					$link['name'] = Display::return_icon('remove.gif', get_lang('Deactivate'));
-					$link['cmd'] = "hide=yes";
-					$lnk[] = $link;
-				}
-
-				if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN)
-				{
-					$link['name'] = Display::return_icon('add.gif', get_lang('Activate'));
-					$link['cmd']  = "restore=yes";
-					$lnk[] = $link;
-
-					if($toolsRow["added_tool"] == 1)
-					{
-						$link['name'] = Display::return_icon('delete.gif', get_lang('Remove'));
-						$link['cmd']  = "remove=yes";
-						$lnk[] = $link;
-					}
-				}
-				if ($toolsRow['adminlink'])
-				{
-					echo	'<a href="'.$toolsRow['adminlink'].'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
-					//echo "edit link:".$properties['adminlink'];
-				}
-
-			}
-			if ( api_is_platform_admin() )
-			{
-				if ($toolsRow["visibility"]==2)
-				{
-					$link['name'] = Display::return_icon('undelete.gif', get_lang('Activate'));
-
-					$link['cmd']  = "hide=yes";
-					$lnk[] = $link;
-
-					if($toolsRow["added_tool"] == 1)
-					{
-						$link['name'] = get_lang("Delete");
-						$link['cmd'] = "askDelete=yes";
-						$lnk[] = $link;
-					}
-				}
-
-				if ($toolsRow["visibility"] == 0 && $toolsRow["added_tool"] == 0)
-				{
-					$link['name'] = Display::return_icon('delete.gif', get_lang('Remove'));
-					$link['cmd'] = "remove=yes";
-					$lnk[] = $link;
-				}
-			}
-			if (is_array($lnk))
-			{
-				foreach($lnk as $this_link)
-				{
-					if (!$toolsRow['adminlink'])
-						{
-							echo "<a href=\"" .api_get_self(). "?".api_get_cidreq()."&amp;id=" . $toolsRow["id"] . "&amp;" . $this_link['cmd'] . "\">" .	$this_link['name'] . "</a>";
-						}
-				}
-			}
-
-			// Allow editing of invisible homepage links (modified external_module)
-			/*
-			if ($toolsRow["added_tool"] == 1 &&
-					api_is_allowed_to_edit() && !$toolsRow["visibility"])
-			*/
-			if ($toolsRow["added_tool"] == 1 && api_is_allowed_to_edit() && !$toolsRow["visibility"]
-				&& $toolsRow['image'] != 'scormbuilder.gif' && $toolsRow['image'] != 'scormbuilder_na.gif')
-				echo	"<a class=\"nobold\" href=\"" . api_get_path(WEB_PATH) .
-						'main/external_module/external_module.php' .
-						"?".api_get_cidreq()."&amp;id=".$toolsRow["id"]."\">". get_lang("Edit"). "</a>";
-
-			echo "</td>\n";
-
-			if($i%2)
-			{
-				echo "</tr>\n";
-			}
-
-			$i++;
-		}
-	}
-
-	if($i%2)
-	{
-		echo	"<td width=\"50%\">&nbsp;</td>\n",
-				"</tr>\n";
-	}
-}
-
-
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
-*/
-
-/*
------------------------------------------------------------
-	Work with data post askable by admin of course (franglais, clean this)
------------------------------------------------------------
-*/
-if (api_is_allowed_to_edit())
-{
-	/*  Work request */
-
-	/*
-	-----------------------------------------------------------
-		Modify home page
-	-----------------------------------------------------------
-	*/
-
-	/*
-	 * display message to confirm that a tool must be hidden from the list of available tools
-	 * (visibility 0,1->2)
-	 */
-
-	if($_GET["remove"])
-	{
-		$msgDestroy=get_lang('DelLk').'<br />';
-		$msgDestroy.='<a href="'.api_get_self().'">'.get_lang('No').'</a>&nbsp;|&nbsp;';
-		$msgDestroy.='<a href="'.api_get_self().'?destroy=yes&amp;id='.$_GET["id"].'">'.get_lang('Yes').'</a>';
-
-		Display :: display_confirmation_message($msgDestroy,false);
-	}
-
-	/*
-	 * Process hiding a tools from available tools.
-	 * visibility=2 are only view  by Dokeos Administrator (visibility 0,1->2)
-	 */
-
-	elseif ($_GET["destroy"])
-	{
-		Database::query("UPDATE $tool_table SET visibility='2' WHERE id='".$_GET["id"]."'",__FILE__,__LINE__);
-	}
-
-  	/*
-	-----------------------------------------------------------
-		HIDE
-	-----------------------------------------------------------
-	*/
-	elseif ($_GET["hide"]) // visibility 1 -> 0
-	{
-		Database::query("UPDATE $tool_table SET visibility=0 WHERE id='".$_GET["id"]."'",__FILE__,__LINE__);
-		Display::display_confirmation_message(get_lang('ToolIsNowHidden'));
-	}
-
-    /*
-	-----------------------------------------------------------
-		REACTIVATE
-	-----------------------------------------------------------
-	*/
-	elseif ($_GET["restore"]) // visibility 0,2 -> 1
-	{
-		Database::query("UPDATE $tool_table SET visibility=1  WHERE id='".$_GET["id"]."'",__FILE__,__LINE__);
-		Display::display_confirmation_message(get_lang('ToolIsNowVisible'));
-	}
-}
-
-// work with data post askable by admin of course
-
-if (api_is_platform_admin())
-{
-	// Show message to confirm that a tools must be hide from available tools
-	// visibility 0,1->2
-	if($_GET["askDelete"])
-	{
-		?>
-			<div id="toolhide">
-			<?php echo get_lang("DelLk"); ?>
-			<br />&nbsp;&nbsp;&nbsp;
-			<a href="<?php echo api_get_self(); ?>"><?php echo get_lang("No"); ?></a>&nbsp;|&nbsp;
-			<a href="<?php echo api_get_self(); ?>?delete=yes&id=<?php echo $_GET["id"]; ?>"><?php echo get_lang("Yes"); ?></a>
-			</div>
-		<?php
-	}
-
-	/*
-	 * Process hiding a tools from available tools.
-	 * visibility=2 are only view  by Dokeos Administrator visibility 0,1->2
-	 */
-
-	elseif (isset($_GET["delete"]) && $_GET["delete"])
-	{
-		Database::query("DELETE FROM $tool_table WHERE id='$id' AND added_tool=1",__FILE__,__LINE__);
-	}
-}
-
-/*
-==============================================================================
-		TOOLS VISIBLE FOR EVERYBODY
-==============================================================================
-*/
-
-echo "<div class=\"everybodyview\">";
-echo "<table width=\"100%\">";
-
-show_tools(TOOL_PUBLIC);
-
-echo "</table>";
-echo "</div>";
-
-
-/*
-==============================================================================
-		COURSE ADMIN ONLY VIEW
-==============================================================================
-*/
-
-// start of tools for CourseAdmins (teachers/tutors)
-if (api_is_allowed_to_edit())
-{
-	echo	"<div class=\"courseadminview\">";
-	echo	"<span class=\"viewcaption\">";
-	echo	get_lang("CourseAdminOnly");
-	echo	"</span>";
-	echo	"<table width=\"100%\">";
-
-	show_tools(TOOL_COURSE_ADMIN);
-
-	/*
-	-----------------------------------------------------------
-		INACTIVE TOOLS - HIDDEN (GREY) LINKS
-	-----------------------------------------------------------
-	*/
-
-	echo	"<tr><td colspan=\"4\"><hr style='color:\"#4171B5\"' noshade=\"noshade\" size=\"1\" /></td></tr>\n",
-
-			"<tr>\n",
-			"<td colspan=\"4\">\n",
-			"<div style=\"margin-bottom: 10px;\"><font color=\"#808080\">\n",get_lang("InLnk"),"</font></div>",
-			"</td>\n",
-			"</tr>\n";
-
-	show_tools(TOOL_PUBLIC_BUT_HIDDEN);
-
-	echo	"</table>";
-	echo	"</div> ";
-}
-
-/*
------------------------------------------------------------
-	Tools for platform admin only
------------------------------------------------------------
-*/
-
-if (api_is_platform_admin() && api_is_allowed_to_edit())
-{
-	?>
-		<div class="platformadminview">
-		<span class="viewcaption"><?php echo get_lang("PlatformAdminOnly"); ?></span>
-		<table width="100%">
-		<?php
-			show_tools(TOOL_PLATFORM_ADMIN);
-		?>
-		</table>
-		</div>
-	<?php
-}
-?>
+			}
+
+			/*
+			echo Display::return_icon($toolsRow['image'], get_lang(ucfirst($toolsRow['name']))),'&nbsp;', ($toolsRow['image']=="external.gif" || $toolsRow['image']=="external_na.gif" || $toolsRow['image']=="scormbuilder.gif" || $toolsRow['image']=="blog.gif") ? htmlspecialchars( $toolsRow['name'],ENT_QUOTES,$charset) : get_lang(ucfirst($toolsRow['name'])),'</a>';
+			*/
+			if ($toolsRow['image'] == 'file_html.gif' || $toolsRow['image'] == 'file_html_na.gif'
+				|| $toolsRow['image'] == 'scormbuilder.gif' || $toolsRow['image'] == 'scormbuilder_na.gif'
+				|| $toolsRow['image'] == 'blog.gif' || $toolsRow['image'] == 'blog_na.gif'
+				|| $toolsRow['image'] == 'external.gif' || $toolsRow['image'] == 'external_na.gif')
+			{
+				$tool_name = htmlspecialchars($toolsRow['name'], ENT_QUOTES, $charset);
+			}
+			else
+			{
+				$tool_name = get_lang(ucfirst($toolsRow['name']));
+			}
+			echo Display::return_icon($toolsRow['image'], $tool_name),'&nbsp;', $tool_name,'</a>';
+
+			// This part displays the links to hide or remove a tool.
+			// These links are only visible by the course manager.
+			unset($lnk);
+			if (api_is_allowed_to_edit())
+			{
+				if ($toolsRow["visibility"] == '1')
+				{
+					$link['name'] = Display::return_icon('remove.gif', get_lang('Deactivate'));
+					$link['cmd'] = "hide=yes";
+					$lnk[] = $link;
+				}
+
+				if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN)
+				{
+					$link['name'] = Display::return_icon('add.gif', get_lang('Activate'));
+					$link['cmd']  = "restore=yes";
+					$lnk[] = $link;
+
+					if($toolsRow["added_tool"] == 1)
+					{
+						$link['name'] = Display::return_icon('delete.gif', get_lang('Remove'));
+						$link['cmd']  = "remove=yes";
+						$lnk[] = $link;
+					}
+				}
+				if ($toolsRow['adminlink'])
+				{
+					echo	'<a href="'.$toolsRow['adminlink'].'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
+					//echo "edit link:".$properties['adminlink'];
+				}
+
+			}
+			if ( api_is_platform_admin() )
+			{
+				if ($toolsRow["visibility"]==2)
+				{
+					$link['name'] = Display::return_icon('undelete.gif', get_lang('Activate'));
+
+					$link['cmd']  = "hide=yes";
+					$lnk[] = $link;
+
+					if($toolsRow["added_tool"] == 1)
+					{
+						$link['name'] = get_lang("Delete");
+						$link['cmd'] = "askDelete=yes";
+						$lnk[] = $link;
+					}
+				}
+
+				if ($toolsRow["visibility"] == 0 && $toolsRow["added_tool"] == 0)
+				{
+					$link['name'] = Display::return_icon('delete.gif', get_lang('Remove'));
+					$link['cmd'] = "remove=yes";
+					$lnk[] = $link;
+				}
+			}
+			if (is_array($lnk))
+			{
+				foreach($lnk as $this_link)
+				{
+					if (!$toolsRow['adminlink'])
+						{
+							echo "<a href=\"" .api_get_self(). "?".api_get_cidreq()."&amp;id=" . $toolsRow["id"] . "&amp;" . $this_link['cmd'] . "\">" .	$this_link['name'] . "</a>";
+						}
+				}
+			}
+
+			// Allow editing of invisible homepage links (modified external_module)
+			/*
+			if ($toolsRow["added_tool"] == 1 &&
+					api_is_allowed_to_edit() && !$toolsRow["visibility"])
+			*/
+			if ($toolsRow["added_tool"] == 1 && api_is_allowed_to_edit() && !$toolsRow["visibility"]
+				&& $toolsRow['image'] != 'scormbuilder.gif' && $toolsRow['image'] != 'scormbuilder_na.gif')
+				echo	"<a class=\"nobold\" href=\"" . api_get_path(WEB_PATH) .
+						'main/external_module/external_module.php' .
+						"?".api_get_cidreq()."&amp;id=".$toolsRow["id"]."\">". get_lang("Edit"). "</a>";
+
+			echo "</td>\n";
+
+			if($i%2)
+			{
+				echo "</tr>\n";
+			}
+
+			$i++;
+		}
+	}
+
+	if($i%2)
+	{
+		echo	"<td width=\"50%\">&nbsp;</td>\n",
+				"</tr>\n";
+	}
+}
+
+
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
+*/
+
+/*
+-----------------------------------------------------------
+	Work with data post askable by admin of course (franglais, clean this)
+-----------------------------------------------------------
+*/
+if (api_is_allowed_to_edit())
+{
+	/*  Work request */
+
+	/*
+	-----------------------------------------------------------
+		Modify home page
+	-----------------------------------------------------------
+	*/
+
+	/*
+	 * display message to confirm that a tool must be hidden from the list of available tools
+	 * (visibility 0,1->2)
+	 */
+
+	if($_GET["remove"])
+	{
+		$msgDestroy=get_lang('DelLk').'<br />';
+		$msgDestroy.='<a href="'.api_get_self().'">'.get_lang('No').'</a>&nbsp;|&nbsp;';
+		$msgDestroy.='<a href="'.api_get_self().'?destroy=yes&amp;id='.$_GET["id"].'">'.get_lang('Yes').'</a>';
+
+		Display :: display_confirmation_message($msgDestroy,false);
+	}
+
+	/*
+	 * Process hiding a tools from available tools.
+	 * visibility=2 are only view  by Dokeos Administrator (visibility 0,1->2)
+	 */
+
+	elseif ($_GET["destroy"])
+	{
+		Database::query("UPDATE $tool_table SET visibility='2' WHERE id='".$_GET["id"]."'",__FILE__,__LINE__);
+	}
+
+  	/*
+	-----------------------------------------------------------
+		HIDE
+	-----------------------------------------------------------
+	*/
+	elseif ($_GET["hide"]) // visibility 1 -> 0
+	{
+		Database::query("UPDATE $tool_table SET visibility=0 WHERE id='".$_GET["id"]."'",__FILE__,__LINE__);
+		Display::display_confirmation_message(get_lang('ToolIsNowHidden'));
+	}
+
+    /*
+	-----------------------------------------------------------
+		REACTIVATE
+	-----------------------------------------------------------
+	*/
+	elseif ($_GET["restore"]) // visibility 0,2 -> 1
+	{
+		Database::query("UPDATE $tool_table SET visibility=1  WHERE id='".$_GET["id"]."'",__FILE__,__LINE__);
+		Display::display_confirmation_message(get_lang('ToolIsNowVisible'));
+	}
+}
+
+// work with data post askable by admin of course
+
+if (api_is_platform_admin())
+{
+	// Show message to confirm that a tools must be hide from available tools
+	// visibility 0,1->2
+	if($_GET["askDelete"])
+	{
+		?>
+			<div id="toolhide">
+			<?php echo get_lang("DelLk"); ?>
+			<br />&nbsp;&nbsp;&nbsp;
+			<a href="<?php echo api_get_self(); ?>"><?php echo get_lang("No"); ?></a>&nbsp;|&nbsp;
+			<a href="<?php echo api_get_self(); ?>?delete=yes&id=<?php echo $_GET["id"]; ?>"><?php echo get_lang("Yes"); ?></a>
+			</div>
+		<?php
+	}
+
+	/*
+	 * Process hiding a tools from available tools.
+	 * visibility=2 are only view  by Dokeos Administrator visibility 0,1->2
+	 */
+
+	elseif (isset($_GET["delete"]) && $_GET["delete"])
+	{
+		Database::query("DELETE FROM $tool_table WHERE id='$id' AND added_tool=1",__FILE__,__LINE__);
+	}
+}
+
+/*
+==============================================================================
+		TOOLS VISIBLE FOR EVERYBODY
+==============================================================================
+*/
+
+echo "<div class=\"everybodyview\">";
+echo "<table width=\"100%\">";
+
+show_tools(TOOL_PUBLIC);
+
+echo "</table>";
+echo "</div>";
+
+
+/*
+==============================================================================
+		COURSE ADMIN ONLY VIEW
+==============================================================================
+*/
+
+// start of tools for CourseAdmins (teachers/tutors)
+if (api_is_allowed_to_edit())
+{
+	echo	"<div class=\"courseadminview\">";
+	echo	"<span class=\"viewcaption\">";
+	echo	get_lang("CourseAdminOnly");
+	echo	"</span>";
+	echo	"<table width=\"100%\">";
+
+	show_tools(TOOL_COURSE_ADMIN);
+
+	/*
+	-----------------------------------------------------------
+		INACTIVE TOOLS - HIDDEN (GREY) LINKS
+	-----------------------------------------------------------
+	*/
+
+	echo	"<tr><td colspan=\"4\"><hr style='color:\"#4171B5\"' noshade=\"noshade\" size=\"1\" /></td></tr>\n",
+
+			"<tr>\n",
+			"<td colspan=\"4\">\n",
+			"<div style=\"margin-bottom: 10px;\"><font color=\"#808080\">\n",get_lang("InLnk"),"</font></div>",
+			"</td>\n",
+			"</tr>\n";
+
+	show_tools(TOOL_PUBLIC_BUT_HIDDEN);
+
+	echo	"</table>";
+	echo	"</div> ";
+}
+
+/*
+-----------------------------------------------------------
+	Tools for platform admin only
+-----------------------------------------------------------
+*/
+
+if (api_is_platform_admin() && api_is_allowed_to_edit())
+{
+	?>
+		<div class="platformadminview">
+		<span class="viewcaption"><?php echo get_lang("PlatformAdminOnly"); ?></span>
+		<table width="100%">
+		<?php
+			show_tools(TOOL_PLATFORM_ADMIN);
+		?>
+		</table>
+		</div>
+	<?php
+}
+?>

+ 308 - 308
main/course_home/3column.php

@@ -1,312 +1,312 @@
-<?php
-
-// $Id: 3column.php,v 1.2 2006/08/10 14:26:12 pcool Exp $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2005 Dokeos S.A.
-	Copyright (c) 2003 Ghent University
-	Copyright (c) 2001 Universite Catholique de Louvain
-	Copyright (c) various contributors
-	Copyright (c) Bart Mollet, Hogeschool Gent
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
-==============================================================================
-*/
-/**
+<?php
+
+// $Id: 3column.php,v 1.2 2006/08/10 14:26:12 pcool Exp $
+/*
 ==============================================================================
-*                  HOME PAGE FOR EACH COURSE (BASIC TOOLS FIXED)
-*
-*	This page, included in every course's index.php is the home
-*	page.To make administration simple, the professor edits his
-*	course from it's home page. Only the login detects that the
-*	visitor is allowed to activate, deactivate home page links,
-*	access to Professor's tools (statistics, edit forums...).
-*
-*	@package dokeos.course_home
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2005 Dokeos S.A.
+	Copyright (c) 2003 Ghent University
+	Copyright (c) 2001 Universite Catholique de Louvain
+	Copyright (c) various contributors
+	Copyright (c) Bart Mollet, Hogeschool Gent
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+/**
 ==============================================================================
-*/
-$hide = isset($_GET['hide']) && $_GET['hide'] == 'yes' ? 'yes' : null;
-$restore = isset($_GET['restore']) && $_GET['restore'] == 'yes' ? 'yes' : null;
-$id  = isset($_GET['id']) ? intval($_GET['id']) : null;
-
-include('../../main/course_home/btf_functions.php');  // RH: extra ../
-$is_AllowedToEdit = is_allowed_to_edit();  // RH: Allowed is not allowed...
-
-
-$TABLE_TOOLS = Database::get_main_table(TABLE_MAIN_COURSE_MODULE);
-$TBL_ACCUEIL = Database::get_course_table(TABLE_TOOL_LIST);
-
-// WORK with data post askable by admin of  course
-if (is_allowed_to_edit())
-{
-/*  Work request */
-
-/*> > > > > > > > > > > > MODIFY HOME PAGE < < < < < < < < < < < <*/
-
-/*
- * Edit visibility of tools
- *
- *     visibility = 1 - everybody
- *     visibility = 0 - prof and admin
- *     visibility = 2 - admin
- *
- * Who can change visibility ?
+*                  HOME PAGE FOR EACH COURSE (BASIC TOOLS FIXED)
+*
+*	This page, included in every course's index.php is the home
+*	page.To make administration simple, the professor edits his
+*	course from it's home page. Only the login detects that the
+*	visitor is allowed to activate, deactivate home page links,
+*	access to Professor's tools (statistics, edit forums...).
+*
+*	@package dokeos.course_home
+==============================================================================
+*/
+$hide = isset($_GET['hide']) && $_GET['hide'] == 'yes' ? 'yes' : null;
+$restore = isset($_GET['restore']) && $_GET['restore'] == 'yes' ? 'yes' : null;
+$id  = isset($_GET['id']) ? intval($_GET['id']) : null;
+
+include('../../main/course_home/btf_functions.php');  // RH: extra ../
+$is_AllowedToEdit = is_allowed_to_edit();  // RH: Allowed is not allowed...
+
+
+$TABLE_TOOLS = Database::get_main_table(TABLE_MAIN_COURSE_MODULE);
+$TBL_ACCUEIL = Database::get_course_table(TABLE_TOOL_LIST);
+
+// WORK with data post askable by admin of  course
+if (is_allowed_to_edit())
+{
+/*  Work request */
+
+/*> > > > > > > > > > > > MODIFY HOME PAGE < < < < < < < < < < < <*/
+
+/*
+ * Edit visibility of tools
+ *
+ *     visibility = 1 - everybody
+ *     visibility = 0 - prof and admin
+ *     visibility = 2 - admin
+ *
+ * Who can change visibility ?
+ *
+ *     admin = 0 - prof and admin
+ *     admin = 1 - admin
  *
- *     admin = 0 - prof and admin
- *     admin = 1 - admin
- *
- * Show message to confirm that a tools must be hide from aivailable tools
- *
- *     visibility 0,1->2 - $remove
+ * Show message to confirm that a tools must be hide from aivailable tools
  *
- * Process hiding a tools from aivailable tools.
- *
- *     visibility=2                         are only view  by Dokeos
- * Administrator visibility 0,1->2 - $destroy
- *
- *     visibility 1 -> 0 - $hide / $restore
- */
-
-	/*
-	 * diplay message to confirm that a tools must be hide from aivailable tools
-	 * (visibility 0,1->2)
-	 */
-
-	if($remove)
-	{
-		$sql = "SELECT * FROM $TBL_ACCUEIL WHERE id=$id";
-		$result = Database::query($sql,__FILE__,__LINE__);
-		$toolsRow = mysql_fetch_array($result);
-		$tool_name = htmlspecialchars($toolsRow['name'] != "" ? $toolsRow['name'] : $toolsRow['link'],ENT_QUOTES,$charset);
-		if($toolsRow['img'] != "external.gif")
-		{
-			$toolsRow['link']=api_get_path(WEB_CODE_PATH).$toolsRow['link'];
-		}
-		$toolsRow['image']=api_get_path(WEB_CODE_PATH)."img/".$toolsRow['image'];
-
-		echo 	"<br><br><br>\n";
-		echo	"<table class=\"message\" width=\"70%\" align=\"center\">\n",
-				"<tr><td width=\"7%\" align=\"center\">\n",
-			   	"<a href=\"".$toolsRow['link']."\">".Display::return_icon($toolsRow['image'], get_lang('Delete')),"</a></td>\n",
-				"<td width=\"28%\" height=\"45\"><small>\n",
-				"<a href=\"".$toolsRow['link']."\">".$tool_name."</a></small></td>\n";
-		echo	"<td align=\"center\">\n",
-				"<font color=\"#ff0000\">",
-				"&nbsp;&nbsp;&nbsp;",
-				"<strong>",get_lang('DelLk'),"</strong>",
-				"<br>&nbsp;&nbsp;&nbsp;\n",
-				"<a href=\"".api_get_self()."\">",get_lang('No'),"</a>\n",
-				"&nbsp;|&nbsp;\n",
-				"<a href=\"".api_get_self()."?destroy=yes&amp;id=$id\">",get_lang('Yes'),"</a>\n",
-				"</font></td></tr>\n",
-				"</table>\n";
-		echo 	"<br><br><br>\n";
-
-	} // if remove
-
-	/*
-	 * Process hiding a tools from aivailable tools.
-	 * visibility=2 are only view  by Dokeos Administrator (visibility 0,1->2)
-	 */
-
-	elseif ($destroy)
-	{
-		Database::query("UPDATE $TBL_ACCUEIL SET visibility='2' WHERE id=$id");
-	}
-
-/*--------------------------------------
-                HIDE
-  --------------------------------------*/
-
-	elseif ($hide) // visibility 1 -> 0
-	{
-		Database::query("UPDATE $TBL_ACCUEIL SET visibility=0 WHERE id=$id");
-		Display::display_confirmation_message(get_lang('ToolIsNowHidden'));
-	}
-
-/*--------------------------------------
-              REACTIVATE
-  --------------------------------------*/
-
-	elseif ($restore) // visibility 0,2 -> 1
-	{
-		Database::query("UPDATE $TBL_ACCUEIL SET visibility=1  WHERE id=$id");
-		Display::display_confirmation_message(get_lang('ToolIsNowVisible'));
-	}
-
-	/*
-	 * editing "apparance" of  a tools  on the course Home Page.
-	 */
-
-	elseif (isset ($update) && $update)
-	{
-		$result 	= Database::query("SELECT * FROM $TBL_ACCUEIL WHERE id=$id");
-		$toolsRow 	= mysql_fetch_array($result);
-		$racine		= $_configuration['root_sys']."/".$currentCourseID."/images/";
-		$chemin		= $racine;
-		$name	= $toolsRow[1];
-		$image		= $toolsRow[3];
-
-		echo	"<tr>\n",
-
-				"<td colspan=\"4\">\n",
-
-				"<table>\n",
-
-				"<tr>\n",
-				"<td>\n",
-
-				"<form method=\"post\" action=\"".api_get_self()."\">\n",
-				"<input type=\"hidden\" name=\"id\" value=\"$id\">\n",
-				"Image : ".Display::return_icon($image)."\n",
-				"</td>\n",
-
-				"<td>\n",
-				"<select name=\"image\">\n",
-				"<option selected>",$image,"</option>\n";
-
-		if ($dir = @opendir($chemin))
-		{
-			while($file = readdir($dir))
-			{
-				if($file==".." OR $file==".")
-				{
-					unset($file);
-				}
-
-				echo "<option>",$file,"</option>\n";
-
-			}
-
-			closedir($dir);
-		}
-
-		echo	"</select>\n",
-
-				"</td>\n",
-				"</tr>\n",
-
-				"<tr>\n",
-				"<td>",get_lang('NameOfTheLink')," : </td>\n",
-				"<td><input type=\"text\" name=\"name\" value=\"",$name,"\"></td>\n",
-				"</tr>\n",
-
-				"<tr>\n",
-				"<td>Lien :</td>\n",
-				"<td><input type=\"text\" name=\"link\" value=\"",$link,"\"></td>\n",
-				"</tr>\n",
-
-				"<tr>\n",
-				"<td colspan=\"2\"><input type=\"submit\" name=\"submit\" value=\"",get_lang('Ok'),"\"></td>\n",
-				"</tr>\n",
-
-				"</form>\n",
-
-				"</table>\n",
-
-				"</td>\n",
-				"</tr>\n";
-	}
-}
-
-
-// work with data post askable by admin of  course
-
-if ($is_platformAdmin and is_allowed_to_edit())
-{
-	// Show message to confirm that a tools must be hide  from aivailable tools
-	// visibility 0,1->2
-	if($askDelete)
-	{
-		echo	"<table align=\"center\"><tr>\n",
-
-				"<td colspan=\"4\">\n",
-				"<br><br>\n",
-				"<font color=\"#ff0000\">",
-				"&nbsp;&nbsp;&nbsp;",
-				"<strong>",get_lang('DelLk'),"</strong>",
-				"<br>&nbsp;&nbsp;&nbsp;\n",
-				"<a href=\"".api_get_self()."\">",get_lang('No'),"</a>\n",
-				"&nbsp;|&nbsp;\n",
-				"<a href=\"".api_get_self()."?delete=yes&amp;id=$id\">",get_lang('Yes'),"</a>\n",
-				"</font>\n",
-				"<br><br><br>\n",
-				"</td>\n",
-
-				"</tr>",
-				"</table>\n";
-	} // if remove
-
-	/*
-	 * Process hiding a tools from aivailable tools.
-	 * visibility=2 are only viewed by Dokeos Administrator visibility 0,1->2
-	 */
-
-	elseif (isset($delete) && $delete)
-	{
-		Database::query("DELETE FROM $TBL_ACCUEIL WHERE id=$id AND added_tool=1");
-	}
-}
-
-
-echo "<table class=\"item\" align=\"center\" border=\"0\" width=\"95%\">\n";
-
-/*==========================
-     TOOLS  FOR  EVERYBODY
-  ==========================*/
-
-echo	"<tr>\n<td colspan=\"6\">&nbsp;</td>\n</tr>\n";
-echo	"<tr>\n<td colspan=\"6\">";
-showtools2('Basic');
-showtools2('External');
-echo 	"</td>\n</tr>\n";
-
-
-/*==========================
-       PROF ONLY VIEW
-  ==========================*/
-
-if (is_allowed_to_edit())
-{
-	echo	"<tr><td colspan=\"6\"><hr noshade size=\"1\" /></td></tr>\n",
-			"<tr>\n","<td colspan=\"6\">\n",
-			"<font color=\"#F66105\">\n",get_lang('CourseAdminOnly'),"</font>\n",
-			"</td>\n","</tr>\n";
-	echo	"<tr>\n<td colspan=\"6\">";
-	showtools2('courseAdmin');
-	echo 	"</td>\n</tr>\n";
-}
-
-
-/*--------------------------------------
-       TOOLS FOR PLATFORM ADMIN ONLY
-  --------------------------------------*/
-
-if ($is_platformAdmin and is_allowed_to_edit())
-{
-	echo	"<tr>","<td colspan=\"6\">",
-			"<hr noshade size=\"1\" />",
-			"</td>","</tr>\n",
-			"<tr>\n","<td colspan=\"6\">\n",
-			"<font color=\"#F66105\" >",get_lang('PlatformAdminOnly'),"</font>\n",
-			"</td>\n","</tr>\n";
-	echo	"<tr>\n<td colspan=\"6\">";
-	showtools2('platformAdmin');
-	echo 	"</td>\n</tr>\n";
-}
-
-echo	"</table>\n";
-?>
+ *     visibility 0,1->2 - $remove
+ *
+ * Process hiding a tools from aivailable tools.
+ *
+ *     visibility=2                         are only view  by Dokeos
+ * Administrator visibility 0,1->2 - $destroy
+ *
+ *     visibility 1 -> 0 - $hide / $restore
+ */
+
+	/*
+	 * diplay message to confirm that a tools must be hide from aivailable tools
+	 * (visibility 0,1->2)
+	 */
+
+	if($remove)
+	{
+		$sql = "SELECT * FROM $TBL_ACCUEIL WHERE id=$id";
+		$result = Database::query($sql,__FILE__,__LINE__);
+		$toolsRow = mysql_fetch_array($result);
+		$tool_name = htmlspecialchars($toolsRow['name'] != "" ? $toolsRow['name'] : $toolsRow['link'],ENT_QUOTES,$charset);
+		if($toolsRow['img'] != "external.gif")
+		{
+			$toolsRow['link']=api_get_path(WEB_CODE_PATH).$toolsRow['link'];
+		}
+		$toolsRow['image']=api_get_path(WEB_CODE_PATH)."img/".$toolsRow['image'];
+
+		echo 	"<br><br><br>\n";
+		echo	"<table class=\"message\" width=\"70%\" align=\"center\">\n",
+				"<tr><td width=\"7%\" align=\"center\">\n",
+			   	"<a href=\"".$toolsRow['link']."\">".Display::return_icon($toolsRow['image'], get_lang('Delete')),"</a></td>\n",
+				"<td width=\"28%\" height=\"45\"><small>\n",
+				"<a href=\"".$toolsRow['link']."\">".$tool_name."</a></small></td>\n";
+		echo	"<td align=\"center\">\n",
+				"<font color=\"#ff0000\">",
+				"&nbsp;&nbsp;&nbsp;",
+				"<strong>",get_lang('DelLk'),"</strong>",
+				"<br>&nbsp;&nbsp;&nbsp;\n",
+				"<a href=\"".api_get_self()."\">",get_lang('No'),"</a>\n",
+				"&nbsp;|&nbsp;\n",
+				"<a href=\"".api_get_self()."?destroy=yes&amp;id=$id\">",get_lang('Yes'),"</a>\n",
+				"</font></td></tr>\n",
+				"</table>\n";
+		echo 	"<br><br><br>\n";
+
+	} // if remove
+
+	/*
+	 * Process hiding a tools from aivailable tools.
+	 * visibility=2 are only view  by Dokeos Administrator (visibility 0,1->2)
+	 */
+
+	elseif ($destroy)
+	{
+		Database::query("UPDATE $TBL_ACCUEIL SET visibility='2' WHERE id=$id");
+	}
+
+/*--------------------------------------
+                HIDE
+  --------------------------------------*/
+
+	elseif ($hide) // visibility 1 -> 0
+	{
+		Database::query("UPDATE $TBL_ACCUEIL SET visibility=0 WHERE id=$id");
+		Display::display_confirmation_message(get_lang('ToolIsNowHidden'));
+	}
+
+/*--------------------------------------
+              REACTIVATE
+  --------------------------------------*/
+
+	elseif ($restore) // visibility 0,2 -> 1
+	{
+		Database::query("UPDATE $TBL_ACCUEIL SET visibility=1  WHERE id=$id");
+		Display::display_confirmation_message(get_lang('ToolIsNowVisible'));
+	}
+
+	/*
+	 * editing "apparance" of  a tools  on the course Home Page.
+	 */
+
+	elseif (isset ($update) && $update)
+	{
+		$result 	= Database::query("SELECT * FROM $TBL_ACCUEIL WHERE id=$id");
+		$toolsRow 	= mysql_fetch_array($result);
+		$racine		= $_configuration['root_sys']."/".$currentCourseID."/images/";
+		$chemin		= $racine;
+		$name	= $toolsRow[1];
+		$image		= $toolsRow[3];
+
+		echo	"<tr>\n",
+
+				"<td colspan=\"4\">\n",
+
+				"<table>\n",
+
+				"<tr>\n",
+				"<td>\n",
+
+				"<form method=\"post\" action=\"".api_get_self()."\">\n",
+				"<input type=\"hidden\" name=\"id\" value=\"$id\">\n",
+				"Image : ".Display::return_icon($image)."\n",
+				"</td>\n",
+
+				"<td>\n",
+				"<select name=\"image\">\n",
+				"<option selected>",$image,"</option>\n";
+
+		if ($dir = @opendir($chemin))
+		{
+			while($file = readdir($dir))
+			{
+				if($file==".." OR $file==".")
+				{
+					unset($file);
+				}
+
+				echo "<option>",$file,"</option>\n";
+
+			}
+
+			closedir($dir);
+		}
+
+		echo	"</select>\n",
+
+				"</td>\n",
+				"</tr>\n",
+
+				"<tr>\n",
+				"<td>",get_lang('NameOfTheLink')," : </td>\n",
+				"<td><input type=\"text\" name=\"name\" value=\"",$name,"\"></td>\n",
+				"</tr>\n",
+
+				"<tr>\n",
+				"<td>Lien :</td>\n",
+				"<td><input type=\"text\" name=\"link\" value=\"",$link,"\"></td>\n",
+				"</tr>\n",
+
+				"<tr>\n",
+				"<td colspan=\"2\"><input type=\"submit\" name=\"submit\" value=\"",get_lang('Ok'),"\"></td>\n",
+				"</tr>\n",
+
+				"</form>\n",
+
+				"</table>\n",
+
+				"</td>\n",
+				"</tr>\n";
+	}
+}
+
+
+// work with data post askable by admin of  course
+
+if ($is_platformAdmin and is_allowed_to_edit())
+{
+	// Show message to confirm that a tools must be hide  from aivailable tools
+	// visibility 0,1->2
+	if($askDelete)
+	{
+		echo	"<table align=\"center\"><tr>\n",
+
+				"<td colspan=\"4\">\n",
+				"<br><br>\n",
+				"<font color=\"#ff0000\">",
+				"&nbsp;&nbsp;&nbsp;",
+				"<strong>",get_lang('DelLk'),"</strong>",
+				"<br>&nbsp;&nbsp;&nbsp;\n",
+				"<a href=\"".api_get_self()."\">",get_lang('No'),"</a>\n",
+				"&nbsp;|&nbsp;\n",
+				"<a href=\"".api_get_self()."?delete=yes&amp;id=$id\">",get_lang('Yes'),"</a>\n",
+				"</font>\n",
+				"<br><br><br>\n",
+				"</td>\n",
+
+				"</tr>",
+				"</table>\n";
+	} // if remove
+
+	/*
+	 * Process hiding a tools from aivailable tools.
+	 * visibility=2 are only viewed by Dokeos Administrator visibility 0,1->2
+	 */
+
+	elseif (isset($delete) && $delete)
+	{
+		Database::query("DELETE FROM $TBL_ACCUEIL WHERE id=$id AND added_tool=1");
+	}
+}
+
+
+echo "<table class=\"item\" align=\"center\" border=\"0\" width=\"95%\">\n";
+
+/*==========================
+     TOOLS  FOR  EVERYBODY
+  ==========================*/
+
+echo	"<tr>\n<td colspan=\"6\">&nbsp;</td>\n</tr>\n";
+echo	"<tr>\n<td colspan=\"6\">";
+showtools2('Basic');
+showtools2('External');
+echo 	"</td>\n</tr>\n";
+
+
+/*==========================
+       PROF ONLY VIEW
+  ==========================*/
+
+if (is_allowed_to_edit())
+{
+	echo	"<tr><td colspan=\"6\"><hr noshade size=\"1\" /></td></tr>\n",
+			"<tr>\n","<td colspan=\"6\">\n",
+			"<font color=\"#F66105\">\n",get_lang('CourseAdminOnly'),"</font>\n",
+			"</td>\n","</tr>\n";
+	echo	"<tr>\n<td colspan=\"6\">";
+	showtools2('courseAdmin');
+	echo 	"</td>\n</tr>\n";
+}
+
+
+/*--------------------------------------
+       TOOLS FOR PLATFORM ADMIN ONLY
+  --------------------------------------*/
+
+if ($is_platformAdmin and is_allowed_to_edit())
+{
+	echo	"<tr>","<td colspan=\"6\">",
+			"<hr noshade size=\"1\" />",
+			"</td>","</tr>\n",
+			"<tr>\n","<td colspan=\"6\">\n",
+			"<font color=\"#F66105\" >",get_lang('PlatformAdminOnly'),"</font>\n",
+			"</td>\n","</tr>\n";
+	echo	"<tr>\n<td colspan=\"6\">";
+	showtools2('platformAdmin');
+	echo 	"</td>\n</tr>\n";
+}
+
+echo	"</table>\n";
+?>

+ 514 - 514
main/course_home/activity.php

@@ -1,315 +1,315 @@
-<?php // $Id: activity.php,v 1.5 2006/08/10 14:34:54 pcool Exp $
-
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2005 Dokeos S.A.
-	Copyright (c) 2003 Ghent University
-	Copyright (c) 2001 Universite Catholique de Louvain
-	Copyright (c) various contributors
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*         HOME PAGE FOR EACH COURSE
-*
-*	This page, included in every course's index.php is the home
-*	page. To make administration simple, the teacher edits his
-*	course from the home page. Only the login detects that the
-*	visitor is allowed to activate, deactivate home page links,
-*	access to the teachers tools (statistics, edit forums...).
-*
-*	@package dokeos.course_home
-==============================================================================
-*/
-require_once '../../main/inc/global.inc.php';
-/*
-==============================================================================
-		FUNCTIONS
-==============================================================================
-*/
-
-/**
- * Displays the tools of a certain category.
- *
- * @return void
- * @param string $course_tool_category	contains the category of tools to display:
- * "toolauthoring", "toolinteraction", "tooladmin", "tooladminplatform"
- */
-
-function show_tools_category($course_tool_category)
-{
-	$web_code_path = api_get_path(WEB_CODE_PATH);
-	$course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
-	$is_allowed_to_edit = api_is_allowed_to_edit();
-	$is_platform_admin = api_is_platform_admin();
-
-	switch ($course_tool_category)
-	{
-		case TOOL_STUDENT_VIEW:
-				$result = Database::query("SELECT * FROM $course_tool_table WHERE visibility = '1' AND (category = 'authoring' OR category = 'interaction') ORDER BY id",__FILE__,__LINE__);
-				$colLink ="##003399";
-				break;
-
-		case TOOL_AUTHORING:
-
-				$result = Database::query("SELECT * FROM $course_tool_table WHERE category = 'authoring' ORDER BY id",__FILE__,__LINE__);
-				$colLink ="##003399";
-				break;
-
-		case TOOL_INTERACTION:
-
-				$result = Database::query("SELECT * FROM $course_tool_table WHERE category = 'interaction' ORDER BY id",__FILE__,__LINE__);
-				$colLink ="##003399";
-				break;
-
-		case TOOL_ADMIN_VISIBLE:
-
-				$result = Database::query("SELECT * FROM $course_tool_table WHERE category = 'admin' AND visibility ='1' ORDER BY id",__FILE__,__LINE__);
-				$colLink ="##003399";
-				break;
-
-		case TOOL_ADMIN_PLATEFORM:
-
-				$result = Database::query("SELECT * FROM $course_tool_table WHERE category = 'admin' ORDER BY id",__FILE__,__LINE__);
-				$colLink ="##003399";
-				break;
-
-
-	}
-
-	while ($temp_row = Database::fetch_array($result))
-	{
-		$all_tools_list[]=$temp_row;
-	}
-
-	/*if(api_is_course_coach())
-	{
-		$result = Database::query("SELECT * FROM $course_tool_table WHERE name='tracking'",__FILE__,__LINE__);
-		$all_tools_list[]=Database :: fetch_array($result);
-	}*/
-
-	$i=0;
-	// grabbing all the links that have the property on_homepage set to 1
-	$course_link_table = Database::get_course_table(TABLE_LINK);
-	$course_item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
-
-	switch ($course_tool_category)
-	{
-			case TOOL_AUTHORING:
-			$sql_links="SELECT tl.*, tip.visibility
-					FROM $course_link_table tl
-					LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
-						WHERE tl.on_homepage='1'";
-
-			break;
-
-			case TOOL_INTERACTION:
-			$sql_links = null;
-			/*
-			$sql_links="SELECT tl.*, tip.visibility
-				FROM $course_link_table tl
-				LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
-						WHERE tl.on_homepage='1' ";
-			*/
-			break;
-
-			case TOOL_STUDENT_VIEW:
-				$sql_links="SELECT tl.*, tip.visibility
-				FROM $course_link_table tl
-				LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
-						WHERE tl.on_homepage='1'";
-			break;
-
-			case TOOL_ADMIN:
-				$sql_links="SELECT tl.*, tip.visibility
-				FROM $course_link_table tl
-				LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
-						WHERE tl.on_homepage='1'";
-			break;
-
-		default:
-			$sql_links = null;
-			break;
-	}
-
-	//edit by Kevin Van Den Haute (kevin@develop-it.be) for integrating Smartblogs
-	if($sql_links != null)
-	{
-		$result_links = Database::query($sql_links,__FILE__,__LINE__);
-		$properties = array();
-		while($links_row = Database::fetch_array($result_links))
-		{
-			unset($properties);
-
-			$properties['name'] = $links_row['title'];
-			$properties['link'] = $links_row['url'];
-			$properties['visibility'] = $links_row['visibility'];
-			$properties['image'] = ($links_row['visibility']== '0') ? "file_html.gif" : "file_html.gif";
-			$properties['adminlink'] = api_get_path(WEB_CODE_PATH) . "link/link.php?action=editlink&id=".$links_row['id'];
-			$properties['target'] = $links_row['target'];
-			$tmp_all_tools_list[] = $properties;
-		}
-	}
-
-	if(isset($tmp_all_tools_list))
-	{
-		foreach($tmp_all_tools_list as $toolsRow)
-		{
-			if (api_get_session_id()!=0 && in_array($toolsRow['name'],array('course_maintenance','course_setting'))) {
-				continue;
-			}
-			if($toolsRow['image'] == 'blog.gif')
-			{
-				// Init
-				$tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
-
-				// Get blog id
-				$blog_id = substr($toolsRow['link'], strrpos($toolsRow['link'], '=') + 1, strlen($toolsRow['link']));
-
-				// Get blog members
-				if($is_platform_admin)
-				{
-					$sql_blogs = "
-						SELECT *
-						FROM " . $tbl_blogs_rel_user . " `blogs_rel_user`
-						WHERE `blog_id` = " . $blog_id;
-				}
-				else
-				{
-					$sql_blogs = "
-						SELECT *
-						FROM " . $tbl_blogs_rel_user . " `blogs_rel_user`
-						WHERE
-							`blog_id` = " . $blog_id . " AND
-							`user_id` = " . api_get_user_id();
-				}
-
-				$result_blogs = Database::query($sql_blogs, __FILE__, __LINE__);
-
-				if(Database::num_rows($result_blogs) > 0)
-					$all_tools_list[] = $toolsRow;
-			}
-			else
-				$all_tools_list[] = $toolsRow;
-		}
-	}
-
-	if(isset($all_tools_list))
-	{
-		$lnk = '';
-		foreach($all_tools_list as $toolsRow)
-		{
-			if(!($i%2))
-				{echo	"<tr valign=\"top\">\n";}
-
-			// This part displays the links to hide or remove a tool.
-			// These links are only visible by the course manager.
-			unset($lnk);
-			echo '<td width="50%">' . "\n";
-			if($is_allowed_to_edit)
-			{
-				if($toolsRow['visibility'] == '1' && $toolsRow['admin'] !='1')
-				{
-
-					$link['name'] = Display::return_icon('visible.gif', get_lang('Deactivate'),array('id'=>'linktool_'.$toolsRow["id"]));
-
-					$link['cmd'] = "hide=yes";
-					$lnk[] = $link;
-				}
-
-				if($toolsRow['visibility'] == '0' && $toolsRow['admin'] !='1')
-				{
-					$link['name'] = Display::return_icon('invisible.gif', get_lang('Activate'),array('id'=>'linktool_'.$toolsRow["id"]));
-					$link['cmd'] = "restore=yes";
-					$lnk[] = $link;
-				}
-
-				if(!empty($toolsRow['adminlink']))
-				{
-					echo	'<a href="'.$toolsRow['adminlink'].'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
-				}
-
-			}
-
-			// Both checks are necessary as is_platform_admin doesn't take student view into account
+<?php // $Id: activity.php,v 1.5 2006/08/10 14:34:54 pcool Exp $
+
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2005 Dokeos S.A.
+	Copyright (c) 2003 Ghent University
+	Copyright (c) 2001 Universite Catholique de Louvain
+	Copyright (c) various contributors
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*         HOME PAGE FOR EACH COURSE
+*
+*	This page, included in every course's index.php is the home
+*	page. To make administration simple, the teacher edits his
+*	course from the home page. Only the login detects that the
+*	visitor is allowed to activate, deactivate home page links,
+*	access to the teachers tools (statistics, edit forums...).
+*
+*	@package dokeos.course_home
+==============================================================================
+*/
+require_once '../../main/inc/global.inc.php';
+/*
+==============================================================================
+		FUNCTIONS
+==============================================================================
+*/
+
+/**
+ * Displays the tools of a certain category.
+ *
+ * @return void
+ * @param string $course_tool_category	contains the category of tools to display:
+ * "toolauthoring", "toolinteraction", "tooladmin", "tooladminplatform"
+ */
+
+function show_tools_category($course_tool_category)
+{
+	$web_code_path = api_get_path(WEB_CODE_PATH);
+	$course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
+	$is_allowed_to_edit = api_is_allowed_to_edit();
+	$is_platform_admin = api_is_platform_admin();
+
+	switch ($course_tool_category)
+	{
+		case TOOL_STUDENT_VIEW:
+				$result = Database::query("SELECT * FROM $course_tool_table WHERE visibility = '1' AND (category = 'authoring' OR category = 'interaction') ORDER BY id",__FILE__,__LINE__);
+				$colLink ="##003399";
+				break;
+
+		case TOOL_AUTHORING:
+
+				$result = Database::query("SELECT * FROM $course_tool_table WHERE category = 'authoring' ORDER BY id",__FILE__,__LINE__);
+				$colLink ="##003399";
+				break;
+
+		case TOOL_INTERACTION:
+
+				$result = Database::query("SELECT * FROM $course_tool_table WHERE category = 'interaction' ORDER BY id",__FILE__,__LINE__);
+				$colLink ="##003399";
+				break;
+
+		case TOOL_ADMIN_VISIBLE:
+
+				$result = Database::query("SELECT * FROM $course_tool_table WHERE category = 'admin' AND visibility ='1' ORDER BY id",__FILE__,__LINE__);
+				$colLink ="##003399";
+				break;
+
+		case TOOL_ADMIN_PLATEFORM:
+
+				$result = Database::query("SELECT * FROM $course_tool_table WHERE category = 'admin' ORDER BY id",__FILE__,__LINE__);
+				$colLink ="##003399";
+				break;
+
+
+	}
+
+	while ($temp_row = Database::fetch_array($result))
+	{
+		$all_tools_list[]=$temp_row;
+	}
+
+	/*if(api_is_course_coach())
+	{
+		$result = Database::query("SELECT * FROM $course_tool_table WHERE name='tracking'",__FILE__,__LINE__);
+		$all_tools_list[]=Database :: fetch_array($result);
+	}*/
+
+	$i=0;
+	// grabbing all the links that have the property on_homepage set to 1
+	$course_link_table = Database::get_course_table(TABLE_LINK);
+	$course_item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
+
+	switch ($course_tool_category)
+	{
+			case TOOL_AUTHORING:
+			$sql_links="SELECT tl.*, tip.visibility
+					FROM $course_link_table tl
+					LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
+						WHERE tl.on_homepage='1'";
+
+			break;
+
+			case TOOL_INTERACTION:
+			$sql_links = null;
+			/*
+			$sql_links="SELECT tl.*, tip.visibility
+				FROM $course_link_table tl
+				LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
+						WHERE tl.on_homepage='1' ";
+			*/
+			break;
+
+			case TOOL_STUDENT_VIEW:
+				$sql_links="SELECT tl.*, tip.visibility
+				FROM $course_link_table tl
+				LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
+						WHERE tl.on_homepage='1'";
+			break;
+
+			case TOOL_ADMIN:
+				$sql_links="SELECT tl.*, tip.visibility
+				FROM $course_link_table tl
+				LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
+						WHERE tl.on_homepage='1'";
+			break;
+
+		default:
+			$sql_links = null;
+			break;
+	}
+
+	//edit by Kevin Van Den Haute (kevin@develop-it.be) for integrating Smartblogs
+	if($sql_links != null)
+	{
+		$result_links = Database::query($sql_links,__FILE__,__LINE__);
+		$properties = array();
+		while($links_row = Database::fetch_array($result_links))
+		{
+			unset($properties);
+
+			$properties['name'] = $links_row['title'];
+			$properties['link'] = $links_row['url'];
+			$properties['visibility'] = $links_row['visibility'];
+			$properties['image'] = ($links_row['visibility']== '0') ? "file_html.gif" : "file_html.gif";
+			$properties['adminlink'] = api_get_path(WEB_CODE_PATH) . "link/link.php?action=editlink&id=".$links_row['id'];
+			$properties['target'] = $links_row['target'];
+			$tmp_all_tools_list[] = $properties;
+		}
+	}
+
+	if(isset($tmp_all_tools_list))
+	{
+		foreach($tmp_all_tools_list as $toolsRow)
+		{
+			if (api_get_session_id()!=0 && in_array($toolsRow['name'],array('course_maintenance','course_setting'))) {
+				continue;
+			}
+			if($toolsRow['image'] == 'blog.gif')
+			{
+				// Init
+				$tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
+
+				// Get blog id
+				$blog_id = substr($toolsRow['link'], strrpos($toolsRow['link'], '=') + 1, strlen($toolsRow['link']));
+
+				// Get blog members
+				if($is_platform_admin)
+				{
+					$sql_blogs = "
+						SELECT *
+						FROM " . $tbl_blogs_rel_user . " `blogs_rel_user`
+						WHERE `blog_id` = " . $blog_id;
+				}
+				else
+				{
+					$sql_blogs = "
+						SELECT *
+						FROM " . $tbl_blogs_rel_user . " `blogs_rel_user`
+						WHERE
+							`blog_id` = " . $blog_id . " AND
+							`user_id` = " . api_get_user_id();
+				}
+
+				$result_blogs = Database::query($sql_blogs, __FILE__, __LINE__);
+
+				if(Database::num_rows($result_blogs) > 0)
+					$all_tools_list[] = $toolsRow;
+			}
+			else
+				$all_tools_list[] = $toolsRow;
+		}
+	}
+
+	if(isset($all_tools_list))
+	{
+		$lnk = '';
+		foreach($all_tools_list as $toolsRow)
+		{
+			if(!($i%2))
+				{echo	"<tr valign=\"top\">\n";}
+
+			// This part displays the links to hide or remove a tool.
+			// These links are only visible by the course manager.
+			unset($lnk);
+			echo '<td width="50%">' . "\n";
+			if($is_allowed_to_edit)
+			{
+				if($toolsRow['visibility'] == '1' && $toolsRow['admin'] !='1')
+				{
+
+					$link['name'] = Display::return_icon('visible.gif', get_lang('Deactivate'),array('id'=>'linktool_'.$toolsRow["id"]));
+
+					$link['cmd'] = "hide=yes";
+					$lnk[] = $link;
+				}
+
+				if($toolsRow['visibility'] == '0' && $toolsRow['admin'] !='1')
+				{
+					$link['name'] = Display::return_icon('invisible.gif', get_lang('Activate'),array('id'=>'linktool_'.$toolsRow["id"]));
+					$link['cmd'] = "restore=yes";
+					$lnk[] = $link;
+				}
+
+				if(!empty($toolsRow['adminlink']))
+				{
+					echo	'<a href="'.$toolsRow['adminlink'].'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
+				}
+
+			}
+
+			// Both checks are necessary as is_platform_admin doesn't take student view into account
 			if( $is_platform_admin && $is_allowed_to_edit)
-			{
- 				if($toolsRow['admin'] !='1')
-				{
-					$link['cmd'] = "hide=yes";
-
-				}
-
-			}
-
-			if(isset($lnk) && is_array($lnk))
-			{
-				foreach($lnk as $this_link)
-				{
-					if(empty($toolsRow['adminlink']))
-					{
-							echo "<a class=\"make_visible_and_invisible\"  href=\"" .api_get_self(). "?".api_get_cidreq()."&amp;id=" . $toolsRow["id"] . "&amp;" . $this_link['cmd'] . "\">" .	$this_link['name'] . "</a>";
-							//echo "<a  class=\"make_visible_and_invisible\" href=\"javascript:void(0)\" >" .	$this_link['name'] . "</a>";
-
-					}
-				}
-			}
-			else{ echo '&nbsp;&nbsp;&nbsp;&nbsp;';}
-
-			// NOTE : table contains only the image file name, not full path
-			if(!stristr($toolsRow['link'], 'http://') && !stristr($toolsRow['link'], 'https://') && !stristr($toolsRow['link'],'ftp://'))
-				$toolsRow['link'] = $web_code_path . $toolsRow['link'];
-
-			if($toolsRow['visibility'] == '0' && $toolsRow['admin'] != '1')
-			{
-			  	$class="class=\"invisible\"";
-			  	$info = pathinfo($toolsRow['image']);
-			  	$basename = basename ($toolsRow['image'],'.'.$info['extension']); // $file is set to "index"
-				$toolsRow['image'] = $basename.'_na.'.$info['extension'];
-			}
- 			else
-				$class='';
-
-			$qm_or_amp = ((strpos($toolsRow['link'], '?') === FALSE) ? '?' : '&amp;');
-			//If it's a link, we don't add the cidReq
-			if($toolsRow['image'] == 'file_html.gif' || $toolsRow['image'] == 'file_html_na.gif'){
-				$toolsRow['link'] = $toolsRow['link'].$qm_or_amp;
-			}
-			else{
-				$toolsRow['link'] = $toolsRow['link'].$qm_or_amp.api_get_cidreq();
-			}
-				if(strpos($toolsRow['name'],'visio_')!==false) {
-
-					/*
-					$toollink = "\t" . '<a ' . $class . ' href="#" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']) . '\',\'window_visio\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '">';
-					*/
-
-					$toollink = "\t" . '<a id="tooldesc_'.$toolsRow["id"].'"  ' . $class . ' href="javascript: void(0);" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']) . '\',\'window_visio'.$_SESSION['_cid'].'\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '">';
-					$my_tool_link = "\t" . '<a id="istooldesc_'.$toolsRow["id"].'"  ' . $class . ' href="javascript: void(0);" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']) . '\',\'window_visio'.$_SESSION['_cid'].'\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '">';
-				} else if(strpos($toolsRow['name'],'chat')!==false && api_get_course_setting('allow_open_chat_window')==true) {
-					/*
-					$toollink = "\t" . '<a ' . $class . ' href="#" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']) . '\',\'window_chat'.$_SESSION['_cid'].'\',config=\'height=\'+380+\', width=\'+625+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '">';
-					*/
-					$toollink = "\t" . '<a id="tooldesc_'.$toolsRow["id"].'" ' . $class . ' href="javascript: void(0);" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']) . '\',\'window_chat'.$_SESSION['_cid'].'\',config=\'height=\'+380+\', width=\'+625+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '">';
-					$my_tool_link="\t" . '<a id="istooldesc_'.$toolsRow["id"].'" ' . $class . ' href="javascript: void(0);" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']) . '\',\'window_chat'.$_SESSION['_cid'].'\',config=\'height=\'+380+\', width=\'+625+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '">';
-
-				} else {
-
+			{
+ 				if($toolsRow['admin'] !='1')
+				{
+					$link['cmd'] = "hide=yes";
+
+				}
+
+			}
+
+			if(isset($lnk) && is_array($lnk))
+			{
+				foreach($lnk as $this_link)
+				{
+					if(empty($toolsRow['adminlink']))
+					{
+							echo "<a class=\"make_visible_and_invisible\"  href=\"" .api_get_self(). "?".api_get_cidreq()."&amp;id=" . $toolsRow["id"] . "&amp;" . $this_link['cmd'] . "\">" .	$this_link['name'] . "</a>";
+							//echo "<a  class=\"make_visible_and_invisible\" href=\"javascript:void(0)\" >" .	$this_link['name'] . "</a>";
+
+					}
+				}
+			}
+			else{ echo '&nbsp;&nbsp;&nbsp;&nbsp;';}
+
+			// NOTE : table contains only the image file name, not full path
+			if(!stristr($toolsRow['link'], 'http://') && !stristr($toolsRow['link'], 'https://') && !stristr($toolsRow['link'],'ftp://'))
+				$toolsRow['link'] = $web_code_path . $toolsRow['link'];
+
+			if($toolsRow['visibility'] == '0' && $toolsRow['admin'] != '1')
+			{
+			  	$class="class=\"invisible\"";
+			  	$info = pathinfo($toolsRow['image']);
+			  	$basename = basename ($toolsRow['image'],'.'.$info['extension']); // $file is set to "index"
+				$toolsRow['image'] = $basename.'_na.'.$info['extension'];
+			}
+ 			else
+				$class='';
+
+			$qm_or_amp = ((strpos($toolsRow['link'], '?') === FALSE) ? '?' : '&amp;');
+			//If it's a link, we don't add the cidReq
+			if($toolsRow['image'] == 'file_html.gif' || $toolsRow['image'] == 'file_html_na.gif'){
+				$toolsRow['link'] = $toolsRow['link'].$qm_or_amp;
+			}
+			else{
+				$toolsRow['link'] = $toolsRow['link'].$qm_or_amp.api_get_cidreq();
+			}
+				if(strpos($toolsRow['name'],'visio_')!==false) {
+
+					/*
+					$toollink = "\t" . '<a ' . $class . ' href="#" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']) . '\',\'window_visio\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '">';
+					*/
+
+					$toollink = "\t" . '<a id="tooldesc_'.$toolsRow["id"].'"  ' . $class . ' href="javascript: void(0);" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']) . '\',\'window_visio'.$_SESSION['_cid'].'\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '">';
+					$my_tool_link = "\t" . '<a id="istooldesc_'.$toolsRow["id"].'"  ' . $class . ' href="javascript: void(0);" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']) . '\',\'window_visio'.$_SESSION['_cid'].'\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '">';
+				} else if(strpos($toolsRow['name'],'chat')!==false && api_get_course_setting('allow_open_chat_window')==true) {
+					/*
+					$toollink = "\t" . '<a ' . $class . ' href="#" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']) . '\',\'window_chat'.$_SESSION['_cid'].'\',config=\'height=\'+380+\', width=\'+625+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '">';
+					*/
+					$toollink = "\t" . '<a id="tooldesc_'.$toolsRow["id"].'" ' . $class . ' href="javascript: void(0);" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']) . '\',\'window_chat'.$_SESSION['_cid'].'\',config=\'height=\'+380+\', width=\'+625+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '">';
+					$my_tool_link="\t" . '<a id="istooldesc_'.$toolsRow["id"].'" ' . $class . ' href="javascript: void(0);" onclick="window.open(\'' . htmlspecialchars($toolsRow['link']) . '\',\'window_chat'.$_SESSION['_cid'].'\',config=\'height=\'+380+\', width=\'+625+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="' . $toolsRow['target'] . '">';
+
+				} else {
+
 					if (count(explode('type=classroom',$toolsRow['link']))==2 || count(explode('type=conference',$toolsRow['link']))==2) {
 						//$toollink = "\t" . '<a ' . $class . ' href="' . $toolsRow['link'] . '" target="_blank">';
 						$toollink = "\t" . '<a id="tooldesc_'.$toolsRow["id"].'" ' . $class . ' href="' . $toolsRow['link'] . '" target="_blank">';
@@ -320,211 +320,211 @@ function show_tools_category($course_tool_category)
 						$toollink = "\t" . '<a id="tooldesc_'.$toolsRow["id"].'" ' . $class . ' href="' . htmlspecialchars($toolsRow['link']) . '" target="' . $toolsRow['target'] . '">';
 						$my_tool_link = "\t" . '<a id="istooldesc_'.$toolsRow["id"].'" ' . $class . ' href="' . htmlspecialchars($toolsRow['link']) . '" target="' . $toolsRow['target'] . '">';
 
-					}
-
-				}
-				echo $toollink;
-				//var_dump($toollink);
-				/*
-				Display::display_icon($toolsRow['image'], get_lang(ucfirst($toolsRow['name'])));
-				*/
-				if ($toolsRow['image'] == 'file_html.gif' || $toolsRow['image'] == 'file_html_na.gif'
-					|| $toolsRow['image'] == 'scormbuilder.gif' || $toolsRow['image'] == 'scormbuilder_na.gif'
-					|| $toolsRow['image'] == 'blog.gif' || $toolsRow['image'] == 'blog_na.gif'
-					|| $toolsRow['image'] == 'external.gif' || $toolsRow['image'] == 'external_na.gif')
-				{
-					$tool_name = stripslashes($toolsRow['name']);
-				} else {
-					$tool_name = get_lang(ucfirst($toolsRow['name']));
-				}
-				Display::display_icon($toolsRow['image'], $tool_name, array('class'=>'tool-icon','id'=>'toolimage_'.$toolsRow["id"]));
-				echo '</a> ';
+					}
+
+				}
+				echo $toollink;
+				//var_dump($toollink);
+				/*
+				Display::display_icon($toolsRow['image'], get_lang(ucfirst($toolsRow['name'])));
+				*/
+				if ($toolsRow['image'] == 'file_html.gif' || $toolsRow['image'] == 'file_html_na.gif'
+					|| $toolsRow['image'] == 'scormbuilder.gif' || $toolsRow['image'] == 'scormbuilder_na.gif'
+					|| $toolsRow['image'] == 'blog.gif' || $toolsRow['image'] == 'blog_na.gif'
+					|| $toolsRow['image'] == 'external.gif' || $toolsRow['image'] == 'external_na.gif')
+				{
+					$tool_name = stripslashes($toolsRow['name']);
+				} else {
+					$tool_name = get_lang(ucfirst($toolsRow['name']));
+				}
+				Display::display_icon($toolsRow['image'], $tool_name, array('class'=>'tool-icon','id'=>'toolimage_'.$toolsRow["id"]));
+				echo '</a> ';
 
 				echo $my_tool_link;
 				/*
-					echo ($toolsRow['image'] == 'file_html_na.gif' || $toolsRow['image'] == 'file_html.gif' || $toolsRow['image'] == 'scormbuilder.gif' || $toolsRow['image'] == 'scormbuilder_na.gif' || $toolsRow['image'] == 'blog.gif' || $toolsRow['image'] == 'blog_na.gif' || $toolsRow['image'] == 'external.gif' || $toolsRow['image'] == 'external_na.gif') ? '  '.stripslashes($toolsRow['name']) : '  '.get_lang(ucfirst($toolsRow['name']));
-				*/
-				echo $tool_name;
-				echo "\t" . '</a>';
-				echo '</td>';
-			if($i%2)
-			{
-				echo "</tr>";
-			}
-
-			$i++;
-		}
-	}
-
-	if($i%2)
-	{
-		echo	"<td width=\"50%\">&nbsp;</td>\n",
-				"</tr>\n";
-	}
-
-}
-
-//End of functions show tools
-
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
-*/
-/*
------------------------------------------------------------
-	Work with data post askable by admin of course (franglais, clean this)
------------------------------------------------------------
-*/
-
-if (isset($_GET['sent_http_request']) && $_GET['sent_http_request']==1) {
-	if(api_is_allowed_to_edit()) {
-		$tool_table = Database::get_course_table(TABLE_TOOL_LIST);
-		$tool_id = Security::remove_XSS($_GET["id"]);
-		$tool_info = api_get_tool_information($tool_id);
-		$tool_visibility   = $tool_info['visibility'];
-		$tool_image        = $tool_info['image'];
-		$new_image         = str_replace('.gif','_na.gif',$tool_image);
-		$requested_image   = ($tool_visibility == 0 ) ? $tool_image : $new_image;
-		$requested_clase   = ($tool_visibility == 0 ) ? 'visible' : 'invisible';
-		$requested_message = ($tool_visibility == 0 ) ? 'is_active' : 'is_inactive';
+					echo ($toolsRow['image'] == 'file_html_na.gif' || $toolsRow['image'] == 'file_html.gif' || $toolsRow['image'] == 'scormbuilder.gif' || $toolsRow['image'] == 'scormbuilder_na.gif' || $toolsRow['image'] == 'blog.gif' || $toolsRow['image'] == 'blog_na.gif' || $toolsRow['image'] == 'external.gif' || $toolsRow['image'] == 'external_na.gif') ? '  '.stripslashes($toolsRow['name']) : '  '.get_lang(ucfirst($toolsRow['name']));
+				*/
+				echo $tool_name;
+				echo "\t" . '</a>';
+				echo '</td>';
+			if($i%2)
+			{
+				echo "</tr>";
+			}
+
+			$i++;
+		}
+	}
+
+	if($i%2)
+	{
+		echo	"<td width=\"50%\">&nbsp;</td>\n",
+				"</tr>\n";
+	}
+
+}
+
+//End of functions show tools
+
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
+*/
+/*
+-----------------------------------------------------------
+	Work with data post askable by admin of course (franglais, clean this)
+-----------------------------------------------------------
+*/
+
+if (isset($_GET['sent_http_request']) && $_GET['sent_http_request']==1) {
+	if(api_is_allowed_to_edit()) {
+		$tool_table = Database::get_course_table(TABLE_TOOL_LIST);
+		$tool_id = Security::remove_XSS($_GET["id"]);
+		$tool_info = api_get_tool_information($tool_id);
+		$tool_visibility   = $tool_info['visibility'];
+		$tool_image        = $tool_info['image'];
+		$new_image         = str_replace('.gif','_na.gif',$tool_image);
+		$requested_image   = ($tool_visibility == 0 ) ? $tool_image : $new_image;
+		$requested_clase   = ($tool_visibility == 0 ) ? 'visible' : 'invisible';
+		$requested_message = ($tool_visibility == 0 ) ? 'is_active' : 'is_inactive';
     $requested_view    = ($tool_visibility == 0 ) ? 'visible.gif' : 'invisible.gif';
-    $requested_visible = ($tool_visibility == 0 ) ? 1 : 0;
-	 	/*
-		-----------------------------------------------------------
-			HIDE AND REACTIVATE
-		-----------------------------------------------------------
-		*/
-			if ($_GET["id"]==strval(intval($_GET["id"]))) {
-				$sql="UPDATE $tool_table SET visibility='".Database::escape_string($requested_visible)."' WHERE id='".$_GET["id"]."'";
-				Database::query($sql,__FILE__,__LINE__);
-			}
-
-		$response_data = array(
-			'image'   => $requested_image,
-			'tclass'  => $requested_clase,
-			'message' => $requested_message,
-      'view'    => $requested_view
-		);
-		print(json_encode($response_data));
-		exit;
-	}
-} else {
-
-	if(api_is_allowed_to_edit()) {
-	 	/*
-		-----------------------------------------------------------
-			HIDE
-		-----------------------------------------------------------
-		*/
-		if(!empty($_GET['hide'])) // visibility 1 -> 0
-		{
-			Database::query("UPDATE $tool_table SET visibility=0 WHERE id='".$_GET["id"]."'",__FILE__,__LINE__);
-			Display::display_confirmation_message(get_lang('ToolIsNowHidden'));
-		}
-
-	  /*
-		-----------------------------------------------------------
-			REACTIVATE
-		-----------------------------------------------------------
-		*/
-		elseif(!empty($_GET['restore'])) // visibility 0,2 -> 1
-		{
-			Database::query("UPDATE $tool_table SET visibility=1 WHERE id='".$_GET["id"]."'",__FILE__,__LINE__);
-			Display::display_confirmation_message(get_lang('ToolIsNowVisible'));
-		}
-	}
-
-}
-
-// work with data post askable by admin of course
-
-if(api_is_platform_admin())
-{
-	// Show message to confirm that a tools must be hide from available tools
-	// visibility 0,1->2
-	if(!empty($_GET['askDelete']))
-	{
-		?>
-			<div id="toolhide">
-			<?php echo get_lang("DelLk")?>
-			<br />&nbsp;&nbsp;&nbsp;
-			<a href="<?php echo api_get_self()?>"><?php echo get_lang("No")?></a>&nbsp;|&nbsp;
-			<a href="<?php echo api_get_self()?>?delete=yes&id=<?php echo $_GET["id"]?>"><?php echo get_lang("Yes")?></a>
-			</div>
-		<?php
-	}
-
-	/*
-	 * Process hiding a tools from available tools.
-	 */
-
-	elseif(isset($_GET["delete"]) && $_GET["delete"])
-	{
-		Database::query("DELETE FROM $tool_table WHERE id='$id' AND added_tool=1",__FILE__,__LINE__);
-	}
-}
-
-
-
-/*
-==============================================================================
-		COURSE ADMIN ONLY VIEW
-==============================================================================
-*/
-
-// start of tools for CourseAdmins (teachers/tutors)
-if(api_is_allowed_to_edit())
-{
-    $current_protocol  = $_SERVER['SERVER_PROTOCOL'];
-    $current_host      = $_SERVER['HTTP_HOST'];
-    $server_protocol = substr($current_protocol,0,strrpos($current_protocol,'/'));
-    $server_protocol = $server_protocol.'://';
-    if ($current_host == 'localhost') {
-      //Get information of path
-      $info = explode('courses',api_get_self());
-      $path_work = substr($info[0], 0, strlen($info[0]));
-    } else {
-      $path_work = "";
-    }
-
-?>
-	<div class="normal-message" id="id_normal_message" style="display:none"><?php echo get_lang("PleaseStandBy")."<br/>".'<img src="'.$server_protocol.$current_host.'/'.$path_work.'main/inc/lib/javascript/indicator.gif"/>'; ?></div>
+    $requested_visible = ($tool_visibility == 0 ) ? 1 : 0;
+	 	/*
+		-----------------------------------------------------------
+			HIDE AND REACTIVATE
+		-----------------------------------------------------------
+		*/
+			if ($_GET["id"]==strval(intval($_GET["id"]))) {
+				$sql="UPDATE $tool_table SET visibility='".Database::escape_string($requested_visible)."' WHERE id='".$_GET["id"]."'";
+				Database::query($sql,__FILE__,__LINE__);
+			}
+
+		$response_data = array(
+			'image'   => $requested_image,
+			'tclass'  => $requested_clase,
+			'message' => $requested_message,
+      'view'    => $requested_view
+		);
+		print(json_encode($response_data));
+		exit;
+	}
+} else {
+
+	if(api_is_allowed_to_edit()) {
+	 	/*
+		-----------------------------------------------------------
+			HIDE
+		-----------------------------------------------------------
+		*/
+		if(!empty($_GET['hide'])) // visibility 1 -> 0
+		{
+			Database::query("UPDATE $tool_table SET visibility=0 WHERE id='".$_GET["id"]."'",__FILE__,__LINE__);
+			Display::display_confirmation_message(get_lang('ToolIsNowHidden'));
+		}
+
+	  /*
+		-----------------------------------------------------------
+			REACTIVATE
+		-----------------------------------------------------------
+		*/
+		elseif(!empty($_GET['restore'])) // visibility 0,2 -> 1
+		{
+			Database::query("UPDATE $tool_table SET visibility=1 WHERE id='".$_GET["id"]."'",__FILE__,__LINE__);
+			Display::display_confirmation_message(get_lang('ToolIsNowVisible'));
+		}
+	}
+
+}
+
+// work with data post askable by admin of course
+
+if(api_is_platform_admin())
+{
+	// Show message to confirm that a tools must be hide from available tools
+	// visibility 0,1->2
+	if(!empty($_GET['askDelete']))
+	{
+		?>
+			<div id="toolhide">
+			<?php echo get_lang("DelLk")?>
+			<br />&nbsp;&nbsp;&nbsp;
+			<a href="<?php echo api_get_self()?>"><?php echo get_lang("No")?></a>&nbsp;|&nbsp;
+			<a href="<?php echo api_get_self()?>?delete=yes&id=<?php echo $_GET["id"]?>"><?php echo get_lang("Yes")?></a>
+			</div>
+		<?php
+	}
+
+	/*
+	 * Process hiding a tools from available tools.
+	 */
+
+	elseif(isset($_GET["delete"]) && $_GET["delete"])
+	{
+		Database::query("DELETE FROM $tool_table WHERE id='$id' AND added_tool=1",__FILE__,__LINE__);
+	}
+}
+
+
+
+/*
+==============================================================================
+		COURSE ADMIN ONLY VIEW
+==============================================================================
+*/
+
+// start of tools for CourseAdmins (teachers/tutors)
+if(api_is_allowed_to_edit())
+{
+    $current_protocol  = $_SERVER['SERVER_PROTOCOL'];
+    $current_host      = $_SERVER['HTTP_HOST'];
+    $server_protocol = substr($current_protocol,0,strrpos($current_protocol,'/'));
+    $server_protocol = $server_protocol.'://';
+    if ($current_host == 'localhost') {
+      //Get information of path
+      $info = explode('courses',api_get_self());
+      $path_work = substr($info[0], 0, strlen($info[0]));
+    } else {
+      $path_work = "";
+    }
+
+?>
+	<div class="normal-message" id="id_normal_message" style="display:none"><?php echo get_lang("PleaseStandBy")."<br/>".'<img src="'.$server_protocol.$current_host.'/'.$path_work.'main/inc/lib/javascript/indicator.gif"/>'; ?></div>
 	<div class="confirmation-message" id="id_confirmation_message" style="display:none"></div>
-	<div class="courseadminview">
-		<span class="viewcaption"><?php echo get_lang("Authoring") ?></span>
-		<table width="100%">
-			<?php show_tools_category(TOOL_AUTHORING);?>
-		</table>
-	</div>
-	<div class="courseadminview">
-		<span class="viewcaption"><?php echo get_lang("Interaction") ?></span>
-		<table width="100%">
-			<?php show_tools_category(TOOL_INTERACTION); ?>
-		</table>
-	</div>
-	<div class="courseadminview">
-		<span class="viewcaption"><?php echo get_lang("Administration") ?></span>
-		<table width="100%">
-			<?php show_tools_category(TOOL_ADMIN_PLATEFORM); ?>
-		</table>
-	</div>
-	<?php
-}
-
-/*
-==============================================================================
-		TOOLS AUTHORING
-==============================================================================
-*/
-else{
-?>
-	<div class="Authoringview">
-
-		<table width="100%">
-			<?php show_tools_category(TOOL_STUDENT_VIEW); ?>
-		</table>
-	</div>
-<?php
-}
-?>
+	<div class="courseadminview">
+		<span class="viewcaption"><?php echo get_lang("Authoring") ?></span>
+		<table width="100%">
+			<?php show_tools_category(TOOL_AUTHORING);?>
+		</table>
+	</div>
+	<div class="courseadminview">
+		<span class="viewcaption"><?php echo get_lang("Interaction") ?></span>
+		<table width="100%">
+			<?php show_tools_category(TOOL_INTERACTION); ?>
+		</table>
+	</div>
+	<div class="courseadminview">
+		<span class="viewcaption"><?php echo get_lang("Administration") ?></span>
+		<table width="100%">
+			<?php show_tools_category(TOOL_ADMIN_PLATEFORM); ?>
+		</table>
+	</div>
+	<?php
+}
+
+/*
+==============================================================================
+		TOOLS AUTHORING
+==============================================================================
+*/
+else{
+?>
+	<div class="Authoringview">
+
+		<table width="100%">
+			<?php show_tools_category(TOOL_STUDENT_VIEW); ?>
+		</table>
+	</div>
+<?php
+}
+?>

+ 71 - 71
main/course_info/maintenance.php

@@ -1,74 +1,74 @@
-<?php // $Id: infocours.php 14956 2008-04-20 14:21:32Z yannoo $
-
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004 Dokeos S.A.
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Hugues Peeters
-	Copyright (c) Roan Embrechts (Vrije Universiteit Brussel)
-	Copyright (c) Olivier Brouckaert
-	Copyright (c) Bart Mollet, Hogeschool Gent
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-
-
-/*
- * Created on 18 October 2006 by Elixir Interactive http://www.elixir-interactive.com
- */
+<?php // $Id: infocours.php 14956 2008-04-20 14:21:32Z yannoo $
+
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004 Dokeos S.A.
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Hugues Peeters
+	Copyright (c) Roan Embrechts (Vrije Universiteit Brussel)
+	Copyright (c) Olivier Brouckaert
+	Copyright (c) Bart Mollet, Hogeschool Gent
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+
+
+/*
+ * Created on 18 October 2006 by Elixir Interactive http://www.elixir-interactive.com
+ */
 // name of the language file that needs to be included
-$language_file = array ('admin','create_course', 'course_info', 'coursebackup');
-
-require ('../inc/global.inc.php');
-
-$this_section = SECTION_COURSES;
-
-$nameTools= get_lang('Maintenance');
-
-api_block_anonymous_users();
-
-Display :: display_header($nameTools);
-
-api_display_tool_title($nameTools);
-
-?>
-
-<div class="sectiontitle"><?php Display::display_icon('save_import.gif', get_lang("backup")); ?>&nbsp;&nbsp;<a href="../coursecopy/backup.php?<?php echo api_get_cidreq();?>"><?php echo get_lang("backup");?></a></div>
-<div class="sectioncomment">
-			<ul>
-			    <li><a href="../coursecopy/create_backup.php?<?php echo api_get_cidreq();?>"><?php echo get_lang('CreateBackup')  ?></a><br/>
-			    <?php echo get_lang('CreateBackupInfo') ?>
-			    </li>
-			    <li><a href="../coursecopy/import_backup.php?<?php echo api_get_cidreq();?>"><?php echo get_lang('ImportBackup')  ?></a><br/>
-			    <?php echo get_lang('ImportBackupInfo') ?>
-			    </li>
-		    </ul>
-</div>
-
-<div class="sectiontitle"><?php Display::display_icon('copy.gif', get_lang("CopyCourse")); ?>&nbsp;&nbsp;<a href="../coursecopy/copy_course.php?<?php echo api_get_cidreq();?>"><?php echo get_lang("CopyCourse");?></a></div>
-<div class="sectioncomment"><?php echo get_lang("DescriptionCopyCourse"); ?></div>
-
-<div class="sectiontitle"><?php Display::display_icon('tool_delete.gif', get_lang("recycle_course")); ?>&nbsp;&nbsp;<a href="../coursecopy/recycle_course.php?<?php echo api_get_cidreq();?>"><?php echo get_lang("recycle_course");?></a></div>
-<div class="sectioncomment"><?php echo get_lang("DescriptionRecycleCourse");?></div>
-
-<div class="sectiontitle"><?php Display::display_icon('delete.gif',get_lang("DelCourse")); ?>&nbsp;&nbsp;<a href="../course_info/delete_course.php?<?php echo api_get_cidreq();?>"><?php echo get_lang("DelCourse");?></a></div>
+$language_file = array ('admin','create_course', 'course_info', 'coursebackup');
+
+require ('../inc/global.inc.php');
+
+$this_section = SECTION_COURSES;
+
+$nameTools= get_lang('Maintenance');
+
+api_block_anonymous_users();
+
+Display :: display_header($nameTools);
+
+api_display_tool_title($nameTools);
+
+?>
+
+<div class="sectiontitle"><?php Display::display_icon('save_import.gif', get_lang("backup")); ?>&nbsp;&nbsp;<a href="../coursecopy/backup.php?<?php echo api_get_cidreq();?>"><?php echo get_lang("backup");?></a></div>
+<div class="sectioncomment">
+			<ul>
+			    <li><a href="../coursecopy/create_backup.php?<?php echo api_get_cidreq();?>"><?php echo get_lang('CreateBackup')  ?></a><br/>
+			    <?php echo get_lang('CreateBackupInfo') ?>
+			    </li>
+			    <li><a href="../coursecopy/import_backup.php?<?php echo api_get_cidreq();?>"><?php echo get_lang('ImportBackup')  ?></a><br/>
+			    <?php echo get_lang('ImportBackupInfo') ?>
+			    </li>
+		    </ul>
+</div>
+
+<div class="sectiontitle"><?php Display::display_icon('copy.gif', get_lang("CopyCourse")); ?>&nbsp;&nbsp;<a href="../coursecopy/copy_course.php?<?php echo api_get_cidreq();?>"><?php echo get_lang("CopyCourse");?></a></div>
+<div class="sectioncomment"><?php echo get_lang("DescriptionCopyCourse"); ?></div>
+
+<div class="sectiontitle"><?php Display::display_icon('tool_delete.gif', get_lang("recycle_course")); ?>&nbsp;&nbsp;<a href="../coursecopy/recycle_course.php?<?php echo api_get_cidreq();?>"><?php echo get_lang("recycle_course");?></a></div>
+<div class="sectioncomment"><?php echo get_lang("DescriptionRecycleCourse");?></div>
+
+<div class="sectiontitle"><?php Display::display_icon('delete.gif',get_lang("DelCourse")); ?>&nbsp;&nbsp;<a href="../course_info/delete_course.php?<?php echo api_get_cidreq();?>"><?php echo get_lang("DelCourse");?></a></div>
 <div class="sectioncomment"><?php echo get_lang("DescriptionDeleteCourse");	?></div>
-
-<?php
-// footer
-Display::display_footer();
+
+<?php
+// footer
+Display::display_footer();
 ?>

+ 5 - 5
main/css/academica/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/baby_orange/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/blue_lagoon/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/blue_lagoon/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/cool_blue/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/cool_blue/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/corporate/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/cosmic_campus/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/delicious_bordeaux/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/delicious_bordeaux/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/dokeos_blue/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/dokeos_blue/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/dokeos_classic/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/dokeos_classic/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/dokeos_classic_2D/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/dokeos_classic_2D/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/empire_green/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/empire_green/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/fruity_orange/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/fruity_orange/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/medical/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/royal_purple/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/royal_purple/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/silver_line/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/sober_brown/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/steel_grey/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/steel_grey/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/tasty_olive/images/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 5 - 5
main/css/tasty_olive/index.html

@@ -1,6 +1,6 @@
-<html>
-<head>
-</head>
-<body>
-</body>
+<html>
+<head>
+</head>
+<body>
+</body>
 </html>

+ 595 - 595
main/dropbox/dropbox_class.inc.php

@@ -1,659 +1,659 @@
-<?php //$id: $
-/* For licensing terms, see /dokeos_license.txt */
-
-/**
- * Dropbox module for Dokeos
- * Classes for the dropbox module.
+<?php //$id: $
+/* For licensing terms, see /dokeos_license.txt */
+
+/**
+ * Dropbox module for Dokeos
+ * Classes for the dropbox module.
+ *
+ * 3 classes are defined:
+ * - Dropbox_Work:
+ * 		. id
+ * 		. uploader_id	=> who sent it		// RH: Mailing: or mailing pseudo_id
+ * 		. uploaderName
+ * 		. filename		=> name of file stored on the server
+ * 		. filesize							// RH: Mailing: zero for sent zip
+ * 		. title			=> name of file returned to user. This is the original name of the file
+ * 							except when the original name contained spaces. In that case the spaces
+ * 							will be replaced by _
+ * 		. description
+ * 		. author
+ * 		. upload_date	=> date when file was first sent
+ * 		. last_upload_date=> date when file was last sent
+ *  	. isOldWork 	=> has the work already been uploaded before
+ *
+ *      . feedback_date  => date of most recent feedback     // RH: Feedback
+ *      . feedback      => feedback text (or HTML?)         // RH: Feedback
  *
- * 3 classes are defined:
- * - Dropbox_Work:
- * 		. id
- * 		. uploader_id	=> who sent it		// RH: Mailing: or mailing pseudo_id
- * 		. uploaderName
- * 		. filename		=> name of file stored on the server
- * 		. filesize							// RH: Mailing: zero for sent zip
- * 		. title			=> name of file returned to user. This is the original name of the file
- * 							except when the original name contained spaces. In that case the spaces
- * 							will be replaced by _
- * 		. description
- * 		. author
- * 		. upload_date	=> date when file was first sent
- * 		. last_upload_date=> date when file was last sent
- *  	. isOldWork 	=> has the work already been uploaded before
- *
- *      . feedback_date  => date of most recent feedback     // RH: Feedback
- *      . feedback      => feedback text (or HTML?)         // RH: Feedback
+ * - Dropbox_SentWork extends Dropbox_Work
+ * 		. recipients	=> array of ["id"]["name"] lists the recipients of the work
+ * 											// RH: Mailing: or mailing pseudo_id
+ *                          ["feedback_date"]["feedback"]    // RH: Feedback
+ * - Dropbox_Person:
+ * 		. userId
+ * 		. receivedWork 	=> array of Dropbox_Work objects
+ * 		. sentWork 		=> array of Dropbox_SentWork objects
+ * 		. isCourseTutor
+ * 		. isCourseAdmin
+ * 		. _orderBy		=>private property used for determining the field by which the works have to be ordered
  *
- * - Dropbox_SentWork extends Dropbox_Work
- * 		. recipients	=> array of ["id"]["name"] lists the recipients of the work
- * 											// RH: Mailing: or mailing pseudo_id
- *                          ["feedback_date"]["feedback"]    // RH: Feedback
- * - Dropbox_Person:
- * 		. userId
- * 		. receivedWork 	=> array of Dropbox_Work objects
- * 		. sentWork 		=> array of Dropbox_SentWork objects
- * 		. isCourseTutor
- * 		. isCourseAdmin
- * 		. _orderBy		=>private property used for determining the field by which the works have to be ordered
- *
- * @version 1.30
- * @copyright 2004
- * @author Jan Bols <jan@ivpv.UGent.be>
- * with contributions by Ren� Haentjens <rene.haentjens@UGent.be> (see RH)
-  *	@package dokeos.dropbox
- **/
-class Dropbox_Work {
-	public $id;
-	public $uploader_id;
-	public $uploaderName;
-	public $filename;
-	public $filesize;
-	public $title;
-	public $description;
-	public $author;
-	public $upload_date;
-	public $last_upload_date;
-	public $isOldWork;
-	public $feedback_date, $feedback;  // RH: Feedback
-
-	/**
-		* Constructor calls private functions to create a new work or retreive an existing work from DB
-		* depending on the number of parameters
-	 *
-	 * @param unknown_type $arg1
-	 * @param unknown_type $arg2
-	 * @param unknown_type $arg3
-	 * @param unknown_type $arg4
-	 * @param unknown_type $arg5
-	 * @param unknown_type $arg6
-	 * @return Dropbox_Work
-		*/
-	function Dropbox_Work ($arg1, $arg2=null, $arg3=null, $arg4=null, $arg5=null, $arg6=null) {
-		if (func_num_args()>1)  {
-		    $this->_createNewWork($arg1, $arg2, $arg3, $arg4, $arg5, $arg6);
-		}  else  {
-			$this->_createExistingWork($arg1);
-		}
-	}
-
-	/**
-		* private function creating a new work object
-	 *
-	 * @param unknown_type $uploader_id
-	 * @param unknown_type $title
-	 * @param unknown_type $description
-	 * @param unknown_type $author
-	 * @param unknown_type $filename
-	 * @param unknown_type $filesize
-	 *
-	 * @todo 	$author was originally a field but this has now been replaced by the first and lastname of the uploader (to prevent anonymous uploads)
-	 * 			As a consequence this parameter can be removed
-		*/
-	function _createNewWork ($uploader_id, $title, $description, $author, $filename, $filesize) {
-		global $_user;
-
-		// Do some sanity checks
-		settype($uploader_id, 'integer') or die(dropbox_lang("generalError")." (code 201)"); //set $uploader_id to correct type
-		//if (! isCourseMember($uploader_id)) die(); //uploader must be coursemember to be able to upload
-			//-->this check is done when submitting data so it isn't checked here
-
-		// Fill in the properties
+ * @version 1.30
+ * @copyright 2004
+ * @author Jan Bols <jan@ivpv.UGent.be>
+ * with contributions by Ren� Haentjens <rene.haentjens@UGent.be> (see RH)
+  *	@package dokeos.dropbox
+ **/
+class Dropbox_Work {
+	public $id;
+	public $uploader_id;
+	public $uploaderName;
+	public $filename;
+	public $filesize;
+	public $title;
+	public $description;
+	public $author;
+	public $upload_date;
+	public $last_upload_date;
+	public $isOldWork;
+	public $feedback_date, $feedback;  // RH: Feedback
+
+	/**
+		* Constructor calls private functions to create a new work or retreive an existing work from DB
+		* depending on the number of parameters
+	 *
+	 * @param unknown_type $arg1
+	 * @param unknown_type $arg2
+	 * @param unknown_type $arg3
+	 * @param unknown_type $arg4
+	 * @param unknown_type $arg5
+	 * @param unknown_type $arg6
+	 * @return Dropbox_Work
+		*/
+	function Dropbox_Work ($arg1, $arg2=null, $arg3=null, $arg4=null, $arg5=null, $arg6=null) {
+		if (func_num_args()>1)  {
+		    $this->_createNewWork($arg1, $arg2, $arg3, $arg4, $arg5, $arg6);
+		}  else  {
+			$this->_createExistingWork($arg1);
+		}
+	}
+
+	/**
+		* private function creating a new work object
+	 *
+	 * @param unknown_type $uploader_id
+	 * @param unknown_type $title
+	 * @param unknown_type $description
+	 * @param unknown_type $author
+	 * @param unknown_type $filename
+	 * @param unknown_type $filesize
+	 *
+	 * @todo 	$author was originally a field but this has now been replaced by the first and lastname of the uploader (to prevent anonymous uploads)
+	 * 			As a consequence this parameter can be removed
+		*/
+	function _createNewWork ($uploader_id, $title, $description, $author, $filename, $filesize) {
+		global $_user;
+
+		// Do some sanity checks
+		settype($uploader_id, 'integer') or die(dropbox_lang("generalError")." (code 201)"); //set $uploader_id to correct type
+		//if (! isCourseMember($uploader_id)) die(); //uploader must be coursemember to be able to upload
+			//-->this check is done when submitting data so it isn't checked here
+
+		// Fill in the properties
 		$this->uploader_id = $uploader_id;
-		$this->uploaderName = getUserNameFromId($this->uploader_id);
-		$this->filename = $filename;
-		$this->filesize = $filesize;
-		$this->title = $title;
-		$this->description = $description;
-		$this->author = api_get_person_name($_user['firstName'], $_user['lastName']);
-		$this->last_upload_date = date("Y-m-d H:i:s",time());
-
-		// Check if object exists already. If it does, the old object is used
-		// with updated information (authors, descriptio, upload_date)
-		$this->isOldWork = FALSE;
+		$this->uploaderName = getUserNameFromId($this->uploader_id);
+		$this->filename = $filename;
+		$this->filesize = $filesize;
+		$this->title = $title;
+		$this->description = $description;
+		$this->author = api_get_person_name($_user['firstName'], $_user['lastName']);
+		$this->last_upload_date = date("Y-m-d H:i:s",time());
+
+		// Check if object exists already. If it does, the old object is used
+		// with updated information (authors, descriptio, upload_date)
+		$this->isOldWork = FALSE;
 		$sql="SELECT id, upload_date
 				FROM ".dropbox_cnf("tbl_file")."
-				WHERE filename = '".addslashes($this->filename)."'";
-        $result = Database::query($sql,__FILE__,__LINE__);
-		$res = mysql_fetch_array($result);
-		if ($res != FALSE) {
-			$this->isOldWork = TRUE;
-		}
-		// insert or update the dropbox_file table and set the id property
-		if ($this->isOldWork) {
-			$this->id = $res["id"];
-			$this->upload_date = $res["upload_date"];
-		    $sql = "UPDATE ".dropbox_cnf("tbl_file")."
-					SET filesize = '".addslashes($this->filesize)."'
-					, title = '".addslashes($this->title)."'
-					, description = '".addslashes($this->description)."'
-					, author = '".addslashes($this->author)."'
-					, last_upload_date = '".addslashes($this->last_upload_date)."'
-					WHERE id='".addslashes($this->id)."'";
-			$result = Database::query($sql,__FILE__,__LINE__);
-		} else {
-			$this->upload_date = $this->last_upload_date;
+				WHERE filename = '".addslashes($this->filename)."'";
+        $result = Database::query($sql,__FILE__,__LINE__);
+		$res = mysql_fetch_array($result);
+		if ($res != FALSE) {
+			$this->isOldWork = TRUE;
+		}
+		// insert or update the dropbox_file table and set the id property
+		if ($this->isOldWork) {
+			$this->id = $res["id"];
+			$this->upload_date = $res["upload_date"];
+		    $sql = "UPDATE ".dropbox_cnf("tbl_file")."
+					SET filesize = '".addslashes($this->filesize)."'
+					, title = '".addslashes($this->title)."'
+					, description = '".addslashes($this->description)."'
+					, author = '".addslashes($this->author)."'
+					, last_upload_date = '".addslashes($this->last_upload_date)."'
+					WHERE id='".addslashes($this->id)."'";
+			$result = Database::query($sql,__FILE__,__LINE__);
+		} else {
+			$this->upload_date = $this->last_upload_date;
 			$sql="INSERT INTO ".dropbox_cnf("tbl_file")."
-				(uploader_id, filename, filesize, title, description, author, upload_date, last_upload_date, session_id)
-				VALUES ('".addslashes($this->uploader_id)."'
-						, '".addslashes($this->filename)."'
-						, '".addslashes($this->filesize)."'
-						, '".addslashes($this->title)."'
-						, '".addslashes($this->description)."'
-						, '".addslashes($this->author)."'
-						, '".addslashes($this->upload_date)."'
-						, '".addslashes($this->last_upload_date)."'
-						, ".intval($_SESSION['id_session'])."
-						)";
-
+				(uploader_id, filename, filesize, title, description, author, upload_date, last_upload_date, session_id)
+				VALUES ('".addslashes($this->uploader_id)."'
+						, '".addslashes($this->filename)."'
+						, '".addslashes($this->filesize)."'
+						, '".addslashes($this->title)."'
+						, '".addslashes($this->description)."'
+						, '".addslashes($this->author)."'
+						, '".addslashes($this->upload_date)."'
+						, '".addslashes($this->last_upload_date)."'
+						, ".intval($_SESSION['id_session'])."
+						)";
+
         	$result = Database::query($sql,__FILE__,__LINE__);
-			$this->id = mysql_insert_id(); //get automatically inserted id
-		}
+			$this->id = mysql_insert_id(); //get automatically inserted id
+		}
 
-		// insert entries into person table
+		// insert entries into person table
 		$sql="INSERT INTO ".dropbox_cnf("tbl_person")."
-				(file_id, user_id)
-				VALUES ('".addslashes($this->id)."'
-						, '".addslashes($this->uploader_id)."'
-						)";
-        $result = Database::query($sql);	//if work already exists no error is generated
-	}
-
-	/**
-		* private function creating existing object by retreiving info from db
-	 *
-	 * @param unknown_type $id
-		*/
-	function _createExistingWork ($id) {
-		global $_user;  // RH: Feedback
-
-		// Do some sanity checks
-		settype($id, 'integer') or die(dropbox_lang("generalError")." (code 205)"); //set $id to correct type
-
-		// get the data from DB
-		$sql="SELECT uploader_id, filename, filesize, title, description, author, upload_date, last_upload_date, cat_id
-				FROM ".dropbox_cnf("tbl_file")."
-				WHERE id='".addslashes($id)."'";
-        $result = Database::query($sql,__FILE__,__LINE__);
-		$res = mysql_fetch_array($result,MYSQL_ASSOC);
-
-		// Check if uploader is still in Dokeos system
+				(file_id, user_id)
+				VALUES ('".addslashes($this->id)."'
+						, '".addslashes($this->uploader_id)."'
+						)";
+        $result = Database::query($sql);	//if work already exists no error is generated
+	}
+
+	/**
+		* private function creating existing object by retreiving info from db
+	 *
+	 * @param unknown_type $id
+		*/
+	function _createExistingWork ($id) {
+		global $_user;  // RH: Feedback
+
+		// Do some sanity checks
+		settype($id, 'integer') or die(dropbox_lang("generalError")." (code 205)"); //set $id to correct type
+
+		// get the data from DB
+		$sql="SELECT uploader_id, filename, filesize, title, description, author, upload_date, last_upload_date, cat_id
+				FROM ".dropbox_cnf("tbl_file")."
+				WHERE id='".addslashes($id)."'";
+        $result = Database::query($sql,__FILE__,__LINE__);
+		$res = mysql_fetch_array($result,MYSQL_ASSOC);
+
+		// Check if uploader is still in Dokeos system
 		$uploader_id = stripslashes($res["uploader_id"]);
-		$uploaderName = getUserNameFromId($uploader_id);
-		if ($uploaderName == FALSE) {
-			//deleted user
-			$this->uploader_id = -1;
+		$uploaderName = getUserNameFromId($uploader_id);
+		if ($uploaderName == FALSE) {
+			//deleted user
+			$this->uploader_id = -1;
 			$this->uploaderName = dropbox_lang("anonymous", "noDLTT");
-		} else {
+		} else {
 			$this->uploader_id = $uploader_id;
 			$this->uploaderName = $uploaderName;
-		}
-
-		// Fill in properties
-		$this->id = $id;
-		$this->filename = stripslashes($res["filename"]);
-		$this->filesize = stripslashes($res["filesize"]);
-		$this->title = stripslashes($res["title"]);
-		$this->description = stripslashes($res["description"]);
-		$this->author = stripslashes($res["author"]);
-		$this->upload_date = stripslashes($res["upload_date"]);
-		$this->last_upload_date = stripslashes($res["last_upload_date"]);
-		$this->category = $res['cat_id'];
-
-
-		// Getting the feedback on the work.
-		if ($_GET['action']=='viewfeedback' AND $this->id==$_GET['id']) {
-			$feedback2=array();
-			$sql_feedback = "SELECT * FROM ".dropbox_cnf("tbl_feedback")." WHERE file_id='".$id."' ORDER BY feedback_id ASC";
-			$result = Database::query($sql_feedback, __FILE__, __LINE__);
-			while ($row_feedback=Database::fetch_array($result)) {
-				$feedback2[]=$row_feedback;
-			}
+		}
+
+		// Fill in properties
+		$this->id = $id;
+		$this->filename = stripslashes($res["filename"]);
+		$this->filesize = stripslashes($res["filesize"]);
+		$this->title = stripslashes($res["title"]);
+		$this->description = stripslashes($res["description"]);
+		$this->author = stripslashes($res["author"]);
+		$this->upload_date = stripslashes($res["upload_date"]);
+		$this->last_upload_date = stripslashes($res["last_upload_date"]);
+		$this->category = $res['cat_id'];
+
+
+		// Getting the feedback on the work.
+		if ($_GET['action']=='viewfeedback' AND $this->id==$_GET['id']) {
+			$feedback2=array();
+			$sql_feedback = "SELECT * FROM ".dropbox_cnf("tbl_feedback")." WHERE file_id='".$id."' ORDER BY feedback_id ASC";
+			$result = Database::query($sql_feedback, __FILE__, __LINE__);
+			while ($row_feedback=Database::fetch_array($result)) {
+				$feedback2[]=$row_feedback;
+			}
 			$this->feedback2=$feedback2;
-		}
-		/*
-		// RH: Feedback
-		$result = Database::query("SELECT feedback_date, feedback, cat_id FROM ".
-		    dropbox_cnf("tbl_post")." WHERE dest_user_id='".$_user['user_id'].
+		}
+		/*
+		// RH: Feedback
+		$result = Database::query("SELECT feedback_date, feedback, cat_id FROM ".
+		    dropbox_cnf("tbl_post")." WHERE dest_user_id='".$_user['user_id'].
 		    "' AND file_id='".$id."'",__FILE__,__LINE__);
-		if ($res = mysql_fetch_array($result))
-		{
-    		$this->feedback_date = $res["feedback_date"];
-    		$this->feedback = $res["feedback"];
-    		$this->category = $res['cat_id'];
-		}  // do not fail if there is no recipient = current user...*/
-	}
-}
-
-class Dropbox_SentWork extends Dropbox_Work
-{
-	public $recipients;	//array of ["id"]["name"] arrays
-
-	/**
-		* Constructor calls private functions to create a new work or retreive an existing work from DB
-		* depending on the number of parameters
-	 *
-	 * @param unknown_type $arg1
-	 * @param unknown_type $arg2
-	 * @param unknown_type $arg3
-	 * @param unknown_type $arg4
-	 * @param unknown_type $arg5
-	 * @param unknown_type $arg6
-	 * @param unknown_type $arg7
-	 * @return Dropbox_SentWork
-		*/
-	function Dropbox_SentWork ($arg1, $arg2=null, $arg3=null, $arg4=null, $arg5=null, $arg6=null, $arg7=null) {
-		if (func_num_args()>1) {
-		    $this->_createNewSentWork ($arg1, $arg2, $arg3, $arg4, $arg5, $arg6, $arg7);
-		} else {
-			$this->_createExistingSentWork ($arg1);
-		}
-	}
-
-	/**
-		* private function creating a new SentWork object
-		*
-	 * @param unknown_type $uploader_id
-	 * @param unknown_type $title
-	 * @param unknown_type $description
-	 * @param unknown_type $author
-	 * @param unknown_type $filename
-	 * @param unknown_type $filesize
-	 * @param unknown_type $recipient_ids
-		*/
-	function _createNewSentWork ($uploader_id, $title, $description, $author, $filename, $filesize, $recipient_ids) {
-		// Call constructor of Dropbox_Work object
-		$this->Dropbox_Work($uploader_id, $title, $description, $author, $filename, $filesize);
-
-		// Do sanity checks on recipient_ids array & property fillin
-		// The sanity check for ex-coursemembers is already done in base constructor
-		settype($uploader_id, 'integer') or die(dropbox_lang("generalError")." (code 208)"); //set $uploader_id to correct type
-
-		$justSubmit = FALSE;  // RH: mailing zip-file or just upload
-		if ( is_int($recipient_ids)) {
-			$justSubmit = TRUE; $recipient_ids = array($recipient_ids + $this->id);
-		} elseif ( count($recipient_ids) == 0) {  // RH: Just Upload
-			$justSubmit = TRUE; $recipient_ids = array($uploader_id);
-		}
-		if (! is_array($recipient_ids) || count($recipient_ids) == 0) {
-			die(dropbox_lang("generalError")." (code 209)");
-		}
-		foreach ($recipient_ids as $rec) {
-			if (empty($rec)) die(dropbox_lang("generalError")." (code 210)");
-			//if (!isCourseMember($rec)) die(); //cannot sent document to someone outside of course
-				//this check is done when validating submitted data
-			$this->recipients[] = array("id"=>$rec, "name"=>getUserNameFromId($rec));
-		}
-
-		// insert data in dropbox_post and dropbox_person table for each recipient
-		foreach ($this->recipients as $rec) {
+		if ($res = mysql_fetch_array($result))
+		{
+    		$this->feedback_date = $res["feedback_date"];
+    		$this->feedback = $res["feedback"];
+    		$this->category = $res['cat_id'];
+		}  // do not fail if there is no recipient = current user...*/
+	}
+}
+
+class Dropbox_SentWork extends Dropbox_Work
+{
+	public $recipients;	//array of ["id"]["name"] arrays
+
+	/**
+		* Constructor calls private functions to create a new work or retreive an existing work from DB
+		* depending on the number of parameters
+	 *
+	 * @param unknown_type $arg1
+	 * @param unknown_type $arg2
+	 * @param unknown_type $arg3
+	 * @param unknown_type $arg4
+	 * @param unknown_type $arg5
+	 * @param unknown_type $arg6
+	 * @param unknown_type $arg7
+	 * @return Dropbox_SentWork
+		*/
+	function Dropbox_SentWork ($arg1, $arg2=null, $arg3=null, $arg4=null, $arg5=null, $arg6=null, $arg7=null) {
+		if (func_num_args()>1) {
+		    $this->_createNewSentWork ($arg1, $arg2, $arg3, $arg4, $arg5, $arg6, $arg7);
+		} else {
+			$this->_createExistingSentWork ($arg1);
+		}
+	}
+
+	/**
+		* private function creating a new SentWork object
+		*
+	 * @param unknown_type $uploader_id
+	 * @param unknown_type $title
+	 * @param unknown_type $description
+	 * @param unknown_type $author
+	 * @param unknown_type $filename
+	 * @param unknown_type $filesize
+	 * @param unknown_type $recipient_ids
+		*/
+	function _createNewSentWork ($uploader_id, $title, $description, $author, $filename, $filesize, $recipient_ids) {
+		// Call constructor of Dropbox_Work object
+		$this->Dropbox_Work($uploader_id, $title, $description, $author, $filename, $filesize);
+
+		// Do sanity checks on recipient_ids array & property fillin
+		// The sanity check for ex-coursemembers is already done in base constructor
+		settype($uploader_id, 'integer') or die(dropbox_lang("generalError")." (code 208)"); //set $uploader_id to correct type
+
+		$justSubmit = FALSE;  // RH: mailing zip-file or just upload
+		if ( is_int($recipient_ids)) {
+			$justSubmit = TRUE; $recipient_ids = array($recipient_ids + $this->id);
+		} elseif ( count($recipient_ids) == 0) {  // RH: Just Upload
+			$justSubmit = TRUE; $recipient_ids = array($uploader_id);
+		}
+		if (! is_array($recipient_ids) || count($recipient_ids) == 0) {
+			die(dropbox_lang("generalError")." (code 209)");
+		}
+		foreach ($recipient_ids as $rec) {
+			if (empty($rec)) die(dropbox_lang("generalError")." (code 210)");
+			//if (!isCourseMember($rec)) die(); //cannot sent document to someone outside of course
+				//this check is done when validating submitted data
+			$this->recipients[] = array("id"=>$rec, "name"=>getUserNameFromId($rec));
+		}
+
+		// insert data in dropbox_post and dropbox_person table for each recipient
+		foreach ($this->recipients as $rec) {
 			$sql="INSERT INTO ".dropbox_cnf("tbl_post")."
-				(file_id, dest_user_id, session_id)
-				VALUES ('".addslashes($this->id)."', '".addslashes($rec["id"])."', ".intval($_SESSION['id_session']).")";
-	        $result = Database::query($sql);	//if work already exists no error is generated
+				(file_id, dest_user_id, session_id)
+				VALUES ('".addslashes($this->id)."', '".addslashes($rec["id"])."', ".intval($_SESSION['id_session']).")";
+	        $result = Database::query($sql);	//if work already exists no error is generated
 
-			//insert entries into person table
+			//insert entries into person table
 			$sql="INSERT INTO ".dropbox_cnf("tbl_person")."
-				(file_id, user_id)
-				VALUES ('".addslashes($this->id)."'
-						, '".addslashes($rec["id"])."'
-						)";
-        	// RH: do not add recipient in person table if mailing zip or just upload
-			if (!$justSubmit) {
-				$result = Database::query($sql);	//if work already exists no error is generated
+				(file_id, user_id)
+				VALUES ('".addslashes($this->id)."'
+						, '".addslashes($rec["id"])."'
+						)";
+        	// RH: do not add recipient in person table if mailing zip or just upload
+			if (!$justSubmit) {
+				$result = Database::query($sql);	//if work already exists no error is generated
+			}
+			//update item_property (previously last_tooledit) table for each recipient
+
+			global $_course, $dropbox_cnf;
+
+			if (($ownerid = $this->uploader_id) > $dropbox_cnf["mailingIdBase"]) {
+			    $ownerid = getUserOwningThisMailing($ownerid);
+			}
+			if (($recipid = $rec["id"]) > $dropbox_cnf["mailingIdBase"]) {
+			    $recipid = $ownerid;  // mailing file recipient = mailing id, not a person
 			}
-			//update item_property (previously last_tooledit) table for each recipient
-
-			global $_course, $dropbox_cnf;
-
-			if (($ownerid = $this->uploader_id) > $dropbox_cnf["mailingIdBase"]) {
-			    $ownerid = getUserOwningThisMailing($ownerid);
-			}
-			if (($recipid = $rec["id"]) > $dropbox_cnf["mailingIdBase"]) {
-			    $recipid = $ownerid;  // mailing file recipient = mailing id, not a person
-			}
-			api_item_property_update($_course, TOOL_DROPBOX, $this->id, "DropboxFileAdded", $ownerid, NULL, $recipid) ;
-		}
-	}
-
-	/**
-		* private function creating existing object by retreiving info from db
-	 *
-	 * @param unknown_type $id
-		*/
-	function _createExistingSentWork  ($id) {
-		// Call constructor of Dropbox_Work object
-		$this->Dropbox_Work($id);
-
-		// Do sanity check. The sanity check for ex-coursemembers is already done in base constructor
-		settype($id, 'integer') or die(dropbox_lang("generalError")." (code 211)"); //set $id to correct type
-
-		//Fill in recipients array/
-		$this->recipients = array();  // RH: Feedback: added to SELECT
+			api_item_property_update($_course, TOOL_DROPBOX, $this->id, "DropboxFileAdded", $ownerid, NULL, $recipid) ;
+		}
+	}
+
+	/**
+		* private function creating existing object by retreiving info from db
+	 *
+	 * @param unknown_type $id
+		*/
+	function _createExistingSentWork  ($id) {
+		// Call constructor of Dropbox_Work object
+		$this->Dropbox_Work($id);
+
+		// Do sanity check. The sanity check for ex-coursemembers is already done in base constructor
+		settype($id, 'integer') or die(dropbox_lang("generalError")." (code 211)"); //set $id to correct type
+
+		//Fill in recipients array/
+		$this->recipients = array();  // RH: Feedback: added to SELECT
 		$sql="SELECT dest_user_id, feedback_date, feedback
-				FROM ".dropbox_cnf("tbl_post")."
-				WHERE file_id='".addslashes($id)."'";
-        $result = Database::query($sql,__FILE__,__LINE__);
-		while ($res = Database::fetch_array($result)) {
-			// check for deleted users
-			$dest_user_id = $res["dest_user_id"];
-			$recipientName = getUserNameFromId($dest_user_id);
-			//$this->category=$res['cat_id'];
-			if ($recipientName == FALSE) {
-				$this->recipients[] = array("id"=>-1, "name"=> dropbox_lang("anonymous", "noDLTT"));
-			} else {
+				FROM ".dropbox_cnf("tbl_post")."
+				WHERE file_id='".addslashes($id)."'";
+        $result = Database::query($sql,__FILE__,__LINE__);
+		while ($res = Database::fetch_array($result)) {
+			// check for deleted users
+			$dest_user_id = $res["dest_user_id"];
+			$recipientName = getUserNameFromId($dest_user_id);
+			//$this->category=$res['cat_id'];
+			if ($recipientName == FALSE) {
+				$this->recipients[] = array("id"=>-1, "name"=> dropbox_lang("anonymous", "noDLTT"));
+			} else {
 				$this->recipients[] = array("id"=>$dest_user_id, "name"=>$recipientName, "user_id"=>$dest_user_id,
-				    "feedback_date"=>$res["feedback_date"], "feedback"=>$res["feedback"]);  // RH: Feedback
-			}
-		}
-	}
-}
-
-class Dropbox_Person
-{
-	public $receivedWork;	//array of Dropbox_Work objects
-	public $sentWork;		//array of Dropbox_SentWork objects
-	public $userId = 0;
-	public $isCourseAdmin = FALSE;
-	public $isCourseTutor = FALSE;
+				    "feedback_date"=>$res["feedback_date"], "feedback"=>$res["feedback"]);  // RH: Feedback
+			}
+		}
+	}
+}
+
+class Dropbox_Person
+{
+	public $receivedWork;	//array of Dropbox_Work objects
+	public $sentWork;		//array of Dropbox_SentWork objects
+	public $userId = 0;
+	public $isCourseAdmin = FALSE;
+	public $isCourseTutor = FALSE;
 	public $_orderBy = '';	//private property that determines by which field
-						//the receivedWork and the sentWork arrays are sorted
-
-	/**
-	 * Constructor for recreating the Dropbox_Person object
-	 *
-	 * @param unknown_type $userId
-	 * @param unknown_type $isCourseAdmin
-	 * @param unknown_type $isCourseTutor
-	 * @return Dropbox_Person
-	 */
-	function Dropbox_Person ($userId, $isCourseAdmin, $isCourseTutor) {
-		// Fill in properties
-		$this->userId = $userId;
-		$this->isCourseAdmin = $isCourseAdmin;
+						//the receivedWork and the sentWork arrays are sorted
+
+	/**
+	 * Constructor for recreating the Dropbox_Person object
+	 *
+	 * @param unknown_type $userId
+	 * @param unknown_type $isCourseAdmin
+	 * @param unknown_type $isCourseTutor
+	 * @return Dropbox_Person
+	 */
+	function Dropbox_Person ($userId, $isCourseAdmin, $isCourseTutor) {
+		// Fill in properties
+		$this->userId = $userId;
+		$this->isCourseAdmin = $isCourseAdmin;
 		$this->isCourseTutor = $isCourseTutor;
-		$this->receivedWork = array();
-		$this->sentWork = array();
-
-		//Note: perhaps include an ex coursemember check to delete old files
-
-		$post_tbl = Database::get_course_table(TABLE_DROPBOX_POST);
-		$person_tbl = Database::get_course_table(TABLE_DROPBOX_PERSON);
-		$file_tbl = Database::get_course_table(TABLE_DROPBOX_FILE);
-		// find all entries where this person is the recipient
-		$sql = "SELECT r.file_id, r.cat_id
-				FROM $post_tbl r, $person_tbl p
+		$this->receivedWork = array();
+		$this->sentWork = array();
+
+		//Note: perhaps include an ex coursemember check to delete old files
+
+		$post_tbl = Database::get_course_table(TABLE_DROPBOX_POST);
+		$person_tbl = Database::get_course_table(TABLE_DROPBOX_PERSON);
+		$file_tbl = Database::get_course_table(TABLE_DROPBOX_FILE);
+		// find all entries where this person is the recipient
+		$sql = "SELECT r.file_id, r.cat_id
+				FROM $post_tbl r, $person_tbl p
 				WHERE r.dest_user_id = '".addslashes($this->userId)."'
-					AND r.dest_user_id = p.user_id
-					AND r.file_id = p.file_id";
-
-		if (intval($_SESSION['id_session']>0)) {
-			$sql .= " AND r.session_id = ".intval($_SESSION['id_session']);
-		}
-        $result = Database::query($sql,__FILE__,__LINE__);
-		while ($res = Database::fetch_array($result)) {
-			$temp = new Dropbox_Work($res["file_id"]);
-			$temp -> category = $res['cat_id'];
-			$this->receivedWork[] = $temp;
+					AND r.dest_user_id = p.user_id
+					AND r.file_id = p.file_id";
+
+		if (intval($_SESSION['id_session']>0)) {
+			$sql .= " AND r.session_id = ".intval($_SESSION['id_session']);
+		}
+        $result = Database::query($sql,__FILE__,__LINE__);
+		while ($res = Database::fetch_array($result)) {
+			$temp = new Dropbox_Work($res["file_id"]);
+			$temp -> category = $res['cat_id'];
+			$this->receivedWork[] = $temp;
 		}
-
-		// find all entries where this person is the sender/uploader
+
+		// find all entries where this person is the sender/uploader
 		$sql = "SELECT f.id
 				FROM $file_tbl f, $person_tbl p
-				WHERE f.uploader_id = '".addslashes($this->userId)."'
-				AND f.uploader_id = p.user_id
+				WHERE f.uploader_id = '".addslashes($this->userId)."'
+				AND f.uploader_id = p.user_id
 				AND f.id = p.file_id";
 
-		if(intval($_SESSION['id_session']>0)) {
-			$sql .= " AND f.session_id = ".intval($_SESSION['id_session']);
-		}
-        $result =Database::query($sql,__FILE__,__LINE__);
-		while ($res = Database::fetch_array($result)) {
-			$this->sentWork[] = new Dropbox_SentWork($res["id"]);
-		}
-	}
+		if(intval($_SESSION['id_session']>0)) {
+			$sql .= " AND f.session_id = ".intval($_SESSION['id_session']);
+		}
+        $result =Database::query($sql,__FILE__,__LINE__);
+		while ($res = Database::fetch_array($result)) {
+			$this->sentWork[] = new Dropbox_SentWork($res["id"]);
+		}
+	}
 
-	/**
+	/**
 		* This private method is used by the usort function in  the
 		* orderSentWork and orderReceivedWork methods.
 		* It compares 2 work-objects by 1 of the properties of that object, dictated by the
-	 * private property _orderBy
-	 *
-	 * @param unknown_type $a
-	 * @param unknown_type $b
-	 * @return -1, 0 or 1 dependent of the result of the comparison.
-		*/
-	function _cmpWork ($a, $b) {
-		$sort = $this->_orderBy;
-		$aval = $a->$sort;
-		$bval = $b->$sort;
-		if ($sort == 'recipients') {	//the recipients property is an array so we do the comparison based on the first item of the recipients array
-		    $aval = $aval[0]['name'];
-			$bval = $bval[0]['name'];
-		}
-		if ($sort == 'filesize') {	//filesize is not a string, so we use other comparison technique
-			return $aval<$bval ? -1 : 1;
-		} elseif ($sort == 'title') { // natural order for sorting titles is more "human-friendly"
-			return api_strnatcmp($aval, $bval);
-		} else {
-		    return api_strcasecmp($aval, $bval);
-		}
-	}
-
-	/**
-		* method that sorts the objects in the sentWork array, dependent on the $sort parameter.
-		* $sort can be lastDate, firstDate, title, size, ...
-	 *
-	 * @param unknown_type $sort
-		*/
-	function orderSentWork($sort) {
-		/*
-
-		*/
-		switch($sort) {
+	 * private property _orderBy
+	 *
+	 * @param unknown_type $a
+	 * @param unknown_type $b
+	 * @return -1, 0 or 1 dependent of the result of the comparison.
+		*/
+	function _cmpWork ($a, $b) {
+		$sort = $this->_orderBy;
+		$aval = $a->$sort;
+		$bval = $b->$sort;
+		if ($sort == 'recipients') {	//the recipients property is an array so we do the comparison based on the first item of the recipients array
+		    $aval = $aval[0]['name'];
+			$bval = $bval[0]['name'];
+		}
+		if ($sort == 'filesize') {	//filesize is not a string, so we use other comparison technique
+			return $aval<$bval ? -1 : 1;
+		} elseif ($sort == 'title') { // natural order for sorting titles is more "human-friendly"
+			return api_strnatcmp($aval, $bval);
+		} else {
+		    return api_strcasecmp($aval, $bval);
+		}
+	}
+
+	/**
+		* method that sorts the objects in the sentWork array, dependent on the $sort parameter.
+		* $sort can be lastDate, firstDate, title, size, ...
+	 *
+	 * @param unknown_type $sort
+		*/
+	function orderSentWork($sort) {
+		/*
+
+		*/
+		switch($sort) {
 			case 'lastDate':
-				$this->_orderBy = 'last_upload_date';
-				break;
+				$this->_orderBy = 'last_upload_date';
+				break;
 			case 'firstDate':
-				$this->_orderBy = 'upload_date';
-				break;
+				$this->_orderBy = 'upload_date';
+				break;
 			case 'title':
-				$this->_orderBy = 'title';
-				break;
+				$this->_orderBy = 'title';
+				break;
 			case 'size':
-				$this->_orderBy = 'filesize';
-				break;
+				$this->_orderBy = 'filesize';
+				break;
 			case 'author':
-				$this->_orderBy = 'author';
-				break;
+				$this->_orderBy = 'author';
+				break;
 			case 'recipient':
-				$this->_orderBy = 'recipients';
-				break;
-			default:
-				$this->_orderBy = 'last_upload_date';
-		} // switch
+				$this->_orderBy = 'recipients';
+				break;
+			default:
+				$this->_orderBy = 'last_upload_date';
+		} // switch
 
 		usort($this->sentWork, array($this,"_cmpWork"));	//this calls the _cmpWork method
-	}
-
-	/**
-		* method that sorts the objects in the receivedWork array, dependent on the $sort parameter.
-		* $sort can be lastDate, firstDate, title, size, ...
-	 * @param unknown_type $sort
-		*/
-	function orderReceivedWork($sort) {
-		switch($sort) {
+	}
+
+	/**
+		* method that sorts the objects in the receivedWork array, dependent on the $sort parameter.
+		* $sort can be lastDate, firstDate, title, size, ...
+	 * @param unknown_type $sort
+		*/
+	function orderReceivedWork($sort) {
+		switch($sort) {
 			case 'lastDate':
-				$this->_orderBy = 'last_upload_date';
-				break;
+				$this->_orderBy = 'last_upload_date';
+				break;
 			case 'firstDate':
-				$this->_orderBy = 'upload_date';
-				break;
+				$this->_orderBy = 'upload_date';
+				break;
 			case 'title':
-				$this->_orderBy = 'title';
-				break;
+				$this->_orderBy = 'title';
+				break;
 			case 'size':
-				$this->_orderBy = 'filesize';
-				break;
+				$this->_orderBy = 'filesize';
+				break;
 			case 'author':
-				$this->_orderBy = 'author';
-				break;
+				$this->_orderBy = 'author';
+				break;
 			case 'sender':
-				$this->_orderBy = 'uploaderName';
-				break;
-			default:
-				$this->_orderBy = 'last_upload_date';
-		} // switch
+				$this->_orderBy = 'uploaderName';
+				break;
+			default:
+				$this->_orderBy = 'last_upload_date';
+		} // switch
 
 		usort($this->receivedWork, array($this,"_cmpWork"));	//this calls the _cmpWork method
-	}
-
-	/**
-		* Deletes all the received work of this person
-	 *
-		*/
-	function deleteAllReceivedWork () {
-		//delete entries in person table concerning received works
-		foreach ($this->receivedWork as $w) {
+	}
+
+	/**
+		* Deletes all the received work of this person
+	 *
+		*/
+	function deleteAllReceivedWork () {
+		//delete entries in person table concerning received works
+		foreach ($this->receivedWork as $w) {
 			Database::query("DELETE FROM ".dropbox_cnf("tbl_person")." WHERE user_id='".$this->userId."' AND file_id='".$w->id."'",__FILE__,__LINE__);
-		}
-		removeUnusedFiles();	//check for unused files
-
-	}
-
-   /**
-    * Deletes all the received categories and work of this person
-	  */
+		}
+		removeUnusedFiles();	//check for unused files
+
+	}
+
+   /**
+    * Deletes all the received categories and work of this person
+	  */
 	function deleteReceivedWorkFolder($id) {
-		$sql = "DELETE FROM ".dropbox_cnf("tbl_file")." where cat_id = '".$id."' ";
-		if(!Database::query($sql))		return false;
-		$sql = "DELETE FROM ".dropbox_cnf("tbl_category")." where cat_id = '".$id."' ";
-		if(!Database::query($sql))		return false;
-		$sql = "DELETE FROM ".dropbox_cnf("tbl_post")." where cat_id = '".$id."' ";
-		if(!Database::query($sql))		return false;
-		return true;
+		$sql = "DELETE FROM ".dropbox_cnf("tbl_file")." where cat_id = '".$id."' ";
+		if(!Database::query($sql))		return false;
+		$sql = "DELETE FROM ".dropbox_cnf("tbl_category")." where cat_id = '".$id."' ";
+		if(!Database::query($sql))		return false;
+		$sql = "DELETE FROM ".dropbox_cnf("tbl_post")." where cat_id = '".$id."' ";
+		if(!Database::query($sql))		return false;
+		return true;
 	}
-	/**
-	 * Deletes a received dropbox file of this person with id=$id
-	 *
-	 * @param integer $id
-		*/
-	function deleteReceivedWork ($id) {
-		//id check
-		$found = false;
-		foreach($this->receivedWork as $w) {
-			if ($w->id == $id) {
-			   $found = true;
-			   break;
-			}
-		}
-		if (! $found) {
-			if(!$this->deleteReceivedWorkFolder($id)) {
-				die(dropbox_lang("generalError")." (code 216)");
+	/**
+	 * Deletes a received dropbox file of this person with id=$id
+	 *
+	 * @param integer $id
+		*/
+	function deleteReceivedWork ($id) {
+		//id check
+		$found = false;
+		foreach($this->receivedWork as $w) {
+			if ($w->id == $id) {
+			   $found = true;
+			   break;
+			}
+		}
+		if (! $found) {
+			if(!$this->deleteReceivedWorkFolder($id)) {
+				die(dropbox_lang("generalError")." (code 216)");
 			}
-		}
-		//delete entries in person table concerning received works
+		}
+		//delete entries in person table concerning received works
 		Database::query("DELETE FROM ".dropbox_cnf("tbl_person")." WHERE user_id='".$this->userId."' AND file_id='".$id."'",__FILE__,__LINE__);
-		removeUnusedFiles();	//check for unused files
-	}
-
-	/**
-	 * Deletes all the sent dropbox files of this person
-		*/
-	function deleteAllSentWork () {
-		//delete entries in person table concerning sent works
-		foreach ($this->sentWork as $w) {
+		removeUnusedFiles();	//check for unused files
+	}
+
+	/**
+	 * Deletes all the sent dropbox files of this person
+		*/
+	function deleteAllSentWork () {
+		//delete entries in person table concerning sent works
+		foreach ($this->sentWork as $w) {
 			Database::query("DELETE FROM ".dropbox_cnf("tbl_person")." WHERE user_id='".$this->userId."' AND file_id='".$w->id."'",__FILE__,__LINE__);
-			removeMoreIfMailing($w->id);  // RH: Mailing: see init1
+			removeMoreIfMailing($w->id);  // RH: Mailing: see init1
+		}
+		removeUnusedFiles();	//check for unused files
+	}
+
+	/**
+	 * Deletes a sent dropbox file of this person with id=$id
+	 *
+	 * @param unknown_type $id
+		*/
+	function deleteSentWork ($id) {
+		//index check
+		$found = false;
+		foreach($this->sentWork as $w) {
+			if ($w->id == $id) {
+			   $found = true;
+			   break;
+			}
 		}
-		removeUnusedFiles();	//check for unused files
-	}
-
-	/**
-	 * Deletes a sent dropbox file of this person with id=$id
-	 *
-	 * @param unknown_type $id
-		*/
-	function deleteSentWork ($id) {
-		//index check
-		$found = false;
-		foreach($this->sentWork as $w) {
-			if ($w->id == $id) {
-			   $found = true;
-			   break;
-			}
-		}
-		if (!$found) {
-			if(!$this->deleteReceivedWorkFolder($id)) {
-				die(dropbox_lang("generalError")." (code 219)");
-			}
-		}
-		//$file_id = $this->sentWork[$index]->id;  // RH: Mailing
-		//delete entries in person table concerning sent works
+		if (!$found) {
+			if(!$this->deleteReceivedWorkFolder($id)) {
+				die(dropbox_lang("generalError")." (code 219)");
+			}
+		}
+		//$file_id = $this->sentWork[$index]->id;  // RH: Mailing
+		//delete entries in person table concerning sent works
 		Database::query("DELETE FROM ".dropbox_cnf("tbl_person")." WHERE user_id='".$this->userId."' AND file_id='".$id."'",__FILE__,__LINE__);
-		removeMoreIfMailing($id);  // RH: Mailing: see init1
-		removeUnusedFiles();	//check for unused files
-	}
-
-	/**
-	 * Updates feedback for received work of this person with id=$id
-	 *
-	 * @param unknown_type $id
-	 * @param unknown_type $text
-	 */
-	function updateFeedback($id, $text) {
-		global $_course, $dropbox_cnf;
-
-		//id check
-		$found = false; $wi = -1;
-		foreach($this->receivedWork as $w) {
+		removeMoreIfMailing($id);  // RH: Mailing: see init1
+		removeUnusedFiles();	//check for unused files
+	}
+
+	/**
+	 * Updates feedback for received work of this person with id=$id
+	 *
+	 * @param unknown_type $id
+	 * @param unknown_type $text
+	 */
+	function updateFeedback($id, $text) {
+		global $_course, $dropbox_cnf;
+
+		//id check
+		$found = false; $wi = -1;
+		foreach($this->receivedWork as $w) {
 			$wi++;
-			if ($w->id == $id){
-			   $found = true;
-			   break;
-			}  // foreach (... as $wi -> $w) gives error 221! (no idea why...)
-		}
-		if (! $found) {
-			die(dropbox_lang("generalError")." (code 221)");
+			if ($w->id == $id){
+			   $found = true;
+			   break;
+			}  // foreach (... as $wi -> $w) gives error 221! (no idea why...)
+		}
+		if (! $found) {
+			die(dropbox_lang("generalError")." (code 221)");
 		}
 
-		$feedback_date = date("Y-m-d H:i:s",time());
-		$this->receivedWork[$wi]->feedback_date = $feedback_date;
-		$this->receivedWork[$wi]->feedback = $text;
+		$feedback_date = date("Y-m-d H:i:s",time());
+		$this->receivedWork[$wi]->feedback_date = $feedback_date;
+		$this->receivedWork[$wi]->feedback = $text;
 
-		Database::query("UPDATE ".dropbox_cnf("tbl_post")." SET feedback_date='".
-		    addslashes($feedback_date)."', feedback='".addslashes($text).
+		Database::query("UPDATE ".dropbox_cnf("tbl_post")." SET feedback_date='".
+		    addslashes($feedback_date)."', feedback='".addslashes($text).
 		    "' WHERE dest_user_id='".$this->userId."' AND file_id='".$id."'",__FILE__,__LINE__);
-
-		//update item_property (previously last_tooledit) table
-
-		if (($ownerid = $this->receivedWork[$wi]->uploader_id) > $dropbox_cnf["mailingIdBase"]) {
-		    $ownerid = getUserOwningThisMailing($ownerid);
-		}
-		api_item_property_update($_course, TOOL_DROPBOX, $this->receivedWork[$wi]->id, "DropboxFileUpdated", $this->userId, NULL, $ownerid) ;
-
-	}
-	/**
-	 * Filter the received work
-	 * @param string $type
-	 * @param string $value
-	 */
-	function filter_received_work($type,$value) {
-		global $dropbox_cnf;
-
-    	$new_received_work = array();
-		foreach ($this->receivedWork as $index => $work) {
-			switch ($type) {
-				case 'uploader_id':
+
+		//update item_property (previously last_tooledit) table
+
+		if (($ownerid = $this->receivedWork[$wi]->uploader_id) > $dropbox_cnf["mailingIdBase"]) {
+		    $ownerid = getUserOwningThisMailing($ownerid);
+		}
+		api_item_property_update($_course, TOOL_DROPBOX, $this->receivedWork[$wi]->id, "DropboxFileUpdated", $this->userId, NULL, $ownerid) ;
+
+	}
+	/**
+	 * Filter the received work
+	 * @param string $type
+	 * @param string $value
+	 */
+	function filter_received_work($type,$value) {
+		global $dropbox_cnf;
+
+    	$new_received_work = array();
+		foreach ($this->receivedWork as $index => $work) {
+			switch ($type) {
+				case 'uploader_id':
 					if ($work->uploader_id == $value ||
-					    ($work->uploader_id > $dropbox_cnf["mailingIdBase"] &&
-					     getUserOwningThisMailing($work->uploader_id) == $value)) {
-						$new_received_work[] = $work;
-					}
-					break;
-				default:
+					    ($work->uploader_id > $dropbox_cnf["mailingIdBase"] &&
+					     getUserOwningThisMailing($work->uploader_id) == $value)) {
+						$new_received_work[] = $work;
+					}
+					break;
+				default:
 					$new_received_work[] = $work;
-			}
-		}
-		$this->receivedWork = $new_received_work;
-	}
-}
+			}
+		}
+		$this->receivedWork = $new_received_work;
+	}
+}

+ 54 - 54
main/dropbox/dropbox_config.inc.php

@@ -1,55 +1,55 @@
-<?php //$id: $
-/* For licensing terms, see /dokeos_license.txt */
-
-/**
- * --------------------------------------
- *  DEBUGGING VARS
- * --------------------------------------
- */
-$DEBUG = TRUE;
-
-/**
- * --------------------------------------
- *  DATABASE TABLE VARIABLES
- * --------------------------------------
- */
-$dropbox_cnf['tbl_post'] 		= Database::get_course_table(TABLE_DROPBOX_POST);
-$dropbox_cnf['tbl_file'] 		= Database::get_course_table(TABLE_DROPBOX_FILE);
-$dropbox_cnf['tbl_person'] 		= Database::get_course_table(TABLE_DROPBOX_PERSON);
-$dropbox_cnf['tbl_intro'] 		= Database::get_course_table(TABLE_TOOL_INTRO);
-$dropbox_cnf['tbl_user'] 		= Database::get_main_table(TABLE_MAIN_USER);
-$dropbox_cnf['tbl_course_user']	= Database::get_main_table(TABLE_MAIN_COURSE_USER);
-$dropbox_cnf['tbl_category'] 	= Database::get_course_table(TABLE_DROPBOX_CATEGORY);
-$dropbox_cnf['tbl_feedback'] 	= Database::get_course_table(TABLE_DROPBOX_FEEDBACK);
-
-/**
- * --------------------------------------
- *  INITIALISE OTHER VARIABLES & CONSTANTS
- * --------------------------------------
- */
-$dropbox_cnf["courseId"] 				= $_cid;
-$dropbox_cnf["sysPath"] 				= api_get_path('SYS_COURSE_PATH') . $_course["path"] . "/dropbox"; //path to dropbox subdir in course containing the uploaded files
-$dropbox_cnf["webPath"] 				= api_get_path('WEB_COURSE_PATH') . $_course["path"] . "/dropbox";
-$dropbox_cnf["maxFilesize"] 			= api_get_setting("dropbox_max_filesize"); //file size limit as imposed by the platform admin (see Dokeos Config Settings on the platform administration section)
-//$dropbox_cnf["version"] 				= "1.4";
-$dropbox_cnf["allowOverwrite"] 			= string_2_boolean(api_get_setting("dropbox_allow_overwrite"));
-$dropbox_cnf["allowJustUpload"] 		= string_2_boolean(api_get_setting("dropbox_allow_just_upload"));
-$dropbox_cnf["allowStudentToStudent"] 	= string_2_boolean(api_get_setting("dropbox_allow_student_to_student"));
-$dropbox_cnf["allowGroup"] 				= string_2_boolean(api_get_setting("dropbox_allow_group"));
-
-/**
- * --------------------------------------
- * RH: INITIALISE MAILING VARIABLES
- * --------------------------------------
- */
-$dropbox_cnf["allowMailing"] = string_2_boolean(api_get_setting("dropbox_allow_mailing"));  // false = no mailing functionality
-$dropbox_cnf["mailingIdBase"] = 10000000;  // bigger than any user_id,
-// allowing enough space for pseudo_ids as uploader_id, dest_user_id, user_id:
-// mailing pseudo_id = dropbox_cnf("mailingIdBase") + mailing id
-$dropbox_cnf["mailingZipRegexp"] = '/^(.*)(STUDENTID|USERID|LOGINNAME)(.*)\.ZIP$/i';
-$dropbox_cnf["mailingWhereSTUDENTID"] = "official_code";
-$dropbox_cnf["mailingWhereUSERID"] = "username";
-$dropbox_cnf["mailingWhereLOGINNAME"] = "username";
-$dropbox_cnf["mailingFileRegexp"] = '/^(.+)\.\w{1,4}$/';
-
+<?php //$id: $
+/* For licensing terms, see /dokeos_license.txt */
+
+/**
+ * --------------------------------------
+ *  DEBUGGING VARS
+ * --------------------------------------
+ */
+$DEBUG = TRUE;
+
+/**
+ * --------------------------------------
+ *  DATABASE TABLE VARIABLES
+ * --------------------------------------
+ */
+$dropbox_cnf['tbl_post'] 		= Database::get_course_table(TABLE_DROPBOX_POST);
+$dropbox_cnf['tbl_file'] 		= Database::get_course_table(TABLE_DROPBOX_FILE);
+$dropbox_cnf['tbl_person'] 		= Database::get_course_table(TABLE_DROPBOX_PERSON);
+$dropbox_cnf['tbl_intro'] 		= Database::get_course_table(TABLE_TOOL_INTRO);
+$dropbox_cnf['tbl_user'] 		= Database::get_main_table(TABLE_MAIN_USER);
+$dropbox_cnf['tbl_course_user']	= Database::get_main_table(TABLE_MAIN_COURSE_USER);
+$dropbox_cnf['tbl_category'] 	= Database::get_course_table(TABLE_DROPBOX_CATEGORY);
+$dropbox_cnf['tbl_feedback'] 	= Database::get_course_table(TABLE_DROPBOX_FEEDBACK);
+
+/**
+ * --------------------------------------
+ *  INITIALISE OTHER VARIABLES & CONSTANTS
+ * --------------------------------------
+ */
+$dropbox_cnf["courseId"] 				= $_cid;
+$dropbox_cnf["sysPath"] 				= api_get_path('SYS_COURSE_PATH') . $_course["path"] . "/dropbox"; //path to dropbox subdir in course containing the uploaded files
+$dropbox_cnf["webPath"] 				= api_get_path('WEB_COURSE_PATH') . $_course["path"] . "/dropbox";
+$dropbox_cnf["maxFilesize"] 			= api_get_setting("dropbox_max_filesize"); //file size limit as imposed by the platform admin (see Dokeos Config Settings on the platform administration section)
+//$dropbox_cnf["version"] 				= "1.4";
+$dropbox_cnf["allowOverwrite"] 			= string_2_boolean(api_get_setting("dropbox_allow_overwrite"));
+$dropbox_cnf["allowJustUpload"] 		= string_2_boolean(api_get_setting("dropbox_allow_just_upload"));
+$dropbox_cnf["allowStudentToStudent"] 	= string_2_boolean(api_get_setting("dropbox_allow_student_to_student"));
+$dropbox_cnf["allowGroup"] 				= string_2_boolean(api_get_setting("dropbox_allow_group"));
+
+/**
+ * --------------------------------------
+ * RH: INITIALISE MAILING VARIABLES
+ * --------------------------------------
+ */
+$dropbox_cnf["allowMailing"] = string_2_boolean(api_get_setting("dropbox_allow_mailing"));  // false = no mailing functionality
+$dropbox_cnf["mailingIdBase"] = 10000000;  // bigger than any user_id,
+// allowing enough space for pseudo_ids as uploader_id, dest_user_id, user_id:
+// mailing pseudo_id = dropbox_cnf("mailingIdBase") + mailing id
+$dropbox_cnf["mailingZipRegexp"] = '/^(.*)(STUDENTID|USERID|LOGINNAME)(.*)\.ZIP$/i';
+$dropbox_cnf["mailingWhereSTUDENTID"] = "official_code";
+$dropbox_cnf["mailingWhereUSERID"] = "username";
+$dropbox_cnf["mailingWhereLOGINNAME"] = "username";
+$dropbox_cnf["mailingFileRegexp"] = '/^(.+)\.\w{1,4}$/';
+
 $dropbox_cnf['sent_received_tabs']=true;

+ 442 - 442
main/dropbox/dropbox_download.php

@@ -1,442 +1,442 @@
-<?php //$id: $
-/* For licensing terms, see /dokeos_license.txt */
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
-*/
-// we cannot use dropbox_init.inc.php because this one already outputs data.
-//name of langfile
-// name of the language file that needs to be included
-$language_file = "dropbox";
-
-// including the basic Dokeos initialisation file
-require("../inc/global.inc.php");
-
-// the dropbox configuration parameters
-include_once('dropbox_config.inc.php');
-
-// the dropbox file that contains additional functions
-include_once('dropbox_functions.inc.php');
-
-// the dropbox class
-require_once( "dropbox_class.inc.php");
-
-//
-include_once(api_get_path(LIBRARY_PATH).'/document.lib.php');
-
-
-/*
-==============================================================================
-		DOWNLOAD A FOLDER
-==============================================================================
-*/
-if ( isset($_GET['cat_id']) AND is_numeric($_GET['cat_id']) AND $_GET['action']=='downloadcategory' AND isset($_GET['sent_received']) )
-{
-	// step 1: constructingd' the sql statement. Due to the nature off the classes of the dropbox the categories for sent files are stored in the table
-	// dropbox_file while the categories for the received files are stored in dropbox_post. It would have been more elegant if these could be stored
-	// in dropbox_person (which stores the link file-person)
-	// Therefore we have to create to separate sql statements to find which files are in the categorie (depending if we zip-download a sent category or a
-	// received category)
-	if ($_GET['sent_received']=='sent')
-	{
-		// here we also incorporate the person table to make sure that deleted sent documents are not included.
-		$sql="SELECT DISTINCT file.id, file.filename, file.title FROM ".$dropbox_cnf["tbl_file"]." file, ".$dropbox_cnf["tbl_person"]." person
-				WHERE file.uploader_id='".mysql_real_escape_string($_user['user_id'])."'
-				AND file.cat_id='".mysql_real_escape_string($_GET['cat_id'])."'
-				AND person.user_id='".mysql_real_escape_string($_user['user_id'])."'
-				AND person.file_id=file.id
-				" ;
-	}
-	if ($_GET['sent_received']=='received')
-	{
-		$sql="SELECT DISTINCT file.id, file.filename, file.title FROM ".$dropbox_cnf["tbl_file"]." file, ".$dropbox_cnf["tbl_person"]." person, ".$dropbox_cnf["tbl_post"]." post
-				WHERE post.cat_id='".mysql_real_escape_string($_GET['cat_id'])."'
-				AND person.user_id='".mysql_real_escape_string($_user['user_id'])."'
-				AND person.file_id=file.id
-				AND post.file_id=file.id
-				" ;
-	}
-	$result=Database::query($sql,__FILE__,__LINE__);
-	while ($row=mysql_fetch_array($result))
-	{
-		$files_to_download[]=$row['id'];
-	}
-	if (!is_array($files_to_download) OR empty($files_to_download))
-	{
-		header ("location: index.php?view=".$_GET['sent_received']."&error=ErrorNoFilesInFolder");
-		exit;
-	}
-
-	zip_download($files_to_download);
-	exit;
-}
-
-
-
-/*
-==============================================================================
-		DOWNLOAD A FILE
-==============================================================================
-*/
-/*
-------------------------------------------------------------------------------
-		AUTHORIZATION
-------------------------------------------------------------------------------
-*/
-// Check if the id makes sense
-if ( ! isset( $_GET['id']) || ! is_numeric( $_GET['id']))
-{
-	Display::display_header($nameTools,"Dropbox");
-	Display :: display_error_message(get_lang('Error'));
-	Display::display_footer();
-	exit;
-}
-
-// Check if the user is allowed to download the file
-$allowed_to_download=false;
-
-// Check if the user has sent or received the file.
-$sql="SELECT * FROM ".$dropbox_cnf["tbl_person"]." WHERE file_id='".mysql_real_escape_string($_GET['id'])."' AND user_id='".mysql_real_escape_string($_user['user_id'])."'";
-$result=Database::query($sql);
-if (mysql_num_rows($result)>0)
-{
-	$allowed_to_download=true;
-}
-
-/*
-------------------------------------------------------------------------------
-		ERROR IF NOT ALLOWED TO DOWNLOAD
-------------------------------------------------------------------------------
-*/
-if (!$allowed_to_download)
-{
-	Display::display_header($nameTools,"Dropbox");
-	Display :: display_error_message(get_lang('YouAreNotAllowedToDownloadThisFile'));
-	Display::display_footer();
-	exit;
-}
-/*
-------------------------------------------------------------------------------
-		DOWNLOAD THE FILE
-------------------------------------------------------------------------------
-*/
-// the user is allowed to download the file
-else
-{
-	$_SESSION['_seen'][$_course['id']][TOOL_DROPBOX][]=$_GET['id'];
-
-	$work = new Dropbox_work($_GET['id']);
-	$path = dropbox_cnf("sysPath") . "/" . $work -> filename; //path to file as stored on server
-	$file = $work->title;
-	require_once(api_get_path(LIBRARY_PATH) . '/document.lib.php');
-	$mimetype = DocumentManager::file_get_mime_type(TRUE);
-	$fileparts = explode( '.', $file);
-	$filepartscount = count( $fileparts);
-	if ( ( $filepartscount > 1) && isset( $mimetype[$fileparts [$filepartscount - 1]]) && $_GET['action']<>'download')
-	{
-	    // give hint to browser about filetype
-    	header( "Content-type: " . $mimetype[$fileparts [$filepartscount - 1]] . "\n");
-	}
-	else
-	{
-		//no information about filetype: force a download dialog window in browser
-		header( "Content-type: application/octet-stream\n");
-	}
-	if (!in_array(strtolower($fileparts [$filepartscount - 1]), array('doc','xls','ppt','pps','sxw','sxc','sxi')))
-	{
-		header('Content-Disposition: inline; filename='.$file); // bugs with open office
-	}
-	else
-	{
-		header('Content-Disposition: attachment; filename='.$file);
-	}
-
-
-	/**
-	 * Note that if you use these two headers from a previous example:
-	 * header('Cache-Control: no-cache, must-revalidate');
-	 * header('Pragma: no-cache');
-	 * before sending a file to the browser, the "Open" option on Internet Explorer's file download dialog will not work properly. If the user clicks "Open" instead of "Save," the target application will open an empty file, because the downloaded file was not cached. The user will have to save the file to their hard drive in order to use it.
-	 * Make sure to leave these headers out if you'd like your visitors to be able to use IE's "Open" option.
-	 */
-	header( "Pragma: \n");
-	header( "Cache-Control: \n");
-	header( "Cache-Control: public\n"); // IE cannot download from sessions without a cache
-
-
-	/*if ( isset( $_SERVER["HTTPS"]))
-	{
-	    /**
-	     * We need to set the following headers to make downloads work using IE in HTTPS mode.
-	     *
-	    //header( "Pragma: ");
-	    //header( "Cache-Control: ");
-	    header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT\n");
-	    header( "Last-Modified: " . gmdate( "D, d M Y H:i:s") . " GMT\n");
-	    header( "Cache-Control: no-store, no-cache, must-revalidate\n"); // HTTP/1.1
-	    header( "Cache-Control: post-check=0, pre-check=0\n", false);
-	}*/
-
-
-
-	header( "Content-Description: " . trim( htmlentities( $file)) . "\n");
-	header( "Content-Transfer-Encoding: binary\n");
-	header( "Content-Length: " . filesize( $path)."\n" );
-
-	$fp = fopen( $path, "rb");
-	fpassthru( $fp);
-	exit();
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-// $Id: dropbox_download.php,v 1.10 2005/05/19 14:41:30 renehaentjens Exp $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004 Dokeos S.A.
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Jan Bols
-	Copyright (c) Rene Haentjens
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
- * Dropbox module for Claroline
- * handles downloads of files. Direct downloading is prevented because of an .htaccess file in the
- * dropbox directory. So everything goes through this script.
- *
- * 1. Initialising vars
- * 2. Authorisation
- * 3. Sanity check of get data & file
- * 4. Send headers
- * 5. Send file
- *
- *
- * NOTE :
- * When testing this with PHP4.0.4 on WinXP and Apache2 there were problems with downloading in IE6
- * After searching the only explanation I could find is a problem with the headers:
- *
- * HEADERS SENT WITH PHP4.3:
- * HTTP/1.1�200�OK(CR)
- * (LF)
- * Date:�Fri,�12�Sep�2003�19:07:33�GMT(CR)
- * (LF)
- * Server:�Apache/2.0.47�(Win32)�PHP/4.3.3(CR)
- * (LF)
- * X-Powered-By:�PHP/4.3.3(CR)
- * (LF)
- * Set-Cookie:�PHPSESSID=06880edcc8363be3f60929576fc1bc6e;�path=/(CR)
- * (LF)
- * Expires:�Thu,�19�Nov�1981�08:52:00�GMT(CR)
- * (LF)
- * Cache-Control:�public(CR)
- * (LF)
- * Pragma:�(CR)
- * (LF)
- * Content-Transfer-Encoding:�binary(CR)
- * (LF)
- * Content-Disposition:�attachment;�filename=SV-262E4.png(CR)
- * (LF)
- * Content-Length:�92178(CR)
- * (LF)
- * Connection:�close(CR)
- * (LF)
- * Content-Type:�application/octet-stream(CR)
- * (LF)
- * (CR)
- * (LF)
- *
- * HEADERS SENT WITH PHP4.0.4:
- * HTTP/1.1�200�OK(CR)
- * (LF)
- * Date:�Fri,�12�Sep�2003�18:28:21�GMT(CR)
- * (LF)
- * Server:�Apache/2.0.47�(Win32)(CR)
- * (LF)
- * X-Powered-By:�PHP/4.0.4(CR)
- * (LF)
- * Expires:�Thu,�19�Nov�1981�08:52:00�GMT(CR)
- * (LF)
- * Cache-Control:�no-store,�no-cache,�must-revalidate,�post-check=0,�pre-check=0,�,�public(CR)
- * (LF)
- * Pragma:�no-cache,�(CR)
- * (LF)
- * Content-Disposition:�attachment;�filename=SV-262E4.png(CR)
- * (LF)
- * Content-Transfer-Encoding:�binary(CR)
- * (LF)
- * Set-Cookie:�PHPSESSID=0a5b1c1b9d5e3b474fef359ee55e82d0;�path=/(CR)
- * (LF)
- * Content-Length:�92178(CR)
- * (LF)
- * Connection:�close(CR)
- * (LF)
- * Content-Type:�application/octet-stream(CR)
- * (LF)
- * (CR)
- * (LF)
- *
- * As you can see the there is a difference in the Cache-Control directive. I suspect that this
- * explains the problem. Also take a look at http://bugs.php.net/bug.php?id=16458.
- *
- * @version 1.21
- * @copyright 2004-2005
- * @author Jan Bols <jan@ivpv.UGent.be>, main programmer
- * @author Ren� Haentjens <rene.haentjens@UGent.be>, several contributions  (see RH)
- * @author Roan Embrechts, virtual course support
- *
- * @package dokeos.dropbox
-==============================================================================
- */
-
-/*
-==============================================================================
-		INITIALISING VARIABLES
-==============================================================================
-*/
-require_once( "dropbox_init.inc.php");	//only call init1 because init2 outputs data
-require_once( "dropbox_class.inc.php");
-
-
-/*
-==============================================================================
-		AUTHORISATION SECTION
-==============================================================================
-*/
-if ( !isset( $_user['user_id']) || !$is_course_member )
-{
-    exit( );
-}
-
-if ($_GET['mailing'])  // RH: Mailing detail window call
-	getUserOwningThisMailing($_GET['mailing'], $_user['user_id'], '500');  // RH or die
-
-/*
-==============================================================================
-		SANITY CHECKS OF GET DATA & FILE
-==============================================================================
-*/
-if ( ! isset( $_GET['id']) || ! is_numeric( $_GET['id'])) die(dropbox_lang("generalError")." (code 501)");
-
-$work = new Dropbox_work($_GET['id']);
-
-$path = dropbox_cnf("sysPath") . "/" . $work -> filename; //path to file as stored on server
-$file = $work->title;
-
-// check that this file exists and that it doesn't include any special characters
-//if ( !is_file( $path) || ! eregi( '^[A-Z0-9_\-][A-Z0-9._\-]*$', $file))
-if ( !is_file( $path))
-{
-    die(dropbox_lang("generalError")." (code 504)");
-}
-
-/*
-==============================================================================
-		SEND HEADERS
-==============================================================================
-*/
-require_once(api_get_path(LIBRARY_PATH) . '/document.lib.php');
-$mimetype = DocumentManager::file_get_mime_type(TRUE);
-
-$fileparts = explode( '.', $file);
-$filepartscount = count( $fileparts);
-
-if ( ( $filepartscount > 1) && isset( $mimetype[$fileparts [$filepartscount - 1]]))
-{
-    // give hint to browser about filetype
-    header( "Content-type: " . $mimetype[$fileparts [$filepartscount - 1]] . "\n");
-}
-else
-{
-	//no information about filetype: force a download dialog window in browser
-	header( "Content-type: application/octet-stream\n");
-}
-
-if (!in_array(strtolower($fileparts [$filepartscount - 1]), array('doc','xls','ppt','pps','sxw','sxc','sxi')))
-{
-	header('Content-Disposition: inline; filename='.$file); // bugs with open office
-}
-else
-{
-	header('Content-Disposition: attachment; filename='.$file);
-}
-
-
-/**
- * Note that if you use these two headers from a previous example:
- * header('Cache-Control: no-cache, must-revalidate');
- * header('Pragma: no-cache');
- * before sending a file to the browser, the "Open" option on Internet Explorer's file download dialog will not work properly. If the user clicks "Open" instead of "Save," the target application will open an empty file, because the downloaded file was not cached. The user will have to save the file to their hard drive in order to use it.
- * Make sure to leave these headers out if you'd like your visitors to be able to use IE's "Open" option.
- */
-header( "Pragma: \n");
-header( "Cache-Control: \n");
-header( "Cache-Control: public\n"); // IE cannot download from sessions without a cache
-
-
-/*if ( isset( $_SERVER["HTTPS"]))
-{
-    /**
-     * We need to set the following headers to make downloads work using IE in HTTPS mode.
-     *
-    //header( "Pragma: ");
-    //header( "Cache-Control: ");
-    header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT\n");
-    header( "Last-Modified: " . gmdate( "D, d M Y H:i:s") . " GMT\n");
-    header( "Cache-Control: no-store, no-cache, must-revalidate\n"); // HTTP/1.1
-    header( "Cache-Control: post-check=0, pre-check=0\n", false);
-}*/
-
-
-
-header( "Content-Description: " . trim( htmlentities( $file)) . "\n");
-header( "Content-Transfer-Encoding: binary\n");
-header( "Content-Length: " . filesize( $path)."\n" );
-
-/*
-==============================================================================
-		SEND FILE
-==============================================================================
-*/
-$fp = fopen( $path, "rb");
-fpassthru( $fp);
-exit( );
-
-/**
- * Found a workaround to another headache that just cropped up tonight.  Apparently Opera 6.1 on Linux (unsure of other versions/platforms) has problems downloading files using the above methods if you have enabled compression via zlib.output_compression in php.ini.
- * It seems that Opera sees that the actual transfer size is less than the size in the "Content-length" header for the download and decides that the transfer was incomplete or corrupted.  It then either continuously retries the download or else leaves you with a corrupted file.
- * Solution:  Make sure your download script/section is off in its own directory. and add the following to your .htaccess file for that directory:
- * php_flag zlib.output_compression off
- */
-?>
+<?php //$id: $
+/* For licensing terms, see /dokeos_license.txt */
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
+*/
+// we cannot use dropbox_init.inc.php because this one already outputs data.
+//name of langfile
+// name of the language file that needs to be included
+$language_file = "dropbox";
+
+// including the basic Dokeos initialisation file
+require("../inc/global.inc.php");
+
+// the dropbox configuration parameters
+include_once('dropbox_config.inc.php');
+
+// the dropbox file that contains additional functions
+include_once('dropbox_functions.inc.php');
+
+// the dropbox class
+require_once( "dropbox_class.inc.php");
+
+//
+include_once(api_get_path(LIBRARY_PATH).'/document.lib.php');
+
+
+/*
+==============================================================================
+		DOWNLOAD A FOLDER
+==============================================================================
+*/
+if ( isset($_GET['cat_id']) AND is_numeric($_GET['cat_id']) AND $_GET['action']=='downloadcategory' AND isset($_GET['sent_received']) )
+{
+	// step 1: constructingd' the sql statement. Due to the nature off the classes of the dropbox the categories for sent files are stored in the table
+	// dropbox_file while the categories for the received files are stored in dropbox_post. It would have been more elegant if these could be stored
+	// in dropbox_person (which stores the link file-person)
+	// Therefore we have to create to separate sql statements to find which files are in the categorie (depending if we zip-download a sent category or a
+	// received category)
+	if ($_GET['sent_received']=='sent')
+	{
+		// here we also incorporate the person table to make sure that deleted sent documents are not included.
+		$sql="SELECT DISTINCT file.id, file.filename, file.title FROM ".$dropbox_cnf["tbl_file"]." file, ".$dropbox_cnf["tbl_person"]." person
+				WHERE file.uploader_id='".mysql_real_escape_string($_user['user_id'])."'
+				AND file.cat_id='".mysql_real_escape_string($_GET['cat_id'])."'
+				AND person.user_id='".mysql_real_escape_string($_user['user_id'])."'
+				AND person.file_id=file.id
+				" ;
+	}
+	if ($_GET['sent_received']=='received')
+	{
+		$sql="SELECT DISTINCT file.id, file.filename, file.title FROM ".$dropbox_cnf["tbl_file"]." file, ".$dropbox_cnf["tbl_person"]." person, ".$dropbox_cnf["tbl_post"]." post
+				WHERE post.cat_id='".mysql_real_escape_string($_GET['cat_id'])."'
+				AND person.user_id='".mysql_real_escape_string($_user['user_id'])."'
+				AND person.file_id=file.id
+				AND post.file_id=file.id
+				" ;
+	}
+	$result=Database::query($sql,__FILE__,__LINE__);
+	while ($row=mysql_fetch_array($result))
+	{
+		$files_to_download[]=$row['id'];
+	}
+	if (!is_array($files_to_download) OR empty($files_to_download))
+	{
+		header ("location: index.php?view=".$_GET['sent_received']."&error=ErrorNoFilesInFolder");
+		exit;
+	}
+
+	zip_download($files_to_download);
+	exit;
+}
+
+
+
+/*
+==============================================================================
+		DOWNLOAD A FILE
+==============================================================================
+*/
+/*
+------------------------------------------------------------------------------
+		AUTHORIZATION
+------------------------------------------------------------------------------
+*/
+// Check if the id makes sense
+if ( ! isset( $_GET['id']) || ! is_numeric( $_GET['id']))
+{
+	Display::display_header($nameTools,"Dropbox");
+	Display :: display_error_message(get_lang('Error'));
+	Display::display_footer();
+	exit;
+}
+
+// Check if the user is allowed to download the file
+$allowed_to_download=false;
+
+// Check if the user has sent or received the file.
+$sql="SELECT * FROM ".$dropbox_cnf["tbl_person"]." WHERE file_id='".mysql_real_escape_string($_GET['id'])."' AND user_id='".mysql_real_escape_string($_user['user_id'])."'";
+$result=Database::query($sql);
+if (mysql_num_rows($result)>0)
+{
+	$allowed_to_download=true;
+}
+
+/*
+------------------------------------------------------------------------------
+		ERROR IF NOT ALLOWED TO DOWNLOAD
+------------------------------------------------------------------------------
+*/
+if (!$allowed_to_download)
+{
+	Display::display_header($nameTools,"Dropbox");
+	Display :: display_error_message(get_lang('YouAreNotAllowedToDownloadThisFile'));
+	Display::display_footer();
+	exit;
+}
+/*
+------------------------------------------------------------------------------
+		DOWNLOAD THE FILE
+------------------------------------------------------------------------------
+*/
+// the user is allowed to download the file
+else
+{
+	$_SESSION['_seen'][$_course['id']][TOOL_DROPBOX][]=$_GET['id'];
+
+	$work = new Dropbox_work($_GET['id']);
+	$path = dropbox_cnf("sysPath") . "/" . $work -> filename; //path to file as stored on server
+	$file = $work->title;
+	require_once(api_get_path(LIBRARY_PATH) . '/document.lib.php');
+	$mimetype = DocumentManager::file_get_mime_type(TRUE);
+	$fileparts = explode( '.', $file);
+	$filepartscount = count( $fileparts);
+	if ( ( $filepartscount > 1) && isset( $mimetype[$fileparts [$filepartscount - 1]]) && $_GET['action']<>'download')
+	{
+	    // give hint to browser about filetype
+    	header( "Content-type: " . $mimetype[$fileparts [$filepartscount - 1]] . "\n");
+	}
+	else
+	{
+		//no information about filetype: force a download dialog window in browser
+		header( "Content-type: application/octet-stream\n");
+	}
+	if (!in_array(strtolower($fileparts [$filepartscount - 1]), array('doc','xls','ppt','pps','sxw','sxc','sxi')))
+	{
+		header('Content-Disposition: inline; filename='.$file); // bugs with open office
+	}
+	else
+	{
+		header('Content-Disposition: attachment; filename='.$file);
+	}
+
+
+	/**
+	 * Note that if you use these two headers from a previous example:
+	 * header('Cache-Control: no-cache, must-revalidate');
+	 * header('Pragma: no-cache');
+	 * before sending a file to the browser, the "Open" option on Internet Explorer's file download dialog will not work properly. If the user clicks "Open" instead of "Save," the target application will open an empty file, because the downloaded file was not cached. The user will have to save the file to their hard drive in order to use it.
+	 * Make sure to leave these headers out if you'd like your visitors to be able to use IE's "Open" option.
+	 */
+	header( "Pragma: \n");
+	header( "Cache-Control: \n");
+	header( "Cache-Control: public\n"); // IE cannot download from sessions without a cache
+
+
+	/*if ( isset( $_SERVER["HTTPS"]))
+	{
+	    /**
+	     * We need to set the following headers to make downloads work using IE in HTTPS mode.
+	     *
+	    //header( "Pragma: ");
+	    //header( "Cache-Control: ");
+	    header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT\n");
+	    header( "Last-Modified: " . gmdate( "D, d M Y H:i:s") . " GMT\n");
+	    header( "Cache-Control: no-store, no-cache, must-revalidate\n"); // HTTP/1.1
+	    header( "Cache-Control: post-check=0, pre-check=0\n", false);
+	}*/
+
+
+
+	header( "Content-Description: " . trim( htmlentities( $file)) . "\n");
+	header( "Content-Transfer-Encoding: binary\n");
+	header( "Content-Length: " . filesize( $path)."\n" );
+
+	$fp = fopen( $path, "rb");
+	fpassthru( $fp);
+	exit();
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+// $Id: dropbox_download.php,v 1.10 2005/05/19 14:41:30 renehaentjens Exp $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004 Dokeos S.A.
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Jan Bols
+	Copyright (c) Rene Haentjens
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+ * Dropbox module for Claroline
+ * handles downloads of files. Direct downloading is prevented because of an .htaccess file in the
+ * dropbox directory. So everything goes through this script.
+ *
+ * 1. Initialising vars
+ * 2. Authorisation
+ * 3. Sanity check of get data & file
+ * 4. Send headers
+ * 5. Send file
+ *
+ *
+ * NOTE :
+ * When testing this with PHP4.0.4 on WinXP and Apache2 there were problems with downloading in IE6
+ * After searching the only explanation I could find is a problem with the headers:
+ *
+ * HEADERS SENT WITH PHP4.3:
+ * HTTP/1.1�200�OK(CR)
+ * (LF)
+ * Date:�Fri,�12�Sep�2003�19:07:33�GMT(CR)
+ * (LF)
+ * Server:�Apache/2.0.47�(Win32)�PHP/4.3.3(CR)
+ * (LF)
+ * X-Powered-By:�PHP/4.3.3(CR)
+ * (LF)
+ * Set-Cookie:�PHPSESSID=06880edcc8363be3f60929576fc1bc6e;�path=/(CR)
+ * (LF)
+ * Expires:�Thu,�19�Nov�1981�08:52:00�GMT(CR)
+ * (LF)
+ * Cache-Control:�public(CR)
+ * (LF)
+ * Pragma:�(CR)
+ * (LF)
+ * Content-Transfer-Encoding:�binary(CR)
+ * (LF)
+ * Content-Disposition:�attachment;�filename=SV-262E4.png(CR)
+ * (LF)
+ * Content-Length:�92178(CR)
+ * (LF)
+ * Connection:�close(CR)
+ * (LF)
+ * Content-Type:�application/octet-stream(CR)
+ * (LF)
+ * (CR)
+ * (LF)
+ *
+ * HEADERS SENT WITH PHP4.0.4:
+ * HTTP/1.1�200�OK(CR)
+ * (LF)
+ * Date:�Fri,�12�Sep�2003�18:28:21�GMT(CR)
+ * (LF)
+ * Server:�Apache/2.0.47�(Win32)(CR)
+ * (LF)
+ * X-Powered-By:�PHP/4.0.4(CR)
+ * (LF)
+ * Expires:�Thu,�19�Nov�1981�08:52:00�GMT(CR)
+ * (LF)
+ * Cache-Control:�no-store,�no-cache,�must-revalidate,�post-check=0,�pre-check=0,�,�public(CR)
+ * (LF)
+ * Pragma:�no-cache,�(CR)
+ * (LF)
+ * Content-Disposition:�attachment;�filename=SV-262E4.png(CR)
+ * (LF)
+ * Content-Transfer-Encoding:�binary(CR)
+ * (LF)
+ * Set-Cookie:�PHPSESSID=0a5b1c1b9d5e3b474fef359ee55e82d0;�path=/(CR)
+ * (LF)
+ * Content-Length:�92178(CR)
+ * (LF)
+ * Connection:�close(CR)
+ * (LF)
+ * Content-Type:�application/octet-stream(CR)
+ * (LF)
+ * (CR)
+ * (LF)
+ *
+ * As you can see the there is a difference in the Cache-Control directive. I suspect that this
+ * explains the problem. Also take a look at http://bugs.php.net/bug.php?id=16458.
+ *
+ * @version 1.21
+ * @copyright 2004-2005
+ * @author Jan Bols <jan@ivpv.UGent.be>, main programmer
+ * @author Ren� Haentjens <rene.haentjens@UGent.be>, several contributions  (see RH)
+ * @author Roan Embrechts, virtual course support
+ *
+ * @package dokeos.dropbox
+==============================================================================
+ */
+
+/*
+==============================================================================
+		INITIALISING VARIABLES
+==============================================================================
+*/
+require_once( "dropbox_init.inc.php");	//only call init1 because init2 outputs data
+require_once( "dropbox_class.inc.php");
+
+
+/*
+==============================================================================
+		AUTHORISATION SECTION
+==============================================================================
+*/
+if ( !isset( $_user['user_id']) || !$is_course_member )
+{
+    exit( );
+}
+
+if ($_GET['mailing'])  // RH: Mailing detail window call
+	getUserOwningThisMailing($_GET['mailing'], $_user['user_id'], '500');  // RH or die
+
+/*
+==============================================================================
+		SANITY CHECKS OF GET DATA & FILE
+==============================================================================
+*/
+if ( ! isset( $_GET['id']) || ! is_numeric( $_GET['id'])) die(dropbox_lang("generalError")." (code 501)");
+
+$work = new Dropbox_work($_GET['id']);
+
+$path = dropbox_cnf("sysPath") . "/" . $work -> filename; //path to file as stored on server
+$file = $work->title;
+
+// check that this file exists and that it doesn't include any special characters
+//if ( !is_file( $path) || ! eregi( '^[A-Z0-9_\-][A-Z0-9._\-]*$', $file))
+if ( !is_file( $path))
+{
+    die(dropbox_lang("generalError")." (code 504)");
+}
+
+/*
+==============================================================================
+		SEND HEADERS
+==============================================================================
+*/
+require_once(api_get_path(LIBRARY_PATH) . '/document.lib.php');
+$mimetype = DocumentManager::file_get_mime_type(TRUE);
+
+$fileparts = explode( '.', $file);
+$filepartscount = count( $fileparts);
+
+if ( ( $filepartscount > 1) && isset( $mimetype[$fileparts [$filepartscount - 1]]))
+{
+    // give hint to browser about filetype
+    header( "Content-type: " . $mimetype[$fileparts [$filepartscount - 1]] . "\n");
+}
+else
+{
+	//no information about filetype: force a download dialog window in browser
+	header( "Content-type: application/octet-stream\n");
+}
+
+if (!in_array(strtolower($fileparts [$filepartscount - 1]), array('doc','xls','ppt','pps','sxw','sxc','sxi')))
+{
+	header('Content-Disposition: inline; filename='.$file); // bugs with open office
+}
+else
+{
+	header('Content-Disposition: attachment; filename='.$file);
+}
+
+
+/**
+ * Note that if you use these two headers from a previous example:
+ * header('Cache-Control: no-cache, must-revalidate');
+ * header('Pragma: no-cache');
+ * before sending a file to the browser, the "Open" option on Internet Explorer's file download dialog will not work properly. If the user clicks "Open" instead of "Save," the target application will open an empty file, because the downloaded file was not cached. The user will have to save the file to their hard drive in order to use it.
+ * Make sure to leave these headers out if you'd like your visitors to be able to use IE's "Open" option.
+ */
+header( "Pragma: \n");
+header( "Cache-Control: \n");
+header( "Cache-Control: public\n"); // IE cannot download from sessions without a cache
+
+
+/*if ( isset( $_SERVER["HTTPS"]))
+{
+    /**
+     * We need to set the following headers to make downloads work using IE in HTTPS mode.
+     *
+    //header( "Pragma: ");
+    //header( "Cache-Control: ");
+    header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT\n");
+    header( "Last-Modified: " . gmdate( "D, d M Y H:i:s") . " GMT\n");
+    header( "Cache-Control: no-store, no-cache, must-revalidate\n"); // HTTP/1.1
+    header( "Cache-Control: post-check=0, pre-check=0\n", false);
+}*/
+
+
+
+header( "Content-Description: " . trim( htmlentities( $file)) . "\n");
+header( "Content-Transfer-Encoding: binary\n");
+header( "Content-Length: " . filesize( $path)."\n" );
+
+/*
+==============================================================================
+		SEND FILE
+==============================================================================
+*/
+$fp = fopen( $path, "rb");
+fpassthru( $fp);
+exit( );
+
+/**
+ * Found a workaround to another headache that just cropped up tonight.  Apparently Opera 6.1 on Linux (unsure of other versions/platforms) has problems downloading files using the above methods if you have enabled compression via zlib.output_compression in php.ini.
+ * It seems that Opera sees that the actual transfer size is less than the size in the "Content-length" header for the download and decides that the transfer was incomplete or corrupted.  It then either continuously retries the download or else leaves you with a corrupted file.
+ * Solution:  Make sure your download script/section is off in its own directory. and add the following to your .htaccess file for that directory:
+ * php_flag zlib.output_compression off
+ */
+?>

+ 1513 - 1513
main/dropbox/dropbox_functions.inc.php

@@ -1,1533 +1,1533 @@
-<?php //$id: $
-/* For licensing terms, see /dokeos_license.txt */
-/**
+<?php //$id: $
+/* For licensing terms, see /dokeos_license.txt */
+/**
 * This file contains additional dropbox functions. Initially there were some
-* functions in the init files also but I have moved them over
-* to one file 		-- Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-/**
-* This function is a wrapper function for the multiple actions feature.
-* @return	Mixed	If there is a problem, return a string message, otherwise nothing
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function handle_multiple_actions()
-{
-	global $_user, $is_courseAdmin, $is_courseTutor;
-
-	// STEP 1: are we performing the actions on the received or on the sent files?
-	if($_POST['action']=='delete_received' || $_POST['action']=='download_received')
-	{
-		$part = 'received';
-	}
-	elseif($_POST['action']=='delete_sent' || $_POST['action']=='download_sent')
-	{
-		$part = 'sent';
-	}
-
-	// STEP 2: at least one file has to be selected. If not we return an error message
-	foreach ($_POST as $key=>$value)
-	{
-		if (strstr($value,$part.'_') AND $key!='view_received_category' AND $key!='view_sent_category')
-		{
-			$checked_files=true;
-			$checked_file_ids[]=intval(substr($value,strrpos($value,'_')));
-		}
-	}
-	$checked_file_ids = $_POST['id'];
-
-	if (!is_array($checked_file_ids) || count($checked_file_ids)==0)
-	{
-		return get_lang('CheckAtLeastOneFile');
-	}
-
-
-	// STEP 3A: deleting
-	if ($_POST['action']=='delete_received' || $_POST['action']=='delete_sent')
-	{
-		$dropboxfile=new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
-		foreach ($checked_file_ids as $key=>$value)
-		{
-			if ($_GET['view']=='received')
-			{
-				$dropboxfile->deleteReceivedWork($value);
-				$message=get_lang('ReceivedFileDeleted');
-			}
-			if ($_GET['view']=='sent' OR empty($_GET['view']))
-			{
-				$dropboxfile->deleteSentWork($value);
-				$message=get_lang('SentFileDeleted');
-			}
-		}
-		return $message;
-	}
-
-	// STEP 3B: giving comment
-	if ($_POST['actions']=='comment')
-	{
-		// This has not been implemented.
-		// The idea was that it would be possible to write the same feedback for the selected documents.
-	}
-
-	// STEP 3C: moving
-	if (strstr($_POST['action'], 'move_'))
-	{
-        	// check move_received_n or move_sent_n command
-		if (strstr($_POST['action'],'received')){
-                	$part = 'received';
-                	$to_cat_id = str_replace('move_received_','',$_POST['action']);
-        	}
-        	else {
-                	$part = 'sent';
-                	$to_cat_id = str_replace('move_sent_','',$_POST['action']);
-        	}
-
-		foreach ($checked_file_ids as $key=>$value)
-		{
-			var_dump($value);
-			var_dump($to_cat_id);
-			var_dump($part);
-			store_move($value, $to_cat_id, $part);
-		}
-		return get_lang('FilesMoved');
-    }
-
-	// STEP 3D: downloading
-	if ($_POST['action']=='download_sent' || $_POST['action']=='download_received')
-	{
-		zip_download($checked_file_ids);
-	}
-
-}
-
-/**
-* This function deletes a dropbox category
-*
-* @todo give the user the possibility what needs to be done with the files in this category: move them to the root, download them as a zip, delete them
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function delete_category($action, $id)
-{
-	global $dropbox_cnf;
-	global $_user, $is_courseAdmin, $is_courseTutor;
-
-	// an additional check that might not be necessary
-	if ($action=='deletereceivedcategory')
-	{
-		$sentreceived='received';
-		$entries_table=$dropbox_cnf['tbl_post'];
-		$id_field='file_id';
-		$return_message = get_lang('ReceivedCatgoryDeleted');
-	}
-	elseif ($action=='deletesentcategory')
-	{
-		$sentreceived='sent';
-		$entries_table=$dropbox_cnf['tbl_file'];
-		$id_field='id';
-		$return_message = get_lang('SentCatgoryDeleted');
-	}
-	else
-	{
-		return get_lang('Error');
-	}
-
-	// step 1: delete the category
-	$sql="DELETE FROM ".$dropbox_cnf['tbl_category']." WHERE cat_id='".Database::escape_string($id)."' AND $sentreceived='1'";
-	$result=Database::query($sql,__FILE__,__LINE__);
-
-	// step 2: delete all the documents in this category
-	$sql="SELECT * FROM ".$entries_table." WHERE cat_id='".Database::escape_string($id)."'";
-	$result=Database::query($sql,__FILE__,__LINE__);
-
-	while ($row=Database::fetch_array($result))
-	{
-		$dropboxfile=new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
-		if ($action=='deletereceivedcategory')
-		{
-			$dropboxfile->deleteReceivedWork($row[$id_field]);
-		}
-		if ($action=='deletesentcategory')
-		{
-			$dropboxfile->deleteSentWork($row[$id_field]);
-		}
-	}
-	return $return_message;
-}
-
-/**
-* Displays the form to move one individual file to a category
-*
-* @return html code of the form that appears in a dokeos message box.
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function display_move_form($part, $id, $target=array())
-{
-	echo '<div class="row"><div class="form_header">'.get_lang('MoveFileTo').'</div></div>';
-	echo '<form name="form1" method="post" action="'.api_get_self().'?view_received_category='.$_GET['view_received_category'].'&view_sent_category='.$_GET['view_sent_category'].'&view='.$_GET['view'].'">';
-	echo '<input type="hidden" name="id" value="'.Security::remove_XSS($id).'">';
-	echo '<input type="hidden" name="part" value="'.Security::remove_XSS($part).'">';
-	echo '
-			<div class="row">
-				<div class="label">
-					<span class="form_required">*</span> '.get_lang('MoveFileTo').'
-				</div>
-				<div class="formw">';
-	echo '<select name="move_target">';
-	echo '<option value="0">'.get_lang('Root').'</option>';
-	foreach ($target as $key=>$category)
-	{
-		echo '<option value="'.$category['cat_id'].'">'.$category['cat_name'].'</option>';
-	}
-	echo  '</select>';
-	echo '	</div>
-			</div>';
-
-	echo '
-		<div class="row">
-			<div class="label">
-			</div>
-			<div class="formw">
-				<button class="next" type="submit" name="do_move" value="'.get_lang('Ok').'">'.get_lang('MoveFile').'</button>
-			</div>
+* functions in the init files also but I have moved them over
+* to one file 		-- Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+/**
+* This function is a wrapper function for the multiple actions feature.
+* @return	Mixed	If there is a problem, return a string message, otherwise nothing
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function handle_multiple_actions()
+{
+	global $_user, $is_courseAdmin, $is_courseTutor;
+
+	// STEP 1: are we performing the actions on the received or on the sent files?
+	if($_POST['action']=='delete_received' || $_POST['action']=='download_received')
+	{
+		$part = 'received';
+	}
+	elseif($_POST['action']=='delete_sent' || $_POST['action']=='download_sent')
+	{
+		$part = 'sent';
+	}
+
+	// STEP 2: at least one file has to be selected. If not we return an error message
+	foreach ($_POST as $key=>$value)
+	{
+		if (strstr($value,$part.'_') AND $key!='view_received_category' AND $key!='view_sent_category')
+		{
+			$checked_files=true;
+			$checked_file_ids[]=intval(substr($value,strrpos($value,'_')));
+		}
+	}
+	$checked_file_ids = $_POST['id'];
+
+	if (!is_array($checked_file_ids) || count($checked_file_ids)==0)
+	{
+		return get_lang('CheckAtLeastOneFile');
+	}
+
+
+	// STEP 3A: deleting
+	if ($_POST['action']=='delete_received' || $_POST['action']=='delete_sent')
+	{
+		$dropboxfile=new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
+		foreach ($checked_file_ids as $key=>$value)
+		{
+			if ($_GET['view']=='received')
+			{
+				$dropboxfile->deleteReceivedWork($value);
+				$message=get_lang('ReceivedFileDeleted');
+			}
+			if ($_GET['view']=='sent' OR empty($_GET['view']))
+			{
+				$dropboxfile->deleteSentWork($value);
+				$message=get_lang('SentFileDeleted');
+			}
+		}
+		return $message;
+	}
+
+	// STEP 3B: giving comment
+	if ($_POST['actions']=='comment')
+	{
+		// This has not been implemented.
+		// The idea was that it would be possible to write the same feedback for the selected documents.
+	}
+
+	// STEP 3C: moving
+	if (strstr($_POST['action'], 'move_'))
+	{
+        	// check move_received_n or move_sent_n command
+		if (strstr($_POST['action'],'received')){
+                	$part = 'received';
+                	$to_cat_id = str_replace('move_received_','',$_POST['action']);
+        	}
+        	else {
+                	$part = 'sent';
+                	$to_cat_id = str_replace('move_sent_','',$_POST['action']);
+        	}
+
+		foreach ($checked_file_ids as $key=>$value)
+		{
+			var_dump($value);
+			var_dump($to_cat_id);
+			var_dump($part);
+			store_move($value, $to_cat_id, $part);
+		}
+		return get_lang('FilesMoved');
+    }
+
+	// STEP 3D: downloading
+	if ($_POST['action']=='download_sent' || $_POST['action']=='download_received')
+	{
+		zip_download($checked_file_ids);
+	}
+
+}
+
+/**
+* This function deletes a dropbox category
+*
+* @todo give the user the possibility what needs to be done with the files in this category: move them to the root, download them as a zip, delete them
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function delete_category($action, $id)
+{
+	global $dropbox_cnf;
+	global $_user, $is_courseAdmin, $is_courseTutor;
+
+	// an additional check that might not be necessary
+	if ($action=='deletereceivedcategory')
+	{
+		$sentreceived='received';
+		$entries_table=$dropbox_cnf['tbl_post'];
+		$id_field='file_id';
+		$return_message = get_lang('ReceivedCatgoryDeleted');
+	}
+	elseif ($action=='deletesentcategory')
+	{
+		$sentreceived='sent';
+		$entries_table=$dropbox_cnf['tbl_file'];
+		$id_field='id';
+		$return_message = get_lang('SentCatgoryDeleted');
+	}
+	else
+	{
+		return get_lang('Error');
+	}
+
+	// step 1: delete the category
+	$sql="DELETE FROM ".$dropbox_cnf['tbl_category']." WHERE cat_id='".Database::escape_string($id)."' AND $sentreceived='1'";
+	$result=Database::query($sql,__FILE__,__LINE__);
+
+	// step 2: delete all the documents in this category
+	$sql="SELECT * FROM ".$entries_table." WHERE cat_id='".Database::escape_string($id)."'";
+	$result=Database::query($sql,__FILE__,__LINE__);
+
+	while ($row=Database::fetch_array($result))
+	{
+		$dropboxfile=new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
+		if ($action=='deletereceivedcategory')
+		{
+			$dropboxfile->deleteReceivedWork($row[$id_field]);
+		}
+		if ($action=='deletesentcategory')
+		{
+			$dropboxfile->deleteSentWork($row[$id_field]);
+		}
+	}
+	return $return_message;
+}
+
+/**
+* Displays the form to move one individual file to a category
+*
+* @return html code of the form that appears in a dokeos message box.
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function display_move_form($part, $id, $target=array())
+{
+	echo '<div class="row"><div class="form_header">'.get_lang('MoveFileTo').'</div></div>';
+	echo '<form name="form1" method="post" action="'.api_get_self().'?view_received_category='.$_GET['view_received_category'].'&view_sent_category='.$_GET['view_sent_category'].'&view='.$_GET['view'].'">';
+	echo '<input type="hidden" name="id" value="'.Security::remove_XSS($id).'">';
+	echo '<input type="hidden" name="part" value="'.Security::remove_XSS($part).'">';
+	echo '
+			<div class="row">
+				<div class="label">
+					<span class="form_required">*</span> '.get_lang('MoveFileTo').'
+				</div>
+				<div class="formw">';
+	echo '<select name="move_target">';
+	echo '<option value="0">'.get_lang('Root').'</option>';
+	foreach ($target as $key=>$category)
+	{
+		echo '<option value="'.$category['cat_id'].'">'.$category['cat_name'].'</option>';
+	}
+	echo  '</select>';
+	echo '	</div>
+			</div>';
+
+	echo '
+		<div class="row">
+			<div class="label">
+			</div>
+			<div class="formw">
+				<button class="next" type="submit" name="do_move" value="'.get_lang('Ok').'">'.get_lang('MoveFile').'</button>
+			</div>
 		</div>
-	';
-	echo '</form>';
-
-	echo '<div style="clear: both;"></div>';
-}
-
-/**
-* This function moves a file to a different category
-*
-* @param $id the id of the file we are moving
-* @param $target the id of the folder we are moving to
-* @param $part are we moving a received file or a sent file?
-*
-* @return language string
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function store_move($id, $target, $part)
-{
-	global $_user;
-	global $dropbox_cnf;
-
-	if ((isset($id) AND $id<>'') AND (isset($target) AND $target<>'') AND (isset($part) AND $part<>''))
-	{
-		if ($part=='received')
-		{
-			$sql="UPDATE ".$dropbox_cnf["tbl_post"]." SET cat_id='".Database::escape_string($target)."'
-						WHERE dest_user_id='".Database::escape_string($_user['user_id'])."'
-						AND file_id='".Database::escape_string($id)."'
-						";
-			Database::query($sql,__FILE__,__LINE__);
-			$return_message=get_lang('ReceivedFileMoved');
-		}
-		if ($part=='sent')
-		{
-			$sql="UPDATE ".$dropbox_cnf["tbl_file"]." SET cat_id='".Database::escape_string($target)."'
-						WHERE uploader_id='".Database::escape_string($_user['user_id'])."'
-						AND id='".Database::escape_string($id)."'
-						";
-			Database::query($sql,__FILE__,__LINE__);
-			$return_message=get_lang('SentFileMoved');
-		}
-	}
-	else
-	{
-		$return_message=get_lang('NotMovedError');
-	}
-	return $return_message;
-}
-
-/**
-* This functions displays all teh possible actions that can be performed on multiple files. This is the dropdown list that
-* appears below the sortable table of the sent / or received files.
-*
-* @return html value for the dropdown list
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function display_action_options($part, $categories, $current_category=0)
-{
-	echo '<select name="actions">';
-	echo '<option value="download">'.get_lang('Download').'</option>';
-	echo '<option value="delete">'.get_lang('Delete').'</option>';
-	if(is_array($categories))
-	{
-		echo '<optgroup label="'.get_lang('MoveTo').'">';
-		if ($current_category<>0)
-		{
-			echo '<option value="move_0">'.get_lang('Root').'</a>';
-		}
-		foreach ($categories as $key=>$value)
-		{
-			if( $current_category<>$value['cat_id'])
-			{
-				echo '<option value="move_'.$value['cat_id'].'">'.$value['cat_name'].'</option>';
-			}
-		}
-		echo '</optgroup>';
-	}
-	echo '</select>';
-	echo '<input type="submit" name="do_actions_'.Security::remove_XSS($part).'" value="'.get_lang('Ok').'" />';
-}
-
-/**
-* this function returns the html code that displays the checkboxes next to the files so that
-* multiple actions on one file are possible.
-*
-* @param $id the unique id of the file
-* @param $part are we dealing with a sent or with a received file?
-*
-* @return html code
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function display_file_checkbox($id, $part)
-{
-	if (isset($_GET['selectall']))
-	{
-		$checked='checked';
-	}
-	$return_value='<input type="checkbox" name="'.Security::remove_XSS($part).'_'.Security::remove_XSS($id).'" value="'.Security::remove_XSS($id).'" '.$checked.' />';
-	return $return_value;
-}
-
-
-/**
-* This function retrieves all the dropbox categories and returns them as an array
-*
-* @param $filter default '', when we need only the categories of the sent or the received part.
-*
-* @return array
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function get_dropbox_categories($filter='')
-{
-	global $_user;
-	global $dropbox_cnf;
-
-	//echo '<h1>'.$filter.'</h1>';
-
-	$return_array=array();
-
-	$sql="SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE user_id='".$_user['user_id']."'";
-
-	$result=Database::query($sql,__FILE__,__LINE__);
-	while ($row=Database::fetch_array($result))
-	{
-		if(($filter=='sent' AND $row['sent']==1) OR ($filter=='received' AND $row['received']==1) OR $filter=='')
-		{
-			$return_array[$row['cat_id']]=$row;
-		}
-	}
-
-	return $return_array;
-}
-
-/**
-* This functions stores a new dropboxcategory
-*
-* @var 	it might not seem very elegant if you create a category in sent and in received with the same name that you get two entries in the
-*		dropbox_category table but it is the easiest solution. You get
-*		cat_name | received | sent | user_id
-*		test	 |	  1		|	0  |	237
-*		test	 |	  0		|	1  |	237
-*		more elegant would be
-*		test	 |	  1		|	1  |	237
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function store_addcategory()
-{
-	global $_user;
-	global $dropbox_cnf;
-
-	// check if the target is valid
-	if ($_POST['target']=='sent')
-	{
-		$sent=1;
-		$received=0;
-	}
-	elseif ($_POST['target']=='received')
-	{
-		$sent=0;
-		$received=1;
-	}
-	else
-	{
-		return get_lang('Error');
-	}
-
-	// check if the category name is valid
-	if ($_POST['category_name']=='')
-	{
-		return array('type' => 'error', 'message'=>get_lang('ErrorPleaseGiveCategoryName'));
-	}
-
-	if (!$_POST['edit_id'])
-	{
-		// step 3a, we check if the category doesn't already exist
-		$sql="SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE user_id='".$_user['user_id']."' AND cat_name='".Database::escape_string(Security::remove_XSS($_POST['category_name']))."' AND received='".$received."' AND sent='".$sent."'";
-		$result=Database::query($sql,__FILE__,__LINE__);
-
-
-		// step 3b, we add the category if it does not exist yet.
-		if (Database::num_rows($result)==0)
-		{
-			$sql="INSERT INTO ".$dropbox_cnf['tbl_category']." (cat_name, received, sent, user_id)
-					VALUES ('".Database::escape_string(Security::remove_XSS($_POST['category_name']))."', '".Database::escape_string($received)."', '".Database::escape_string($sent)."', '".Database::escape_string($_user['user_id'])."')";
-			Database::query($sql,__FILE__,__LINE__);
-			return array('type' => 'confirmation', 'message'=>get_lang('CategoryStored'));
-		}
-		else
-		{
-			return array('type' => 'error', 'message'=>get_lang('CategoryAlreadyExistsEditIt'));
-		}
-	}
-	else
-	{
-		$sql="UPDATE ".$dropbox_cnf['tbl_category']." SET cat_name='".Database::escape_string(Security::remove_XSS($_POST['category_name']))."', received='".Database::escape_string($received)."' , sent='".Database::escape_string($sent)."'
-				WHERE user_id='".Database::escape_string($_user['user_id'])."'
-				AND cat_id='".Database::escape_string(Security::remove_XSS($_POST['edit_id']))."'";
-		Database::query($sql,__FILE__,__LINE__);
-		return array('type' => 'confirmation', 'message'=>get_lang('CategoryModified'));
-	}
-}
-
-/**
-* This function displays the form to add a new category.
-*
-* @param $category_name this parameter is the name of the category (used when no section is selected)
-* @param $id this is the id of the category we are editing.
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function display_addcategory_form($category_name='', $id='',$action)
-{
-	global $dropbox_cnf;
-
-	$title=get_lang('AddNewCategory');
-
-	if (isset($id) AND $id<>'')
-	{
-		// retrieve the category we are editing
-		$sql="SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE cat_id='".Database::escape_string($id)."'";
-		$result=Database::query($sql,__FILE__,__LINE__);
-		$row=Database::fetch_array($result);
-
-		if ($category_name=='') // after an edit with an error we do not want to return to the original name but the name we already modified. (happens when createinrecievedfiles AND createinsentfiles are not checked)
-		{
-			$category_name=$row['cat_name'];
-		}
-		if ($row['received']=='1')
-		{
-			$target='received';
-		}
-		if ($row['sent']=='1')
-		{
-			$target='sent';
-		}
-		$title=get_lang('EditCategory');
-
-	}
-
-	if ($action=='addreceivedcategory') {
-		$target='received';
-	}
-	if ($action=='addsentcategory') {
-		$target='sent';
-	}
-
-	if ($action=='editcategory') {
-		$text=get_lang('ModifyCategory');
-		$class='save';
-	} else if ($action=='addreceivedcategory' or $action=='addsentcategory')  {
-		$text=get_lang('CreateCategory');
-		$class='add';
-	}
-
-
-	echo "<form name=\"add_new_category\" method=\"post\" action=\"".api_get_self()."?view=".Security::remove_XSS($_GET['view'])."\">\n";
-	if (isset($id) AND $id<>'')
-	{
-		echo '<input name="edit_id" type="hidden" value="'.Security::remove_XSS($id).'">';
-	}
-	echo '<input name="action" type="hidden" value="'.Security::remove_XSS($action).'">';
-	echo '<input name="target" type="hidden" value="'.$target.'">';
-
-	echo '<div class="row"><div class="form_header">'.$title.'</div></div>';
-
-	echo '	<div class="row">
-				<div class="label">
-					<span class="form_required">*</span> '.get_lang('CategoryName').'
-				</div>
-				<div class="formw">';
-	if ($_POST AND empty($_POST['category_name']))
-	{
-		echo '<span class="form_error">'.get_lang('ThisFieldIsRequired').'. '.get_lang('ErrorPleaseGiveCategoryName').'<span><br />';
-	}
-	if ($_POST AND !empty($_POST['category_name']))
-	{
-		echo '<span class="form_error">'.get_lang('CategoryAlreadyExistsEditIt').'<span><br />';
-	}
-	echo '			<input type="text" name="category_name" value="'.Security::remove_XSS($category_name).'" />
-				</div>
-			</div>';
-
-	echo '	<div class="row">
-				<div class="label">
-				</div>
-				<div class="formw">
-					<button class="'.$class.'" type="submit" name="StoreCategory">'.$text.'</button>
-				</div>
+	';
+	echo '</form>';
+
+	echo '<div style="clear: both;"></div>';
+}
+
+/**
+* This function moves a file to a different category
+*
+* @param $id the id of the file we are moving
+* @param $target the id of the folder we are moving to
+* @param $part are we moving a received file or a sent file?
+*
+* @return language string
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function store_move($id, $target, $part)
+{
+	global $_user;
+	global $dropbox_cnf;
+
+	if ((isset($id) AND $id<>'') AND (isset($target) AND $target<>'') AND (isset($part) AND $part<>''))
+	{
+		if ($part=='received')
+		{
+			$sql="UPDATE ".$dropbox_cnf["tbl_post"]." SET cat_id='".Database::escape_string($target)."'
+						WHERE dest_user_id='".Database::escape_string($_user['user_id'])."'
+						AND file_id='".Database::escape_string($id)."'
+						";
+			Database::query($sql,__FILE__,__LINE__);
+			$return_message=get_lang('ReceivedFileMoved');
+		}
+		if ($part=='sent')
+		{
+			$sql="UPDATE ".$dropbox_cnf["tbl_file"]." SET cat_id='".Database::escape_string($target)."'
+						WHERE uploader_id='".Database::escape_string($_user['user_id'])."'
+						AND id='".Database::escape_string($id)."'
+						";
+			Database::query($sql,__FILE__,__LINE__);
+			$return_message=get_lang('SentFileMoved');
+		}
+	}
+	else
+	{
+		$return_message=get_lang('NotMovedError');
+	}
+	return $return_message;
+}
+
+/**
+* This functions displays all teh possible actions that can be performed on multiple files. This is the dropdown list that
+* appears below the sortable table of the sent / or received files.
+*
+* @return html value for the dropdown list
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function display_action_options($part, $categories, $current_category=0)
+{
+	echo '<select name="actions">';
+	echo '<option value="download">'.get_lang('Download').'</option>';
+	echo '<option value="delete">'.get_lang('Delete').'</option>';
+	if(is_array($categories))
+	{
+		echo '<optgroup label="'.get_lang('MoveTo').'">';
+		if ($current_category<>0)
+		{
+			echo '<option value="move_0">'.get_lang('Root').'</a>';
+		}
+		foreach ($categories as $key=>$value)
+		{
+			if( $current_category<>$value['cat_id'])
+			{
+				echo '<option value="move_'.$value['cat_id'].'">'.$value['cat_name'].'</option>';
+			}
+		}
+		echo '</optgroup>';
+	}
+	echo '</select>';
+	echo '<input type="submit" name="do_actions_'.Security::remove_XSS($part).'" value="'.get_lang('Ok').'" />';
+}
+
+/**
+* this function returns the html code that displays the checkboxes next to the files so that
+* multiple actions on one file are possible.
+*
+* @param $id the unique id of the file
+* @param $part are we dealing with a sent or with a received file?
+*
+* @return html code
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function display_file_checkbox($id, $part)
+{
+	if (isset($_GET['selectall']))
+	{
+		$checked='checked';
+	}
+	$return_value='<input type="checkbox" name="'.Security::remove_XSS($part).'_'.Security::remove_XSS($id).'" value="'.Security::remove_XSS($id).'" '.$checked.' />';
+	return $return_value;
+}
+
+
+/**
+* This function retrieves all the dropbox categories and returns them as an array
+*
+* @param $filter default '', when we need only the categories of the sent or the received part.
+*
+* @return array
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function get_dropbox_categories($filter='')
+{
+	global $_user;
+	global $dropbox_cnf;
+
+	//echo '<h1>'.$filter.'</h1>';
+
+	$return_array=array();
+
+	$sql="SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE user_id='".$_user['user_id']."'";
+
+	$result=Database::query($sql,__FILE__,__LINE__);
+	while ($row=Database::fetch_array($result))
+	{
+		if(($filter=='sent' AND $row['sent']==1) OR ($filter=='received' AND $row['received']==1) OR $filter=='')
+		{
+			$return_array[$row['cat_id']]=$row;
+		}
+	}
+
+	return $return_array;
+}
+
+/**
+* This functions stores a new dropboxcategory
+*
+* @var 	it might not seem very elegant if you create a category in sent and in received with the same name that you get two entries in the
+*		dropbox_category table but it is the easiest solution. You get
+*		cat_name | received | sent | user_id
+*		test	 |	  1		|	0  |	237
+*		test	 |	  0		|	1  |	237
+*		more elegant would be
+*		test	 |	  1		|	1  |	237
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function store_addcategory()
+{
+	global $_user;
+	global $dropbox_cnf;
+
+	// check if the target is valid
+	if ($_POST['target']=='sent')
+	{
+		$sent=1;
+		$received=0;
+	}
+	elseif ($_POST['target']=='received')
+	{
+		$sent=0;
+		$received=1;
+	}
+	else
+	{
+		return get_lang('Error');
+	}
+
+	// check if the category name is valid
+	if ($_POST['category_name']=='')
+	{
+		return array('type' => 'error', 'message'=>get_lang('ErrorPleaseGiveCategoryName'));
+	}
+
+	if (!$_POST['edit_id'])
+	{
+		// step 3a, we check if the category doesn't already exist
+		$sql="SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE user_id='".$_user['user_id']."' AND cat_name='".Database::escape_string(Security::remove_XSS($_POST['category_name']))."' AND received='".$received."' AND sent='".$sent."'";
+		$result=Database::query($sql,__FILE__,__LINE__);
+
+
+		// step 3b, we add the category if it does not exist yet.
+		if (Database::num_rows($result)==0)
+		{
+			$sql="INSERT INTO ".$dropbox_cnf['tbl_category']." (cat_name, received, sent, user_id)
+					VALUES ('".Database::escape_string(Security::remove_XSS($_POST['category_name']))."', '".Database::escape_string($received)."', '".Database::escape_string($sent)."', '".Database::escape_string($_user['user_id'])."')";
+			Database::query($sql,__FILE__,__LINE__);
+			return array('type' => 'confirmation', 'message'=>get_lang('CategoryStored'));
+		}
+		else
+		{
+			return array('type' => 'error', 'message'=>get_lang('CategoryAlreadyExistsEditIt'));
+		}
+	}
+	else
+	{
+		$sql="UPDATE ".$dropbox_cnf['tbl_category']." SET cat_name='".Database::escape_string(Security::remove_XSS($_POST['category_name']))."', received='".Database::escape_string($received)."' , sent='".Database::escape_string($sent)."'
+				WHERE user_id='".Database::escape_string($_user['user_id'])."'
+				AND cat_id='".Database::escape_string(Security::remove_XSS($_POST['edit_id']))."'";
+		Database::query($sql,__FILE__,__LINE__);
+		return array('type' => 'confirmation', 'message'=>get_lang('CategoryModified'));
+	}
+}
+
+/**
+* This function displays the form to add a new category.
+*
+* @param $category_name this parameter is the name of the category (used when no section is selected)
+* @param $id this is the id of the category we are editing.
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function display_addcategory_form($category_name='', $id='',$action)
+{
+	global $dropbox_cnf;
+
+	$title=get_lang('AddNewCategory');
+
+	if (isset($id) AND $id<>'')
+	{
+		// retrieve the category we are editing
+		$sql="SELECT * FROM ".$dropbox_cnf['tbl_category']." WHERE cat_id='".Database::escape_string($id)."'";
+		$result=Database::query($sql,__FILE__,__LINE__);
+		$row=Database::fetch_array($result);
+
+		if ($category_name=='') // after an edit with an error we do not want to return to the original name but the name we already modified. (happens when createinrecievedfiles AND createinsentfiles are not checked)
+		{
+			$category_name=$row['cat_name'];
+		}
+		if ($row['received']=='1')
+		{
+			$target='received';
+		}
+		if ($row['sent']=='1')
+		{
+			$target='sent';
+		}
+		$title=get_lang('EditCategory');
+
+	}
+
+	if ($action=='addreceivedcategory') {
+		$target='received';
+	}
+	if ($action=='addsentcategory') {
+		$target='sent';
+	}
+
+	if ($action=='editcategory') {
+		$text=get_lang('ModifyCategory');
+		$class='save';
+	} else if ($action=='addreceivedcategory' or $action=='addsentcategory')  {
+		$text=get_lang('CreateCategory');
+		$class='add';
+	}
+
+
+	echo "<form name=\"add_new_category\" method=\"post\" action=\"".api_get_self()."?view=".Security::remove_XSS($_GET['view'])."\">\n";
+	if (isset($id) AND $id<>'')
+	{
+		echo '<input name="edit_id" type="hidden" value="'.Security::remove_XSS($id).'">';
+	}
+	echo '<input name="action" type="hidden" value="'.Security::remove_XSS($action).'">';
+	echo '<input name="target" type="hidden" value="'.$target.'">';
+
+	echo '<div class="row"><div class="form_header">'.$title.'</div></div>';
+
+	echo '	<div class="row">
+				<div class="label">
+					<span class="form_required">*</span> '.get_lang('CategoryName').'
+				</div>
+				<div class="formw">';
+	if ($_POST AND empty($_POST['category_name']))
+	{
+		echo '<span class="form_error">'.get_lang('ThisFieldIsRequired').'. '.get_lang('ErrorPleaseGiveCategoryName').'<span><br />';
+	}
+	if ($_POST AND !empty($_POST['category_name']))
+	{
+		echo '<span class="form_error">'.get_lang('CategoryAlreadyExistsEditIt').'<span><br />';
+	}
+	echo '			<input type="text" name="category_name" value="'.Security::remove_XSS($category_name).'" />
+				</div>
 			</div>';
-	echo '	<div class="row">
-				<div class="label">
-				</div>
-				<div class="formw">
-					<span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small>
-				</div>
+
+	echo '	<div class="row">
+				<div class="label">
+				</div>
+				<div class="formw">
+					<button class="'.$class.'" type="submit" name="StoreCategory">'.$text.'</button>
+				</div>
+			</div>';
+	echo '	<div class="row">
+				<div class="label">
+				</div>
+				<div class="formw">
+					<span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small>
+				</div>
 			</div>';
-	echo '</form>';
-	echo '<div style="clear: both;"></div>';
-}
-
-/**
-* this function displays the form to upload a new item to the dropbox.
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function display_add_form()
-{
-	global $_user, $is_courseAdmin, $is_courseTutor, $course_info, $origin, $dropbox_unid;
-
-	$token = Security::get_token();
-	$dropbox_person = new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
-	?>
-	<form method="post" action="index.php?view_received_category=<?php echo Security::remove_XSS($_GET['view_received_category']); ?>&view_sent_category=<?php echo Security::remove_XSS($_GET['view_sent_category']); ?>&view=<?php echo Security::remove_XSS($_GET['view']); ?>&<?php echo "origin=$origin"."&".api_get_cidreq(); ?>" enctype="multipart/form-data" onsubmit="return checkForm(this)">
-
-	<div class="row"><div class="form_header"><?php echo get_lang('UploadNewFile'); ?></div></div>
-
-	<div class="row">
-		<div class="label">
-			<span class="form_required">*</span><?php echo dropbox_lang("uploadFile")?>:
-		</div>
+	echo '</form>';
+	echo '<div style="clear: both;"></div>';
+}
+
+/**
+* this function displays the form to upload a new item to the dropbox.
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function display_add_form()
+{
+	global $_user, $is_courseAdmin, $is_courseTutor, $course_info, $origin, $dropbox_unid;
+
+	$token = Security::get_token();
+	$dropbox_person = new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
+	?>
+	<form method="post" action="index.php?view_received_category=<?php echo Security::remove_XSS($_GET['view_received_category']); ?>&view_sent_category=<?php echo Security::remove_XSS($_GET['view_sent_category']); ?>&view=<?php echo Security::remove_XSS($_GET['view']); ?>&<?php echo "origin=$origin"."&".api_get_cidreq(); ?>" enctype="multipart/form-data" onsubmit="return checkForm(this)">
+
+	<div class="row"><div class="form_header"><?php echo get_lang('UploadNewFile'); ?></div></div>
+
+	<div class="row">
+		<div class="label">
+			<span class="form_required">*</span><?php echo dropbox_lang("uploadFile")?>:
+		</div>
 		<div class="formw">
-				<input type="hidden" name="MAX_FILE_SIZE" value='<?php echo dropbox_cnf("maxFilesize")?>' />
-				<input type="file" name="file" size="20" <?php if (dropbox_cnf("allowOverwrite")) echo 'onChange="checkfile(this.value)"'; ?> />
-				<input type="hidden" name="dropbox_unid" value="<?php echo $dropbox_unid ?>" />
-				<input type="hidden" name="sec_token" value="<?php echo $token ?>" />
-				<?php
-				if ($origin=='learnpath')
-				{
-					echo '<input type="hidden" name="origin" value="learnpath" />';
-				}
-				?>
-		</div>
-	</div>
-
-	<?php
-	if (dropbox_cnf("allowOverwrite"))
-	{
-		?>
-		<div class="row">
-			<div class="label">
-
-			</div>
-			<div class="formw">
-				<input type="checkbox" name="cb_overwrite" id="cb_overwrite" value="true" /><?php echo dropbox_lang("overwriteFile")?>
-			</div>
+				<input type="hidden" name="MAX_FILE_SIZE" value='<?php echo dropbox_cnf("maxFilesize")?>' />
+				<input type="file" name="file" size="20" <?php if (dropbox_cnf("allowOverwrite")) echo 'onChange="checkfile(this.value)"'; ?> />
+				<input type="hidden" name="dropbox_unid" value="<?php echo $dropbox_unid ?>" />
+				<input type="hidden" name="sec_token" value="<?php echo $token ?>" />
+				<?php
+				if ($origin=='learnpath')
+				{
+					echo '<input type="hidden" name="origin" value="learnpath" />';
+				}
+				?>
+		</div>
+	</div>
+
+	<?php
+	if (dropbox_cnf("allowOverwrite"))
+	{
+		?>
+		<div class="row">
+			<div class="label">
+
+			</div>
+			<div class="formw">
+				<input type="checkbox" name="cb_overwrite" id="cb_overwrite" value="true" /><?php echo dropbox_lang("overwriteFile")?>
+			</div>
 		</div>
-		<?php
-	}
-	?>
-
-	<div class="row">
-		<div class="label">
-			<?php echo dropbox_lang("sendTo")?>
-		</div>
-		<div class="formw">
-	<?php
-
-	//list of all users in this course and all virtual courses combined with it
-	if(isset($_SESSION['id_session'])){
-		$complete_user_list_for_dropbox = array();
-		if(api_get_setting('dropbox_allow_student_to_student')=='true' || $_user['status'] != STUDENT)
-		{
-			$complete_user_list_for_dropbox = CourseManager :: get_user_list_from_course_code($course_info['code'],true,$_SESSION['id_session']);
-		}
-		$complete_user_list2 = CourseManager :: get_coach_list_from_course_code($course_info['code'],$_SESSION['id_session']);
-		$complete_user_list_for_dropbox = array_merge($complete_user_list_for_dropbox,$complete_user_list2);
-	}
-	else{
-		if(api_get_setting('dropbox_allow_student_to_student')=='true' || $_user['status'] != STUDENT)
-		{
-			$complete_user_list_for_dropbox = CourseManager :: get_user_list_from_course_code($course_info['code'],true,$_SESSION['id_session']);
-		}
-		else
-		{
-			$complete_user_list_for_dropbox = CourseManager :: get_teacher_list_from_course_code($course_info['code']);
-		}
-	}
-
+		<?php
+	}
+	?>
+
+	<div class="row">
+		<div class="label">
+			<?php echo dropbox_lang("sendTo")?>
+		</div>
+		<div class="formw">
+	<?php
+
+	//list of all users in this course and all virtual courses combined with it
+	if(isset($_SESSION['id_session'])){
+		$complete_user_list_for_dropbox = array();
+		if(api_get_setting('dropbox_allow_student_to_student')=='true' || $_user['status'] != STUDENT)
+		{
+			$complete_user_list_for_dropbox = CourseManager :: get_user_list_from_course_code($course_info['code'],true,$_SESSION['id_session']);
+		}
+		$complete_user_list2 = CourseManager :: get_coach_list_from_course_code($course_info['code'],$_SESSION['id_session']);
+		$complete_user_list_for_dropbox = array_merge($complete_user_list_for_dropbox,$complete_user_list2);
+	}
+	else{
+		if(api_get_setting('dropbox_allow_student_to_student')=='true' || $_user['status'] != STUDENT)
+		{
+			$complete_user_list_for_dropbox = CourseManager :: get_user_list_from_course_code($course_info['code'],true,$_SESSION['id_session']);
+		}
+		else
+		{
+			$complete_user_list_for_dropbox = CourseManager :: get_teacher_list_from_course_code($course_info['code']);
+		}
+	}
+
 	foreach ($complete_user_list_for_dropbox as $k => $e) {
 	    $complete_user_list_for_dropbox[$k] = $e + array('lastcommafirst' => api_get_person_name($e['firstname'], $e['lastname']));
 	}
-
-	$complete_user_list_for_dropbox = TableSort::sort_table($complete_user_list_for_dropbox, 'lastcommafirst');
-
-	?>
-
-				<select name="recipients[]" size="
-	<?php
-		if ( $dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin)
-		{
-			echo 10;
-		}
-		else
-		{
-			echo 6;
-		}
-
-
-	?>" multiple style="width: 350px;">
-	<?php
-
-	/*
-		Create the options inside the select box:
-		List all selected users their user id as value and a name string as display
-	*/
-	foreach ($complete_user_list_for_dropbox as $current_user)
-	{
-		if ( ($dropbox_person -> isCourseTutor
-		|| $dropbox_person -> isCourseAdmin
-		|| dropbox_cnf("allowStudentToStudent")	// RH: also if option is set
-		|| $current_user['status']!=5				// always allow teachers
-		|| $current_user['tutor_id']==1				// always allow tutors
-		) && $current_user['user_id'] != $_user['user_id'] ) 	// don't include yourself
-		{
-			$full_name = $current_user['lastcommafirst'];
-			echo '<option value="user_' . $current_user['user_id'] . '">' . $full_name . '</option>';
-		}
-	}
-
-	/*
-	* Show groups
-	*/
-    if ( ($dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin)
-    && dropbox_cnf("allowGroup") || dropbox_cnf("allowStudentToStudent"))
-    {
-		$complete_group_list_for_dropbox = GroupManager::get_group_list(null,dropbox_cnf("courseId"));
-
-		if (count($complete_group_list_for_dropbox) > 0)
-		{
-			foreach ($complete_group_list_for_dropbox as $current_group)
-			{
-				if ($current_group['number_of_members'] > 0)
-				{
-					echo '<option value="group_'.$current_group['id'].'">G: '.$current_group['name'].' - '.$current_group['number_of_members'].' '.get_lang('Users').'</option>';
-				}
-			}
-		}
-    }
-
-    if ( ($dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin) && dropbox_cnf("allowMailing"))  // RH: Mailing starting point
-	{
-			// echo '<option value="mailing">'.dropbox_lang("mailingInSelect").'</option>';
-	}
-
-    if ( dropbox_cnf("allowJustUpload"))  // RH
-    {
-	  //echo '<option value="upload">'.dropbox_lang("justUploadInSelect").'</option>';
-	  echo '<option value="user_'.$_user['user_id'].'">'.dropbox_lang("justUploadInSelect").'</option>';
-    }
-
-		echo '</select>
-		</div>
-	</div>';
-
-	echo '
-		<div class="row">
-			<div class="label">
-			</div>
-			<div class="formw">
-				<button type="Submit" class="upload" name="submitWork">'.dropbox_lang("upload", "noDLTT").'</button>
-			</div>
-		</div>
+
+	$complete_user_list_for_dropbox = TableSort::sort_table($complete_user_list_for_dropbox, 'lastcommafirst');
+
+	?>
+
+				<select name="recipients[]" size="
+	<?php
+		if ( $dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin)
+		{
+			echo 10;
+		}
+		else
+		{
+			echo 6;
+		}
+
+
+	?>" multiple style="width: 350px;">
+	<?php
+
+	/*
+		Create the options inside the select box:
+		List all selected users their user id as value and a name string as display
+	*/
+	foreach ($complete_user_list_for_dropbox as $current_user)
+	{
+		if ( ($dropbox_person -> isCourseTutor
+		|| $dropbox_person -> isCourseAdmin
+		|| dropbox_cnf("allowStudentToStudent")	// RH: also if option is set
+		|| $current_user['status']!=5				// always allow teachers
+		|| $current_user['tutor_id']==1				// always allow tutors
+		) && $current_user['user_id'] != $_user['user_id'] ) 	// don't include yourself
+		{
+			$full_name = $current_user['lastcommafirst'];
+			echo '<option value="user_' . $current_user['user_id'] . '">' . $full_name . '</option>';
+		}
+	}
+
+	/*
+	* Show groups
+	*/
+    if ( ($dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin)
+    && dropbox_cnf("allowGroup") || dropbox_cnf("allowStudentToStudent"))
+    {
+		$complete_group_list_for_dropbox = GroupManager::get_group_list(null,dropbox_cnf("courseId"));
+
+		if (count($complete_group_list_for_dropbox) > 0)
+		{
+			foreach ($complete_group_list_for_dropbox as $current_group)
+			{
+				if ($current_group['number_of_members'] > 0)
+				{
+					echo '<option value="group_'.$current_group['id'].'">G: '.$current_group['name'].' - '.$current_group['number_of_members'].' '.get_lang('Users').'</option>';
+				}
+			}
+		}
+    }
+
+    if ( ($dropbox_person -> isCourseTutor || $dropbox_person -> isCourseAdmin) && dropbox_cnf("allowMailing"))  // RH: Mailing starting point
+	{
+			// echo '<option value="mailing">'.dropbox_lang("mailingInSelect").'</option>';
+	}
+
+    if ( dropbox_cnf("allowJustUpload"))  // RH
+    {
+	  //echo '<option value="upload">'.dropbox_lang("justUploadInSelect").'</option>';
+	  echo '<option value="user_'.$_user['user_id'].'">'.dropbox_lang("justUploadInSelect").'</option>';
+    }
+
+		echo '</select>
+		</div>
+	</div>';
+
+	echo '
+		<div class="row">
+			<div class="label">
+			</div>
+			<div class="formw">
+				<button type="Submit" class="upload" name="submitWork">'.dropbox_lang("upload", "noDLTT").'</button>
+			</div>
+		</div>
 	';
 
-	echo "</form>";
-}
-
-/**
-* returns username or false if user isn't registered anymore
-* @todo check if this function is still necessary. There might be a library function for this.
-*/
-function getUserNameFromId ( $id)  // RH: Mailing: return 'Mailing ' + id
-{
-    $mailingId = $id - dropbox_cnf("mailingIdBase");
-    if ( $mailingId > 0)
-    {
-	    return dropbox_lang("mailingAsUsername", "noDLTT") . $mailingId;
-    }
-    $id = intval($id);
+	echo "</form>";
+}
+
+/**
+* returns username or false if user isn't registered anymore
+* @todo check if this function is still necessary. There might be a library function for this.
+*/
+function getUserNameFromId ( $id)  // RH: Mailing: return 'Mailing ' + id
+{
+    $mailingId = $id - dropbox_cnf("mailingIdBase");
+    if ( $mailingId > 0)
+    {
+	    return dropbox_lang("mailingAsUsername", "noDLTT") . $mailingId;
+    }
+    $id = intval($id);
     $sql = "SELECT ".(api_is_western_name_order() ? "CONCAT(firstname,' ', lastname)" : "CONCAT(lastname,' ', firstname)")." AS name
-			FROM " . dropbox_cnf("tbl_user") . "
-			WHERE user_id='$id'";
-    $result = Database::query($sql,__FILE__,__LINE__);
-    $res = Database::fetch_array( $result);
-
-    if ( $res == FALSE) return FALSE;
-    return stripslashes( $res["name"]);
-}
-
-/**
-* returns loginname or false if user isn't registered anymore
-* @todo check if this function is still necessary. There might be a library function for this.
-*/
-function getLoginFromId ( $id)
-{
-    $id = intval($id);
-    $sql = "SELECT username
-			FROM " . dropbox_cnf("tbl_user") . "
-			WHERE user_id='$id'";
-    $result =Database::query($sql,__FILE__,__LINE__);
-    $res = Database::fetch_array( $result);
-    if ( $res == FALSE) return FALSE;
-    return stripslashes( $res["username"]);
-}
-
-/**
-* @return boolean indicating if user with user_id=$user_id is a course member
-* @todo eliminate global
-* @todo check if this function is still necessary. There might be a library function for this.
-*/
-function isCourseMember( $user_id)
-{
-    global $_course;
-	$course_code = $_course['sysCode'];
-	$is_course_member = CourseManager::is_user_subscribed_in_course($user_id, $course_code,true);
-	return $is_course_member;
-}
-
-/**
-* Checks if there are files in the dropbox_file table that aren't used anymore in dropbox_person table.
-* If there are, all entries concerning the file are deleted from the db + the file is deleted from the server
-*/
-function removeUnusedFiles( )
-{
-    // select all files that aren't referenced anymore
-    $sql = "SELECT DISTINCT f.id, f.filename
-			FROM " . dropbox_cnf("tbl_file") . " f
-			LEFT JOIN " . dropbox_cnf("tbl_person") . " p ON f.id = p.file_id
-			WHERE p.user_id IS NULL";
-    $result = Database::query($sql,__FILE__,__LINE__);
-    while ( $res = Database::fetch_array( $result))
-    {
-		//delete the selected files from the post and file tables
-        $sql = "DELETE FROM " . dropbox_cnf("tbl_post") . " WHERE file_id='" . $res['id'] . "'";
-        $result1 = Database::query($sql,__FILE__,__LINE__);
-        $sql = "DELETE FROM " . dropbox_cnf("tbl_file") . " WHERE id='" . $res['id'] . "'";
-        $result1 = Database::query($sql,__FILE__,__LINE__);
-
-		//delete file from server
-        @unlink( dropbox_cnf("sysPath") . "/" . $res["filename"]);
-    }
-}
-
-/**
-* RH: Mailing (2 new functions)
-*
-* Mailing zip-file is posted to (dest_user_id = ) mailing pseudo_id
-* and is only visible to its uploader (user_id).
-*
-* Mailing content files have uploader_id == mailing pseudo_id, a normal recipient,
-* and are visible initially to recipient and pseudo_id.
-*
-* @author René Haentjens, Ghent University
-*
-* @todo check if this function is still necessary.
-*/
-function getUserOwningThisMailing($mailingPseudoId, $owner = 0, $or_die = '')
-{
-    $mailingPseudoId = intval($mailingPseudoId);
-    $sql = "SELECT f.uploader_id
-			FROM " . dropbox_cnf("tbl_file") . " f
-			LEFT JOIN " . dropbox_cnf("tbl_post") . " p ON f.id = p.file_id
-			WHERE p.dest_user_id = '" . $mailingPseudoId . "'";
-    $result = Database::query($sql,__FILE__,__LINE__);
-
-    if (!($res = Database::fetch_array($result)))
-        die(dropbox_lang("generalError")." (code 901)");
-
-    if ($owner == 0) return $res['uploader_id'];
-
-    if ($res['uploader_id'] == $owner) return TRUE;
-
-    die(dropbox_lang("generalError")." (code ".$or_die.")");
-}
-/**
-* @author Ren� Haentjens, Ghent University
-* @todo check if this function is still necessary.
-*/
-function removeMoreIfMailing($file_id)
-{
-    // when deleting a mailing zip-file (posted to mailingPseudoId):
-    // 1. the detail window is no longer reachable, so
-    //    for all content files, delete mailingPseudoId from person-table
-    // 2. finding the owner (getUserOwningThisMailing) is no longer possible, so
-    //    for all content files, replace mailingPseudoId by owner as uploader
-    $file_id = intval($file_id);
-    $sql = "SELECT p.dest_user_id
-			FROM " . dropbox_cnf("tbl_post") . " p
-			WHERE p.file_id = '" . $file_id . "'";
-    $result = Database::query($sql,__FILE__,__LINE__);
-
-    if ( $res = Database::fetch_array( $result))
-    {
-	    $mailingPseudoId = $res['dest_user_id'];
-	    if ( $mailingPseudoId > dropbox_cnf("mailingIdBase"))
-	    {
-	        $sql = "DELETE FROM " . dropbox_cnf("tbl_person") . " WHERE user_id='" . $mailingPseudoId . "'";
-	        $result1 = Database::query($sql,__FILE__,__LINE__);
-
-	        $sql = "UPDATE " . dropbox_cnf("tbl_file") .
-	            " SET uploader_id='" . api_get_user_id() . "' WHERE uploader_id='" . $mailingPseudoId . "'";
-	        $result1 = Database::query($sql,__FILE__,__LINE__);
-        }
-    }
-}
-
-/**
-* The dropbox has a deviant naming scheme for language files so it needs an additional language function
-*
-* @todo check if this function is still necessary.
-*
-* @author René Haentjens, Ghent University
-*/
-function dropbox_lang($variable, $notrans = 'DLTT')
-{
-    global $charset;
-    return (api_get_setting('server_type') == 'test' ?
-        get_lang('dropbox_lang["'.$variable.'"]', $notrans) :
-        api_html_entity_decode(api_to_system_encoding(str_replace("\\'", "'", $GLOBALS['dropbox_lang'][$variable]), null, true), ENT_QUOTES, $charset));
-}
-/**
-* Function that finds a given config setting
-*
+			FROM " . dropbox_cnf("tbl_user") . "
+			WHERE user_id='$id'";
+    $result = Database::query($sql,__FILE__,__LINE__);
+    $res = Database::fetch_array( $result);
+
+    if ( $res == FALSE) return FALSE;
+    return stripslashes( $res["name"]);
+}
+
+/**
+* returns loginname or false if user isn't registered anymore
+* @todo check if this function is still necessary. There might be a library function for this.
+*/
+function getLoginFromId ( $id)
+{
+    $id = intval($id);
+    $sql = "SELECT username
+			FROM " . dropbox_cnf("tbl_user") . "
+			WHERE user_id='$id'";
+    $result =Database::query($sql,__FILE__,__LINE__);
+    $res = Database::fetch_array( $result);
+    if ( $res == FALSE) return FALSE;
+    return stripslashes( $res["username"]);
+}
+
+/**
+* @return boolean indicating if user with user_id=$user_id is a course member
+* @todo eliminate global
+* @todo check if this function is still necessary. There might be a library function for this.
+*/
+function isCourseMember( $user_id)
+{
+    global $_course;
+	$course_code = $_course['sysCode'];
+	$is_course_member = CourseManager::is_user_subscribed_in_course($user_id, $course_code,true);
+	return $is_course_member;
+}
+
+/**
+* Checks if there are files in the dropbox_file table that aren't used anymore in dropbox_person table.
+* If there are, all entries concerning the file are deleted from the db + the file is deleted from the server
+*/
+function removeUnusedFiles( )
+{
+    // select all files that aren't referenced anymore
+    $sql = "SELECT DISTINCT f.id, f.filename
+			FROM " . dropbox_cnf("tbl_file") . " f
+			LEFT JOIN " . dropbox_cnf("tbl_person") . " p ON f.id = p.file_id
+			WHERE p.user_id IS NULL";
+    $result = Database::query($sql,__FILE__,__LINE__);
+    while ( $res = Database::fetch_array( $result))
+    {
+		//delete the selected files from the post and file tables
+        $sql = "DELETE FROM " . dropbox_cnf("tbl_post") . " WHERE file_id='" . $res['id'] . "'";
+        $result1 = Database::query($sql,__FILE__,__LINE__);
+        $sql = "DELETE FROM " . dropbox_cnf("tbl_file") . " WHERE id='" . $res['id'] . "'";
+        $result1 = Database::query($sql,__FILE__,__LINE__);
+
+		//delete file from server
+        @unlink( dropbox_cnf("sysPath") . "/" . $res["filename"]);
+    }
+}
+
+/**
+* RH: Mailing (2 new functions)
+*
+* Mailing zip-file is posted to (dest_user_id = ) mailing pseudo_id
+* and is only visible to its uploader (user_id).
+*
+* Mailing content files have uploader_id == mailing pseudo_id, a normal recipient,
+* and are visible initially to recipient and pseudo_id.
+*
+* @author René Haentjens, Ghent University
+*
+* @todo check if this function is still necessary.
+*/
+function getUserOwningThisMailing($mailingPseudoId, $owner = 0, $or_die = '')
+{
+    $mailingPseudoId = intval($mailingPseudoId);
+    $sql = "SELECT f.uploader_id
+			FROM " . dropbox_cnf("tbl_file") . " f
+			LEFT JOIN " . dropbox_cnf("tbl_post") . " p ON f.id = p.file_id
+			WHERE p.dest_user_id = '" . $mailingPseudoId . "'";
+    $result = Database::query($sql,__FILE__,__LINE__);
+
+    if (!($res = Database::fetch_array($result)))
+        die(dropbox_lang("generalError")." (code 901)");
+
+    if ($owner == 0) return $res['uploader_id'];
+
+    if ($res['uploader_id'] == $owner) return TRUE;
+
+    die(dropbox_lang("generalError")." (code ".$or_die.")");
+}
+/**
+* @author Ren� Haentjens, Ghent University
+* @todo check if this function is still necessary.
+*/
+function removeMoreIfMailing($file_id)
+{
+    // when deleting a mailing zip-file (posted to mailingPseudoId):
+    // 1. the detail window is no longer reachable, so
+    //    for all content files, delete mailingPseudoId from person-table
+    // 2. finding the owner (getUserOwningThisMailing) is no longer possible, so
+    //    for all content files, replace mailingPseudoId by owner as uploader
+    $file_id = intval($file_id);
+    $sql = "SELECT p.dest_user_id
+			FROM " . dropbox_cnf("tbl_post") . " p
+			WHERE p.file_id = '" . $file_id . "'";
+    $result = Database::query($sql,__FILE__,__LINE__);
+
+    if ( $res = Database::fetch_array( $result))
+    {
+	    $mailingPseudoId = $res['dest_user_id'];
+	    if ( $mailingPseudoId > dropbox_cnf("mailingIdBase"))
+	    {
+	        $sql = "DELETE FROM " . dropbox_cnf("tbl_person") . " WHERE user_id='" . $mailingPseudoId . "'";
+	        $result1 = Database::query($sql,__FILE__,__LINE__);
+
+	        $sql = "UPDATE " . dropbox_cnf("tbl_file") .
+	            " SET uploader_id='" . api_get_user_id() . "' WHERE uploader_id='" . $mailingPseudoId . "'";
+	        $result1 = Database::query($sql,__FILE__,__LINE__);
+        }
+    }
+}
+
+/**
+* The dropbox has a deviant naming scheme for language files so it needs an additional language function
+*
+* @todo check if this function is still necessary.
+*
+* @author René Haentjens, Ghent University
+*/
+function dropbox_lang($variable, $notrans = 'DLTT')
+{
+    global $charset;
+    return (api_get_setting('server_type') == 'test' ?
+        get_lang('dropbox_lang["'.$variable.'"]', $notrans) :
+        api_html_entity_decode(api_to_system_encoding(str_replace("\\'", "'", $GLOBALS['dropbox_lang'][$variable]), null, true), ENT_QUOTES, $charset));
+}
+/**
+* Function that finds a given config setting
+*
 * @author René Haentjens, Ghent University
-*/
-function dropbox_cnf($variable)
-{
-    return $GLOBALS['dropbox_cnf'][$variable];
-}
-
-
-
-
-
-/**
-*
-*/
-function store_add_dropbox()
-{
-	global $dropbox_cnf;
-	global $_user;
-	global $_course;
-
-	// ----------------------------------------------------------
-	// Validating the form data
-	// ----------------------------------------------------------
-
-	// the author is
-	/*
-    if (!isset( $_POST['authors']))
-    {
-        return get_lang('AuthorFieldCannotBeEmpty');
-    }
-    */
-
-    // there are no recipients selected
-	if ( !isset( $_POST['recipients']) || count( $_POST['recipients']) <= 0)
-    {
-        return get_lang('YouMustSelectAtLeastOneDestinee');
-    }
-    // Check if all the recipients are valid
-    else
-    {
-        $thisIsAMailing = FALSE;  // RH: Mailing selected as destination
-        $thisIsJustUpload = FALSE;  // RH
-	    foreach( $_POST['recipients'] as $rec)
-        {
-			if ( $rec == 'mailing')
-			{
-				$thisIsAMailing = TRUE;
-			}
-			elseif ( $rec == 'upload')
-			{
-				$thisIsJustUpload = TRUE;
-			}
-			elseif (strpos($rec, 'user_') === 0 && !isCourseMember(substr($rec, strlen('user_') ) ))
-			{
-		        return get_lang('InvalideUserDetected');
-			}
-			elseif (strpos($rec, 'group_') !== 0 && strpos($rec, 'user_') !== 0)
-			{
-				return get_lang('InvalideGroupDetected');
-			}
-        }
-    }
-
-	// we are doing a mailing but an additional recipient is selected
-	if ( $thisIsAMailing && ( count($_POST['recipients']) != 1))
-	{
-		return get_lang('MailingSelectNoOther');
-	}
-
-	// we are doing a just upload but an additional recipient is selected.
-	// note: why can't this be valid? It is like sending a document to yourself AND to a different person (I do this quite often with my e-mails)
-	if ( $thisIsJustUpload && ( count($_POST['recipients']) != 1))
-	{
-		return get_lang('mailingJustUploadSelectNoOther');
-	}
-
-	if ( empty( $_FILES['file']['name']))
-	{
-		$error = TRUE;
-		return  get_lang('NoFileSpecified');
-	}
-
-	// ----------------------------------------------------------
-	// are we overwriting a previous file or sending a new one
-	// ----------------------------------------------------------
-	$dropbox_overwrite = false;
-	if ( isset($_POST['cb_overwrite']) && $_POST['cb_overwrite']==true)
-	{
-		$dropbox_overwrite = true;
-	}
-
-	// ----------------------------------------------------------
-	// doing the upload
-	// ----------------------------------------------------------
-	$dropbox_filename = $_FILES['file']['name'];
-	$dropbox_filesize = $_FILES['file']['size'];
-	$dropbox_filetype = $_FILES['file']['type'];
-	$dropbox_filetmpname = $_FILES['file']['tmp_name'];
-
-	// check if the filesize does not exceed the allowed size.
-	if ( $dropbox_filesize <= 0 || $dropbox_filesize > $dropbox_cnf["maxFilesize"])
-	{
-		return get_lang('DropboxFileTooBig');
-	}
-
-	// check if the file is actually uploaded
-	if ( !is_uploaded_file( $dropbox_filetmpname)) // check user fraud : no clean error msg.
-	{
-		return get_lang('TheFileIsNotUploaded');
-	}
-
-	// Try to add an extension to the file if it hasn't got one
-	$dropbox_filename = add_ext_on_mime( $dropbox_filename,$dropbox_filetype);
-	// Replace dangerous characters
-	$dropbox_filename = replace_dangerous_char( $dropbox_filename);
-	// Transform any .php file in .phps fo security
-	$dropbox_filename = php2phps ( $dropbox_filename);
-	//filter extension
-    if(!filter_extension($dropbox_filename))
-    {
-    	return get_lang('UplUnableToSaveFileFilteredExtension');
-    }
-
-	// set title
-	$dropbox_title = $dropbox_filename;
-	// set author
-	if ( $_POST['authors'] == '')
-	{
-		$_POST['authors'] = getUserNameFromId( $_user['user_id']);
-	}
-
-	// note: I think we could better migrate everything from here on to separate functions: store_new_dropbox, store_new_mailing, store_just_upload
-
-	if ($dropbox_overwrite)  // RH: Mailing: adapted
-	{
-		$dropbox_person = new Dropbox_Person( $_user['user_id'], api_is_course_admin(), api_is_course_tutor());
-
-		foreach($dropbox_person->sentWork as $w)
-		{
-			if ($w->title == $dropbox_filename)
-			{
-			    if ( ($w->recipients[0]['id'] > dropbox_cnf("mailingIdBase")) xor $thisIsAMailing)
-			    {
-					return get_lang('MailingNonMailingError');
-				}
-				if ( ($w->recipients[0]['id'] == $_user['user_id']) xor $thisIsJustUpload)
-				{
-					return get_lang('MailingJustUploadSelectNoOther');
-				}
-				$dropbox_filename = $w->filename;
-				$found = true; // note: do we still need this?
-				break;
-			}
-		}
-	}
-	else  // rename file to login_filename_uniqueId format
-	{
-		$dropbox_filename = getLoginFromId( $_user['user_id']) . "_" . $dropbox_filename . "_".uniqid('');
-	}
-
-	// creating the array that contains all the users who will receive the file
-	$new_work_recipients = array();
-	foreach ($_POST["recipients"] as $rec)
-	{
-		if (strpos($rec, 'user_') === 0)
-		{
-			$new_work_recipients[] = substr($rec, strlen('user_') );
-		}
-		elseif (strpos($rec, 'group_') === 0 )
-		{
-			$userList = GroupManager::get_subscribed_users(substr($rec, strlen('group_') ));
-			foreach ($userList as $usr)
-			{
-				if (! in_array($usr['user_id'], $new_work_recipients) && $usr['user_id'] != $_user['user_id'])
-				{
-					$new_work_recipients[] = $usr['user_id'];
-				}
-			}
-		}
-	}
-
-	@move_uploaded_file( $dropbox_filetmpname, dropbox_cnf("sysPath") . '/' . $dropbox_filename);
-
-	$b_send_mail = api_get_course_setting('email_alert_on_new_doc_dropbox');
-
-	if($b_send_mail)
-	{
-		foreach($new_work_recipients as $recipient_id)
-		{
-			include_once(api_get_path(LIBRARY_PATH) . 'usermanager.lib.php');
-			$recipent_temp=UserManager :: get_user_info_by_id($recipient_id);
+*/
+function dropbox_cnf($variable)
+{
+    return $GLOBALS['dropbox_cnf'][$variable];
+}
+
+
+
+
+
+/**
+*
+*/
+function store_add_dropbox()
+{
+	global $dropbox_cnf;
+	global $_user;
+	global $_course;
+
+	// ----------------------------------------------------------
+	// Validating the form data
+	// ----------------------------------------------------------
+
+	// the author is
+	/*
+    if (!isset( $_POST['authors']))
+    {
+        return get_lang('AuthorFieldCannotBeEmpty');
+    }
+    */
+
+    // there are no recipients selected
+	if ( !isset( $_POST['recipients']) || count( $_POST['recipients']) <= 0)
+    {
+        return get_lang('YouMustSelectAtLeastOneDestinee');
+    }
+    // Check if all the recipients are valid
+    else
+    {
+        $thisIsAMailing = FALSE;  // RH: Mailing selected as destination
+        $thisIsJustUpload = FALSE;  // RH
+	    foreach( $_POST['recipients'] as $rec)
+        {
+			if ( $rec == 'mailing')
+			{
+				$thisIsAMailing = TRUE;
+			}
+			elseif ( $rec == 'upload')
+			{
+				$thisIsJustUpload = TRUE;
+			}
+			elseif (strpos($rec, 'user_') === 0 && !isCourseMember(substr($rec, strlen('user_') ) ))
+			{
+		        return get_lang('InvalideUserDetected');
+			}
+			elseif (strpos($rec, 'group_') !== 0 && strpos($rec, 'user_') !== 0)
+			{
+				return get_lang('InvalideGroupDetected');
+			}
+        }
+    }
+
+	// we are doing a mailing but an additional recipient is selected
+	if ( $thisIsAMailing && ( count($_POST['recipients']) != 1))
+	{
+		return get_lang('MailingSelectNoOther');
+	}
+
+	// we are doing a just upload but an additional recipient is selected.
+	// note: why can't this be valid? It is like sending a document to yourself AND to a different person (I do this quite often with my e-mails)
+	if ( $thisIsJustUpload && ( count($_POST['recipients']) != 1))
+	{
+		return get_lang('mailingJustUploadSelectNoOther');
+	}
+
+	if ( empty( $_FILES['file']['name']))
+	{
+		$error = TRUE;
+		return  get_lang('NoFileSpecified');
+	}
+
+	// ----------------------------------------------------------
+	// are we overwriting a previous file or sending a new one
+	// ----------------------------------------------------------
+	$dropbox_overwrite = false;
+	if ( isset($_POST['cb_overwrite']) && $_POST['cb_overwrite']==true)
+	{
+		$dropbox_overwrite = true;
+	}
+
+	// ----------------------------------------------------------
+	// doing the upload
+	// ----------------------------------------------------------
+	$dropbox_filename = $_FILES['file']['name'];
+	$dropbox_filesize = $_FILES['file']['size'];
+	$dropbox_filetype = $_FILES['file']['type'];
+	$dropbox_filetmpname = $_FILES['file']['tmp_name'];
+
+	// check if the filesize does not exceed the allowed size.
+	if ( $dropbox_filesize <= 0 || $dropbox_filesize > $dropbox_cnf["maxFilesize"])
+	{
+		return get_lang('DropboxFileTooBig');
+	}
+
+	// check if the file is actually uploaded
+	if ( !is_uploaded_file( $dropbox_filetmpname)) // check user fraud : no clean error msg.
+	{
+		return get_lang('TheFileIsNotUploaded');
+	}
+
+	// Try to add an extension to the file if it hasn't got one
+	$dropbox_filename = add_ext_on_mime( $dropbox_filename,$dropbox_filetype);
+	// Replace dangerous characters
+	$dropbox_filename = replace_dangerous_char( $dropbox_filename);
+	// Transform any .php file in .phps fo security
+	$dropbox_filename = php2phps ( $dropbox_filename);
+	//filter extension
+    if(!filter_extension($dropbox_filename))
+    {
+    	return get_lang('UplUnableToSaveFileFilteredExtension');
+    }
+
+	// set title
+	$dropbox_title = $dropbox_filename;
+	// set author
+	if ( $_POST['authors'] == '')
+	{
+		$_POST['authors'] = getUserNameFromId( $_user['user_id']);
+	}
+
+	// note: I think we could better migrate everything from here on to separate functions: store_new_dropbox, store_new_mailing, store_just_upload
+
+	if ($dropbox_overwrite)  // RH: Mailing: adapted
+	{
+		$dropbox_person = new Dropbox_Person( $_user['user_id'], api_is_course_admin(), api_is_course_tutor());
+
+		foreach($dropbox_person->sentWork as $w)
+		{
+			if ($w->title == $dropbox_filename)
+			{
+			    if ( ($w->recipients[0]['id'] > dropbox_cnf("mailingIdBase")) xor $thisIsAMailing)
+			    {
+					return get_lang('MailingNonMailingError');
+				}
+				if ( ($w->recipients[0]['id'] == $_user['user_id']) xor $thisIsJustUpload)
+				{
+					return get_lang('MailingJustUploadSelectNoOther');
+				}
+				$dropbox_filename = $w->filename;
+				$found = true; // note: do we still need this?
+				break;
+			}
+		}
+	}
+	else  // rename file to login_filename_uniqueId format
+	{
+		$dropbox_filename = getLoginFromId( $_user['user_id']) . "_" . $dropbox_filename . "_".uniqid('');
+	}
+
+	// creating the array that contains all the users who will receive the file
+	$new_work_recipients = array();
+	foreach ($_POST["recipients"] as $rec)
+	{
+		if (strpos($rec, 'user_') === 0)
+		{
+			$new_work_recipients[] = substr($rec, strlen('user_') );
+		}
+		elseif (strpos($rec, 'group_') === 0 )
+		{
+			$userList = GroupManager::get_subscribed_users(substr($rec, strlen('group_') ));
+			foreach ($userList as $usr)
+			{
+				if (! in_array($usr['user_id'], $new_work_recipients) && $usr['user_id'] != $_user['user_id'])
+				{
+					$new_work_recipients[] = $usr['user_id'];
+				}
+			}
+		}
+	}
+
+	@move_uploaded_file( $dropbox_filetmpname, dropbox_cnf("sysPath") . '/' . $dropbox_filename);
+
+	$b_send_mail = api_get_course_setting('email_alert_on_new_doc_dropbox');
+
+	if($b_send_mail)
+	{
+		foreach($new_work_recipients as $recipient_id)
+		{
+			include_once(api_get_path(LIBRARY_PATH) . 'usermanager.lib.php');
+			$recipent_temp=UserManager :: get_user_info_by_id($recipient_id);
 			api_mail(api_get_person_name($recipent_temp['firstname'].' '.$recipent_temp['lastname'], null, PERSON_NAME_EMAIL_ADDRESS), $recipent_temp['email'],
-				get_lang('NewDropboxFileUploaded'),
+				get_lang('NewDropboxFileUploaded'),
 				get_lang('NewDropboxFileUploadedContent').' '.api_get_path(WEB_CODE_PATH).'dropbox/index.php?cidReq='.$_course['sysCode']."\n\n".api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS)."\n".  get_lang('Email') ." : ".$_user['mail'], api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS), $_user['mail']);
-				//get_lang('NewDropboxFileUploadedContent').' '.api_get_path(WEB_CODE_PATH).'dropbox/index.php?cidReq='.$_course['sysCode']."\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS)."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator'), api_get_person_name(api_get_setting('administratorName')." ".api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS), api_get_setting('emailAdministrator'));
-		}
-	}
-
-	new Dropbox_SentWork( $_user['user_id'], $dropbox_title, $_POST['description'], strip_tags($_POST['authors']), $dropbox_filename, $dropbox_filesize, $new_work_recipients);
-
-	Security::clear_token();
-    return get_lang('FileUploadSucces');
-}
-
-
-
-/**
-* This function displays the firstname and lastname of the user as a link to the user tool.
-*
-* @see this is the same function as in the new forum, so this probably has to move to a user library.
-*
-* @todo move this function to the user library
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function display_user_link($user_id, $name='')
-{
-	global $_otherusers;
-
-	if ($user_id<>0)
-	{
-		if ($name=='')
-		{
-			$table_user = Database::get_main_table(TABLE_MAIN_USER);
-			$sql="SELECT * FROM $table_user WHERE user_id='".Database::escape_string($user_id)."'";
-			$result=Database::query($sql,__FILE__,__LINE__);
-			$row=Database::fetch_array($result);
+				//get_lang('NewDropboxFileUploadedContent').' '.api_get_path(WEB_CODE_PATH).'dropbox/index.php?cidReq='.$_course['sysCode']."\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS)."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator'), api_get_person_name(api_get_setting('administratorName')." ".api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS), api_get_setting('emailAdministrator'));
+		}
+	}
+
+	new Dropbox_SentWork( $_user['user_id'], $dropbox_title, $_POST['description'], strip_tags($_POST['authors']), $dropbox_filename, $dropbox_filesize, $new_work_recipients);
+
+	Security::clear_token();
+    return get_lang('FileUploadSucces');
+}
+
+
+
+/**
+* This function displays the firstname and lastname of the user as a link to the user tool.
+*
+* @see this is the same function as in the new forum, so this probably has to move to a user library.
+*
+* @todo move this function to the user library
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function display_user_link($user_id, $name='')
+{
+	global $_otherusers;
+
+	if ($user_id<>0)
+	{
+		if ($name=='')
+		{
+			$table_user = Database::get_main_table(TABLE_MAIN_USER);
+			$sql="SELECT * FROM $table_user WHERE user_id='".Database::escape_string($user_id)."'";
+			$result=Database::query($sql,__FILE__,__LINE__);
+			$row=Database::fetch_array($result);
 			return "<a href=\"../user/userInfo.php?uInfo=".$row['user_id']."\">".api_get_person_name($row['firstname'], $row['lastname'])."</a>";
-		}
-		else
-		{
-            $user_id = intval($user_id);
-			return "<a href=\"../user/userInfo.php?uInfo=".$user_id."\">".Security::remove_XSS($name)."</a>";
-		}
-	}
-	else
-	{
-		return $name.' ('.get_lang('Anonymous').')';
-	}
-}
-
-/**
-* this function transforms the array containing all the feedback into something visually attractive.
-*
-* @param an array containing all the feedback about the given message.
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function feedback($array)
-{
-
-	foreach ($array as $key=>$value)
-	{
-		$output.=format_feedback($value);
-	}
-	$output.=feedback_form();
-	return $output;
-}
-
-/**
-* This function returns the html code to display the feedback messages on a given dropbox file
-* @param $feedback_array an array that contains all the feedback messages about the given document.
-* @return html code
-* @todo add the form for adding new comment (if the other party has not deleted it yet).
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function format_feedback($feedback)
-{
-	$output.=display_user_link($feedback['author_user_id']);
-	$output.='&nbsp;&nbsp;['.$feedback['feedback_date'].']<br />';
-	$output.='<div style="padding-top:6px">'.nl2br($feedback['feedback']).'</div><hr size="1" noshade/><br />';
-	return $output;
-}
-
-/**
-* this function returns the code for the form for adding a new feedback message to a dropbox file.
-* @return html code
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function feedback_form()
-{
-	global $dropbox_cnf;
-
-	$return = get_lang('AddNewFeedback').'<br />';
-
-	// we now check if the other users have not delete this document yet. If this is the case then it is useless to see the
-	// add feedback since the other users will never get to see the feedback.
-	$sql="SELECT * FROM ".$dropbox_cnf["tbl_person"]." WHERE file_id='".Database::escape_string($_GET['id'])."'";
-	$result=Database::query($sql,__LINE__, __FILE__);
-	$number_users_who_see_file=Database::num_rows($result);
-	if ($number_users_who_see_file>1)
-	{
+		}
+		else
+		{
+            $user_id = intval($user_id);
+			return "<a href=\"../user/userInfo.php?uInfo=".$user_id."\">".Security::remove_XSS($name)."</a>";
+		}
+	}
+	else
+	{
+		return $name.' ('.get_lang('Anonymous').')';
+	}
+}
+
+/**
+* this function transforms the array containing all the feedback into something visually attractive.
+*
+* @param an array containing all the feedback about the given message.
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function feedback($array)
+{
+
+	foreach ($array as $key=>$value)
+	{
+		$output.=format_feedback($value);
+	}
+	$output.=feedback_form();
+	return $output;
+}
+
+/**
+* This function returns the html code to display the feedback messages on a given dropbox file
+* @param $feedback_array an array that contains all the feedback messages about the given document.
+* @return html code
+* @todo add the form for adding new comment (if the other party has not deleted it yet).
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function format_feedback($feedback)
+{
+	$output.=display_user_link($feedback['author_user_id']);
+	$output.='&nbsp;&nbsp;['.$feedback['feedback_date'].']<br />';
+	$output.='<div style="padding-top:6px">'.nl2br($feedback['feedback']).'</div><hr size="1" noshade/><br />';
+	return $output;
+}
+
+/**
+* this function returns the code for the form for adding a new feedback message to a dropbox file.
+* @return html code
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function feedback_form()
+{
+	global $dropbox_cnf;
+
+	$return = get_lang('AddNewFeedback').'<br />';
+
+	// we now check if the other users have not delete this document yet. If this is the case then it is useless to see the
+	// add feedback since the other users will never get to see the feedback.
+	$sql="SELECT * FROM ".$dropbox_cnf["tbl_person"]." WHERE file_id='".Database::escape_string($_GET['id'])."'";
+	$result=Database::query($sql,__LINE__, __FILE__);
+	$number_users_who_see_file=Database::num_rows($result);
+	if ($number_users_who_see_file>1)
+	{
 		$return .= '<textarea name="feedback" style="width: 80%; height: 80px;"></textarea><br /><button type="submit" class="add" name="store_feedback" value="'.get_lang('Ok').'"
-			onclick="document.form_tablename.attributes.action.value = document.location;">'.get_lang('AddComment').'</button>';
-	}
-	else
-	{
-		$return .= get_lang('AllUsersHaveDeletedTheFileAndWillNotSeeFeedback');
-	}
-	return $return;
-}
-
-/**
-* @return a language string (depending on the success or failure.
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function store_feedback()
-{
-	global $dropbox_cnf;
-	global $_user;
-
-	if (!is_numeric($_GET['id']))
-	{
-		return get_lang('FeedbackError');
-	}
-
-	if ($_POST['feedback']=='')
-	{
-		return get_lang('PleaseTypeText');
-	}
-	else
-	{
-		$sql="INSERT INTO ".$dropbox_cnf['tbl_feedback']." (file_id, author_user_id, feedback, feedback_date) VALUES
-				('".Database::escape_string($_GET['id'])."','".Database::escape_string($_user['user_id'])."','".Database::escape_string($_POST['feedback'])."',NOW())";
-		Database::query($sql,__FILE__,__LINE__);
-		return get_lang('DropboxFeedbackStored');
-	}
-}
-
-/**
-* This function downloads all the files of the inputarray into one zip
-* @param $array an array containing all the ids of the files that have to be downloaded.
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @todo consider removing the check if the user has received or sent this file (zip download of a folder already sufficiently checks for this).
-* @todo integrate some cleanup function that removes zip files that are older than 2 days
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function zip_download ($array)
-{
-	global $_course;
-	global $dropbox_cnf;
-	global $_user;
-	global $files;
-
-	$sys_course_path = api_get_path(SYS_COURSE_PATH);
-
-	// zip library for creation of the zipfile
-	include(api_get_path(LIBRARY_PATH)."/pclzip/pclzip.lib.php");
-
-	// place to temporarily stash the zipfiles
-	$temp_zip_dir = api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/";
-
-	// create the directory if it does not exist yet.
-	if(!is_dir($temp_zip_dir))
-	{
-		mkdir($temp_zip_dir);
-	}
-
-	cleanup_temp_dropbox();
-
-	$files='';
-
-	// note: we also have to add the check if the user has received or sent this file. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-	$sql="SELECT distinct file.filename, file.title, file.author, file.description
-			FROM ".$dropbox_cnf["tbl_file"]." file, ".$dropbox_cnf["tbl_person"]." person
-			WHERE file.id IN (".implode(', ',$array).")
-			AND file.id=person.file_id
-			AND person.user_id='".$_user['user_id']."'";
-	$result=Database::query($sql,__FILE__,__LINE__);
-	while ($row=Database::fetch_array($result))
-	{
-		$files[$row['filename']]=array('filename'=>$row['filename'],'title'=>$row['title'], 'author'=>$row['author'], 'description'=>$row['description']);
-	}
-
-	//$alternative is a variable that uses an alternative method to create the zip
-	// because the renaming of the files inside the zip causes error on php5 (unexpected end of archive)
-	$alternative=true;
-	if ($alternative)
-	{
-		zip_download_alternative($files);
-		exit;
-	}
-
-	// create the zip file
-    $name = 'dropboxdownload-'.$_user['user_id'].'-'.mktime().'.zip';
-	$temp_zip_file=$temp_zip_dir.'/'.$name;
-	$zip_folder=new PclZip($temp_zip_file);
-
-	foreach ($files as $key=>$value)
-	{
-		// met hernoemen van de files in de zip
-		$zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox/".$value['filename'],PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox", PCLZIP_CB_PRE_ADD, 'my_pre_add_callback');
-		// zonder hernoemen van de files in de zip
-		//$zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox/".$value['filename'],PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox");
-	}
-
-	// create the overview file
-	$overview_file_content=generate_html_overview($files, array('filename'), array('title'));
-	$overview_file=$temp_zip_dir.'/overview.html';
-	$handle=fopen($overview_file,'w');
-	fwrite($handle,$overview_file_content);
-
-
-	// send the zip file
-	DocumentManager::file_send_for_download($temp_zip_file,true,$name);
-	exit;
-}
-/**
-* This is a callback function to decrypt the files in the zip file to their normal filename (as stored in the database)
-* @param $p_event a variable of PCLZip
-* @param $p_header a variable of PCLZip
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function my_pre_add_callback($p_event, &$p_header)
-{
-	global $files;
-
-	$p_header['stored_filename']=$files[$p_header['stored_filename']]['title'];
-	return 1;
-}
-
-/**
-* This function is an alternative zip download. It was added because PCLZip causes problems on PHP5 when using PCLZIP_CB_PRE_ADD and a callback function to rename
-* the files inside the zip file (dropbox scrambles the files to prevent
-* @todo consider using a htaccess that denies direct access to the file but only allows the php file to access it. This would remove the scrambling requirement
-*		but it would require additional checks to see if the filename of the uploaded file is not used yet.
-* @param $files is an associative array that contains the files that the user wants to download (check to see if the user is allowed to download these files already
-*		 happened so the array is clean!!. The key is the filename on the filesystem. The value is an array that contains both the filename on the filesystem and
-*		 the original filename (that will be used in the zip file)
-* @todo when we copy the files there might be two files with the same name. We need a function that (recursively) checks this and changes the name
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function zip_download_alternative($files)
-{
-	global $_course;
-	global $_user;
-
-	$temp_zip_dir = api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/";
-
-	// Step 2: we copy all the original dropbox files to the temp folder and change their name into the original name
-	foreach ($files as $key=>$value)
-	{
-		$value['title']=check_file_name(api_strtolower($value['title']));
-		$files[$value['filename']]['title']=$value['title'];
-		copy(api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox/".$value['filename'], api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$value['title']);
-	}
-
-	// Step 3: create the zip file and add all the files to it
-	$temp_zip_file=$temp_zip_dir.'/dropboxdownload-'.$_user['user_id'].'-'.mktime().'.zip';
-	$zip_folder=new PclZip($temp_zip_file);
-	foreach ($files as $key=>$value)
-	{
-		$zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$value['title'],PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/temp");
-	}
-
-	// Step 1: create the overview file and add it to the zip
-	$overview_file_content=generate_html_overview($files, array('filename'), array('title'));
+			onclick="document.form_tablename.attributes.action.value = document.location;">'.get_lang('AddComment').'</button>';
+	}
+	else
+	{
+		$return .= get_lang('AllUsersHaveDeletedTheFileAndWillNotSeeFeedback');
+	}
+	return $return;
+}
+
+/**
+* @return a language string (depending on the success or failure.
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function store_feedback()
+{
+	global $dropbox_cnf;
+	global $_user;
+
+	if (!is_numeric($_GET['id']))
+	{
+		return get_lang('FeedbackError');
+	}
+
+	if ($_POST['feedback']=='')
+	{
+		return get_lang('PleaseTypeText');
+	}
+	else
+	{
+		$sql="INSERT INTO ".$dropbox_cnf['tbl_feedback']." (file_id, author_user_id, feedback, feedback_date) VALUES
+				('".Database::escape_string($_GET['id'])."','".Database::escape_string($_user['user_id'])."','".Database::escape_string($_POST['feedback'])."',NOW())";
+		Database::query($sql,__FILE__,__LINE__);
+		return get_lang('DropboxFeedbackStored');
+	}
+}
+
+/**
+* This function downloads all the files of the inputarray into one zip
+* @param $array an array containing all the ids of the files that have to be downloaded.
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @todo consider removing the check if the user has received or sent this file (zip download of a folder already sufficiently checks for this).
+* @todo integrate some cleanup function that removes zip files that are older than 2 days
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function zip_download ($array)
+{
+	global $_course;
+	global $dropbox_cnf;
+	global $_user;
+	global $files;
+
+	$sys_course_path = api_get_path(SYS_COURSE_PATH);
+
+	// zip library for creation of the zipfile
+	include(api_get_path(LIBRARY_PATH)."/pclzip/pclzip.lib.php");
+
+	// place to temporarily stash the zipfiles
+	$temp_zip_dir = api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/";
+
+	// create the directory if it does not exist yet.
+	if(!is_dir($temp_zip_dir))
+	{
+		mkdir($temp_zip_dir);
+	}
+
+	cleanup_temp_dropbox();
+
+	$files='';
+
+	// note: we also have to add the check if the user has received or sent this file. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+	$sql="SELECT distinct file.filename, file.title, file.author, file.description
+			FROM ".$dropbox_cnf["tbl_file"]." file, ".$dropbox_cnf["tbl_person"]." person
+			WHERE file.id IN (".implode(', ',$array).")
+			AND file.id=person.file_id
+			AND person.user_id='".$_user['user_id']."'";
+	$result=Database::query($sql,__FILE__,__LINE__);
+	while ($row=Database::fetch_array($result))
+	{
+		$files[$row['filename']]=array('filename'=>$row['filename'],'title'=>$row['title'], 'author'=>$row['author'], 'description'=>$row['description']);
+	}
+
+	//$alternative is a variable that uses an alternative method to create the zip
+	// because the renaming of the files inside the zip causes error on php5 (unexpected end of archive)
+	$alternative=true;
+	if ($alternative)
+	{
+		zip_download_alternative($files);
+		exit;
+	}
+
+	// create the zip file
+    $name = 'dropboxdownload-'.$_user['user_id'].'-'.mktime().'.zip';
+	$temp_zip_file=$temp_zip_dir.'/'.$name;
+	$zip_folder=new PclZip($temp_zip_file);
+
+	foreach ($files as $key=>$value)
+	{
+		// met hernoemen van de files in de zip
+		$zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox/".$value['filename'],PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox", PCLZIP_CB_PRE_ADD, 'my_pre_add_callback');
+		// zonder hernoemen van de files in de zip
+		//$zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox/".$value['filename'],PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox");
+	}
+
+	// create the overview file
+	$overview_file_content=generate_html_overview($files, array('filename'), array('title'));
+	$overview_file=$temp_zip_dir.'/overview.html';
+	$handle=fopen($overview_file,'w');
+	fwrite($handle,$overview_file_content);
+
+
+	// send the zip file
+	DocumentManager::file_send_for_download($temp_zip_file,true,$name);
+	exit;
+}
+/**
+* This is a callback function to decrypt the files in the zip file to their normal filename (as stored in the database)
+* @param $p_event a variable of PCLZip
+* @param $p_header a variable of PCLZip
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function my_pre_add_callback($p_event, &$p_header)
+{
+	global $files;
+
+	$p_header['stored_filename']=$files[$p_header['stored_filename']]['title'];
+	return 1;
+}
+
+/**
+* This function is an alternative zip download. It was added because PCLZip causes problems on PHP5 when using PCLZIP_CB_PRE_ADD and a callback function to rename
+* the files inside the zip file (dropbox scrambles the files to prevent
+* @todo consider using a htaccess that denies direct access to the file but only allows the php file to access it. This would remove the scrambling requirement
+*		but it would require additional checks to see if the filename of the uploaded file is not used yet.
+* @param $files is an associative array that contains the files that the user wants to download (check to see if the user is allowed to download these files already
+*		 happened so the array is clean!!. The key is the filename on the filesystem. The value is an array that contains both the filename on the filesystem and
+*		 the original filename (that will be used in the zip file)
+* @todo when we copy the files there might be two files with the same name. We need a function that (recursively) checks this and changes the name
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function zip_download_alternative($files)
+{
+	global $_course;
+	global $_user;
+
+	$temp_zip_dir = api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/";
+
+	// Step 2: we copy all the original dropbox files to the temp folder and change their name into the original name
+	foreach ($files as $key=>$value)
+	{
+		$value['title']=check_file_name(api_strtolower($value['title']));
+		$files[$value['filename']]['title']=$value['title'];
+		copy(api_get_path(SYS_COURSE_PATH).$_course['path']."/dropbox/".$value['filename'], api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$value['title']);
+	}
+
+	// Step 3: create the zip file and add all the files to it
+	$temp_zip_file=$temp_zip_dir.'/dropboxdownload-'.$_user['user_id'].'-'.mktime().'.zip';
+	$zip_folder=new PclZip($temp_zip_file);
+	foreach ($files as $key=>$value)
+	{
+		$zip_folder->add(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$value['title'],PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/temp");
+	}
+
+	// Step 1: create the overview file and add it to the zip
+	$overview_file_content=generate_html_overview($files, array('filename'), array('title'));
 	$overview_file=$temp_zip_dir.'overview'.replace_dangerous_char(api_is_western_name_order() ? $_user['firstname'].$_user['lastname'] : $_user['lastname'].$_user['firstname'], 'strict').'.html';
-	$handle=fopen($overview_file,'w');
-	fwrite($handle,$overview_file_content);
-	// todo: find a different solution for this because even 2 seconds is no guarantee.
+	$handle=fopen($overview_file,'w');
+	fwrite($handle,$overview_file_content);
+	// todo: find a different solution for this because even 2 seconds is no guarantee.
 	sleep(2);
-
-	// Step 4: we add the overview file
-	$zip_folder->add($overview_file,PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/temp");
-
-	// Step 5: send the file for download;
-	DocumentManager::file_send_for_download($temp_zip_file,true);
-
-	// Step 6: remove the files in the temp dir
-	foreach ($files as $key=>$value)
-	{
-		unlink(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$value['title']);
-	}
-	//unlink($overview_file);
-
-	exit;
-}
-
-/**
-* @desc This function checks if the real filename of the dropbox files doesn't already exist in the temp folder. If this is the case then
-*		it will generate a different filename;
-*
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function check_file_name($file_name_2_check, $counter=0)
-{
-	global $_course;
-
-	$new_file_name=$file_name_2_check;
-	if ($counter<>0)
-	{
-		$new_file_name=$counter.$new_file_name;
-	}
-
-	if (!file_exists(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$new_file_name))
-	{
-		return $new_file_name;
-	}
-	else
-	{
-		$counter++;
-		$new_file_name=check_file_name($file_name_2_check,$counter);
-		return $new_file_name;
-	}
-}
-
-
-/**
-* @desc Cleans the temp zip files that were created when users download several files or a whole folder at once.
-*		T
-* @return true
-* @todo
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-
-function cleanup_temp_dropbox()
-{
-	global $_course;
-
-	$handle=opendir(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp");
-	while (false !== ($file = readdir($handle)))
-	{
-		if ($file<>'.' OR $file<>'..')
-		{
-			$name=str_replace('.zip', '',$file);
-			$name_part=explode('-',$name);
-			$timestamp_of_file=$name_part[count($name_part)-1];
-			// if it is a dropboxdownloadfile and the file is older than one day then we delete it
-			if (strstr($file, 'dropboxdownload') AND $timestamp_of_file<(mktime()-86400))
-			{
-				unlink(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$file);
-			}
-		}
-
-	}
-	closedir($handle);
-	return true;
-}
-
-/**
-* @desc generates the contents of a html file that gives an overview of all the files in the zip file.
-*		This is to know the information of the files that are inside the zip file (who send it, the comment, ...)
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function generate_html_overview($files, $dont_show_columns=array(), $make_link=array())
-{
-	$return="<html>\n<head>\n\t<title>".get_lang('OverviewOfFilesInThisZip')."</title>\n</head>";
-	$return.="\n\n<body>\n<table border=\"1px\">";
-
-	$counter=0;
-	foreach ($files as $key=>$value)
-	{
-		// We add the header
-		if ($counter==0)
-		{
-			$columns_array=array_keys($value);
-			$return.="\n<tr>";
-			foreach ($columns_array AS $columns_array_key=>$columns_array_value)
-			{
-				if (!in_array($columns_array_value,$dont_show_columns))
-				{
-					$return.="\n\t<th>".$columns_array_value."</th>";
-				}
-				$column[]=$columns_array_value;
-			}
-			$return.="</tr><n";
-		}
-		$counter++;
-
-		// We add the content
-		$return.="\n<tr>";
-		foreach ($column AS $column_key=>$column_value)
-		{
-			if (!in_array($column_value,$dont_show_columns))
-			{
-				$return.="\n\t<td>";
-				if (in_array($column_value, $make_link))
-				{
-					$return.='<a href="'.$value[$column_value].'">'.$value[$column_value].'</a>';
-				}
-				else
-				{
-					$return.=$value[$column_value];
-				}
-				$return.="</td>";
-			}
-		}
-		$return.="</tr><n";
-
-
-	}
-	$return.="\n</table>\n\n</body>";
-	$return.="\n</html>";
-
-	return $return;
-}
-
-/**
-* @desc This function retrieves the number of feedback messages on every document. This function might become obsolete when
-* 		the feedback becomes user individual.
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function get_total_number_feedback($file_id='')
-{
-	global $dropbox_cnf;
-
-	$sql="SELECT COUNT(feedback_id) AS total, file_id FROM ".$dropbox_cnf['tbl_feedback']." GROUP BY file_id";
-	$result=Database::query($sql, __FILE__, __LINE__);
-	while ($row=Database::fetch_array($result))
-	{
-		$return[$row['file_id']]=$row['total'];
-	}
-	return $return;
-}
-
-
-/**
-* @desc this function checks if the key exists. If this is the case it returns the value, if not it returns 0
-* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-* @version march 2006
-*/
-function check_number_feedback($key, $array)
-{
-	if (is_array($array))
-	{
-		if (key_exists($key,$array))
-		{
-			return $array[$key];
-		}
-		else
-		{
-			return 0;
-		}
-	}
-	else
-	{
-		return 0;
-	}
-}
-
-
-
-
-
-
-/**
- * Get the last access to a given tool of a given user
- * @param $tool string the tool constant
- * @param $course_code the course_id
- * @param $user_id the id of the user
- * @return string last tool access date
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
- * @version march 2006
- *
- * @todo consider moving this function to a more appropriate place.
- */
-function get_last_tool_access($tool, $course_code='', $user_id='')
-{
-	global $_course, $_user;
-
-	// The default values of the parameters
-	if ($course_code=='')
-	{
-		$course_code=$_course['id'];
-	}
-	if ($user_id=='')
-	{
-		$user_id=$_user['user_id'];
-	}
-
-	// the table where the last tool access is stored (=track_e_lastaccess)
-	$table_last_access=Database::get_statistic_table('track_e_lastaccess');
-
-	$sql="SELECT access_date FROM $table_last_access WHERE access_user_id='".Database::escape_string($user_id)."'
-				AND access_cours_code='".Database::escape_string($course_code)."'
-				AND access_tool='".Database::escape_string($tool)."'
-				ORDER BY access_date DESC
-				LIMIT 1";
-	$result=Database::query($sql,__FILE__,__LINE__);
-	$row=Database::fetch_array($result);
-	return $row['access_date'];
+
+	// Step 4: we add the overview file
+	$zip_folder->add($overview_file,PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_COURSE_PATH).$_course['path']."/temp");
+
+	// Step 5: send the file for download;
+	DocumentManager::file_send_for_download($temp_zip_file,true);
+
+	// Step 6: remove the files in the temp dir
+	foreach ($files as $key=>$value)
+	{
+		unlink(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$value['title']);
+	}
+	//unlink($overview_file);
+
+	exit;
+}
+
+/**
+* @desc This function checks if the real filename of the dropbox files doesn't already exist in the temp folder. If this is the case then
+*		it will generate a different filename;
+*
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function check_file_name($file_name_2_check, $counter=0)
+{
+	global $_course;
+
+	$new_file_name=$file_name_2_check;
+	if ($counter<>0)
+	{
+		$new_file_name=$counter.$new_file_name;
+	}
+
+	if (!file_exists(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$new_file_name))
+	{
+		return $new_file_name;
+	}
+	else
+	{
+		$counter++;
+		$new_file_name=check_file_name($file_name_2_check,$counter);
+		return $new_file_name;
+	}
+}
+
+
+/**
+* @desc Cleans the temp zip files that were created when users download several files or a whole folder at once.
+*		T
+* @return true
+* @todo
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+
+function cleanup_temp_dropbox()
+{
+	global $_course;
+
+	$handle=opendir(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp");
+	while (false !== ($file = readdir($handle)))
+	{
+		if ($file<>'.' OR $file<>'..')
+		{
+			$name=str_replace('.zip', '',$file);
+			$name_part=explode('-',$name);
+			$timestamp_of_file=$name_part[count($name_part)-1];
+			// if it is a dropboxdownloadfile and the file is older than one day then we delete it
+			if (strstr($file, 'dropboxdownload') AND $timestamp_of_file<(mktime()-86400))
+			{
+				unlink(api_get_path(SYS_COURSE_PATH).$_course['path']."/temp/".$file);
+			}
+		}
+
+	}
+	closedir($handle);
+	return true;
+}
+
+/**
+* @desc generates the contents of a html file that gives an overview of all the files in the zip file.
+*		This is to know the information of the files that are inside the zip file (who send it, the comment, ...)
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function generate_html_overview($files, $dont_show_columns=array(), $make_link=array())
+{
+	$return="<html>\n<head>\n\t<title>".get_lang('OverviewOfFilesInThisZip')."</title>\n</head>";
+	$return.="\n\n<body>\n<table border=\"1px\">";
+
+	$counter=0;
+	foreach ($files as $key=>$value)
+	{
+		// We add the header
+		if ($counter==0)
+		{
+			$columns_array=array_keys($value);
+			$return.="\n<tr>";
+			foreach ($columns_array AS $columns_array_key=>$columns_array_value)
+			{
+				if (!in_array($columns_array_value,$dont_show_columns))
+				{
+					$return.="\n\t<th>".$columns_array_value."</th>";
+				}
+				$column[]=$columns_array_value;
+			}
+			$return.="</tr><n";
+		}
+		$counter++;
+
+		// We add the content
+		$return.="\n<tr>";
+		foreach ($column AS $column_key=>$column_value)
+		{
+			if (!in_array($column_value,$dont_show_columns))
+			{
+				$return.="\n\t<td>";
+				if (in_array($column_value, $make_link))
+				{
+					$return.='<a href="'.$value[$column_value].'">'.$value[$column_value].'</a>';
+				}
+				else
+				{
+					$return.=$value[$column_value];
+				}
+				$return.="</td>";
+			}
+		}
+		$return.="</tr><n";
+
+
+	}
+	$return.="\n</table>\n\n</body>";
+	$return.="\n</html>";
+
+	return $return;
+}
+
+/**
+* @desc This function retrieves the number of feedback messages on every document. This function might become obsolete when
+* 		the feedback becomes user individual.
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function get_total_number_feedback($file_id='')
+{
+	global $dropbox_cnf;
+
+	$sql="SELECT COUNT(feedback_id) AS total, file_id FROM ".$dropbox_cnf['tbl_feedback']." GROUP BY file_id";
+	$result=Database::query($sql, __FILE__, __LINE__);
+	while ($row=Database::fetch_array($result))
+	{
+		$return[$row['file_id']]=$row['total'];
+	}
+	return $return;
+}
+
+
+/**
+* @desc this function checks if the key exists. If this is the case it returns the value, if not it returns 0
+* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+* @version march 2006
+*/
+function check_number_feedback($key, $array)
+{
+	if (is_array($array))
+	{
+		if (key_exists($key,$array))
+		{
+			return $array[$key];
+		}
+		else
+		{
+			return 0;
+		}
+	}
+	else
+	{
+		return 0;
+	}
+}
+
+
+
+
+
+
+/**
+ * Get the last access to a given tool of a given user
+ * @param $tool string the tool constant
+ * @param $course_code the course_id
+ * @param $user_id the id of the user
+ * @return string last tool access date
+ *
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+ * @version march 2006
+ *
+ * @todo consider moving this function to a more appropriate place.
+ */
+function get_last_tool_access($tool, $course_code='', $user_id='')
+{
+	global $_course, $_user;
+
+	// The default values of the parameters
+	if ($course_code=='')
+	{
+		$course_code=$_course['id'];
+	}
+	if ($user_id=='')
+	{
+		$user_id=$_user['user_id'];
+	}
+
+	// the table where the last tool access is stored (=track_e_lastaccess)
+	$table_last_access=Database::get_statistic_table('track_e_lastaccess');
+
+	$sql="SELECT access_date FROM $table_last_access WHERE access_user_id='".Database::escape_string($user_id)."'
+				AND access_cours_code='".Database::escape_string($course_code)."'
+				AND access_tool='".Database::escape_string($tool)."'
+				ORDER BY access_date DESC
+				LIMIT 1";
+	$result=Database::query($sql,__FILE__,__LINE__);
+	$row=Database::fetch_array($result);
+	return $row['access_date'];
 }

+ 311 - 311
main/dropbox/dropbox_init.inc.php

@@ -1,333 +1,333 @@
-<?php  //$id: $
-/* For licensing terms, see /dokeos_license.txt */
-
-/**
-==============================================================================
- * First initialisation file with initialisation of variables and
- * without outputting anything to browser.
- * 1. Calls global.inc.php and lang file
- * 2. Initialises $dropbox_cnf array with all relevant vars
- * 3. Often used functions
- *
- * @version 1.31
- * @copyright 2004-2005
- * @author Jan Bols <jan@ivpv.UGent.be>, main programmer
- * @author Rene Haentjens, severalcontributions <rene.haentjens@UGent.be> (see RH)
- * @author Roan Embrechts, virtual course support
- * @author Patrick Cool <patrick.cool@UGent.be>
- 				Dokeos Config Settings (AWACS)
- 				Refactoring
- 				tool introduction
- 				folders
- 				download file / folder (download icon)
- 				same action on multiple documents
- 				extended feedback
- * @package dokeos.dropbox
-==============================================================================
- */
-
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
+<?php  //$id: $
+/* For licensing terms, see /dokeos_license.txt */
+
+/**
+==============================================================================
+ * First initialisation file with initialisation of variables and
+ * without outputting anything to browser.
+ * 1. Calls global.inc.php and lang file
+ * 2. Initialises $dropbox_cnf array with all relevant vars
+ * 3. Often used functions
+ *
+ * @version 1.31
+ * @copyright 2004-2005
+ * @author Jan Bols <jan@ivpv.UGent.be>, main programmer
+ * @author Rene Haentjens, severalcontributions <rene.haentjens@UGent.be> (see RH)
+ * @author Roan Embrechts, virtual course support
+ * @author Patrick Cool <patrick.cool@UGent.be>
+ 				Dokeos Config Settings (AWACS)
+ 				Refactoring
+ 				tool introduction
+ 				folders
+ 				download file / folder (download icon)
+ 				same action on multiple documents
+ 				extended feedback
+ * @package dokeos.dropbox
+==============================================================================
+ */
+
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
 */
 // name of the language file that needs to be included
 $language_file = "dropbox";
-
-//this var disables the link in the breadcrumbs on top of the page
+
+//this var disables the link in the breadcrumbs on top of the page
 //$noPHP_SELF = TRUE;
-
-// including the basic Dokeos initialisation file
-require("../inc/global.inc.php");
-require_once(api_get_path(LIBRARY_PATH) . "security.lib.php");
-
-// the dropbox configuration parameters
-require_once('dropbox_config.inc.php');
-
-// the dropbox sanity files (adds a new table and some new fields)
-//require_once('dropbox_sanity.inc.php');
-
-// the dropbox file that contains additional functions
-require_once('dropbox_functions.inc.php');
-
-require(api_get_path(INCLUDE_PATH).'/conf/mail.conf.php');
-
-include_once(api_get_path(LIBRARY_PATH) . 'mail.lib.inc.php');
-include_once(api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php');
-
+
+// including the basic Dokeos initialisation file
+require("../inc/global.inc.php");
+require_once(api_get_path(LIBRARY_PATH) . "security.lib.php");
+
+// the dropbox configuration parameters
+require_once('dropbox_config.inc.php');
+
+// the dropbox sanity files (adds a new table and some new fields)
+//require_once('dropbox_sanity.inc.php');
+
+// the dropbox file that contains additional functions
+require_once('dropbox_functions.inc.php');
+
+require(api_get_path(INCLUDE_PATH).'/conf/mail.conf.php');
+
+include_once(api_get_path(LIBRARY_PATH) . 'mail.lib.inc.php');
+include_once(api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php');
+
 // protecting the script
-api_protect_course_script();
-
-
-/*
------------------------------------------------------------
-	Libraries
------------------------------------------------------------
+api_protect_course_script();
+
+
+/*
+-----------------------------------------------------------
+	Libraries
+-----------------------------------------------------------
 */
-require_once(api_get_path(LIBRARY_PATH)."/debug.lib.inc.php");
-require_once(api_get_path(LIBRARY_PATH) . "/course.lib.php");
-require_once(api_get_path(LIBRARY_PATH) . "/groupmanager.lib.php");
-
-
-// including the library for the sortable table
-require_once(api_get_path(LIBRARY_PATH).'/tablesort.lib.php');
-
-// including the library for the dropbox
-require_once( "dropbox_class.inc.php");
-
-// including some libraries that are also used in the documents tool
-require_once('../document/document.inc.php');  // we use a function build_document_icon_tag
+require_once(api_get_path(LIBRARY_PATH)."/debug.lib.inc.php");
+require_once(api_get_path(LIBRARY_PATH) . "/course.lib.php");
+require_once(api_get_path(LIBRARY_PATH) . "/groupmanager.lib.php");
+
+
+// including the library for the sortable table
+require_once(api_get_path(LIBRARY_PATH).'/tablesort.lib.php');
+
+// including the library for the dropbox
+require_once( "dropbox_class.inc.php");
+
+// including some libraries that are also used in the documents tool
+require_once('../document/document.inc.php');  // we use a function build_document_icon_tag
 require_once(api_get_path(LIBRARY_PATH).'/fileDisplay.lib.php'); // the function choose_image is used
-require_once(api_get_path(LIBRARY_PATH).'/document.lib.php');
-
-
-
-/*
------------------------------------------------------------
-	Virtual course support
------------------------------------------------------------
+require_once(api_get_path(LIBRARY_PATH).'/document.lib.php');
+
+
+
+/*
+-----------------------------------------------------------
+	Virtual course support
+-----------------------------------------------------------
+*/
+$user_id = api_get_user_id();
+$course_code = $_course['sysCode'];
+$course_info = Database::get_course_info($course_code);
+
+$is_course_member = CourseManager::is_user_subscribed_in_real_or_linked_course($user_id, $course_code);
+
+
+/*
+-----------------------------------------------------------
+	Object Initialisation
+-----------------------------------------------------------
 */
-$user_id = api_get_user_id();
-$course_code = $_course['sysCode'];
-$course_info = Database::get_course_info($course_code);
-
-$is_course_member = CourseManager::is_user_subscribed_in_real_or_linked_course($user_id, $course_code);
-
-
-/*
------------------------------------------------------------
-	Object Initialisation
------------------------------------------------------------
-*/
-// we need this here because the javascript to re-upload the file needs an array
+// we need this here because the javascript to re-upload the file needs an array
 // off all the documents that have already been sent.
-// @todo consider moving the javascripts in a function that displays the javascripts
+// @todo consider moving the javascripts in a function that displays the javascripts
 // only when it is needed.
-if ($_GET['action']=='add')
-{
-	$dropbox_person = new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
-}
-
-/*
------------------------------------------------------------
-	create javascript and htmlHeaders
-	// RH: Mailing: new function confirmsend
------------------------------------------------------------
-*/
-
-$javascript = "<script type=\"text/javascript\">
-	function confirmsend ()
-	{
-		if (confirm(\"".dropbox_lang("mailingConfirmSend", "noDLTT")."\")){
-			return true;
-		} else {
-			return false;
-		}
-		return true;
-	}
-
-	function confirmation (name)
-	{
-		if (confirm(\"".dropbox_lang("confirmDelete", "noDLTT")." : \"+ name )){
-			return true;
-		} else {
-			return false;
-		}
-		return true;
-	}
-
-	function checkForm (frm)
-	{
-		if (frm.elements['recipients[]'].selectedIndex < 0){
-			alert(\"".dropbox_lang("noUserSelected", "noDLTT")."\");
-			return false;
-		} else if (frm.file.value == '') {
-			alert(\"".dropbox_lang("noFileSpecified", "noDLTT")."\");
-			return false;
-		} else {
-			return true;
-		}
-	}
-	";
-
-if (dropbox_cnf("allowOverwrite"))
-{
-	$javascript .= "
-		var sentArray = new Array(";	//sentArray keeps list of all files still available in the sent files list
-										//of the user.
-										//This is used to show or hide the overwrite file-radio button of the upload form
-	for($i=0; $i<count($dropbox_person->sentWork); $i++)
-	{
-		if ($i > 0)
-		{
-		    $javascript .= ", ";
-		}
-		$javascript .= "'".$dropbox_person->sentWork[$i]->title."'";
-		//echo '***'.$dropbox_person->sentWork[$i]->title;
-	}
-	$javascript .=");
-
-		function checkfile(str)
-		{
-
-			ind = str.lastIndexOf('/'); //unix separator
-			if (ind == -1) ind = str.lastIndexOf('\\\');	//windows separator
-			filename = str.substring(ind+1, str.length);
-
-			found = 0;
-			for (i=0; i<sentArray.length; i++) {
-				if (sentArray[i] == filename) found=1;
-			}
-
-			//always start with unchecked box
-			el = getElement('cb_overwrite');
-			el.checked = false;
-
-			//show/hide checkbox
-			if (found == 1) {
-				displayEl('overwrite');
-			} else {
-				undisplayEl('overwrite');
-			}
-		}
-
-		function getElement(id)
-		{
-			return document.getElementById ? document.getElementById(id) :
-			document.all ? document.all(id) : null;
-		}
-
-		function displayEl(id)
-		{
-			var el = getElement(id);
-			if (el && el.style) el.style.display = '';
-		}
-
-		function undisplayEl(id)
-		{
-			var el = getElement(id);
-			if (el && el.style) el.style.display = 'none';
-		}";
-}
-
-$javascript .="
-	</script>";
-
-$htmlHeadXtra[] = $javascript;
-
-$htmlHeadXtra[] =
-"<script type=\"text/javascript\">
-function confirmation (name)
-{
-	if (confirm(\" ". get_lang("AreYouSureToDelete") ." \"+ name + \" ?\"))
-		{return true;}
-	else
-		{return false;}
-}
-</script>";
-
-api_session_register('javascript');
-
-$htmlHeadXtra[] = '<meta http-equiv="cache-control" content="no-cache">
-	<meta http-equiv="pragma" content="no-cache">
-	<meta http-equiv="expires" content="-1">';
-
-
-
-$checked_files=false;
-if (!$_GET['view'] OR $_GET['view']=='received')
-{
-	$part='received';
-}
-elseif ($_GET['view']='sent')
-{
-	$part='sent';
-}
+if ($_GET['action']=='add')
+{
+	$dropbox_person = new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
+}
+
+/*
+-----------------------------------------------------------
+	create javascript and htmlHeaders
+	// RH: Mailing: new function confirmsend
+-----------------------------------------------------------
+*/
+
+$javascript = "<script type=\"text/javascript\">
+	function confirmsend ()
+	{
+		if (confirm(\"".dropbox_lang("mailingConfirmSend", "noDLTT")."\")){
+			return true;
+		} else {
+			return false;
+		}
+		return true;
+	}
+
+	function confirmation (name)
+	{
+		if (confirm(\"".dropbox_lang("confirmDelete", "noDLTT")." : \"+ name )){
+			return true;
+		} else {
+			return false;
+		}
+		return true;
+	}
+
+	function checkForm (frm)
+	{
+		if (frm.elements['recipients[]'].selectedIndex < 0){
+			alert(\"".dropbox_lang("noUserSelected", "noDLTT")."\");
+			return false;
+		} else if (frm.file.value == '') {
+			alert(\"".dropbox_lang("noFileSpecified", "noDLTT")."\");
+			return false;
+		} else {
+			return true;
+		}
+	}
+	";
+
+if (dropbox_cnf("allowOverwrite"))
+{
+	$javascript .= "
+		var sentArray = new Array(";	//sentArray keeps list of all files still available in the sent files list
+										//of the user.
+										//This is used to show or hide the overwrite file-radio button of the upload form
+	for($i=0; $i<count($dropbox_person->sentWork); $i++)
+	{
+		if ($i > 0)
+		{
+		    $javascript .= ", ";
+		}
+		$javascript .= "'".$dropbox_person->sentWork[$i]->title."'";
+		//echo '***'.$dropbox_person->sentWork[$i]->title;
+	}
+	$javascript .=");
+
+		function checkfile(str)
+		{
+
+			ind = str.lastIndexOf('/'); //unix separator
+			if (ind == -1) ind = str.lastIndexOf('\\\');	//windows separator
+			filename = str.substring(ind+1, str.length);
+
+			found = 0;
+			for (i=0; i<sentArray.length; i++) {
+				if (sentArray[i] == filename) found=1;
+			}
+
+			//always start with unchecked box
+			el = getElement('cb_overwrite');
+			el.checked = false;
+
+			//show/hide checkbox
+			if (found == 1) {
+				displayEl('overwrite');
+			} else {
+				undisplayEl('overwrite');
+			}
+		}
+
+		function getElement(id)
+		{
+			return document.getElementById ? document.getElementById(id) :
+			document.all ? document.all(id) : null;
+		}
+
+		function displayEl(id)
+		{
+			var el = getElement(id);
+			if (el && el.style) el.style.display = '';
+		}
+
+		function undisplayEl(id)
+		{
+			var el = getElement(id);
+			if (el && el.style) el.style.display = 'none';
+		}";
+}
+
+$javascript .="
+	</script>";
+
+$htmlHeadXtra[] = $javascript;
+
+$htmlHeadXtra[] =
+"<script type=\"text/javascript\">
+function confirmation (name)
+{
+	if (confirm(\" ". get_lang("AreYouSureToDelete") ." \"+ name + \" ?\"))
+		{return true;}
+	else
+		{return false;}
+}
+</script>";
+
+api_session_register('javascript');
+
+$htmlHeadXtra[] = '<meta http-equiv="cache-control" content="no-cache">
+	<meta http-equiv="pragma" content="no-cache">
+	<meta http-equiv="expires" content="-1">';
+
+
+
+$checked_files=false;
+if (!$_GET['view'] OR $_GET['view']=='received')
+{
+	$part='received';
+}
+elseif ($_GET['view']='sent')
+{
+	$part='sent';
+}
 else
-{
-	header ('location: index.php?view='.$_GET['view'].'&error=Error');
-}
-if (($_POST['action']=='download_received' || $_POST['action']=='download_sent') and !$_POST['store_feedback'])
-{
-	{
-	$checked_file_ids = $_POST['id'];
-	if (!is_array($checked_file_ids) || count($checked_file_ids)==0)
-	{
-		header ('location: index.php?view='.$_GET['view'].'&error=CheckAtLeastOneFile');
+{
+	header ('location: index.php?view='.$_GET['view'].'&error=Error');
+}
+if (($_POST['action']=='download_received' || $_POST['action']=='download_sent') and !$_POST['store_feedback'])
+{
+	{
+	$checked_file_ids = $_POST['id'];
+	if (!is_array($checked_file_ids) || count($checked_file_ids)==0)
+	{
+		header ('location: index.php?view='.$_GET['view'].'&error=CheckAtLeastOneFile');
 		exit;
-	}
+	}
 	else
-		handle_multiple_actions();
+		handle_multiple_actions();
 		exit;
-	}
-}
-
-/*
- * ========================================
- *         AUTHORISATION SECTION
- * ========================================
- * Prevents access of all users that are not course members
- */
-if((!$is_allowed_in_course || !$is_courseMember) && !api_is_allowed_to_edit())
-{
-	if ($origin != 'learnpath')
-	{
-		api_not_allowed(true);//print headers/footers
-	}else{
-		api_not_allowed();
-	}
-	exit();
-}
-
-/*
-==============================================================================
-		BREADCRUMBS
-==============================================================================
+	}
+}
+
+/*
+ * ========================================
+ *         AUTHORISATION SECTION
+ * ========================================
+ * Prevents access of all users that are not course members
+ */
+if((!$is_allowed_in_course || !$is_courseMember) && !api_is_allowed_to_edit())
+{
+	if ($origin != 'learnpath')
+	{
+		api_not_allowed(true);//print headers/footers
+	}else{
+		api_not_allowed();
+	}
+	exit();
+}
+
+/*
+==============================================================================
+		BREADCRUMBS
+==============================================================================
 */
-if ($_GET['view']=='received')
-{
-	$interbreadcrumb[] = array ("url" => "../dropbox/index.php", "name" => dropbox_lang("dropbox", "noDLTT"));
-	$nameTools = get_lang('ReceivedFiles');
-
-	if ($_GET['action'] == 'addreceivedcategory')
-	{
-		$interbreadcrumb[] = array ("url" => "../dropbox/index.php?view=received", "name" => get_lang("ReceivedFiles"));
+if ($_GET['view']=='received')
+{
+	$interbreadcrumb[] = array ("url" => "../dropbox/index.php", "name" => dropbox_lang("dropbox", "noDLTT"));
+	$nameTools = get_lang('ReceivedFiles');
+
+	if ($_GET['action'] == 'addreceivedcategory')
+	{
+		$interbreadcrumb[] = array ("url" => "../dropbox/index.php?view=received", "name" => get_lang("ReceivedFiles"));
 		$nameTools = get_lang('AddNewCategory');
-	}
-}
-if ($_GET['view']=='sent' OR empty($_GET['view']))
-{
-	$interbreadcrumb[] = array ("url" => "../dropbox/index.php", "name" => dropbox_lang("dropbox", "noDLTT"));
-	$nameTools = get_lang('SentFiles');
-
-	if ($_GET['action'] == 'addsentcategory')
-	{
-		$interbreadcrumb[] = array ("url" => "../dropbox/index.php?view=sent", "name" => get_lang("SentFiles"));
+	}
+}
+if ($_GET['view']=='sent' OR empty($_GET['view']))
+{
+	$interbreadcrumb[] = array ("url" => "../dropbox/index.php", "name" => dropbox_lang("dropbox", "noDLTT"));
+	$nameTools = get_lang('SentFiles');
+
+	if ($_GET['action'] == 'addsentcategory')
+	{
+		$interbreadcrumb[] = array ("url" => "../dropbox/index.php?view=sent", "name" => get_lang("SentFiles"));
 		$nameTools = get_lang('AddNewCategory');
-	}
-	if ($_GET['action'] == 'add')
-	{
-		$interbreadcrumb[] = array ("url" => "../dropbox/index.php?view=sent", "name" => get_lang("SentFiles"));
+	}
+	if ($_GET['action'] == 'add')
+	{
+		$interbreadcrumb[] = array ("url" => "../dropbox/index.php?view=sent", "name" => get_lang("SentFiles"));
 		$nameTools = get_lang('UploadNewFile');
 	}
-}
-
-
-/*
-==============================================================================
-		HEADER & TITLE
-==============================================================================
+}
+
+
+/*
+==============================================================================
+		HEADER & TITLE
+==============================================================================
 */
-
-if ($origin != 'learnpath')
-{
-    Display::display_header($nameTools,"Dropbox");
-}
+
+if ($origin != 'learnpath')
+{
+    Display::display_header($nameTools,"Dropbox");
+}
 else // if we come from the learning path we have to include the stylesheet and the required javascripts manually.
-{
-	echo '<link rel="stylesheet" type="text/css" href="',api_get_path(WEB_CODE_PATH), 'css/default.css">';
-	echo $javascript;
-}
-
-// api_display_tool_title($nameTools);
+{
+	echo '<link rel="stylesheet" type="text/css" href="',api_get_path(WEB_CODE_PATH), 'css/default.css">';
+	echo $javascript;
+}
+
+// api_display_tool_title($nameTools);
 ?>

+ 677 - 677
main/dropbox/dropbox_submit.php

@@ -1,686 +1,686 @@
-<?php //$id: $
-/* For licensing terms, see /dokeos_license.txt */
-
-
-/*
- * ========================================
- * PREVENT RESUBMITING
- * ========================================
- * This part checks if the $dropbox_unid var has the same ID
- * as the session var $dropbox_uniqueid that was registered as a session
- * var before.
- * The resubmit prevention only works with GET requests, because it gives some annoying
- * behaviours with POST requests.
- */
-/*
-if (isset($_POST["dropbox_unid"])) {
-	$dropbox_unid = $_POST["dropbox_unid"];
-} elseif (isset($_GET["dropbox_unid"]))
-{
-	$dropbox_unid = $_GET["dropbox_unid"];
-} else {
-	die(dropbox_lang("badFormData")." (code 400)");
-}
-
-if (isset($_SESSION["dropbox_uniqueid"]) && isset($_GET["dropbox_unid"]) && $dropbox_unid == $_SESSION["dropbox_uniqueid"]) {
-	//resubmit : go to index.php
-	// only prevent resending of data for GETS, not POSTS because this gives annoying results
-
-	if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"]=="on") {
-		$mypath = "https";
-	} else {
-		$mypath = "http";
-	}
-	$mypath=$mypath."://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/index.php";
-
-echo 'hier';
-    header("Location: $mypath");
-
-}
-
-$dropbox_uniqueid = $dropbox_unid;
-
-api_session_register("dropbox_uniqueid");
-*/
-
-
-/**
- * ========================================
- * FORM SUBMIT
- * ========================================
- * - VALIDATE POSTED DATA
- * - UPLOAD NEW FILE
- */
-if ( isset( $_POST["submitWork"]))
-{
+<?php //$id: $
+/* For licensing terms, see /dokeos_license.txt */
+
+
+/*
+ * ========================================
+ * PREVENT RESUBMITING
+ * ========================================
+ * This part checks if the $dropbox_unid var has the same ID
+ * as the session var $dropbox_uniqueid that was registered as a session
+ * var before.
+ * The resubmit prevention only works with GET requests, because it gives some annoying
+ * behaviours with POST requests.
+ */
+/*
+if (isset($_POST["dropbox_unid"])) {
+	$dropbox_unid = $_POST["dropbox_unid"];
+} elseif (isset($_GET["dropbox_unid"]))
+{
+	$dropbox_unid = $_GET["dropbox_unid"];
+} else {
+	die(dropbox_lang("badFormData")." (code 400)");
+}
+
+if (isset($_SESSION["dropbox_uniqueid"]) && isset($_GET["dropbox_unid"]) && $dropbox_unid == $_SESSION["dropbox_uniqueid"]) {
+	//resubmit : go to index.php
+	// only prevent resending of data for GETS, not POSTS because this gives annoying results
+
+	if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"]=="on") {
+		$mypath = "https";
+	} else {
+		$mypath = "http";
+	}
+	$mypath=$mypath."://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/index.php";
+
+echo 'hier';
+    header("Location: $mypath");
+
+}
+
+$dropbox_uniqueid = $dropbox_unid;
+
+api_session_register("dropbox_uniqueid");
+*/
+
+
+/**
+ * ========================================
+ * FORM SUBMIT
+ * ========================================
+ * - VALIDATE POSTED DATA
+ * - UPLOAD NEW FILE
+ */
+if ( isset( $_POST["submitWork"]))
+{
     if (file_exists(api_get_path(INCLUDE_PATH) . "/fileUploadLib.inc.php"))
-    {
-        require_once(api_get_path(INCLUDE_PATH) . "/fileUploadLib.inc.php");
+    {
+        require_once(api_get_path(INCLUDE_PATH) . "/fileUploadLib.inc.php");
+    }
+    else
+    {
+        require_once(api_get_path(LIBRARY_PATH) . "/fileUpload.lib.php");
+	}
+
+    $error = FALSE;
+    $errormsg = '';
+
+
+    /**
+     * --------------------------------------
+     * FORM SUBMIT : VALIDATE POSTED DATA
+     * --------------------------------------
+     */
+    // the author or description field is empty
+    if ( !isset( $_POST['authors']) || !isset( $_POST['description']))
+    {
+        $error = TRUE;
+
+        $errormsg = dropbox_lang("badFormData");
+    }
+	elseif ( !isset( $_POST['recipients']) || count( $_POST['recipients']) <= 0)
+    {
+        $error = TRUE;
+
+        $errormsg = dropbox_lang("noUserSelected");
+    }
+    else
+    {
+        $thisIsAMailing = FALSE;  // RH: Mailing selected as destination
+        $thisIsJustUpload = FALSE;  // RH
+
+	    foreach( $_POST['recipients'] as $rec)
+        {
+            if ( $rec == 'mailing')
+            {
+	            $thisIsAMailing = TRUE;
+            }
+            elseif ( $rec == 'upload')
+            {
+	            $thisIsJustUpload = TRUE;
+            }
+	        elseif (strpos($rec, 'user_') === 0 && !isCourseMember(substr($rec, strlen('user_') ) ))
+	        {
+	        	echo '401';
+	        	die( dropbox_lang("badFormData")." (code 401)");
+	        }
+	        elseif (strpos($rec, 'group_') !== 0 && strpos($rec, 'user_') !== 0)
+	        {
+	        	echo '402';
+	        	die( dropbox_lang("badFormData")." (code 402)");
+	        }
+        }
+
+		// we are doing a mailing but an additional recipient is selected
+        if ( $thisIsAMailing && ( count($_POST['recipients']) != 1))
+        {
+            $error = TRUE;
+
+            $errormsg = dropbox_lang("mailingSelectNoOther");
+        }
+        // we are doing a just upload but an additional recipient is selected.
+        elseif ( $thisIsJustUpload && ( count($_POST['recipients']) != 1))
+        {
+            $error = TRUE;
+
+            $errormsg = get_lang("MailingJustUploadSelectNoOther");
+        }
+        elseif ( empty( $_FILES['file']['name']))
+        {
+            $error = TRUE;
+
+            $errormsg = dropbox_lang("noFileSpecified");
+        }
+    }
+
+	//check if $_POST['cb_overwrite'] is true or false
+	$dropbox_overwrite = false;
+	if ( isset($_POST['cb_overwrite']) && $_POST['cb_overwrite']==true)
+	{
+		$dropbox_overwrite = true;
+	}
+
+    /**
+     * --------------------------------------
+     * FORM SUBMIT : UPLOAD NEW FILE
+     * --------------------------------------
+     */
+    if ( !$error)
+    {
+        $dropbox_filename = $_FILES['file']['name'];
+
+        $dropbox_filesize = $_FILES['file']['size'];
+
+        $dropbox_filetype = $_FILES['file']['type'];
+
+        $dropbox_filetmpname = $_FILES['file']['tmp_name'];
+
+        if ( $dropbox_filesize <= 0 || $dropbox_filesize > dropbox_cnf("maxFilesize"))
+        {
+            $errormsg = dropbox_lang("tooBig");
+
+            $error = TRUE;
+        }elseif ( !is_uploaded_file( $dropbox_filetmpname)) // check user fraud : no clean error msg.
+            {
+                die ( dropbox_lang("badFormData")." (code 403)");
+        }
+
+        if ( !$error)
+        {
+            // Try to add an extension to the file if it hasn't got one
+            $dropbox_filename = add_ext_on_mime( $dropbox_filename,$dropbox_filetype);
+            // Replace dangerous characters
+            $dropbox_filename = replace_dangerous_char( $dropbox_filename);
+            // Transform any .php file in .phps fo security
+            $dropbox_filename = php2phps ( $dropbox_filename);
+            if(!filter_extension($dropbox_filename))
+            {
+            	$error = true;
+            	$errormsg = get_lang('UplUnableToSaveFileFilteredExtension');
+            }
+            else
+            {
+	            // set title
+	            $dropbox_title = $dropbox_filename;
+
+	            // set author
+	            if ( $_POST['authors'] == '')
+	            {
+	                $_POST['authors'] = getUserNameFromId( $_user['user_id']);
+	            }
+
+				if ( $dropbox_overwrite)  // RH: Mailing: adapted
+				{
+					$dropbox_person = new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
+
+					foreach($dropbox_person->sentWork as $w)
+					{
+						if ($w->title == $dropbox_filename)
+						{
+						    if ( ($w->recipients[0]['id'] > dropbox_cnf("mailingIdBase")) xor $thisIsAMailing)
+						    {
+								$error = TRUE;
+								$errormsg = dropbox_lang("mailingNonMailingError");
+							}
+							if ( ($w->recipients[0]['id'] == $_user['user_id']) xor $thisIsJustUpload)
+							{
+								$error = TRUE;
+								$errormsg = get_lang("MailingJustUploadSelectNoOther");
+							}
+							$dropbox_filename = $w->filename; $found = true;
+							break;
+						}
+					}
+				}
+				else  // rename file to login_filename_uniqueId format
+				{
+					$dropbox_filename = getLoginFromId( $_user['user_id']) . "_" . $dropbox_filename . "_".uniqid('');
+				}
+
+				if ( ( ! is_dir( dropbox_cnf("sysPath"))))
+	            {
+					//The dropbox subdir doesn't exist yet so make it and create the .htaccess file
+	                mkdir( dropbox_cnf("sysPath"), 0700) or die ( dropbox_lang("errorCreatingDir")." (code 404)");
+					$fp = fopen( dropbox_cnf("sysPath")."/.htaccess", "w") or die (dropbox_lang("errorCreatingDir")." (code 405)");
+					fwrite($fp, "AuthName AllowLocalAccess
+	                             AuthType Basic
+
+	                             order deny,allow
+	                             deny from all
+
+	                             php_flag zlib.output_compression off") or die (dropbox_lang("errorCreatingDir")." (code 406)");
+	            }
+
+				if ( $error) {}
+	            elseif ( $thisIsAMailing)  // RH: $newWorkRecipients is integer - see class
+				{
+				    if ( preg_match( dropbox_cnf("mailingZipRegexp"), $dropbox_title))
+					{
+			            $newWorkRecipients = dropbox_cnf("mailingIdBase");
+					}
+					else
+					{
+				        $error = TRUE;
+				        $errormsg = $dropbox_title . ": " . dropbox_lang("mailingWrongZipfile");
+					}
+				}
+				elseif ( $thisIsJustUpload)  // RH: $newWorkRecipients is empty array
+				{
+		            $newWorkRecipients = array();
+	        	}
+				else
+				{ 	// creating the array that contains all the users who will receive the file
+					$newWorkRecipients = array();
+		            foreach ($_POST["recipients"] as $rec)
+		            {
+		            	if (strpos($rec, 'user_') === 0) {
+		            		$newWorkRecipients[] = substr($rec, strlen('user_') );
+		            	}
+		            	elseif (strpos($rec, 'group_') === 0 )
+		            	{
+		            		$userList = GroupManager::get_subscribed_users(substr($rec, strlen('group_') ));
+		            		foreach ($userList as $usr)
+		            		{
+		            			if (! in_array($usr['user_id'], $newWorkRecipients) && $usr['user_id'] != $_user['user_id'])
+		            			{
+		            				$newWorkRecipients[] = $usr['user_id'];
+		            			}
+		            		}
+		            	}
+		            }
+	        	}
+
+				//After uploading the file, create the db entries
+
+	        	if ( !$error)
+	        	{
+		            @move_uploaded_file( $dropbox_filetmpname, dropbox_cnf("sysPath") . '/' . $dropbox_filename)
+		            	or die( dropbox_lang("uploadError")." (code 407)");
+		            new Dropbox_SentWork( $_user['user_id'], $dropbox_title, $_POST['description'], strip_tags($_POST['authors']), $dropbox_filename, $dropbox_filesize, $newWorkRecipients);
+	        	}
+            }
+        }
+    } //end if(!$error)
+
+
+    /**
+     * ========================================
+     * SUBMIT FORM RESULTMESSAGE
+     * ========================================
+     */
+    if ( !$error)
+    {
+		$return_message=get_lang('FileUploadSucces');
     }
+
     else
-    {
-        require_once(api_get_path(LIBRARY_PATH) . "/fileUpload.lib.php");
-	}
-
-    $error = FALSE;
-    $errormsg = '';
-
-
-    /**
-     * --------------------------------------
-     * FORM SUBMIT : VALIDATE POSTED DATA
-     * --------------------------------------
-     */
-    // the author or description field is empty
-    if ( !isset( $_POST['authors']) || !isset( $_POST['description']))
-    {
-        $error = TRUE;
-
-        $errormsg = dropbox_lang("badFormData");
-    }
-	elseif ( !isset( $_POST['recipients']) || count( $_POST['recipients']) <= 0)
-    {
-        $error = TRUE;
-
-        $errormsg = dropbox_lang("noUserSelected");
-    }
-    else
-    {
-        $thisIsAMailing = FALSE;  // RH: Mailing selected as destination
-        $thisIsJustUpload = FALSE;  // RH
-
-	    foreach( $_POST['recipients'] as $rec)
-        {
-            if ( $rec == 'mailing')
-            {
-	            $thisIsAMailing = TRUE;
-            }
-            elseif ( $rec == 'upload')
-            {
-	            $thisIsJustUpload = TRUE;
-            }
-	        elseif (strpos($rec, 'user_') === 0 && !isCourseMember(substr($rec, strlen('user_') ) ))
-	        {
-	        	echo '401';
-	        	die( dropbox_lang("badFormData")." (code 401)");
-	        }
-	        elseif (strpos($rec, 'group_') !== 0 && strpos($rec, 'user_') !== 0)
-	        {
-	        	echo '402';
-	        	die( dropbox_lang("badFormData")." (code 402)");
-	        }
-        }
-
-		// we are doing a mailing but an additional recipient is selected
-        if ( $thisIsAMailing && ( count($_POST['recipients']) != 1))
-        {
-            $error = TRUE;
-
-            $errormsg = dropbox_lang("mailingSelectNoOther");
-        }
-        // we are doing a just upload but an additional recipient is selected.
-        elseif ( $thisIsJustUpload && ( count($_POST['recipients']) != 1))
-        {
-            $error = TRUE;
-
-            $errormsg = get_lang("MailingJustUploadSelectNoOther");
-        }
-        elseif ( empty( $_FILES['file']['name']))
-        {
-            $error = TRUE;
-
-            $errormsg = dropbox_lang("noFileSpecified");
-        }
-    }
-
-	//check if $_POST['cb_overwrite'] is true or false
-	$dropbox_overwrite = false;
-	if ( isset($_POST['cb_overwrite']) && $_POST['cb_overwrite']==true)
-	{
-		$dropbox_overwrite = true;
-	}
-
-    /**
-     * --------------------------------------
-     * FORM SUBMIT : UPLOAD NEW FILE
-     * --------------------------------------
-     */
-    if ( !$error)
-    {
-        $dropbox_filename = $_FILES['file']['name'];
-
-        $dropbox_filesize = $_FILES['file']['size'];
-
-        $dropbox_filetype = $_FILES['file']['type'];
-
-        $dropbox_filetmpname = $_FILES['file']['tmp_name'];
-
-        if ( $dropbox_filesize <= 0 || $dropbox_filesize > dropbox_cnf("maxFilesize"))
-        {
-            $errormsg = dropbox_lang("tooBig");
-
-            $error = TRUE;
-        }elseif ( !is_uploaded_file( $dropbox_filetmpname)) // check user fraud : no clean error msg.
-            {
-                die ( dropbox_lang("badFormData")." (code 403)");
-        }
-
-        if ( !$error)
-        {
-            // Try to add an extension to the file if it hasn't got one
-            $dropbox_filename = add_ext_on_mime( $dropbox_filename,$dropbox_filetype);
-            // Replace dangerous characters
-            $dropbox_filename = replace_dangerous_char( $dropbox_filename);
-            // Transform any .php file in .phps fo security
-            $dropbox_filename = php2phps ( $dropbox_filename);
-            if(!filter_extension($dropbox_filename))
-            {
-            	$error = true;
-            	$errormsg = get_lang('UplUnableToSaveFileFilteredExtension');
-            }
-            else
-            {
-	            // set title
-	            $dropbox_title = $dropbox_filename;
-
-	            // set author
-	            if ( $_POST['authors'] == '')
-	            {
-	                $_POST['authors'] = getUserNameFromId( $_user['user_id']);
-	            }
-
-				if ( $dropbox_overwrite)  // RH: Mailing: adapted
-				{
-					$dropbox_person = new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
-
-					foreach($dropbox_person->sentWork as $w)
-					{
-						if ($w->title == $dropbox_filename)
-						{
-						    if ( ($w->recipients[0]['id'] > dropbox_cnf("mailingIdBase")) xor $thisIsAMailing)
-						    {
-								$error = TRUE;
-								$errormsg = dropbox_lang("mailingNonMailingError");
-							}
-							if ( ($w->recipients[0]['id'] == $_user['user_id']) xor $thisIsJustUpload)
-							{
-								$error = TRUE;
-								$errormsg = get_lang("MailingJustUploadSelectNoOther");
-							}
-							$dropbox_filename = $w->filename; $found = true;
-							break;
-						}
-					}
-				}
-				else  // rename file to login_filename_uniqueId format
-				{
-					$dropbox_filename = getLoginFromId( $_user['user_id']) . "_" . $dropbox_filename . "_".uniqid('');
-				}
-
-				if ( ( ! is_dir( dropbox_cnf("sysPath"))))
-	            {
-					//The dropbox subdir doesn't exist yet so make it and create the .htaccess file
-	                mkdir( dropbox_cnf("sysPath"), 0700) or die ( dropbox_lang("errorCreatingDir")." (code 404)");
-					$fp = fopen( dropbox_cnf("sysPath")."/.htaccess", "w") or die (dropbox_lang("errorCreatingDir")." (code 405)");
-					fwrite($fp, "AuthName AllowLocalAccess
-	                             AuthType Basic
-
-	                             order deny,allow
-	                             deny from all
-
-	                             php_flag zlib.output_compression off") or die (dropbox_lang("errorCreatingDir")." (code 406)");
-	            }
-
-				if ( $error) {}
-	            elseif ( $thisIsAMailing)  // RH: $newWorkRecipients is integer - see class
-				{
-				    if ( preg_match( dropbox_cnf("mailingZipRegexp"), $dropbox_title))
-					{
-			            $newWorkRecipients = dropbox_cnf("mailingIdBase");
-					}
-					else
-					{
-				        $error = TRUE;
-				        $errormsg = $dropbox_title . ": " . dropbox_lang("mailingWrongZipfile");
-					}
-				}
-				elseif ( $thisIsJustUpload)  // RH: $newWorkRecipients is empty array
-				{
-		            $newWorkRecipients = array();
-	        	}
-				else
-				{ 	// creating the array that contains all the users who will receive the file
-					$newWorkRecipients = array();
-		            foreach ($_POST["recipients"] as $rec)
-		            {
-		            	if (strpos($rec, 'user_') === 0) {
-		            		$newWorkRecipients[] = substr($rec, strlen('user_') );
-		            	}
-		            	elseif (strpos($rec, 'group_') === 0 )
-		            	{
-		            		$userList = GroupManager::get_subscribed_users(substr($rec, strlen('group_') ));
-		            		foreach ($userList as $usr)
-		            		{
-		            			if (! in_array($usr['user_id'], $newWorkRecipients) && $usr['user_id'] != $_user['user_id'])
-		            			{
-		            				$newWorkRecipients[] = $usr['user_id'];
-		            			}
-		            		}
-		            	}
-		            }
-	        	}
-
-				//After uploading the file, create the db entries
-
-	        	if ( !$error)
-	        	{
-		            @move_uploaded_file( $dropbox_filetmpname, dropbox_cnf("sysPath") . '/' . $dropbox_filename)
-		            	or die( dropbox_lang("uploadError")." (code 407)");
-		            new Dropbox_SentWork( $_user['user_id'], $dropbox_title, $_POST['description'], strip_tags($_POST['authors']), $dropbox_filename, $dropbox_filesize, $newWorkRecipients);
-	        	}
-            }
-        }
-    } //end if(!$error)
-
-
-    /**
-     * ========================================
-     * SUBMIT FORM RESULTMESSAGE
-     * ========================================
-     */
-    if ( !$error)
-    {
-		$return_message=get_lang('FileUploadSucces');
-    }
-
-    else
-    {
-		$return_message=$errormsg;
-    }
-} // end if ( isset( $_POST["submitWork"]))
-
-
-/**
- * ========================================
- * // RH: EXAMINE OR SEND MAILING  (NEW)
- * ========================================
- */
-if ( isset( $_GET['mailingIndex']))  // examine or send
-{
-    $dropbox_person = new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
-	if ( isset($_SESSION["sentOrder"]))
-	{
-		$dropbox_person->orderSentWork ($_SESSION["sentOrder"]);
-	}
-    $i = $_GET['mailingIndex']; $mailing_item = $dropbox_person->sentWork[$i];
-    $mailing_title = $mailing_item->title;
-    $mailing_file = dropbox_cnf("sysPath") . '/' . $mailing_item->filename;
-    $errormsg = '<b>' . $mailing_item->recipients[0]['name'] . ' ('
-    	. "<a href='dropbox_download.php?origin=$origin&id=".urlencode($mailing_item->id)."'>"
-		. htmlspecialchars($mailing_title,ENT_QUOTES,$charset) . '</a>):</b><br /><br />';
-
-    if ( preg_match( dropbox_cnf("mailingZipRegexp"), $mailing_title, $nameParts))
-	{
-		$var = api_strtoupper($nameParts[2]);  // the variable part of the name
-		$course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
-		$sel = "SELECT u.user_id, u.lastname, u.firstname, cu.status
-				FROM `".$_configuration['main_database']."`.`user` u
-				LEFT JOIN $course_user cu
-				ON cu.user_id = u.user_id AND cu.course_code = '".$_course['sysCode']."'";
-		$sel .= " WHERE u.".dropbox_cnf("mailingWhere".$var)." = '";
-
-        function getUser($thisRecip)
-        {
-			// string result = error message, array result = [user_id, lastname, firstname]
-
+    {
+		$return_message=$errormsg;
+    }
+} // end if ( isset( $_POST["submitWork"]))
+
+
+/**
+ * ========================================
+ * // RH: EXAMINE OR SEND MAILING  (NEW)
+ * ========================================
+ */
+if ( isset( $_GET['mailingIndex']))  // examine or send
+{
+    $dropbox_person = new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
+	if ( isset($_SESSION["sentOrder"]))
+	{
+		$dropbox_person->orderSentWork ($_SESSION["sentOrder"]);
+	}
+    $i = $_GET['mailingIndex']; $mailing_item = $dropbox_person->sentWork[$i];
+    $mailing_title = $mailing_item->title;
+    $mailing_file = dropbox_cnf("sysPath") . '/' . $mailing_item->filename;
+    $errormsg = '<b>' . $mailing_item->recipients[0]['name'] . ' ('
+    	. "<a href='dropbox_download.php?origin=$origin&id=".urlencode($mailing_item->id)."'>"
+		. htmlspecialchars($mailing_title,ENT_QUOTES,$charset) . '</a>):</b><br /><br />';
+
+    if ( preg_match( dropbox_cnf("mailingZipRegexp"), $mailing_title, $nameParts))
+	{
+		$var = api_strtoupper($nameParts[2]);  // the variable part of the name
+		$course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
+		$sel = "SELECT u.user_id, u.lastname, u.firstname, cu.status
+				FROM `".$_configuration['main_database']."`.`user` u
+				LEFT JOIN $course_user cu
+				ON cu.user_id = u.user_id AND cu.course_code = '".$_course['sysCode']."'";
+		$sel .= " WHERE u.".dropbox_cnf("mailingWhere".$var)." = '";
+
+        function getUser($thisRecip)
+        {
+			// string result = error message, array result = [user_id, lastname, firstname]
+
 	    	global $var, $sel;
-            if (isset($students)) {
-                unset($students);
-            }
-
-	        $result = Database::query($sel . $thisRecip . "'",__FILE__,__LINE__);
-	        while ( ($res = mysql_fetch_array($result))) {$students[] = $res;}
-	        mysql_free_result($result);
-
-	    	if (count($students) == 1)
-	    	{
-		    	return($students[0]);
-	    	}
-	    	elseif (count($students) > 1)
-	    	{
-	        	return ' <'.dropbox_lang("mailingFileRecipDup", "noDLTT").$var."= $thisRecip>";
-	    	}
-	    	else
-	    	{
-	        	return ' <'.dropbox_lang("mailingFileRecipNotFound", "noDLTT").$var."= $thisRecip>";
-	    	}
-        }
-
-		$preFix = $nameParts[1]; $postFix = $nameParts[3];
-		$preLen = api_strlen($preFix); $postLen = api_strlen($postFix);
-
-		function findRecipient($thisFile)
-		{
-			// string result = error message, array result = [user_id, lastname, firstname, status]
-
-			global $nameParts, $preFix, $preLen, $postFix, $postLen;
-
-            if ( preg_match(dropbox_cnf("mailingFileRegexp"), $thisFile, $matches))
-            {
-	            $thisName = $matches[1];
-	            if ( api_substr($thisName, 0, $preLen) == $preFix)
-	            {
-		            if ( $postLen == 0 || api_substr($thisName, -$postLen) == $postFix)
-		            {
-			            $thisRecip = api_substr($thisName, $preLen, api_strlen($thisName) - $preLen - $postLen);
-			            if ( $thisRecip) return getUser($thisRecip);
-			            return ' <'.dropbox_lang("mailingFileNoRecip", "noDLTT").'>';
-		            }
-		            else
-		            {
-			            return ' <'.dropbox_lang("mailingFileNoPostfix", "noDLTT").$postFix.'>';
-		            }
-	            }
-	            else
-	            {
-		            return ' <'.dropbox_lang("mailingFileNoPrefix", "noDLTT").$preFix.'>';
-	            }
-            }
-            else
-            {
-	            return ' <'.dropbox_lang("mailingFileFunny", "noDLTT").'>';
-            }
-        }
-
+            if (isset($students)) {
+                unset($students);
+            }
+
+	        $result = Database::query($sel . $thisRecip . "'",__FILE__,__LINE__);
+	        while ( ($res = mysql_fetch_array($result))) {$students[] = $res;}
+	        mysql_free_result($result);
+
+	    	if (count($students) == 1)
+	    	{
+		    	return($students[0]);
+	    	}
+	    	elseif (count($students) > 1)
+	    	{
+	        	return ' <'.dropbox_lang("mailingFileRecipDup", "noDLTT").$var."= $thisRecip>";
+	    	}
+	    	else
+	    	{
+	        	return ' <'.dropbox_lang("mailingFileRecipNotFound", "noDLTT").$var."= $thisRecip>";
+	    	}
+        }
+
+		$preFix = $nameParts[1]; $postFix = $nameParts[3];
+		$preLen = api_strlen($preFix); $postLen = api_strlen($postFix);
+
+		function findRecipient($thisFile)
+		{
+			// string result = error message, array result = [user_id, lastname, firstname, status]
+
+			global $nameParts, $preFix, $preLen, $postFix, $postLen;
+
+            if ( preg_match(dropbox_cnf("mailingFileRegexp"), $thisFile, $matches))
+            {
+	            $thisName = $matches[1];
+	            if ( api_substr($thisName, 0, $preLen) == $preFix)
+	            {
+		            if ( $postLen == 0 || api_substr($thisName, -$postLen) == $postFix)
+		            {
+			            $thisRecip = api_substr($thisName, $preLen, api_strlen($thisName) - $preLen - $postLen);
+			            if ( $thisRecip) return getUser($thisRecip);
+			            return ' <'.dropbox_lang("mailingFileNoRecip", "noDLTT").'>';
+		            }
+		            else
+		            {
+			            return ' <'.dropbox_lang("mailingFileNoPostfix", "noDLTT").$postFix.'>';
+		            }
+	            }
+	            else
+	            {
+		            return ' <'.dropbox_lang("mailingFileNoPrefix", "noDLTT").$preFix.'>';
+	            }
+            }
+            else
+            {
+	            return ' <'.dropbox_lang("mailingFileFunny", "noDLTT").'>';
+            }
+        }
+
 	    if (file_exists(api_get_path(INCLUDE_PATH) . "/pclzip/pclzip.lib.php"))
-	    {
-	        require(api_get_path(INCLUDE_PATH) . "/pclzip/pclzip.lib.php");
+	    {
+	        require(api_get_path(INCLUDE_PATH) . "/pclzip/pclzip.lib.php");
 	    }
 	    else
-	    {
-	        require(api_get_path(LIBRARY_PATH) . "/pclzip/pclzip.lib.php");
-		}
-
-		$zipFile = new pclZip($mailing_file);  $goodFiles  = array();
-		$zipContent = $zipFile->listContent(); $ucaseFiles = array();
-
-		if ( $zipContent)
-		{
-			foreach( $zipFile->listContent() as $thisContent)
-			{
-	            $thisFile = substr(strrchr('/' . $thisContent['filename'], '/'), 1);
-	            $thisFileUcase = strtoupper($thisFile);
-				if ( preg_match("~.(php.*|phtml)$~i", $thisFile) )
-				{
-		            $error = TRUE; $errormsg .= $thisFile . ': ' . dropbox_lang("mailingZipPhp");
-					break;
-				}
-				elseif ( !$thisContent['folder'])
-				{
-		            if ( $ucaseFiles[$thisFileUcase])
-		            {
-			            $error = TRUE; $errormsg .= $thisFile . ': ' . dropbox_lang("mailingZipDups");
-						break;
-		            }
-		            else
-		            {
-			            $goodFiles[$thisFile] = findRecipient($thisFile);
-			            $ucaseFiles[$thisFileUcase] = "yep";
-		            }
-				}
-
-			}
-		}
-		else
-		{
-            $error = TRUE; $errormsg .= dropbox_lang("mailingZipEmptyOrCorrupt");
-        }
-
-		if ( !$error)
-		{
-			$students = array();  // collect all recipients in this course
-
-			foreach( $goodFiles as $thisFile => $thisRecip)
-			{
-				$errormsg .= htmlspecialchars($thisFile,ENT_QUOTES,$charset) . ': ';
-	            if ( is_string($thisRecip))  // see findRecipient
-	            {
-					$errormsg .= '<font color="#FF0000">'
-						. htmlspecialchars($thisRecip,ENT_QUOTES,$charset) . '</font><br>';
-	            }
-	            else
-	            {
-					if ( isset( $_GET['mailingSend']))
-					{
-			            $errormsg .= dropbox_lang("mailingFileSentTo");
-		            }
-		            else
-		            {
-						$errormsg .= dropbox_lang("mailingFileIsFor");
-		            }
+	    {
+	        require(api_get_path(LIBRARY_PATH) . "/pclzip/pclzip.lib.php");
+		}
+
+		$zipFile = new pclZip($mailing_file);  $goodFiles  = array();
+		$zipContent = $zipFile->listContent(); $ucaseFiles = array();
+
+		if ( $zipContent)
+		{
+			foreach( $zipFile->listContent() as $thisContent)
+			{
+	            $thisFile = substr(strrchr('/' . $thisContent['filename'], '/'), 1);
+	            $thisFileUcase = strtoupper($thisFile);
+				if ( preg_match("~.(php.*|phtml)$~i", $thisFile) )
+				{
+		            $error = TRUE; $errormsg .= $thisFile . ': ' . dropbox_lang("mailingZipPhp");
+					break;
+				}
+				elseif ( !$thisContent['folder'])
+				{
+		            if ( $ucaseFiles[$thisFileUcase])
+		            {
+			            $error = TRUE; $errormsg .= $thisFile . ': ' . dropbox_lang("mailingZipDups");
+						break;
+		            }
+		            else
+		            {
+			            $goodFiles[$thisFile] = findRecipient($thisFile);
+			            $ucaseFiles[$thisFileUcase] = "yep";
+		            }
+				}
+
+			}
+		}
+		else
+		{
+            $error = TRUE; $errormsg .= dropbox_lang("mailingZipEmptyOrCorrupt");
+        }
+
+		if ( !$error)
+		{
+			$students = array();  // collect all recipients in this course
+
+			foreach( $goodFiles as $thisFile => $thisRecip)
+			{
+				$errormsg .= htmlspecialchars($thisFile,ENT_QUOTES,$charset) . ': ';
+	            if ( is_string($thisRecip))  // see findRecipient
+	            {
+					$errormsg .= '<font color="#FF0000">'
+						. htmlspecialchars($thisRecip,ENT_QUOTES,$charset) . '</font><br>';
+	            }
+	            else
+	            {
+					if ( isset( $_GET['mailingSend']))
+					{
+			            $errormsg .= dropbox_lang("mailingFileSentTo");
+		            }
+		            else
+		            {
+						$errormsg .= dropbox_lang("mailingFileIsFor");
+		            }
 					$errormsg .= htmlspecialchars(api_get_person_name($thisRecip[2], $thisRecip[1]), ENT_QUOTES, $charset);
-
-					if ( is_null($thisRecip[3]))
-					{
-						$errormsg .= dropbox_lang("mailingFileNotRegistered");
-					}
-					else
-					{
-						$students[] = $thisRecip[0];
-					}
-					$errormsg .= '<br>';
-
-	            }
-			}
-
-			// find student course members not among the recipients
-
-			$course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
-			$sql = "SELECT u.lastname, u.firstname
-					FROM $course_user cu
-					LEFT JOIN  `".$_configuration['main_database']."`.`user` u
-					ON cu.user_id = u.user_id AND cu.course_code = '".$_course['sysCode']."'
-					WHERE cu.status = 5
-					AND u.user_id NOT IN ('" . implode("', '" , $students) . "')";
-	        $result = Database::query($sql,__FILE__,__LINE__);
-
-	        if ( mysql_num_rows($result) > 0)
-	        {
-		        $remainingUsers = '';
-		        while ( ($res = mysql_fetch_array($result)))
-		        {
+
+					if ( is_null($thisRecip[3]))
+					{
+						$errormsg .= dropbox_lang("mailingFileNotRegistered");
+					}
+					else
+					{
+						$students[] = $thisRecip[0];
+					}
+					$errormsg .= '<br>';
+
+	            }
+			}
+
+			// find student course members not among the recipients
+
+			$course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
+			$sql = "SELECT u.lastname, u.firstname
+					FROM $course_user cu
+					LEFT JOIN  `".$_configuration['main_database']."`.`user` u
+					ON cu.user_id = u.user_id AND cu.course_code = '".$_course['sysCode']."'
+					WHERE cu.status = 5
+					AND u.user_id NOT IN ('" . implode("', '" , $students) . "')";
+	        $result = Database::query($sql,__FILE__,__LINE__);
+
+	        if ( mysql_num_rows($result) > 0)
+	        {
+		        $remainingUsers = '';
+		        while ( ($res = mysql_fetch_array($result)))
+		        {
 					$remainingUsers .= ', ' . htmlspecialchars(api_get_person_name($res[1], $res[0]), ENT_QUOTES, $charset);
-		        }
-		        $errormsg .= '<br />' . dropbox_lang("mailingNothingFor") . api_substr($remainingUsers, 1) . '.<br />';
-	        }
-
-			if ( isset( $_GET['mailingSend']))
-			{
-				chdir(dropbox_cnf("sysPath"));
-				$zipFile->extract(PCLZIP_OPT_REMOVE_ALL_PATH);
-
-				$mailingPseudoId = dropbox_cnf("mailingIdBase") + $mailing_item->id;
-
-				foreach( $goodFiles as $thisFile => $thisRecip)
-				{
-		            if ( is_string($thisRecip))  // remove problem file
-		            {
-			            @unlink(dropbox_cnf("sysPath") . '/' . $thisFile);
-		            }
-		            else
-		            {
-				        $newName = getLoginFromId( $_user['user_id']) . "_" . $thisFile . "_" . uniqid('');
-				        if ( rename(dropbox_cnf("sysPath") . '/' . $thisFile, dropbox_cnf("sysPath") . '/' . $newName))
-							new Dropbox_SentWork( $mailingPseudoId, $thisFile, $mailing_item->description, $mailing_item->author, $newName, $thisContent['size'], array($thisRecip[0]));
-		            }
-				}
-
-			    $sendDT = addslashes(date("Y-m-d H:i:s",time()));
-			    // set filesize to zero on send, to avoid 2nd send (see index.php)
-				$sql = "UPDATE ".dropbox_cnf("tbl_file")."
-						SET filesize = '0'
-						, upload_date = '".$sendDT."', last_upload_date = '".$sendDT."'
-						WHERE id='".addslashes($mailing_item->id)."'";
-				$result =Database::query($sql,__FILE__,__LINE__);
-			}
-			elseif ( $mailing_item->filesize != 0)
-			{
-		        $errormsg .= '<br>' . dropbox_lang("mailingNotYetSent") . '<br>';
-			}
-        }
-    }
-    else
-    {
-        $error = TRUE; $errormsg .= dropbox_lang("mailingWrongZipfile");
-    }
-
-
-    /**
-     * ========================================
-     * EXAMINE OR SEND MAILING RESULTMESSAGE
-     * ========================================
-     */
-    if ( $error)
-    {
-        ?>
-		<b><font color="#FF0000"><?php echo $errormsg?></font></b><br><br>
-		<a href="index.php<?php echo "?origin=$origin"; ?>"><?php echo dropbox_lang("backList")?></a><br>
-		<?php
-    }
-
-    else
-    {
-        ?>
-		<?php echo $errormsg?><br><br>
-		<a href="index.php<?php echo "?origin=$origin"; ?>"><?php echo dropbox_lang("backList")?></a><br>
-		<?php
-    }
-
-
-
-}
-
-
-/**
- * =============================================
- * DELETE RECEIVED OR SENT FILES - EDIT FEEDBACK  // RH: Feedback
- * =============================================
- * - DELETE ALL RECEIVED FILES
- * - DELETE 1 RECEIVED FILE
- * - DELETE ALL SENT FILES
- * - DELETE 1 SENT FILE
- * - EDIT FEEDBACK                                // RH: Feedback
- */
-if ( isset( $_GET['deleteReceived']) || isset( $_GET['deleteSent'])
-         || isset( $_GET['showFeedback']) || isset( $_GET['editFeedback']))  // RH: Feedback
-{
-	if ( $_GET['mailing'])  // RH: Mailing
-	{
-		getUserOwningThisMailing($_GET['mailing'], $_user['user_id'], '408');  // RH or die
-		$dropbox_person = new Dropbox_Person( $_GET['mailing'], $is_courseAdmin, $is_courseTutor);
-	}
-	else
-	{
-	    $dropbox_person = new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
-    }
-
-	// RH: these two are needed, I think
-
-	if ( isset($_SESSION["sentOrder"]))
-	{
-		$dropbox_person->orderSentWork ($_SESSION["sentOrder"]);
-	}
-	if ( isset($_SESSION["receivedOrder"]))
-	{
-		$dropbox_person->orderReceivedWork ($_SESSION["receivedOrder"]);
-	}
-
-	/*if (! $dropbox_person->isCourseAdmin || ! $dropbox_person->isCourseTutor) {
-	    die(dropbox_lang("generalError")." (code 408)");
-	}*/
-
-	$tellUser = dropbox_lang("fileDeleted");  // RH: Feedback
-
-    if ( isset( $_GET['deleteReceived']))
-    {
-        if ( $_GET["deleteReceived"] == "all")
-        {
-            $dropbox_person->deleteAllReceivedWork( );
-        }elseif ( is_numeric( $_GET["deleteReceived"]))
-        {
-            $dropbox_person->deleteReceivedWork( $_GET['deleteReceived']);
-        }
-        else
-        {
-            die(dropbox_lang("generalError")." (code 409)");
-        }
-    }
-    elseif ( isset( $_GET['deleteSent']))  // RH: Feedback
-    {
-        if ( $_GET["deleteSent"] == "all")
-        {
-            $dropbox_person->deleteAllSentWork( );
-        }elseif ( is_numeric( $_GET["deleteSent"]))
-        {
-            $dropbox_person->deleteSentWork( $_GET['deleteSent']);
-        }
-        else
-        {
-            die(dropbox_lang("generalError")." (code 410)");
-        }
-    }
-    elseif ( isset( $_GET['showFeedback']))  // RH: Feedback
-    {
-		$w = new Dropbox_SentWork($id = $_GET['showFeedback']);
-
-		if ($w->uploader_id != $_user['user_id'])
-		    getUserOwningThisMailing($w->uploader_id, $_user['user_id'], '411');  // RH or die
-
-    	foreach( $w -> recipients as $r) if (($fb = $r["feedback"]))
-    	{
-            $fbarray [$r["feedback_date"].$r["name"]]=
-                $r["name"] . ' ' . dropbox_lang("sentOn", "noDLTT") .
-                ' ' . $r["feedback_date"] . ":\n" . $fb;
-    	}
-
-    	if ($fbarray)
-    	{
-        	krsort($fbarray);
-            echo '<textarea class="dropbox_feedbacks">',
-                    htmlspecialchars(implode("\n\n", $fbarray),ENT_QUOTES,$charset), '</textarea>', "\n";
-        }
-        else
-        {
-            echo '<textarea class="dropbox_feedbacks">&nbsp;</textarea>', "\n";
-        }
-
-        $tellUser = dropbox_lang("showFeedback");
-    }
-    else  // if ( isset( $_GET['editFeedback']))  // RH: Feedback
-    {
-        $id = $_GET['editFeedback']; $found = false;
-		foreach($dropbox_person->receivedWork as $w) {
-			if ($w->id == $id) {
-			   $found = true; break;
-			}
-		}
-		if (! $found) die(dropbox_lang("generalError")." (code 415)");
-
-        echo '<form method="post" action="index.php">', "\n",
-            '<input type="hidden" name="feedbackid" value="',
-                $id, '"/>', "\n",
-            '<textarea name="feedbacktext" class="dropbox_feedbacks">',
-                htmlspecialchars($w->feedback,ENT_QUOTES,$charset), '</textarea>', "<br>\n",
-            '<input type="submit" name="feedbacksubmit" value="', dropbox_lang("ok", "noDLTT"), '"/>', "\n",
-            '</form>', "\n";
-        $tellUser = dropbox_lang("giveFeedback");
-    }
-
-    /**
-     * ==============================================
-     * RESULTMESSAGE FOR DELETE FILE OR EDIT FEEDBACK  // RH: Feedback
-     * ==============================================
-     */
-    $return_message=dropbox_lang("backList");
-}
-?>
+		        }
+		        $errormsg .= '<br />' . dropbox_lang("mailingNothingFor") . api_substr($remainingUsers, 1) . '.<br />';
+	        }
+
+			if ( isset( $_GET['mailingSend']))
+			{
+				chdir(dropbox_cnf("sysPath"));
+				$zipFile->extract(PCLZIP_OPT_REMOVE_ALL_PATH);
+
+				$mailingPseudoId = dropbox_cnf("mailingIdBase") + $mailing_item->id;
+
+				foreach( $goodFiles as $thisFile => $thisRecip)
+				{
+		            if ( is_string($thisRecip))  // remove problem file
+		            {
+			            @unlink(dropbox_cnf("sysPath") . '/' . $thisFile);
+		            }
+		            else
+		            {
+				        $newName = getLoginFromId( $_user['user_id']) . "_" . $thisFile . "_" . uniqid('');
+				        if ( rename(dropbox_cnf("sysPath") . '/' . $thisFile, dropbox_cnf("sysPath") . '/' . $newName))
+							new Dropbox_SentWork( $mailingPseudoId, $thisFile, $mailing_item->description, $mailing_item->author, $newName, $thisContent['size'], array($thisRecip[0]));
+		            }
+				}
+
+			    $sendDT = addslashes(date("Y-m-d H:i:s",time()));
+			    // set filesize to zero on send, to avoid 2nd send (see index.php)
+				$sql = "UPDATE ".dropbox_cnf("tbl_file")."
+						SET filesize = '0'
+						, upload_date = '".$sendDT."', last_upload_date = '".$sendDT."'
+						WHERE id='".addslashes($mailing_item->id)."'";
+				$result =Database::query($sql,__FILE__,__LINE__);
+			}
+			elseif ( $mailing_item->filesize != 0)
+			{
+		        $errormsg .= '<br>' . dropbox_lang("mailingNotYetSent") . '<br>';
+			}
+        }
+    }
+    else
+    {
+        $error = TRUE; $errormsg .= dropbox_lang("mailingWrongZipfile");
+    }
+
+
+    /**
+     * ========================================
+     * EXAMINE OR SEND MAILING RESULTMESSAGE
+     * ========================================
+     */
+    if ( $error)
+    {
+        ?>
+		<b><font color="#FF0000"><?php echo $errormsg?></font></b><br><br>
+		<a href="index.php<?php echo "?origin=$origin"; ?>"><?php echo dropbox_lang("backList")?></a><br>
+		<?php
+    }
+
+    else
+    {
+        ?>
+		<?php echo $errormsg?><br><br>
+		<a href="index.php<?php echo "?origin=$origin"; ?>"><?php echo dropbox_lang("backList")?></a><br>
+		<?php
+    }
+
+
+
+}
+
+
+/**
+ * =============================================
+ * DELETE RECEIVED OR SENT FILES - EDIT FEEDBACK  // RH: Feedback
+ * =============================================
+ * - DELETE ALL RECEIVED FILES
+ * - DELETE 1 RECEIVED FILE
+ * - DELETE ALL SENT FILES
+ * - DELETE 1 SENT FILE
+ * - EDIT FEEDBACK                                // RH: Feedback
+ */
+if ( isset( $_GET['deleteReceived']) || isset( $_GET['deleteSent'])
+         || isset( $_GET['showFeedback']) || isset( $_GET['editFeedback']))  // RH: Feedback
+{
+	if ( $_GET['mailing'])  // RH: Mailing
+	{
+		getUserOwningThisMailing($_GET['mailing'], $_user['user_id'], '408');  // RH or die
+		$dropbox_person = new Dropbox_Person( $_GET['mailing'], $is_courseAdmin, $is_courseTutor);
+	}
+	else
+	{
+	    $dropbox_person = new Dropbox_Person( $_user['user_id'], $is_courseAdmin, $is_courseTutor);
+    }
+
+	// RH: these two are needed, I think
+
+	if ( isset($_SESSION["sentOrder"]))
+	{
+		$dropbox_person->orderSentWork ($_SESSION["sentOrder"]);
+	}
+	if ( isset($_SESSION["receivedOrder"]))
+	{
+		$dropbox_person->orderReceivedWork ($_SESSION["receivedOrder"]);
+	}
+
+	/*if (! $dropbox_person->isCourseAdmin || ! $dropbox_person->isCourseTutor) {
+	    die(dropbox_lang("generalError")." (code 408)");
+	}*/
+
+	$tellUser = dropbox_lang("fileDeleted");  // RH: Feedback
+
+    if ( isset( $_GET['deleteReceived']))
+    {
+        if ( $_GET["deleteReceived"] == "all")
+        {
+            $dropbox_person->deleteAllReceivedWork( );
+        }elseif ( is_numeric( $_GET["deleteReceived"]))
+        {
+            $dropbox_person->deleteReceivedWork( $_GET['deleteReceived']);
+        }
+        else
+        {
+            die(dropbox_lang("generalError")." (code 409)");
+        }
+    }
+    elseif ( isset( $_GET['deleteSent']))  // RH: Feedback
+    {
+        if ( $_GET["deleteSent"] == "all")
+        {
+            $dropbox_person->deleteAllSentWork( );
+        }elseif ( is_numeric( $_GET["deleteSent"]))
+        {
+            $dropbox_person->deleteSentWork( $_GET['deleteSent']);
+        }
+        else
+        {
+            die(dropbox_lang("generalError")." (code 410)");
+        }
+    }
+    elseif ( isset( $_GET['showFeedback']))  // RH: Feedback
+    {
+		$w = new Dropbox_SentWork($id = $_GET['showFeedback']);
+
+		if ($w->uploader_id != $_user['user_id'])
+		    getUserOwningThisMailing($w->uploader_id, $_user['user_id'], '411');  // RH or die
+
+    	foreach( $w -> recipients as $r) if (($fb = $r["feedback"]))
+    	{
+            $fbarray [$r["feedback_date"].$r["name"]]=
+                $r["name"] . ' ' . dropbox_lang("sentOn", "noDLTT") .
+                ' ' . $r["feedback_date"] . ":\n" . $fb;
+    	}
+
+    	if ($fbarray)
+    	{
+        	krsort($fbarray);
+            echo '<textarea class="dropbox_feedbacks">',
+                    htmlspecialchars(implode("\n\n", $fbarray),ENT_QUOTES,$charset), '</textarea>', "\n";
+        }
+        else
+        {
+            echo '<textarea class="dropbox_feedbacks">&nbsp;</textarea>', "\n";
+        }
+
+        $tellUser = dropbox_lang("showFeedback");
+    }
+    else  // if ( isset( $_GET['editFeedback']))  // RH: Feedback
+    {
+        $id = $_GET['editFeedback']; $found = false;
+		foreach($dropbox_person->receivedWork as $w) {
+			if ($w->id == $id) {
+			   $found = true; break;
+			}
+		}
+		if (! $found) die(dropbox_lang("generalError")." (code 415)");
+
+        echo '<form method="post" action="index.php">', "\n",
+            '<input type="hidden" name="feedbackid" value="',
+                $id, '"/>', "\n",
+            '<textarea name="feedbacktext" class="dropbox_feedbacks">',
+                htmlspecialchars($w->feedback,ENT_QUOTES,$charset), '</textarea>', "<br>\n",
+            '<input type="submit" name="feedbacksubmit" value="', dropbox_lang("ok", "noDLTT"), '"/>', "\n",
+            '</form>', "\n";
+        $tellUser = dropbox_lang("giveFeedback");
+    }
+
+    /**
+     * ==============================================
+     * RESULTMESSAGE FOR DELETE FILE OR EDIT FEEDBACK  // RH: Feedback
+     * ==============================================
+     */
+    $return_message=dropbox_lang("backList");
+}
+?>

+ 5 - 5
main/dropbox/dropbox_zipdownload.inc.php

@@ -1,6 +1,6 @@
-<?php //$id: $
-/* For licensing terms, see /dokeos_license.txt */
-
-// the file that contains all the initialisation stuff (and includes all the configuration stuff)
-require_once( "dropbox_init.inc.php");
+<?php //$id: $
+/* For licensing terms, see /dokeos_license.txt */
+
+// the file that contains all the initialisation stuff (and includes all the configuration stuff)
+require_once( "dropbox_init.inc.php");
 ?>

+ 250 - 250
main/exercice/addlimits.php

@@ -1,252 +1,252 @@
-<?php
-/*
-    DOKEOS - elearning and course management software
-
-    For a full list of contributors, see documentation/credits.html
-
-    This program is free software; you can redistribute it and/or
-    modify it under the terms of the GNU General Public License
-    as published by the Free Software Foundation; either version 2
-    of the License, or (at your option) any later version.
-    See "documentation/licence.html" more details.
-
-    Contact:
-		Dokeos
-		Rue des Palais 44 Paleizenstraat
-		B-1030 Brussels - Belgium
-		Tel. +32 (2) 211 34 56
-*/
-
-
-/**
-*	Adding limits
-*	@package dokeos.exercise
-* 	@author
-* 	@version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $
-*/
-/*
------------------------------------------------------------
-	including the global file
------------------------------------------------------------
-*/
-include('../inc/global.inc.php');
-
-/*
------------------------------------------------------------
-	Including necessary files
------------------------------------------------------------
-*/
-include('exercise.class.php');
-include('question.class.php');
-include('answer.class.php');
-include_once(api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-
-/*
------------------------------------------------------------
-	Answer types
------------------------------------------------------------
-*/
-define('UNIQUE_ANSWER',	1);
-define('MULTIPLE_ANSWER',	2);
-define('FILL_IN_BLANKS',	3);
-define('MATCHING',		4);
-define('FREE_ANSWER', 5);
-
-/*
------------------------------------------------------------
-	Language
------------------------------------------------------------
-*/
-// name of the language file that needs to be included
-$language_file='exercice';
-
-/*
------------------------------------------------------------
-	section (for the tabs)
------------------------------------------------------------
-*/
-$this_section=SECTION_COURSES;
-
-api_protect_course_script();
-
-/*
------------------------------------------------------------
-	Table definitions
-	@todo: use the Database :: get_course_table functions
------------------------------------------------------------
-*/
-$TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
-$TBL_EXERCICES         = Database::get_course_table(TABLE_QUIZ_TEST);
-$TBL_QUESTIONS         = Database::get_course_table(TABLE_QUIZ_QUESTION);
-$TBL_REPONSES          = Database::get_course_table('quiz_answer');
-$main_user_table = Database :: get_main_table(TABLE_MAIN_USER);
-$main_course_user_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-$TBL_TRACK_EXERCICES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-$TBL_TRACK_ATTEMPT		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-
-$dsp_percent = false;
-$debug=0;
-if($debug>0)
-{
-	echo str_repeat('&nbsp;',0).'Entered exercise_result.php'."<br />\n";var_dump($_POST);
-}
-// general parameters passed via POST/GET
-if ( empty ( $origin ) )
-{
-    $origin = $_REQUEST['origin'];
-}
-if ( empty ( $learnpath_id ) )
-{
-    $learnpath_id       = $_REQUEST['learnpath_id'];
-}
-if ( empty ( $learnpath_item_id ) )
-{
-    $learnpath_item_id  = $_REQUEST['learnpath_item_id'];
-}
-if ( empty ( $formSent ) )
-{
-    $formSent= $_REQUEST['formSent'];
-}
-if ( empty ( $exerciseResult ) )
-{
-    $exerciseResult = $_SESSION['exerciseResult'];
-}
-if ( empty ( $questionId ) )
-{
-    $questionId = $_REQUEST['questionId'];
-}
-if ( empty ( $choice ) ) {
-    $choice = $_REQUEST['choice'];
-}
-if ( empty ( $questionNum ) )
-{
-    $questionNum    = $_REQUEST['questionNum'];
-}
-if ( empty ( $nbrQuestions ) )
-{
-    $nbrQuestions   = $_REQUEST['nbrQuestions'];
-}
-if ( empty ( $questionList ) )
-{
-    $questionList = $_SESSION['questionList'];
-}
-if ( empty ( $objExercise ) )
-{
-    $objExercise = $_SESSION['objExercise'];
-}
-$exercise_id = intval($_GET['exercise_id']);
-$is_allowedToEdit=$is_courseAdmin;
-
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+<?php
+/*
+    DOKEOS - elearning and course management software
+
+    For a full list of contributors, see documentation/credits.html
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+    See "documentation/licence.html" more details.
+
+    Contact:
+		Dokeos
+		Rue des Palais 44 Paleizenstraat
+		B-1030 Brussels - Belgium
+		Tel. +32 (2) 211 34 56
+*/
+
+
+/**
+*	Adding limits
+*	@package dokeos.exercise
+* 	@author
+* 	@version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $
+*/
+/*
+-----------------------------------------------------------
+	including the global file
+-----------------------------------------------------------
+*/
+include('../inc/global.inc.php');
+
+/*
+-----------------------------------------------------------
+	Including necessary files
+-----------------------------------------------------------
+*/
+include('exercise.class.php');
+include('question.class.php');
+include('answer.class.php');
+include_once(api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+
+/*
+-----------------------------------------------------------
+	Answer types
+-----------------------------------------------------------
+*/
+define('UNIQUE_ANSWER',	1);
+define('MULTIPLE_ANSWER',	2);
+define('FILL_IN_BLANKS',	3);
+define('MATCHING',		4);
+define('FREE_ANSWER', 5);
+
+/*
+-----------------------------------------------------------
+	Language
+-----------------------------------------------------------
+*/
+// name of the language file that needs to be included
+$language_file='exercice';
+
+/*
+-----------------------------------------------------------
+	section (for the tabs)
+-----------------------------------------------------------
+*/
+$this_section=SECTION_COURSES;
+
+api_protect_course_script();
+
+/*
+-----------------------------------------------------------
+	Table definitions
+	@todo: use the Database :: get_course_table functions
+-----------------------------------------------------------
+*/
+$TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
+$TBL_EXERCICES         = Database::get_course_table(TABLE_QUIZ_TEST);
+$TBL_QUESTIONS         = Database::get_course_table(TABLE_QUIZ_QUESTION);
+$TBL_REPONSES          = Database::get_course_table('quiz_answer');
+$main_user_table = Database :: get_main_table(TABLE_MAIN_USER);
+$main_course_user_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+$TBL_TRACK_EXERCICES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+$TBL_TRACK_ATTEMPT		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+
+$dsp_percent = false;
+$debug=0;
+if($debug>0)
+{
+	echo str_repeat('&nbsp;',0).'Entered exercise_result.php'."<br />\n";var_dump($_POST);
+}
+// general parameters passed via POST/GET
+if ( empty ( $origin ) )
+{
+    $origin = $_REQUEST['origin'];
+}
+if ( empty ( $learnpath_id ) )
+{
+    $learnpath_id       = $_REQUEST['learnpath_id'];
+}
+if ( empty ( $learnpath_item_id ) )
+{
+    $learnpath_item_id  = $_REQUEST['learnpath_item_id'];
+}
+if ( empty ( $formSent ) )
+{
+    $formSent= $_REQUEST['formSent'];
+}
+if ( empty ( $exerciseResult ) )
+{
+    $exerciseResult = $_SESSION['exerciseResult'];
+}
+if ( empty ( $questionId ) )
+{
+    $questionId = $_REQUEST['questionId'];
+}
+if ( empty ( $choice ) ) {
+    $choice = $_REQUEST['choice'];
+}
+if ( empty ( $questionNum ) )
+{
+    $questionNum    = $_REQUEST['questionNum'];
+}
+if ( empty ( $nbrQuestions ) )
+{
+    $nbrQuestions   = $_REQUEST['nbrQuestions'];
+}
+if ( empty ( $questionList ) )
+{
+    $questionList = $_SESSION['questionList'];
+}
+if ( empty ( $objExercise ) )
+{
+    $objExercise = $_SESSION['objExercise'];
+}
+$exercise_id = intval($_GET['exercise_id']);
+$is_allowedToEdit=$is_courseAdmin;
+
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.Security::remove_XSS($_SESSION['gradebook_dest']),
-			'name' => get_lang('Gradebook')
-		);
-}
-$nameTools=get_lang('Exercice');
-$interbreadcrumb[]=array("url" => "exercice.php","name" => get_lang('Exercices'));
-Display::display_header($nameTools,"Exercise");
-
-/*
------------------------------------------------------------
-	Action handling
------------------------------------------------------------
-*/
-include('../inc/global.inc.php');
-if (isset($_POST['ok']))
-{
-	$message = get_lang('TestLimitsAdded');
-	Display::display_normal_message($message);
-}
-?>
-  <script type="text/javascript">
-  function selectlimited()
-  {
-  	document.getElementById('limited').checked="checked";
-  }
-   function selectattempts()
-  {
-  	document.getElementById('attemptlimited').checked="checked";
-  }
-  </script>
-  <h3><?php  echo get_lang('AddLimits'); ?></h3>
-<br>
-<form action="addlimits.php" name="frmlimit" method="post">
-<h4>
-Time :
-</h4>
-<input type="hidden" name="exe_id" value="<?php echo $exercise_id; ?>" />
-<input type="radio" name="limit" checked="checked" value="0" id="unlimit"><?php echo get_lang('Unlimited'); ?>
-<br>
-<input type="radio" name="limit" value="1" id="limited"><?php echo get_lang('LimitedTime'); ?>
-<select name="minutes" onfocus="selectlimited();" >
-  <option selected="selected">1</option>
-  <option>2</option>
-  <option>3</option>
-  <option>4</option>
-  <option>5</option>
-  <option>6</option>
-  <option>7</option>
-  <option>8</option>
-  <option>9</option>
-  <option>10</option>
-  <option>15</option>
-  <option>20</option>
-  <option>25</option>
-  <option>30</option>
-  <option>40</option>
-  <option>50</option>
-  <option>60</option>
-</select><?php echo get_lang('Minutes'); ?>.
-<h4>
-<?php echo get_lang('Attempts'); ?>:
-</h4>
-<input type="radio" name="attempt" checked="checked" value="0" id="attemptunlimited"><?php echo get_lang('Unlimited'); ?>
-<br>
-<input type="radio" name="attempt" value="1" id="attemptlimited"><?php echo get_lang('LimitedAttempts'); ?>
-<select name="attempts" onfocus="selectattempts();">
-  <option selected="selected">1</option>
-  <option>2</option>
-  <option>3</option>
-  <option>4</option>
-  <option>5</option>
-  <option>6</option>
-  <option>7</option>
-  <option>8</option>
-  <option>9</option>
-  <option>10</option>
-  </select><?php echo get_lang('Times'); ?>.
-
-<br> <br>
-<input type="submit" name="ok" value="<?php echo get_lang('Ok'); ?>">
-</form>
-<?php
-/**
- * @todo shouldn't this be moved to the part above (around line 111: action handling)
- */
-if (isset($_POST['ok'])) {
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.Security::remove_XSS($_SESSION['gradebook_dest']),
+			'name' => get_lang('Gradebook')
+		);
+}
+$nameTools=get_lang('Exercice');
+$interbreadcrumb[]=array("url" => "exercice.php","name" => get_lang('Exercices'));
+Display::display_header($nameTools,"Exercise");
+
+/*
+-----------------------------------------------------------
+	Action handling
+-----------------------------------------------------------
+*/
+include('../inc/global.inc.php');
+if (isset($_POST['ok']))
+{
+	$message = get_lang('TestLimitsAdded');
+	Display::display_normal_message($message);
+}
+?>
+  <script type="text/javascript">
+  function selectlimited()
+  {
+  	document.getElementById('limited').checked="checked";
+  }
+   function selectattempts()
+  {
+  	document.getElementById('attemptlimited').checked="checked";
+  }
+  </script>
+  <h3><?php  echo get_lang('AddLimits'); ?></h3>
+<br>
+<form action="addlimits.php" name="frmlimit" method="post">
+<h4>
+Time :
+</h4>
+<input type="hidden" name="exe_id" value="<?php echo $exercise_id; ?>" />
+<input type="radio" name="limit" checked="checked" value="0" id="unlimit"><?php echo get_lang('Unlimited'); ?>
+<br>
+<input type="radio" name="limit" value="1" id="limited"><?php echo get_lang('LimitedTime'); ?>
+<select name="minutes" onfocus="selectlimited();" >
+  <option selected="selected">1</option>
+  <option>2</option>
+  <option>3</option>
+  <option>4</option>
+  <option>5</option>
+  <option>6</option>
+  <option>7</option>
+  <option>8</option>
+  <option>9</option>
+  <option>10</option>
+  <option>15</option>
+  <option>20</option>
+  <option>25</option>
+  <option>30</option>
+  <option>40</option>
+  <option>50</option>
+  <option>60</option>
+</select><?php echo get_lang('Minutes'); ?>.
+<h4>
+<?php echo get_lang('Attempts'); ?>:
+</h4>
+<input type="radio" name="attempt" checked="checked" value="0" id="attemptunlimited"><?php echo get_lang('Unlimited'); ?>
+<br>
+<input type="radio" name="attempt" value="1" id="attemptlimited"><?php echo get_lang('LimitedAttempts'); ?>
+<select name="attempts" onfocus="selectattempts();">
+  <option selected="selected">1</option>
+  <option>2</option>
+  <option>3</option>
+  <option>4</option>
+  <option>5</option>
+  <option>6</option>
+  <option>7</option>
+  <option>8</option>
+  <option>9</option>
+  <option>10</option>
+  </select><?php echo get_lang('Times'); ?>.
+
+<br> <br>
+<input type="submit" name="ok" value="<?php echo get_lang('Ok'); ?>">
+</form>
+<?php
+/**
+ * @todo shouldn't this be moved to the part above (around line 111: action handling)
+ */
+if (isset($_POST['ok'])) {
 	$exercise_id = Database::escape_string($_POST['exe_id']);
-	if ($_POST['limit']==1) {
-		$minutes = Database::escape_string($_POST['minutes']);
-		$query = "UPDATE ".$TBL_EXERCICES." SET ques_time_limit= $minutes where id= $exercise_id";
-		Database::query($query,__FILE__,__LINE__);
-	} else {
-		$query = "UPDATE ".$TBL_EXERCICES." SET ques_time_limit= 0 WHERE id= $exercise_id";
-		Database::query($query,__FILE__,__LINE__);
-	}
-
-	if ($_POST['attempt']==1) {
-		$attempts = Database::escape_string($_POST['attempts']);
-		$query = "UPDATE ".$TBL_EXERCICES." SET num_attempts = $attempts WHERE id= $exercise_id";
-		Database::query($query,__FILE__,__LINE__);
-	} else {
-		$query = "UPDATE ".$TBL_EXERCICES." SET num_attempts = 0 WHERE id= $exercise_id";
-		Database::query($query,__FILE__,__LINE__);
-	}
-}
-?>
-
+	if ($_POST['limit']==1) {
+		$minutes = Database::escape_string($_POST['minutes']);
+		$query = "UPDATE ".$TBL_EXERCICES." SET ques_time_limit= $minutes where id= $exercise_id";
+		Database::query($query,__FILE__,__LINE__);
+	} else {
+		$query = "UPDATE ".$TBL_EXERCICES." SET ques_time_limit= 0 WHERE id= $exercise_id";
+		Database::query($query,__FILE__,__LINE__);
+	}
+
+	if ($_POST['attempt']==1) {
+		$attempts = Database::escape_string($_POST['attempts']);
+		$query = "UPDATE ".$TBL_EXERCICES." SET num_attempts = $attempts WHERE id= $exercise_id";
+		Database::query($query,__FILE__,__LINE__);
+	} else {
+		$query = "UPDATE ".$TBL_EXERCICES." SET num_attempts = 0 WHERE id= $exercise_id";
+		Database::query($query,__FILE__,__LINE__);
+	}
+}
+?>
+

+ 966 - 966
main/exercice/exercise_show.php

@@ -1,1104 +1,1104 @@
-<?php //$id: $
-/* For licensing terms, see /dokeos_license.txt */
-/**
-*
-*	@package dokeos.exercise
-* 	@author Julio Montoya Armas Added switchable fill in blank option added
-* 	@version $Id: exercise_show.php 22256 2009-07-20 17:40:20Z ivantcholakov $
-*
-* 	@todo remove the debug code and use the general debug library
-* 	@todo use the Database:: functions
-* 	@todo small letters for table variables
-*/
-
-// name of the language file that needs to be included
-$language_file=array('exercice','tracking');
-
-// including the global dokeos file
-include('../inc/global.inc.php');
-include('../inc/lib/course.lib.php');
-// including additional libraries
-include_once('exercise.class.php');
-include_once('question.class.php'); //also defines answer type constants
-include_once('answer.class.php');
-include_once(api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-
-if ( empty ( $origin ) ) {
-    $origin = $_REQUEST['origin'];
-}
-
-if ($origin == 'learnpath')
-	api_protect_course_script();
+<?php //$id: $
+/* For licensing terms, see /dokeos_license.txt */
+/**
+*
+*	@package dokeos.exercise
+* 	@author Julio Montoya Armas Added switchable fill in blank option added
+* 	@version $Id: exercise_show.php 22256 2009-07-20 17:40:20Z ivantcholakov $
+*
+* 	@todo remove the debug code and use the general debug library
+* 	@todo use the Database:: functions
+* 	@todo small letters for table variables
+*/
+
+// name of the language file that needs to be included
+$language_file=array('exercice','tracking');
+
+// including the global dokeos file
+include('../inc/global.inc.php');
+include('../inc/lib/course.lib.php');
+// including additional libraries
+include_once('exercise.class.php');
+include_once('question.class.php'); //also defines answer type constants
+include_once('answer.class.php');
+include_once(api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+
+if ( empty ( $origin ) ) {
+    $origin = $_REQUEST['origin'];
+}
+
+if ($origin == 'learnpath')
+	api_protect_course_script();
 else
-	api_protect_course_script(true);
-
-// Database table definitions
-$TBL_EXERCICE_QUESTION 	= Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
-$TBL_EXERCICES         	= Database::get_course_table(TABLE_QUIZ_TEST);
-$TBL_QUESTIONS         	= Database::get_course_table(TABLE_QUIZ_QUESTION);
-$TBL_REPONSES          	= Database::get_course_table(TABLE_QUIZ_ANSWER);
-$main_user_table 		= Database :: get_main_table(TABLE_MAIN_USER);
-$main_course_user_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-$TBL_TRACK_EXERCICES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-$TBL_TRACK_ATTEMPT		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-
-$dsp_percent = false;
-$debug=0;
-
-if($debug>0) {
-	echo str_repeat('&nbsp;',0).'Entered exercise_result.php'."<br />\n";var_dump($_POST);
-}
-// general parameters passed via POST/GET
-
-if ( empty ( $learnpath_id ) ) {
-    $learnpath_id       = $_REQUEST['learnpath_id'];
-}
-if ( empty ( $learnpath_item_id ) ) {
-    $learnpath_item_id  = $_REQUEST['learnpath_item_id'];
-}
-if ( empty ( $formSent ) ) {
-    $formSent= $_REQUEST['formSent'];
-}
-if ( empty ( $exerciseResult ) ) {
-    $exerciseResult = $_SESSION['exerciseResult'];
-}
-if ( empty ( $questionId ) ) {
-    $questionId = $_REQUEST['questionId'];
-}
-if ( empty ( $choice ) ) {
-    $choice = $_REQUEST['choice'];
-}
-if ( empty ( $questionNum ) ) {
-    $questionNum    = $_REQUEST['questionNum'];
-}
-if ( empty ( $nbrQuestions ) ) {
-    $nbrQuestions   = $_REQUEST['nbrQuestions'];
-}
-if ( empty ( $questionList ) ) {
-    $questionList = $_SESSION['questionList'];
-}
-if ( empty ( $objExercise ) ) {
-    $objExercise = $_SESSION['objExercise'];
-}
-if ( empty ( $exeId ) ) {
-    $exeId = $_REQUEST['id'];
-}
-
-if ( empty ( $action ) ) {
-    $action = $_GET['action'];
-}
-
-$is_allowedToEdit=api_is_allowed_to_edit() || $is_courseTutor;
-$nameTools=get_lang('CorrectTest');
-
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+	api_protect_course_script(true);
+
+// Database table definitions
+$TBL_EXERCICE_QUESTION 	= Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
+$TBL_EXERCICES         	= Database::get_course_table(TABLE_QUIZ_TEST);
+$TBL_QUESTIONS         	= Database::get_course_table(TABLE_QUIZ_QUESTION);
+$TBL_REPONSES          	= Database::get_course_table(TABLE_QUIZ_ANSWER);
+$main_user_table 		= Database :: get_main_table(TABLE_MAIN_USER);
+$main_course_user_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+$TBL_TRACK_EXERCICES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+$TBL_TRACK_ATTEMPT		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+
+$dsp_percent = false;
+$debug=0;
+
+if($debug>0) {
+	echo str_repeat('&nbsp;',0).'Entered exercise_result.php'."<br />\n";var_dump($_POST);
+}
+// general parameters passed via POST/GET
+
+if ( empty ( $learnpath_id ) ) {
+    $learnpath_id       = $_REQUEST['learnpath_id'];
+}
+if ( empty ( $learnpath_item_id ) ) {
+    $learnpath_item_id  = $_REQUEST['learnpath_item_id'];
+}
+if ( empty ( $formSent ) ) {
+    $formSent= $_REQUEST['formSent'];
+}
+if ( empty ( $exerciseResult ) ) {
+    $exerciseResult = $_SESSION['exerciseResult'];
+}
+if ( empty ( $questionId ) ) {
+    $questionId = $_REQUEST['questionId'];
+}
+if ( empty ( $choice ) ) {
+    $choice = $_REQUEST['choice'];
+}
+if ( empty ( $questionNum ) ) {
+    $questionNum    = $_REQUEST['questionNum'];
+}
+if ( empty ( $nbrQuestions ) ) {
+    $nbrQuestions   = $_REQUEST['nbrQuestions'];
+}
+if ( empty ( $questionList ) ) {
+    $questionList = $_SESSION['questionList'];
+}
+if ( empty ( $objExercise ) ) {
+    $objExercise = $_SESSION['objExercise'];
+}
+if ( empty ( $exeId ) ) {
+    $exeId = $_REQUEST['id'];
+}
+
+if ( empty ( $action ) ) {
+    $action = $_GET['action'];
+}
+
+$is_allowedToEdit=api_is_allowed_to_edit() || $is_courseTutor;
+$nameTools=get_lang('CorrectTest');
+
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-$fromlink = '';
-if($origin=='user_course') {
-	$interbreadcrumb[] = array ("url" => "../user/user.php?cidReq=".Security::remove_XSS($_GET['course']), "name" => get_lang("Users"));
-	$interbreadcrumb[] = array("url" => "../mySpace/myStudents.php?student=".Security::remove_XSS($_GET['student'])."&course=".$_course['id']."&details=true&origin=".Security::remove_XSS($_GET['origin']) , "name" => get_lang("DetailsStudentInCourse"));
-} else if($origin=='tracking_course') {
-
-	//$interbreadcrumb[] = array ("url" => "../mySpace/index.php", "name" => get_lang('MySpace'));
- 	//$interbreadcrumb[] = array ("url" => "../mySpace/myStudents.php?student=".Security::remove_XSS($_GET['student']).'&details=true&origin='.$origin.'&course='.Security::remove_XSS($_GET['cidReq']), "name" => get_lang("DetailsStudentInCourse"));
- 	$interbreadcrumb[] = array ("url" => api_get_path(WEB_COURSE_PATH).$_course['directory'], 'name' => $_course['title']);
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
+$fromlink = '';
+if($origin=='user_course') {
+	$interbreadcrumb[] = array ("url" => "../user/user.php?cidReq=".Security::remove_XSS($_GET['course']), "name" => get_lang("Users"));
+	$interbreadcrumb[] = array("url" => "../mySpace/myStudents.php?student=".Security::remove_XSS($_GET['student'])."&course=".$_course['id']."&details=true&origin=".Security::remove_XSS($_GET['origin']) , "name" => get_lang("DetailsStudentInCourse"));
+} else if($origin=='tracking_course') {
+
+	//$interbreadcrumb[] = array ("url" => "../mySpace/index.php", "name" => get_lang('MySpace'));
+ 	//$interbreadcrumb[] = array ("url" => "../mySpace/myStudents.php?student=".Security::remove_XSS($_GET['student']).'&details=true&origin='.$origin.'&course='.Security::remove_XSS($_GET['cidReq']), "name" => get_lang("DetailsStudentInCourse"));
+ 	$interbreadcrumb[] = array ("url" => api_get_path(WEB_COURSE_PATH).$_course['directory'], 'name' => $_course['title']);
 	$interbreadcrumb[] = array ("url" => "../tracking/courseLog.php?cidReq=".$cidReq.'&studentlist=true&id_session='.$_SESSION['id_session'], "name" => get_lang("Tracking"));
-	$interbreadcrumb[] = array ("url" => "../mySpace/myStudents.php?student=".Security::remove_XSS($_GET['student']).'&details=true&origin='.$origin.'&course='.Security::remove_XSS($_GET['cidReq']), "name" => get_lang("DetailsStudentInCourse"));
-	$interbreadcrumb[] = array ("url" => "../mySpace/lp_tracking.php?action=stats&course=".$cidReq."&student_id=".Security::remove_XSS($_GET['student'])."&lp_id=".$_GET['my_lp_id']."&origin=".Security::remove_XSS($_GET['origin']) , "name" => get_lang("LearningPathDetails"));
-
-	$from_myspace = false;
-	if (isset ($_GET['from']) && $_GET['from'] == 'myspace') {
-		$fromlink = '&from=myspace';
-		$this_section = "session_my_space";
-	} else {
-		$this_section = SECTION_COURSES;
-	}
-
-} else if($origin=='student_progress') {
-	$interbreadcrumb[] = array ("url" => "../auth/my_progress.php?id_session".Security::remove_XSS($_GET['id_session'])."&course=".$_cid, "name" => get_lang('MyProgress'));
-	unset($_cid);
-} else {
-	$interbreadcrumb[]=array("url" => "exercice.php?gradebook=$gradebook","name" => get_lang('Exercices'));
-	$this_section=SECTION_COURSES;
-}
-
-
-if ($origin != 'learnpath') {
-	Display::display_header($nameTools,"Exercise");
-} else {
-	Display::display_reduced_header();
-}
-$emailId   = $_REQUEST['email'];
-$user_name = $_REQUEST['user'];
-$test 	   = $_REQUEST['test'];
-$dt	 	   = $_REQUEST['dt'];
-$marks 	   = $_REQUEST['res'];
-$id 	   = $_REQUEST['id'];
-
-$sql_fb_type='SELECT feedback_type FROM '.$TBL_EXERCICES.' as exercises, '.$TBL_TRACK_EXERCICES.' as track_exercises WHERE exercises.id=track_exercises.exe_exo_id AND track_exercises.exe_id="'.Database::escape_string($id).'"';
-$res_fb_type=Database::query($sql_fb_type,__FILE__,__LINE__);
-$row_fb_type=Database::fetch_row($res_fb_type);
+	$interbreadcrumb[] = array ("url" => "../mySpace/myStudents.php?student=".Security::remove_XSS($_GET['student']).'&details=true&origin='.$origin.'&course='.Security::remove_XSS($_GET['cidReq']), "name" => get_lang("DetailsStudentInCourse"));
+	$interbreadcrumb[] = array ("url" => "../mySpace/lp_tracking.php?action=stats&course=".$cidReq."&student_id=".Security::remove_XSS($_GET['student'])."&lp_id=".$_GET['my_lp_id']."&origin=".Security::remove_XSS($_GET['origin']) , "name" => get_lang("LearningPathDetails"));
+
+	$from_myspace = false;
+	if (isset ($_GET['from']) && $_GET['from'] == 'myspace') {
+		$fromlink = '&from=myspace';
+		$this_section = "session_my_space";
+	} else {
+		$this_section = SECTION_COURSES;
+	}
+
+} else if($origin=='student_progress') {
+	$interbreadcrumb[] = array ("url" => "../auth/my_progress.php?id_session".Security::remove_XSS($_GET['id_session'])."&course=".$_cid, "name" => get_lang('MyProgress'));
+	unset($_cid);
+} else {
+	$interbreadcrumb[]=array("url" => "exercice.php?gradebook=$gradebook","name" => get_lang('Exercices'));
+	$this_section=SECTION_COURSES;
+}
+
+
+if ($origin != 'learnpath') {
+	Display::display_header($nameTools,"Exercise");
+} else {
+	Display::display_reduced_header();
+}
+$emailId   = $_REQUEST['email'];
+$user_name = $_REQUEST['user'];
+$test 	   = $_REQUEST['test'];
+$dt	 	   = $_REQUEST['dt'];
+$marks 	   = $_REQUEST['res'];
+$id 	   = $_REQUEST['id'];
+
+$sql_fb_type='SELECT feedback_type FROM '.$TBL_EXERCICES.' as exercises, '.$TBL_TRACK_EXERCICES.' as track_exercises WHERE exercises.id=track_exercises.exe_exo_id AND track_exercises.exe_id="'.Database::escape_string($id).'"';
+$res_fb_type=Database::query($sql_fb_type,__FILE__,__LINE__);
+$row_fb_type=Database::fetch_row($res_fb_type);
 $feedback_type = $row_fb_type[0];
-
-?>
-<style type="text/css">
-<!--
-#comments {
-	position:absolute;
-	left:795px;
-	top:0px;
-	width:200px;
-	height:75px;
-	z-index:1;
-}
-
--->
-</style>
-<script language="javascript">
-function showfck(sid,marksid)
-{
-	document.getElementById(sid).style.display='block';
-	document.getElementById(marksid).style.display='block';
+
+?>
+<style type="text/css">
+<!--
+#comments {
+	position:absolute;
+	left:795px;
+	top:0px;
+	width:200px;
+	height:75px;
+	z-index:1;
+}
+
+-->
+</style>
+<script language="javascript">
+function showfck(sid,marksid)
+{
+	document.getElementById(sid).style.display='block';
+	document.getElementById(marksid).style.display='block';
 	var comment = 'feedback_'+sid;
-	document.getElementById(comment).style.display='none';
-}
-
-function getFCK(vals,marksid)
-{
-  var f=document.getElementById('myform');
-
-  var m_id = marksid.split(',');
-  for(var i=0;i<m_id.length;i++){
-  var oHidn = document.createElement("input");
-			oHidn.type = "hidden";
-			var selname = oHidn.name = "marks_"+m_id[i];
-			var selid = document.forms['marksform_'+m_id[i]].marks.selectedIndex;
-			oHidn.value = document.forms['marksform_'+m_id[i]].marks.options[selid].text;
-			f.appendChild(oHidn);
-	}
-
-	var ids = vals.split(',');
-	for(var k=0;k<ids.length;k++){
-			var oHidden = document.createElement("input");
-			oHidden.type = "hidden";
-			oHidden.name = "comments_"+ids[k];
-			oEditor = FCKeditorAPI.GetInstance(oHidden.name) ;
-			oHidden.value = oEditor.GetXHTML(true);
-			f.appendChild(oHidden);
-	}
-//f.submit();
-}
-</script>
-<?php
-
-/**
- * This function gets the comments of an exercise
- *
- * @param int $id
- * @param int $question_id
- * @return str the comment
- */
-function get_comments($id,$question_id)
-{
-	global $TBL_TRACK_ATTEMPT;
-	$sql = "SELECT teacher_comment FROM ".$TBL_TRACK_ATTEMPT." where exe_id='".Database::escape_string($id)."' and question_id = '".Database::escape_string($question_id)."' ORDER by question_id";
-	$sqlres = Database::query($sql, __FILE__, __LINE__);
-	$comm = Database::result($sqlres,0,"teacher_comment");
-	return $comm;
-}
-/**
- * Display the answers to a multiple choice question
- *
- * @param integer Answer type
- * @param integer Student choice
- * @param string  Textual answer
- * @param string  Comment on answer
- * @param string  Correct answer comment
- * @param integer Exercise ID
- * @param integer Question ID
+	document.getElementById(comment).style.display='none';
+}
+
+function getFCK(vals,marksid)
+{
+  var f=document.getElementById('myform');
+
+  var m_id = marksid.split(',');
+  for(var i=0;i<m_id.length;i++){
+  var oHidn = document.createElement("input");
+			oHidn.type = "hidden";
+			var selname = oHidn.name = "marks_"+m_id[i];
+			var selid = document.forms['marksform_'+m_id[i]].marks.selectedIndex;
+			oHidn.value = document.forms['marksform_'+m_id[i]].marks.options[selid].text;
+			f.appendChild(oHidn);
+	}
+
+	var ids = vals.split(',');
+	for(var k=0;k<ids.length;k++){
+			var oHidden = document.createElement("input");
+			oHidden.type = "hidden";
+			oHidden.name = "comments_"+ids[k];
+			oEditor = FCKeditorAPI.GetInstance(oHidden.name) ;
+			oHidden.value = oEditor.GetXHTML(true);
+			f.appendChild(oHidden);
+	}
+//f.submit();
+}
+</script>
+<?php
+
+/**
+ * This function gets the comments of an exercise
+ *
+ * @param int $id
+ * @param int $question_id
+ * @return str the comment
+ */
+function get_comments($id,$question_id)
+{
+	global $TBL_TRACK_ATTEMPT;
+	$sql = "SELECT teacher_comment FROM ".$TBL_TRACK_ATTEMPT." where exe_id='".Database::escape_string($id)."' and question_id = '".Database::escape_string($question_id)."' ORDER by question_id";
+	$sqlres = Database::query($sql, __FILE__, __LINE__);
+	$comm = Database::result($sqlres,0,"teacher_comment");
+	return $comm;
+}
+/**
+ * Display the answers to a multiple choice question
+ *
+ * @param integer Answer type
+ * @param integer Student choice
+ * @param string  Textual answer
+ * @param string  Comment on answer
+ * @param string  Correct answer comment
+ * @param integer Exercise ID
+ * @param integer Question ID
  * @param boolean Whether to show the answer comment or not
- * @return void
- */
-function display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect, $id, $questionId, $ans)
-{
-	?>
-	<tr>
-	<td width="5%" align="center">
-		<img src="../img/<?php echo ($answerType == UNIQUE_ANSWER)?'radio':'checkbox'; echo $studentChoice?'_on':'_off'; ?>.gif"
-		border="0" alt="" />
-	</td>
-	<td width="5%" align="center">
-		<img src="../img/<?php echo ($answerType == UNIQUE_ANSWER)?'radio':'checkbox'; echo $answerCorrect?'_on':'_off'; ?>.gif"
-		border="0" alt=" " />
-	</td>
-	<td width="40%" style="border-bottom: 1px solid #4171B5;">
-		<?php
-		$answer=api_parse_tex($answer);
+ * @return void
+ */
+function display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect, $id, $questionId, $ans)
+{
+	?>
+	<tr>
+	<td width="5%" align="center">
+		<img src="../img/<?php echo ($answerType == UNIQUE_ANSWER)?'radio':'checkbox'; echo $studentChoice?'_on':'_off'; ?>.gif"
+		border="0" alt="" />
+	</td>
+	<td width="5%" align="center">
+		<img src="../img/<?php echo ($answerType == UNIQUE_ANSWER)?'radio':'checkbox'; echo $answerCorrect?'_on':'_off'; ?>.gif"
+		border="0" alt=" " />
+	</td>
+	<td width="40%" style="border-bottom: 1px solid #4171B5;">
+		<?php
+		$answer=api_parse_tex($answer);
 		echo $answer;
 		?>
 	</td>
-	<td width="20%" style="border-bottom: 1px solid #4171B5;">
-		<?php
-		$answerComment=api_parse_tex($answerComment);
-		if($studentChoice)
-		{
-			if(!$answerCorrect)
-			{
-				echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(make_clickable($answerComment)).'</span>';
-			}
-			else{
-				echo '<span style="font-weight: bold; color: #008000;">'.nl2br(make_clickable($answerComment)).'</span>';
-			}
-		}
-		else
-		{
-			echo '&nbsp;';
+	<td width="20%" style="border-bottom: 1px solid #4171B5;">
+		<?php
+		$answerComment=api_parse_tex($answerComment);
+		if($studentChoice)
+		{
+			if(!$answerCorrect)
+			{
+				echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(make_clickable($answerComment)).'</span>';
+			}
+			else{
+				echo '<span style="font-weight: bold; color: #008000;">'.nl2br(make_clickable($answerComment)).'</span>';
+			}
+		}
+		else
+		{
+			echo '&nbsp;';
 		}
-		?>
+		?>
 	</td>
 		<?php
-	    if ($ans==1) {
-	        $comm = get_comments($id,$questionId);
-		}
+	    if ($ans==1) {
+	        $comm = get_comments($id,$questionId);
+		}
 	    ?>
-	</tr>
-	<?php
-}
-/**
- * Shows the answer to a fill-in-the-blanks question, as HTML
- * @param string    Answer text
- * @param int       Exercise ID
- * @param int       Question ID
- * @return void
- */
-
-function display_fill_in_blanks_answer($answer,$id,$questionId)
-{
-	?>
-		<tr>
-		<td>
-			<?php echo nl2br(Security::remove_XSS($answer,COURSEMANAGERLOWSECURITY)); ?>
-		</td><?php
-		if(!api_is_allowed_to_edit()) {?>
-			<td>
-			<?php
-			$comm = get_comments($id,$questionId);
-			?>
-			</td>
-			</tr>
-	<?php }
-}
-/**
- * Shows the answer to a free-answer question, as HTML
- * @param string    Answer text
- * @param int       Exercise ID
- * @param int       Question ID
- * @return void
- */
-function display_free_answer($answer,$id,$questionId) {
-	?>
-		<tr>
-		<td>
-			<?php echo nl2br(Security::remove_XSS($answer,COURSEMANAGERLOWSECURITY)); ?>
-		</td> <?php if(!api_is_allowed_to_edit()) {?>
-        <td>
+	</tr>
+	<?php
+}
+/**
+ * Shows the answer to a fill-in-the-blanks question, as HTML
+ * @param string    Answer text
+ * @param int       Exercise ID
+ * @param int       Question ID
+ * @return void
+ */
+
+function display_fill_in_blanks_answer($answer,$id,$questionId)
+{
+	?>
+		<tr>
+		<td>
+			<?php echo nl2br(Security::remove_XSS($answer,COURSEMANAGERLOWSECURITY)); ?>
+		</td><?php
+		if(!api_is_allowed_to_edit()) {?>
+			<td>
+			<?php
+			$comm = get_comments($id,$questionId);
+			?>
+			</td>
+			</tr>
+	<?php }
+}
+/**
+ * Shows the answer to a free-answer question, as HTML
+ * @param string    Answer text
+ * @param int       Exercise ID
+ * @param int       Question ID
+ * @return void
+ */
+function display_free_answer($answer,$id,$questionId) {
+	?>
+		<tr>
+		<td>
+			<?php echo nl2br(Security::remove_XSS($answer,COURSEMANAGERLOWSECURITY)); ?>
+		</td> <?php if(!api_is_allowed_to_edit()) {?>
+        <td>
         <?php
-        $comm = get_comments($id,$questionId);
-        ?>
+        $comm = get_comments($id,$questionId);
+        ?>
         </td>
-    <?php }?>
-    </tr>
-    <?php
-}
-/**
- * Displays the answer to a hotspot question
- *
- * @param int $answerId
- * @param string $answer
- * @param string $studentChoice
- * @param string $answerComment
- */
-function display_hotspot_answer($answerId, $answer, $studentChoice, $answerComment) {
-	//global $hotspot_colors;
-	$hotspot_colors = array("", // $i starts from 1 on next loop (ugly fix)
-            						"#4271B5",
-									"#FE8E16",
-									"#3B3B3B",
-									"#BCD631",
-									"#D63173",
-									"#D7D7D7",
-									"#90AFDD",
-									"#AF8640",
-									"#4F9242",
-									"#F4EB24",
-									"#ED2024",
-									"#45C7F0",
-									"#F7BDE2");
-	?>
-	<tr>
-		<td width="100px" valign="top" align="left">
-			<div style="width:100%;">
-				<div style="height:11px; width:11px; background-color:<?php echo $hotspot_colors[$answerId]; ?>; display:inline; float:left; margin-top:3px;"></div>
-				<div style="float:left; padding-left:5px;">
-				<?php echo $answerId; ?>
-				</div>
-				<div><?php echo '&nbsp;'.$answer ?></div>
-			</div>
-		</td>
-		<td width="50px" style="padding-right:15px" valign="top" align="left">
+    <?php }?>
+    </tr>
+    <?php
+}
+/**
+ * Displays the answer to a hotspot question
+ *
+ * @param int $answerId
+ * @param string $answer
+ * @param string $studentChoice
+ * @param string $answerComment
+ */
+function display_hotspot_answer($answerId, $answer, $studentChoice, $answerComment) {
+	//global $hotspot_colors;
+	$hotspot_colors = array("", // $i starts from 1 on next loop (ugly fix)
+            						"#4271B5",
+									"#FE8E16",
+									"#3B3B3B",
+									"#BCD631",
+									"#D63173",
+									"#D7D7D7",
+									"#90AFDD",
+									"#AF8640",
+									"#4F9242",
+									"#F4EB24",
+									"#ED2024",
+									"#45C7F0",
+									"#F7BDE2");
+	?>
+	<tr>
+		<td width="100px" valign="top" align="left">
+			<div style="width:100%;">
+				<div style="height:11px; width:11px; background-color:<?php echo $hotspot_colors[$answerId]; ?>; display:inline; float:left; margin-top:3px;"></div>
+				<div style="float:left; padding-left:5px;">
+				<?php echo $answerId; ?>
+				</div>
+				<div><?php echo '&nbsp;'.$answer ?></div>
+			</div>
+		</td>
+		<td width="50px" style="padding-right:15px" valign="top" align="left">
 			<?php
-			$my_choice = ($studentChoice)?get_lang('Correct'):get_lang('Fault'); echo $my_choice; ?>
-		</td>
+			$my_choice = ($studentChoice)?get_lang('Correct'):get_lang('Fault'); echo $my_choice; ?>
+		</td>
 
-		<td valign="top" align="left" >
-			<?php
-			$answerComment=api_parse_tex($answerComment);
-			if($studentChoice) {
+		<td valign="top" align="left" >
+			<?php
+			$answerComment=api_parse_tex($answerComment);
+			if($studentChoice) {
 				echo '<span style="font-weight: bold; color: #008000;">'.nl2br(make_clickable($answerComment)).'</span>';
-			} else {
+			} else {
 				echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(make_clickable($answerComment)).'</span>';
 			}
-			?>
+			?>
 		</td>
-	</tr>
-	<?php
-}
-
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
-*/
-
-?>
-<table width="100%" border="0" cellspacing="0" cellpadding="0">
-  <tr>
-    <td colspan="2">
-<?php
-$sql_test_name='SELECT title, description, results_disabled FROM '.$TBL_EXERCICES.' as exercises, '.$TBL_TRACK_EXERCICES.' as track_exercises WHERE exercises.id=track_exercises.exe_exo_id AND track_exercises.exe_id="'.Database::escape_string($id).'"';
-$result=Database::query($sql_test_name);
-$show_results = true;
+	</tr>
+	<?php
+}
+
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
+*/
+
+?>
+<table width="100%" border="0" cellspacing="0" cellpadding="0">
+  <tr>
+    <td colspan="2">
+<?php
+$sql_test_name='SELECT title, description, results_disabled FROM '.$TBL_EXERCICES.' as exercises, '.$TBL_TRACK_EXERCICES.' as track_exercises WHERE exercises.id=track_exercises.exe_exo_id AND track_exercises.exe_id="'.Database::escape_string($id).'"';
+$result=Database::query($sql_test_name);
+$show_results = true;
 // Avoiding the "Score 0/0" message  when the exe_id is not set
-if (Database::num_rows($result)>0 && isset($id)) {
+if (Database::num_rows($result)>0 && isset($id)) {
 	$test=Database::result($result,0,0);
-	$exerciseTitle=api_parse_tex($test);
-	$exerciseDescription=Database::result($result,0,1);
+	$exerciseTitle=api_parse_tex($test);
+	$exerciseDescription=Database::result($result,0,1);
 
 	// if the results_disabled of the Quiz is 1 when block the script
-	$result_disabled=Database::result($result,0,2);
+	$result_disabled=Database::result($result,0,2);
 	if (!(api_is_platform_admin() || api_is_course_admin()) ) {
 		if ($result_disabled==1) {
-			//api_not_allowed();
-			$show_results = false;
-			//Display::display_warning_message(get_lang('CantViewResults'));
-			if ($origin!='learnpath') {
+			//api_not_allowed();
+			$show_results = false;
+			//Display::display_warning_message(get_lang('CantViewResults'));
+			if ($origin!='learnpath') {
 				Display::display_warning_message(get_lang('ThankYouForPassingTheTest').'<br /><br /><a href="exercice.php">'.(get_lang('BackToExercisesList')).'</a>', false);
-				echo '</td>
-				</tr>
-				</table>';
+				echo '</td>
+				</tr>
+				</table>';
 			}
-		}
-	}
-	if ($show_results == true) {
-		$user_restriction = $is_allowedToEdit ? '' :  "AND user_id=".intval($_user['user_id'])." ";
+		}
+	}
+	if ($show_results == true) {
+		$user_restriction = $is_allowedToEdit ? '' :  "AND user_id=".intval($_user['user_id'])." ";
 		$query = "SELECT attempts.question_id, answer  from ".$TBL_TRACK_ATTEMPT." as attempts
 						INNER JOIN ".$TBL_TRACK_EXERCICES." as stats_exercices ON stats_exercices.exe_id=attempts.exe_id
-						INNER JOIN ".$TBL_EXERCICE_QUESTION." as quizz_rel_questions ON quizz_rel_questions.exercice_id=stats_exercices.exe_exo_id AND quizz_rel_questions.question_id = attempts.question_id
+						INNER JOIN ".$TBL_EXERCICE_QUESTION." as quizz_rel_questions ON quizz_rel_questions.exercice_id=stats_exercices.exe_exo_id AND quizz_rel_questions.question_id = attempts.question_id
 						INNER JOIN ".$TBL_QUESTIONS." as questions ON questions.id=quizz_rel_questions.question_id
-				  WHERE attempts.exe_id='".Database::escape_string($id)."' $user_restriction
+				  WHERE attempts.exe_id='".Database::escape_string($id)."' $user_restriction
 				  GROUP BY quizz_rel_questions.question_order, attempts.question_id";
-					//GROUP BY questions.position, attempts.question_id";
-		$result =Database::query($query, __FILE__, __LINE__);
+					//GROUP BY questions.position, attempts.question_id";
+		$result =Database::query($query, __FILE__, __LINE__);
 	}
-} else {
-	Display::display_warning_message(get_lang('CantViewResults'));
-	$show_results = false;
-	echo '</td>
-	</tr>
-	</table>';
+} else {
+	Display::display_warning_message(get_lang('CantViewResults'));
+	$show_results = false;
+	echo '</td>
+	</tr>
+	</table>';
+}
+if ($origin == 'learnpath' && !isset($_GET['fb_type']) ) {
+	$show_results = false;
 }
-if ($origin == 'learnpath' && !isset($_GET['fb_type']) ) {
-	$show_results = false;
-}
 
 if ($show_results == true ) {
-	?>
-	<table width="100%">
-		<tr>
-			<td style="font-weight:bold" width="10%"><div class="actions-message"><?php echo '&nbsp;'.get_lang('CourseTitle')?> : </div></td>
-			<td><div class="actions-message" width="90%"><?php echo $_course['name'] ?></div></td>
-		</tr>
-		<tr>
-			<td style="font-weight:bold" width="10%"><div class="actions-message"><?php echo '&nbsp;'.get_lang('User')?> : </div></td>
-			<td><div class="actions-message" width="90%"><?php
-			if (isset($_GET['cidReq'])) {
-				$course_code=Security::remove_XSS($_GET['cidReq']);
-			} else {
+	?>
+	<table width="100%">
+		<tr>
+			<td style="font-weight:bold" width="10%"><div class="actions-message"><?php echo '&nbsp;'.get_lang('CourseTitle')?> : </div></td>
+			<td><div class="actions-message" width="90%"><?php echo $_course['name'] ?></div></td>
+		</tr>
+		<tr>
+			<td style="font-weight:bold" width="10%"><div class="actions-message"><?php echo '&nbsp;'.get_lang('User')?> : </div></td>
+			<td><div class="actions-message" width="90%"><?php
+			if (isset($_GET['cidReq'])) {
+				$course_code=Security::remove_XSS($_GET['cidReq']);
+			} else {
 				$course_code=api_get_course_id();
-			}
-			if (isset($_GET['student'])) {
-				$user_id=Security::remove_XSS($_GET['student']);
-			}else {
-				$user_id=api_get_user_id();
-			}
-
-			$status_info=CourseManager::get_user_in_course_status($user_id,$course_code);
-			if (STUDENT==$status_info) {
+			}
+			if (isset($_GET['student'])) {
+				$user_id=Security::remove_XSS($_GET['student']);
+			}else {
+				$user_id=api_get_user_id();
+			}
+
+			$status_info=CourseManager::get_user_in_course_status($user_id,$course_code);
+			if (STUDENT==$status_info) {
 				$user_info=api_get_user_info($user_id);
-				echo api_get_person_name($user_info['firstName'], $user_info['lastName']);
-			} elseif(COURSEMANAGER==$status_info && !isset($_GET['user'])) {
+				echo api_get_person_name($user_info['firstName'], $user_info['lastName']);
+			} elseif(COURSEMANAGER==$status_info && !isset($_GET['user'])) {
 				$user_info=api_get_user_info($user_id);
-				echo api_get_person_name($user_info['firstName'], $user_info['lastName']);
-			} else {
-				echo $user_name;
-			}
-
-			?></div></td>
-		</tr>
-		<tr>
-			<td style="font-weight:bold" width="10%" class="actions-message">
-				<?php echo '&nbsp;'.get_lang("Exercise").' :'; ?>
-			</td>
-			<td width="90%">
-			<?php echo $test; ?><br />
-			<?php echo $exerciseDescription; ?>
-			</td>
-		</tr>
+				echo api_get_person_name($user_info['firstName'], $user_info['lastName']);
+			} else {
+				echo $user_name;
+			}
+
+			?></div></td>
+		</tr>
+		<tr>
+			<td style="font-weight:bold" width="10%" class="actions-message">
+				<?php echo '&nbsp;'.get_lang("Exercise").' :'; ?>
+			</td>
+			<td width="90%">
+			<?php echo $test; ?><br />
+			<?php echo $exerciseDescription; ?>
+			</td>
+		</tr>
 	</table>
-	<br />
+	<br />
 	</table>
-  	<?php
-}
-$i=$totalScore=$totalWeighting=0;
-
-if($debug>0){echo "ExerciseResult: "; var_dump($exerciseResult); echo "QuestionList: ";var_dump($questionList);}
-
-if ($show_results) {
-	$questionList = array();
-	$exerciseResult = array();
-	$k=0;
-	$counter=0;
-	while ($row = Database::fetch_array($result)) {
-		$questionList[] = $row['question_id'];
-		$exerciseResult[] = $row['answer'];
-	}
-	// for each question
-	foreach($questionList as $questionId) {
-		$counter++;
-		$k++;
-		$choice=$exerciseResult[$questionId];
-		// creates a temporary Question object
-		$objQuestionTmp = Question::read($questionId);
-		$questionName=$objQuestionTmp->selectTitle();
-		$questionDescription=$objQuestionTmp->selectDescription();
-		$questionWeighting=$objQuestionTmp->selectWeighting();
-		$answerType=$objQuestionTmp->selectType();
-		$quesId =$objQuestionTmp->selectId(); //added by priya saini
-
-		// destruction of the Question object
-		unset($objQuestionTmp);
-
-		if($answerType == UNIQUE_ANSWER || $answerType == MULTIPLE_ANSWER) {
-			$colspan=2;
+  	<?php
+}
+$i=$totalScore=$totalWeighting=0;
+
+if($debug>0){echo "ExerciseResult: "; var_dump($exerciseResult); echo "QuestionList: ";var_dump($questionList);}
+
+if ($show_results) {
+	$questionList = array();
+	$exerciseResult = array();
+	$k=0;
+	$counter=0;
+	while ($row = Database::fetch_array($result)) {
+		$questionList[] = $row['question_id'];
+		$exerciseResult[] = $row['answer'];
+	}
+	// for each question
+	foreach($questionList as $questionId) {
+		$counter++;
+		$k++;
+		$choice=$exerciseResult[$questionId];
+		// creates a temporary Question object
+		$objQuestionTmp = Question::read($questionId);
+		$questionName=$objQuestionTmp->selectTitle();
+		$questionDescription=$objQuestionTmp->selectDescription();
+		$questionWeighting=$objQuestionTmp->selectWeighting();
+		$answerType=$objQuestionTmp->selectType();
+		$quesId =$objQuestionTmp->selectId(); //added by priya saini
+
+		// destruction of the Question object
+		unset($objQuestionTmp);
+
+		if($answerType == UNIQUE_ANSWER || $answerType == MULTIPLE_ANSWER) {
+			$colspan=2;
+		}
+		if($answerType == MATCHING || $answerType == FREE_ANSWER) {
+			$colspan=2;
+		} else {
+			$colspan=2;
 		}
-		if($answerType == MATCHING || $answerType == FREE_ANSWER) {
-			$colspan=2;
-		} else {
-			$colspan=2;
-		}
 		?>
-    	<div id="question_title" class="sectiontitle">
-    		<?php echo get_lang("Question").' '.($counter).' : '.$questionName; ?>
+    	<div id="question_title" class="sectiontitle">
+    		<?php echo get_lang("Question").' '.($counter).' : '.$questionName; ?>
     	</div>
-    	<div id="question_description">
-    		<?php echo $questionDescription; ?>
-    	</div>
-
-	 	<?php
-		if ($answerType == MULTIPLE_ANSWER) {
-			$choice=array();
-			?>
-			<table width="100%" border="0" cellspacing="3" cellpadding="3">
-			<tr>
-			<td>&nbsp;</td>
-			</tr>
-			<tr>
-				<td><i><?php echo get_lang("Choice"); ?></i> </td>
-				<td><i><?php echo get_lang("ExpectedChoice"); ?></i></td>
-				<td><i><?php echo get_lang("Answer"); ?></i></td>
+    	<div id="question_description">
+    		<?php echo $questionDescription; ?>
+    	</div>
+
+	 	<?php
+		if ($answerType == MULTIPLE_ANSWER) {
+			$choice=array();
+			?>
+			<table width="100%" border="0" cellspacing="3" cellpadding="3">
+			<tr>
+			<td>&nbsp;</td>
+			</tr>
+			<tr>
+				<td><i><?php echo get_lang("Choice"); ?></i> </td>
+				<td><i><?php echo get_lang("ExpectedChoice"); ?></i></td>
+				<td><i><?php echo get_lang("Answer"); ?></i></td>
 				<td><i><?php echo get_lang("Comment"); ?></i></td>
-			</tr>
-			<tr>
-			<td>&nbsp;</td>
-			</tr>
-			<?php
-			// construction of the Answer object
-			$objAnswerTmp=new Answer($questionId);
-			$nbrAnswers=$objAnswerTmp->selectNbrAnswers();
-			$questionScore=0;
-			for ($answerId=1;$answerId <= $nbrAnswers;$answerId++) {
-				$answer=$objAnswerTmp->selectAnswer($answerId);
-				$answerComment=$objAnswerTmp->selectComment($answerId);
-				$answerCorrect=$objAnswerTmp->isCorrect($answerId);
-				$answerWeighting=$objAnswerTmp->selectWeighting($answerId);
-				$queryans = "select * from ".$TBL_TRACK_ATTEMPT." where exe_id = '".Database::escape_string($id)."' and question_id= '".Database::escape_string($questionId)."'";
-				$resultans = Database::query($queryans, __FILE__, __LINE__);
-				while ($row = Database::fetch_array($resultans)) {
-					$ind = $row['answer'];
-					$choice[$ind] = 1;
-				}
-				$studentChoice=$choice[$answerId];
-				if ($studentChoice) {
-					$questionScore+=$answerWeighting;
-					$totalScore+=$answerWeighting;
-				}
-				echo '<tr><td>';
-				if ($answerId==1) {
-						display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$id,$questionId,$answerId);
-				} else {
-						display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$id,$questionId,"");
-				}
-				echo '</td></tr>';
-				$i++;
-		 	}
-		 	echo '</table>';
-		} elseif ($answerType == UNIQUE_ANSWER) {
-			?>
-			<table width="100%" border="0" cellspacing="3" cellpadding="3">
-				<tr>
-				<td>&nbsp;</td>
-				</tr>
-				<tr>
-					<td><i><?php echo get_lang("Choice"); ?></i> </td>
-					<td><i><?php echo get_lang("ExpectedChoice"); ?></i></td>
-					<td><i><?php echo get_lang("Answer"); ?></i></td>
+			</tr>
+			<tr>
+			<td>&nbsp;</td>
+			</tr>
+			<?php
+			// construction of the Answer object
+			$objAnswerTmp=new Answer($questionId);
+			$nbrAnswers=$objAnswerTmp->selectNbrAnswers();
+			$questionScore=0;
+			for ($answerId=1;$answerId <= $nbrAnswers;$answerId++) {
+				$answer=$objAnswerTmp->selectAnswer($answerId);
+				$answerComment=$objAnswerTmp->selectComment($answerId);
+				$answerCorrect=$objAnswerTmp->isCorrect($answerId);
+				$answerWeighting=$objAnswerTmp->selectWeighting($answerId);
+				$queryans = "select * from ".$TBL_TRACK_ATTEMPT." where exe_id = '".Database::escape_string($id)."' and question_id= '".Database::escape_string($questionId)."'";
+				$resultans = Database::query($queryans, __FILE__, __LINE__);
+				while ($row = Database::fetch_array($resultans)) {
+					$ind = $row['answer'];
+					$choice[$ind] = 1;
+				}
+				$studentChoice=$choice[$answerId];
+				if ($studentChoice) {
+					$questionScore+=$answerWeighting;
+					$totalScore+=$answerWeighting;
+				}
+				echo '<tr><td>';
+				if ($answerId==1) {
+						display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$id,$questionId,$answerId);
+				} else {
+						display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$id,$questionId,"");
+				}
+				echo '</td></tr>';
+				$i++;
+		 	}
+		 	echo '</table>';
+		} elseif ($answerType == UNIQUE_ANSWER) {
+			?>
+			<table width="100%" border="0" cellspacing="3" cellpadding="3">
+				<tr>
+				<td>&nbsp;</td>
+				</tr>
+				<tr>
+					<td><i><?php echo get_lang("Choice"); ?></i> </td>
+					<td><i><?php echo get_lang("ExpectedChoice"); ?></i></td>
+					<td><i><?php echo get_lang("Answer"); ?></i></td>
 					<td><i><?php echo get_lang("Comment"); ?></i></td>
-				</tr>
-				<tr>
-				<td>&nbsp;</td>
-				</tr>
-			<?php
-			$objAnswerTmp=new Answer($questionId);
-			$nbrAnswers=$objAnswerTmp->selectNbrAnswers();
-			$questionScore=0;
+				</tr>
+				<tr>
+				<td>&nbsp;</td>
+				</tr>
+			<?php
+			$objAnswerTmp=new Answer($questionId);
+			$nbrAnswers=$objAnswerTmp->selectNbrAnswers();
+			$questionScore=0;
 			for ($answerId=1;$answerId <= $nbrAnswers;$answerId++) {
-				$answer=$objAnswerTmp->selectAnswer($answerId);
-				$answerComment=$objAnswerTmp->selectComment($answerId);
-				$answerCorrect=$objAnswerTmp->isCorrect($answerId);
-				$answerWeighting=$objAnswerTmp->selectWeighting($answerId);
-				$queryans = "select answer from ".$TBL_TRACK_ATTEMPT." where exe_id = '".Database::escape_string($id)."' and question_id= '".Database::escape_string($questionId)."'";
-				$resultans = Database::query($queryans, __FILE__, __LINE__);
-				$choice = Database::result($resultans,0,"answer");
-				$studentChoice=($choice == $answerId)?1:0;
-				if ($studentChoice) {
-				  	$questionScore+=$answerWeighting;
-					$totalScore+=$answerWeighting;
-				}
-				echo '<tr><td>';
-				if ($answerId==1) {
-					display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$id,$questionId,$answerId);
-				} else {
-					display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$id,$questionId,"");
+				$answer=$objAnswerTmp->selectAnswer($answerId);
+				$answerComment=$objAnswerTmp->selectComment($answerId);
+				$answerCorrect=$objAnswerTmp->isCorrect($answerId);
+				$answerWeighting=$objAnswerTmp->selectWeighting($answerId);
+				$queryans = "select answer from ".$TBL_TRACK_ATTEMPT." where exe_id = '".Database::escape_string($id)."' and question_id= '".Database::escape_string($questionId)."'";
+				$resultans = Database::query($queryans, __FILE__, __LINE__);
+				$choice = Database::result($resultans,0,"answer");
+				$studentChoice=($choice == $answerId)?1:0;
+				if ($studentChoice) {
+				  	$questionScore+=$answerWeighting;
+					$totalScore+=$answerWeighting;
+				}
+				echo '<tr><td>';
+				if ($answerId==1) {
+					display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$id,$questionId,$answerId);
+				} else {
+					display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$id,$questionId,"");
 				}
-				echo '</td></tr>';
-				$i++;
-			}
-			echo '</table>';
-
-		} elseif ($answerType == FILL_IN_BLANKS) {
-
-			?>
-			<table width="100%" border="0" cellspacing="3" cellpadding="3">
-			<tr>
-			<td>&nbsp;</td>
-			</tr>
-			<tr>
-			<td><i><?php echo get_lang("Answer"); ?></i> </td>
-			</tr>
-			<tr>
-			<td>&nbsp;</td>
-			</tr>
-			<?php
-			$objAnswerTmp=new Answer($questionId);
-			$nbrAnswers=$objAnswerTmp->selectNbrAnswers();
-			$questionScore=0;
-
-			for ($answerId=1;$answerId <= $nbrAnswers;$answerId++) {
-				$answer = $objAnswerTmp->selectAnswer($answerId);
-				$answerComment = $objAnswerTmp->selectComment($answerId);
-				$answerCorrect = $objAnswerTmp->isCorrect($answerId);
-				$answerWeighting = $objAnswerTmp->selectWeighting($answerId);
-
-			    // the question is encoded like this
-			    // [A] B [C] D [E] F::10,10,10@1
-			    // number 1 before the "@" means that is a switchable fill in blank question
-			    // [A] B [C] D [E] F::10,10,10@ or  [A] B [C] D [E] F::10,10,10
-			    // means that is a normal fill blank question
-
+				echo '</td></tr>';
+				$i++;
+			}
+			echo '</table>';
+
+		} elseif ($answerType == FILL_IN_BLANKS) {
+
+			?>
+			<table width="100%" border="0" cellspacing="3" cellpadding="3">
+			<tr>
+			<td>&nbsp;</td>
+			</tr>
+			<tr>
+			<td><i><?php echo get_lang("Answer"); ?></i> </td>
+			</tr>
+			<tr>
+			<td>&nbsp;</td>
+			</tr>
+			<?php
+			$objAnswerTmp=new Answer($questionId);
+			$nbrAnswers=$objAnswerTmp->selectNbrAnswers();
+			$questionScore=0;
+
+			for ($answerId=1;$answerId <= $nbrAnswers;$answerId++) {
+				$answer = $objAnswerTmp->selectAnswer($answerId);
+				$answerComment = $objAnswerTmp->selectComment($answerId);
+				$answerCorrect = $objAnswerTmp->isCorrect($answerId);
+				$answerWeighting = $objAnswerTmp->selectWeighting($answerId);
+
+			    // the question is encoded like this
+			    // [A] B [C] D [E] F::10,10,10@1
+			    // number 1 before the "@" means that is a switchable fill in blank question
+			    // [A] B [C] D [E] F::10,10,10@ or  [A] B [C] D [E] F::10,10,10
+			    // means that is a normal fill blank question
+
 				$pre_array = explode('::', $answer);
 
 				// is switchable fill blank or not
-				$is_set_switchable = explode('@', $pre_array[1]);
-				$switchable_answer_set=false;
-				if ($is_set_switchable[1]==1) {
-					$switchable_answer_set=true;
+				$is_set_switchable = explode('@', $pre_array[1]);
+				$switchable_answer_set=false;
+				if ($is_set_switchable[1]==1) {
+					$switchable_answer_set=true;
 				}
 
-				$answer = $pre_array[0];
+				$answer = $pre_array[0];
 
-				// splits weightings that are joined with a comma
+				// splits weightings that are joined with a comma
 				$answerWeighting = explode(',',$is_set_switchable[0]);
 				//list($answer,$answerWeighting)=explode('::',$multiple[0]);
 
-				//$answerWeighting=explode(',',$answerWeighting);
-				// we save the answer because it will be modified
-			    $temp=$answer;
-
-				// TeX parsing
-				// 1. find everything between the [tex] and [/tex] tags
-				$startlocations=api_strpos($temp,'[tex]');
-				$endlocations=api_strpos($temp,'[/tex]');
-				if ($startlocations !== false && $endlocations !== false) {
-					$texstring=api_substr($temp,$startlocations,$endlocations-$startlocations+6);
-					// 2. replace this by {texcode}
-					$temp=str_replace($texstring,'{texcode}',$temp);
-				}
-				$j=0;
-				// the loop will stop at the end of the text
-				$i=0;
-				//normal fill in blank
-				if (!$switchable_answer_set) {
-					while (1) {
-						// quits the loop if there are no more blanks
-						if (($pos = api_strpos($temp,'[')) === false) {
-							// adds the end of the text
+				//$answerWeighting=explode(',',$answerWeighting);
+				// we save the answer because it will be modified
+			    $temp=$answer;
+
+				// TeX parsing
+				// 1. find everything between the [tex] and [/tex] tags
+				$startlocations=api_strpos($temp,'[tex]');
+				$endlocations=api_strpos($temp,'[/tex]');
+				if ($startlocations !== false && $endlocations !== false) {
+					$texstring=api_substr($temp,$startlocations,$endlocations-$startlocations+6);
+					// 2. replace this by {texcode}
+					$temp=str_replace($texstring,'{texcode}',$temp);
+				}
+				$j=0;
+				// the loop will stop at the end of the text
+				$i=0;
+				//normal fill in blank
+				if (!$switchable_answer_set) {
+					while (1) {
+						// quits the loop if there are no more blanks
+						if (($pos = api_strpos($temp,'[')) === false) {
+							// adds the end of the text
 							$answer.=$temp;
-							// TeX parsing
-							$texstring = api_parse_tex($texstring);
-							break;
-						}
-					    $temp=api_substr($temp,$pos+1);
-						// quits the loop if there are no more blanks
-						if (($pos = api_strpos($temp,']')) === false) {
-							break;
-						}
-
-						$queryfill = "select answer from ".$TBL_TRACK_ATTEMPT." where exe_id = '".Database::escape_string($id)."' and question_id= '".Database::escape_string($questionId)."'";
-						$resfill = Database::query($queryfill, __FILE__, __LINE__);
-						$str = Database::result($resfill,0,"answer");
-
-						preg_match_all('#\[([^[]*)\]#', $str, $arr);
-						$choice = $arr[1];
-						$tmp=strrpos($choice[$j],' / ');
-						$choice[$j]=substr($choice[$j],0,$tmp);
-						$choice[$j]=trim($choice[$j]);
-
-
-						// if the word entered by the student IS the same as the one defined by the professor
-						if (api_strtolower(api_substr($temp,0,$pos)) == api_strtolower($choice[$j])) {
-							// gives the related weighting to the student
-							$questionScore+=$answerWeighting[$j];
-							// increments total score
-							$totalScore+=$answerWeighting[$j];
-						}
-						// else if the word entered by the student IS NOT the same as the one defined by the professor
-						$j++;
-						$temp=api_substr($temp,$pos+1);
-						$i=$i+1;
-					}
-
-					$answer = stripslashes($str);
-					$answer = str_replace('rn', '', $answer);
+							// TeX parsing
+							$texstring = api_parse_tex($texstring);
+							break;
+						}
+					    $temp=api_substr($temp,$pos+1);
+						// quits the loop if there are no more blanks
+						if (($pos = api_strpos($temp,']')) === false) {
+							break;
+						}
+
+						$queryfill = "select answer from ".$TBL_TRACK_ATTEMPT." where exe_id = '".Database::escape_string($id)."' and question_id= '".Database::escape_string($questionId)."'";
+						$resfill = Database::query($queryfill, __FILE__, __LINE__);
+						$str = Database::result($resfill,0,"answer");
+
+						preg_match_all('#\[([^[]*)\]#', $str, $arr);
+						$choice = $arr[1];
+						$tmp=strrpos($choice[$j],' / ');
+						$choice[$j]=substr($choice[$j],0,$tmp);
+						$choice[$j]=trim($choice[$j]);
+
+
+						// if the word entered by the student IS the same as the one defined by the professor
+						if (api_strtolower(api_substr($temp,0,$pos)) == api_strtolower($choice[$j])) {
+							// gives the related weighting to the student
+							$questionScore+=$answerWeighting[$j];
+							// increments total score
+							$totalScore+=$answerWeighting[$j];
+						}
+						// else if the word entered by the student IS NOT the same as the one defined by the professor
+						$j++;
+						$temp=api_substr($temp,$pos+1);
+						$i=$i+1;
+					}
+
+					$answer = stripslashes($str);
+					$answer = str_replace('rn', '', $answer);
 
 				} else {
 					//multiple fill in blank
-					while (1) {
-						// quits the loop if there are no more blanks
-						if (($pos = api_strpos($temp,'[')) === false) {
-							// adds the end of the text
-							$answer.=$temp;
-							// TeX parsing
-							$texstring = api_parse_tex($texstring);
-							//$answer=str_replace("{texcode}",$texstring,$answer);
-							break;
-						}
-						// adds the piece of text that is before the blank and ended by [
-						$real_text[]=api_substr($temp,0,$pos+1);
+					while (1) {
+						// quits the loop if there are no more blanks
+						if (($pos = api_strpos($temp,'[')) === false) {
+							// adds the end of the text
+							$answer.=$temp;
+							// TeX parsing
+							$texstring = api_parse_tex($texstring);
+							//$answer=str_replace("{texcode}",$texstring,$answer);
+							break;
+						}
+						// adds the piece of text that is before the blank and ended by [
+						$real_text[]=api_substr($temp,0,$pos+1);
 						$answer.=api_substr($temp,0,$pos+1);
-						$temp=api_substr($temp,$pos+1);
-
-						// quits the loop if there are no more blanks
-						if (($pos = api_strpos($temp,']')) === false) {
-							// adds the end of the text
-							//$answer.=$temp;
-							break;
-						}
-
-						$queryfill = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".Database::escape_string($id)."' and question_id= '".Database::escape_string($questionId)."'";
-						$resfill = Database::query($queryfill, __FILE__, __LINE__);
-						$str=Database::result($resfill,0,"answer");
-						preg_match_all ('#\[([^[/]*)/#', $str, $arr);
-						$choice = $arr[1];
+						$temp=api_substr($temp,$pos+1);
+
+						// quits the loop if there are no more blanks
+						if (($pos = api_strpos($temp,']')) === false) {
+							// adds the end of the text
+							//$answer.=$temp;
+							break;
+						}
+
+						$queryfill = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".Database::escape_string($id)."' and question_id= '".Database::escape_string($questionId)."'";
+						$resfill = Database::query($queryfill, __FILE__, __LINE__);
+						$str=Database::result($resfill,0,"answer");
+						preg_match_all ('#\[([^[/]*)/#', $str, $arr);
+						$choice = $arr[1];
 
 						$choice[$j]=trim($choice[$j]);
-						$user_tags[]=api_strtolower($choice[$j]);
+						$user_tags[]=api_strtolower($choice[$j]);
 						$correct_tags[]=api_strtolower(api_substr($temp,0,$pos));
 
-						$j++;
-						$temp=api_substr($temp,$pos+1);
-						$i=$i+1;
-					}
-					$answer='';
+						$j++;
+						$temp=api_substr($temp,$pos+1);
+						$i=$i+1;
+					}
+					$answer='';
 					for ($i=0;$i<count($correct_tags);$i++) {
-						if (in_array($user_tags[$i],$correct_tags)) {
-							// gives the related weighting to the student
-							$questionScore+=$answerWeighting[$i];
-							// increments total score
-							$totalScore+=$answerWeighting[$i];
+						if (in_array($user_tags[$i],$correct_tags)) {
+							// gives the related weighting to the student
+							$questionScore+=$answerWeighting[$i];
+							// increments total score
+							$totalScore+=$answerWeighting[$i];
 						}
-					}
-					$answer = stripslashes($str);
-					$answer = str_replace('rn', '', $answer);
-				}
-				//echo $questionScore."-".$totalScore;
+					}
+					$answer = stripslashes($str);
+					$answer = str_replace('rn', '', $answer);
+				}
+				//echo $questionScore."-".$totalScore;
 				echo '<tr><td>';
-				display_fill_in_blanks_answer($answer,$id,$questionId);
-				echo '</td></tr>';
-				$i++;
-			}
-			echo '</table>';
-		} elseif ($answerType == FREE_ANSWER) {$answer = $str;
-			?>
-			<table width="100%" border="0" cellspacing="3" cellpadding="3">
-			<tr>
-			<td>&nbsp;</td>
-			</tr>
-			<tr>
-			<td><i><?php echo get_lang("Answer"); ?></i> </td>
-			</tr>
-			<tr>
-			<td>&nbsp;</td>
-			</tr>
-
-			<?php
-			$objAnswerTmp = new Answer($questionId);
-			$nbrAnswers = $objAnswerTmp->selectNbrAnswers();
-			$questionScore = 0;
-			$query = "select answer, marks from ".$TBL_TRACK_ATTEMPT." where exe_id = '".Database::escape_string($id)."' and question_id= '".Database::escape_string($questionId)."'";
-			$resq = Database::query($query);
-			$choice = Database::result($resq,0,"answer");
-			$choice = stripslashes($choice);
-			$choice = str_replace('rn', '', $choice);
-
-			$questionScore = Database::result($resq,0,"marks");
-			if ($questionScore==-1) {
-				$totalScore+=0;
-			} else {
-				$totalScore+=$questionScore;
-			}
-			echo '<tr>
-			<td valign="top">'.display_free_answer($choice, $id, $questionId).'</td>
-			</tr>
-			</table>';
-
-		} elseif ($answerType == MATCHING) {
-
+				display_fill_in_blanks_answer($answer,$id,$questionId);
+				echo '</td></tr>';
+				$i++;
+			}
+			echo '</table>';
+		} elseif ($answerType == FREE_ANSWER) {$answer = $str;
+			?>
+			<table width="100%" border="0" cellspacing="3" cellpadding="3">
+			<tr>
+			<td>&nbsp;</td>
+			</tr>
+			<tr>
+			<td><i><?php echo get_lang("Answer"); ?></i> </td>
+			</tr>
+			<tr>
+			<td>&nbsp;</td>
+			</tr>
+
+			<?php
+			$objAnswerTmp = new Answer($questionId);
+			$nbrAnswers = $objAnswerTmp->selectNbrAnswers();
+			$questionScore = 0;
+			$query = "select answer, marks from ".$TBL_TRACK_ATTEMPT." where exe_id = '".Database::escape_string($id)."' and question_id= '".Database::escape_string($questionId)."'";
+			$resq = Database::query($query);
+			$choice = Database::result($resq,0,"answer");
+			$choice = stripslashes($choice);
+			$choice = str_replace('rn', '', $choice);
+
+			$questionScore = Database::result($resq,0,"marks");
+			if ($questionScore==-1) {
+				$totalScore+=0;
+			} else {
+				$totalScore+=$questionScore;
+			}
+			echo '<tr>
+			<td valign="top">'.display_free_answer($choice, $id, $questionId).'</td>
+			</tr>
+			</table>';
+
+		} elseif ($answerType == MATCHING) {
+
 			$objAnswerTmp=new Answer($questionId);
-			$table_ans = Database :: get_course_table(TABLE_QUIZ_ANSWER);
-			$TBL_TRACK_ATTEMPT= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+			$table_ans = Database :: get_course_table(TABLE_QUIZ_ANSWER);
+			$TBL_TRACK_ATTEMPT= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 
 			$sql_select_answer = 'SELECT id, answer, correct, position FROM '.$table_ans.' WHERE question_id="'.Database::escape_string($questionId).'" AND correct<>0';
-			$sql_answer = 'SELECT position, answer FROM '.$table_ans.' WHERE question_id="'.Database::escape_string($questionId).'" AND correct=0';
-			$res_answer = Database::query($sql_answer, __FILE__, __LINE__);
-			// getting the real answer
+			$sql_answer = 'SELECT position, answer FROM '.$table_ans.' WHERE question_id="'.Database::escape_string($questionId).'" AND correct=0';
+			$res_answer = Database::query($sql_answer, __FILE__, __LINE__);
+			// getting the real answer
 			$real_list =array();
 			while ($real_answer = Database::fetch_array($res_answer)) {
-				$real_list[$real_answer['position']]= $real_answer['answer'];
+				$real_list[$real_answer['position']]= $real_answer['answer'];
 			}
 
-			$res_answers = Database::query($sql_select_answer, __FILE__, __LINE__);
+			$res_answers = Database::query($sql_select_answer, __FILE__, __LINE__);
 
-			echo '<table width="100%" height="71" border="0" cellspacing="3" cellpadding="3" >';
-			echo '<tr><td colspan="2">&nbsp;</td></tr>';
-			echo '<tr>
-					<td><span style="font-style: italic;">'.get_lang("ElementList").'</span> </td>
-					<td><span style="font-style: italic;">'.get_lang("CorrespondsTo").'</span></td>
-				  </tr>';
-			echo '<tr><td colspan="2">&nbsp;</td></tr>';
+			echo '<table width="100%" height="71" border="0" cellspacing="3" cellpadding="3" >';
+			echo '<tr><td colspan="2">&nbsp;</td></tr>';
+			echo '<tr>
+					<td><span style="font-style: italic;">'.get_lang("ElementList").'</span> </td>
+					<td><span style="font-style: italic;">'.get_lang("CorrespondsTo").'</span></td>
+				  </tr>';
+			echo '<tr><td colspan="2">&nbsp;</td></tr>';
 
-			$questionScore=0;
+			$questionScore=0;
 
 			while ($a_answers = Database::fetch_array($res_answers)) {
-				$i_answer_id = $a_answers['id']; //3
+				$i_answer_id = $a_answers['id']; //3
 				$s_answer_label = $a_answers['answer'];  // your dady - you mother
 				$i_answer_correct_answer = $a_answers['correct']; //1 - 2
-				$i_answer_position = $a_answers['position']; // 3 - 4
+				$i_answer_position = $a_answers['position']; // 3 - 4
 
 				$sql_user_answer =
 						'SELECT answers.answer
 						FROM '.$TBL_TRACK_ATTEMPT.' as track_e_attempt
 						INNER JOIN '.$table_ans.' as answers
-							ON answers.position = track_e_attempt.answer
-							AND track_e_attempt.question_id=answers.question_id
-						WHERE answers.correct = 0
-						AND track_e_attempt.exe_id = "'.Database::escape_string($id).'"
+							ON answers.position = track_e_attempt.answer
+							AND track_e_attempt.question_id=answers.question_id
+						WHERE answers.correct = 0
+						AND track_e_attempt.exe_id = "'.Database::escape_string($id).'"
 						AND track_e_attempt.question_id = "'.Database::escape_string($questionId).'"
-						AND track_e_attempt.position="'.Database::escape_string($i_answer_position).'"';
+						AND track_e_attempt.position="'.Database::escape_string($i_answer_position).'"';
 
 
-				$res_user_answer = Database::query($sql_user_answer, __FILE__, __LINE__);
-				if (Database::num_rows($res_user_answer)>0 ) {
-					$s_user_answer = Database::result($res_user_answer,0,0); //  rich - good looking
+				$res_user_answer = Database::query($sql_user_answer, __FILE__, __LINE__);
+				if (Database::num_rows($res_user_answer)>0 ) {
+					$s_user_answer = Database::result($res_user_answer,0,0); //  rich - good looking
 				} else {
-					$s_user_answer = '';
-				}
+					$s_user_answer = '';
+				}
 
-				//$s_correct_answer = $s_answer_label; // your ddady - your mother
-				$s_correct_answer = $real_list[$i_answer_correct_answer];
+				//$s_correct_answer = $s_answer_label; // your ddady - your mother
+				$s_correct_answer = $real_list[$i_answer_correct_answer];
 
-				$i_answerWeighting=$objAnswerTmp->selectWeighting($i_answer_id);
+				$i_answerWeighting=$objAnswerTmp->selectWeighting($i_answer_id);
 
-				//if($s_user_answer == $s_correct_answer) // rich == your ddady?? wrong
-				//echo $s_user_answer.' - '.$real_list[$i_answer_correct_answer];
+				//if($s_user_answer == $s_correct_answer) // rich == your ddady?? wrong
+				//echo $s_user_answer.' - '.$real_list[$i_answer_correct_answer];
 
-				if ($s_user_answer == $real_list[$i_answer_correct_answer]) { // rich == your ddady?? wrong
-					$questionScore+=$i_answerWeighting;
-					$totalScore+=$i_answerWeighting;
-				} else {
-					$s_user_answer = '<span style="color: #FF0000; text-decoration: line-through;">'.$s_user_answer.'</span>';
+				if ($s_user_answer == $real_list[$i_answer_correct_answer]) { // rich == your ddady?? wrong
+					$questionScore+=$i_answerWeighting;
+					$totalScore+=$i_answerWeighting;
+				} else {
+					$s_user_answer = '<span style="color: #FF0000; text-decoration: line-through;">'.$s_user_answer.'</span>';
 				}
-				echo '<tr>';
-				echo '<td>'.$s_answer_label.'</td><td>'.$s_user_answer.' / <b><span style="color: #008000;">'.$s_correct_answer.'</span></b></td>';
+				echo '<tr>';
+				echo '<td>'.$s_answer_label.'</td><td>'.$s_user_answer.' / <b><span style="color: #008000;">'.$s_correct_answer.'</span></b></td>';
 				echo '</tr>';
-			}
+			}
 			echo '</table>';
-		} elseif ($answerType == HOT_SPOT) {
-			?>
+		} elseif ($answerType == HOT_SPOT) {
+			?>
 			<table width="500" border="0">
-
-			<?php
-			$objAnswerTmp=new Answer($questionId);
-			$nbrAnswers=$objAnswerTmp->selectNbrAnswers();
-			$questionScore=0;
-			?>
-				<tr>
-					<td valign="top" align="center" style="padding-left:0px;" >
-						<table border="1" bordercolor="#A4A4A4" style="border-collapse: collapse;" width="552">
+
 			<?php
-			for ($answerId=1;$answerId <= $nbrAnswers;$answerId++) {
-				$answer=$objAnswerTmp->selectAnswer($answerId);
-				$answerComment=$objAnswerTmp->selectComment($answerId);
-				$answerCorrect=$objAnswerTmp->isCorrect($answerId);
-				$answerWeighting=$objAnswerTmp->selectWeighting($answerId);
-
-				$TBL_TRACK_HOTSPOT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
-				$query = "select hotspot_correct from ".$TBL_TRACK_HOTSPOT." where hotspot_exe_id = '".Database::escape_string($id)."' and hotspot_question_id= '".Database::escape_string($questionId)."' AND hotspot_answer_id='".Database::escape_string($answerId)."'";
-				$resq=Database::query($query);
-				$choice = Database::result($resq,0,"hotspot_correct");
-				display_hotspot_answer($answerId,$answer,$choice,$answerComment);
-
-				$i++;
-		 	}
-		 	$queryfree = "select marks from ".$TBL_TRACK_ATTEMPT." where exe_id = '".Database::escape_string($id)."' and question_id= '".Database::escape_string($questionId)."'";
-			$resfree = Database::query($queryfree, __FILE__, __LINE__);
-			$questionScore= Database::result($resfree,0,"marks");
-			$totalScore+=$questionScore;
-			echo '</table></td></tr>';
-		 	echo '<tr>
-				<td colspan="2">'.
-					//<object type="application/x-shockwave-flash" data="../plugin/hotspot/hotspot_solution.swf?modifyAnswers='.$questionId.'&exe_id='.$id.'&from_db=1" width="556" height="421">
-					'<object type="application/x-shockwave-flash" data="../plugin/hotspot/hotspot_solution.swf?modifyAnswers='.Security::remove_XSS($questionId).'&exe_id='.$id.'&from_db=1" width="552" height="352">
-						<param name="movie" value="../plugin/hotspot/hotspot_solution.swf?modifyAnswers='.Security::remove_XSS($questionId).'&exe_id='.$id.'&from_db=1" />
-					</object>
-
-				</td>
-			</tr>
-			</table><br/>';
-		}
-
+			$objAnswerTmp=new Answer($questionId);
+			$nbrAnswers=$objAnswerTmp->selectNbrAnswers();
+			$questionScore=0;
+			?>
+				<tr>
+					<td valign="top" align="center" style="padding-left:0px;" >
+						<table border="1" bordercolor="#A4A4A4" style="border-collapse: collapse;" width="552">
+			<?php
+			for ($answerId=1;$answerId <= $nbrAnswers;$answerId++) {
+				$answer=$objAnswerTmp->selectAnswer($answerId);
+				$answerComment=$objAnswerTmp->selectComment($answerId);
+				$answerCorrect=$objAnswerTmp->isCorrect($answerId);
+				$answerWeighting=$objAnswerTmp->selectWeighting($answerId);
+
+				$TBL_TRACK_HOTSPOT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
+				$query = "select hotspot_correct from ".$TBL_TRACK_HOTSPOT." where hotspot_exe_id = '".Database::escape_string($id)."' and hotspot_question_id= '".Database::escape_string($questionId)."' AND hotspot_answer_id='".Database::escape_string($answerId)."'";
+				$resq=Database::query($query);
+				$choice = Database::result($resq,0,"hotspot_correct");
+				display_hotspot_answer($answerId,$answer,$choice,$answerComment);
+
+				$i++;
+		 	}
+		 	$queryfree = "select marks from ".$TBL_TRACK_ATTEMPT." where exe_id = '".Database::escape_string($id)."' and question_id= '".Database::escape_string($questionId)."'";
+			$resfree = Database::query($queryfree, __FILE__, __LINE__);
+			$questionScore= Database::result($resfree,0,"marks");
+			$totalScore+=$questionScore;
+			echo '</table></td></tr>';
+		 	echo '<tr>
+				<td colspan="2">'.
+					//<object type="application/x-shockwave-flash" data="../plugin/hotspot/hotspot_solution.swf?modifyAnswers='.$questionId.'&exe_id='.$id.'&from_db=1" width="556" height="421">
+					'<object type="application/x-shockwave-flash" data="../plugin/hotspot/hotspot_solution.swf?modifyAnswers='.Security::remove_XSS($questionId).'&exe_id='.$id.'&from_db=1" width="552" height="352">
+						<param name="movie" value="../plugin/hotspot/hotspot_solution.swf?modifyAnswers='.Security::remove_XSS($questionId).'&exe_id='.$id.'&from_db=1" />
+					</object>
+
+				</td>
+			</tr>
+			</table><br/>';
+		}
+
 		echo '<table width="100%" border="0" cellspacing="3" cellpadding="0">';
-		if ($is_allowedToEdit) {
+		if ($is_allowedToEdit) {
 			echo '<tr><td>';
-			$name = "fckdiv".$questionId;
-			$marksname = "marksName".$questionId;
+			$name = "fckdiv".$questionId;
+			$marksname = "marksName".$questionId;
 			?>
-			<br />
-			<a href="javascript://" onclick="showfck('<?php echo $name; ?>','<?php echo $marksname; ?>');">
+			<br />
+			<a href="javascript://" onclick="showfck('<?php echo $name; ?>','<?php echo $marksname; ?>');">
 			<?php
 			if ($answerType == FREE_ANSWER) {
 				echo get_lang('EditCommentsAndMarks');
-			} else {
-				if ($action=='edit') {
-					echo '<img src="../img/edit.gif"/>'.get_lang('EditIndividualComment');
-				} else {
-					echo get_lang('AddComments');
-				}
-			}
-			echo '</a><br /><div id="feedback_'.$name.'" style="width:100%">';
-			$comnt = trim(get_comments($id,$questionId));
-			if (empty($comnt)) {
-				echo '<br />';
-			} else {
+			} else {
+				if ($action=='edit') {
+					echo '<img src="../img/edit.gif"/>'.get_lang('EditIndividualComment');
+				} else {
+					echo get_lang('AddComments');
+				}
+			}
+			echo '</a><br /><div id="feedback_'.$name.'" style="width:100%">';
+			$comnt = trim(get_comments($id,$questionId));
+			if (empty($comnt)) {
+				echo '<br />';
+			} else {
 				echo '<div id="question_feedback">'.$comnt.'</div>';
-			}
-			echo '</div><div id="'.$name.'" style="display:none">';
-			$arrid[] = $questionId;
-
-			$feedback_form = new FormValidator('frmcomments'.$questionId,'post','');
-			$feedback_form->addElement('html','<br>');
-			$renderer =& $feedback_form->defaultRenderer();
-			$renderer->setFormTemplate('<form{attributes}><div align="left">{content}</div></form>');
-			$renderer->setElementTemplate('<div align="left">{element}</div>');
-			$comnt = get_comments($id,$questionId);
-			${user.$questionId}['comments_'.$questionId] = $comnt;
-			$feedback_form->addElement('html_editor', 'comments_'.$questionId, null, null, array('ToolbarSet' => 'TestAnswerFeedback', 'Width' => '100%', 'Height' => '120'));
-			$feedback_form->addElement('html','<br>');
-			//$feedback_form->addElement('submit','submitQuestion',get_lang('Ok'));
+			}
+			echo '</div><div id="'.$name.'" style="display:none">';
+			$arrid[] = $questionId;
+
+			$feedback_form = new FormValidator('frmcomments'.$questionId,'post','');
+			$feedback_form->addElement('html','<br>');
+			$renderer =& $feedback_form->defaultRenderer();
+			$renderer->setFormTemplate('<form{attributes}><div align="left">{content}</div></form>');
+			$renderer->setElementTemplate('<div align="left">{element}</div>');
+			$comnt = get_comments($id,$questionId);
+			${user.$questionId}['comments_'.$questionId] = $comnt;
+			$feedback_form->addElement('html_editor', 'comments_'.$questionId, null, null, array('ToolbarSet' => 'TestAnswerFeedback', 'Width' => '100%', 'Height' => '120'));
+			$feedback_form->addElement('html','<br>');
+			//$feedback_form->addElement('submit','submitQuestion',get_lang('Ok'));
 			$feedback_form->setDefaults(${user.$questionId});
 			$feedback_form->display();
-			echo '</div>';
-		} else {
-			$comnt = get_comments($id,$questionId);
-			echo '<tr><td><br />';
-			if (!empty($comnt)) {
+			echo '</div>';
+		} else {
+			$comnt = get_comments($id,$questionId);
+			echo '<tr><td><br />';
+			if (!empty($comnt)) {
 				echo '<b>'.get_lang('Feedback').'</b>';
-				echo '<div id="question_feedback">'.$comnt.'</div>';
-			}
-			echo '</td><td>';
-		}
-		if ($is_allowedToEdit) {
-			if ($answerType == FREE_ANSWER) {
-				$marksname = "marksName".$questionId;
-				?>
-				<div id="<?php echo $marksname; ?>" style="display:none">
-				<form name="marksform_<?php echo $questionId; ?>" method="post" action="">
-			    <?php
-				$arrmarks[] = $questionId;
+				echo '<div id="question_feedback">'.$comnt.'</div>';
+			}
+			echo '</td><td>';
+		}
+		if ($is_allowedToEdit) {
+			if ($answerType == FREE_ANSWER) {
+				$marksname = "marksName".$questionId;
+				?>
+				<div id="<?php echo $marksname; ?>" style="display:none">
+				<form name="marksform_<?php echo $questionId; ?>" method="post" action="">
+			    <?php
+				$arrmarks[] = $questionId;
 				echo get_lang("AssignMarks");
-				echo "&nbsp;<select name='marks' id='marks'>";
-				for ($i=0;$i<=$questionWeighting;$i++) {
-					echo '<option '.(($i==$questionScore)?"selected='selected'":'').'>'.$i.'</option>';
-				}
-				echo '</select>';
-				echo '</form><br/ ></div>';
-				if ($questionScore==-1) {
-					$questionScore=0;
-				  	echo '<br />'.get_lang('notCorrectedYet');
-				}
-			} else {
-				$arrmarks[] = $questionId;
-				echo '<div id="'.$marksname.'" style="display:none"><form name="marksform_'.$questionId.'" method="post" action="">
-					  <select name="marks" id="marks" style="display:none;"><option>'.$questionScore.'</option></select></form><br/ ></div>';
-			}
-		} else {
-			if ($questionScore==-1) {
-				 $questionScore=0;
-			}
-		}
+				echo "&nbsp;<select name='marks' id='marks'>";
+				for ($i=0;$i<=$questionWeighting;$i++) {
+					echo '<option '.(($i==$questionScore)?"selected='selected'":'').'>'.$i.'</option>';
+				}
+				echo '</select>';
+				echo '</form><br/ ></div>';
+				if ($questionScore==-1) {
+					$questionScore=0;
+				  	echo '<br />'.get_lang('notCorrectedYet');
+				}
+			} else {
+				$arrmarks[] = $questionId;
+				echo '<div id="'.$marksname.'" style="display:none"><form name="marksform_'.$questionId.'" method="post" action="">
+					  <select name="marks" id="marks" style="display:none;"><option>'.$questionScore.'</option></select></form><br/ ></div>';
+			}
+		} else {
+			if ($questionScore==-1) {
+				 $questionScore=0;
+			}
+		}
 		?>
-		</td>
-		</tr>
-		</table>
+		</td>
+		</tr>
+		</table>
 
-		<div id="question_score">
-		<?php
-		$my_total_score  = float_format($questionScore,1);
+		<div id="question_score">
+		<?php
+		$my_total_score  = float_format($questionScore,1);
 		$my_total_weight = float_format($questionWeighting,1);
 		echo get_lang('Score')." : $my_total_score/$my_total_weight";
-		echo '</div>';
-		unset($objAnswerTmp);
-		$i++;
-		$totalWeighting+=$questionWeighting;
-	} // end of large foreach on questions
-} //end of condition if $show_results
-
-if ($origin!='learnpath' || ($origin == 'learnpath' && isset($_GET['fb_type']))) {
-	//$query = "update ".$TBL_TRACK_EXERCICES." set exe_result = $totalScore where exe_id = '$id'";
-	//Database::query($query,__FILE__,__LINE__);
-	if ($show_results) {
-		echo '<div id="question_score">'.get_lang('YourTotalScore')." ";
-		if($dsp_percent == true) {
-			$my_result = number_format(($totalScore/$totalWeighting)*100,1,'.','');
-			$my_result = float_format($my_result,1);
-			echo $my_result."%";
-		} else {
-			$my_total_score  = float_format($totalScore,1);
+		echo '</div>';
+		unset($objAnswerTmp);
+		$i++;
+		$totalWeighting+=$questionWeighting;
+	} // end of large foreach on questions
+} //end of condition if $show_results
+
+if ($origin!='learnpath' || ($origin == 'learnpath' && isset($_GET['fb_type']))) {
+	//$query = "update ".$TBL_TRACK_EXERCICES." set exe_result = $totalScore where exe_id = '$id'";
+	//Database::query($query,__FILE__,__LINE__);
+	if ($show_results) {
+		echo '<div id="question_score">'.get_lang('YourTotalScore')." ";
+		if($dsp_percent == true) {
+			$my_result = number_format(($totalScore/$totalWeighting)*100,1,'.','');
+			$my_result = float_format($my_result,1);
+			echo $my_result."%";
+		} else {
+			$my_total_score  = float_format($totalScore,1);
 			$my_total_weight = float_format($totalWeighting,1);
-			echo $my_total_score."/".$my_total_weight;
-		}
+			echo $my_total_score."/".$my_total_weight;
+		}
 		echo '!</div>';
-	}
-}
-
-if (is_array($arrid) && is_array($arrmarks)) {
-	$strids = implode(",",$arrid);
-	$marksid = implode(",",$arrmarks);
-}
-
+	}
+}
+
+if (is_array($arrid) && is_array($arrmarks)) {
+	$strids = implode(",",$arrid);
+	$marksid = implode(",",$arrmarks);
+}
+
 if ($is_allowedToEdit) {
-	if (in_array($origin, array('tracking_course','user_course'))) {
+	if (in_array($origin, array('tracking_course','user_course'))) {
 
-		echo ' <form name="myform" id="myform" action="exercice.php?show=result&comments=update&exeid='.$id.'&test='.urlencode($test).'&emailid='.$emailId.'&origin='.$origin.'&student='.$_GET['student'].'&details=true&course='.$_GET['cidReq'].$fromlink.'" method="post">';
-		echo ' <input type = "hidden" name="totalWeighting" value="'.$totalWeighting.'">';
+		echo ' <form name="myform" id="myform" action="exercice.php?show=result&comments=update&exeid='.$id.'&test='.urlencode($test).'&emailid='.$emailId.'&origin='.$origin.'&student='.$_GET['student'].'&details=true&course='.$_GET['cidReq'].$fromlink.'" method="post">';
+		echo ' <input type = "hidden" name="totalWeighting" value="'.$totalWeighting.'">';
 		if (isset($_GET['myid']) && isset($_GET['my_lp_id']) && isset($_GET['student'])) {
-			?>
-			<input type = "hidden" name="lp_item_id" value="<?php echo Security::remove_XSS($_GET['myid']); ?>">
-			<input type = "hidden" name="lp_item_view_id" value="<?php echo Security::remove_XSS($_GET['my_lp_id']); ?>">
-			<input type = "hidden" name="student_id" value="<?php echo Security::remove_XSS($_GET['student']);?>">
-			<input type = "hidden" name="total_score" value="<?php echo $totalScore; ?>">
+			?>
+			<input type = "hidden" name="lp_item_id" value="<?php echo Security::remove_XSS($_GET['myid']); ?>">
+			<input type = "hidden" name="lp_item_view_id" value="<?php echo Security::remove_XSS($_GET['my_lp_id']); ?>">
+			<input type = "hidden" name="student_id" value="<?php echo Security::remove_XSS($_GET['student']);?>">
+			<input type = "hidden" name="total_score" value="<?php echo $totalScore; ?>">
 			<input type = "hidden" name="total_time" value="<?php echo Security::remove_XSS($_GET['total_time']);?>">
 			<input type = "hidden" name="my_exe_exo_id" value="<?php echo Security::remove_XSS($_GET['my_exe_exo_id']); ?>">
 			<?php
-		}
-	} else {
-		echo ' <form name="myform" id="myform" action="exercice.php?show=result&comments=update&exeid='.$id.'&test='.$test.'&emailid='.$emailId.'&totalWeighting='.$totalWeighting.'" method="post">';
+		}
+	} else {
+		echo ' <form name="myform" id="myform" action="exercice.php?show=result&comments=update&exeid='.$id.'&test='.$test.'&emailid='.$emailId.'&totalWeighting='.$totalWeighting.'" method="post">';
 	}
-	if ($origin!='learnpath' && $origin!='student_progress') {
+	if ($origin!='learnpath' && $origin!='student_progress') {
 		?>
 		<button type="submit" class="save" value="<?php echo get_lang('Ok'); ?>" onclick="getFCK('<?php echo $strids; ?>','<?php echo $marksid; ?>');"><?php echo get_lang('FinishTest'); ?></button>
-		</form>
+		</form>
 		<?php
-	}
+	}
 }
-
+
 if ($origin=='student_progress') {?>
 	<button type="button" class="back" onclick="window.back();" value="<?php echo get_lang('Back'); ?>" ><?php echo get_lang('Back');?></button>
 <?php
-} else if($origin=='myprogress') {
-?>
+} else if($origin=='myprogress') {
+?>
 	<button type="button" class="save" onclick="top.location.href='../auth/my_progress.php?course=<?php echo api_get_course_id()?>'" value="<?php echo get_lang('Finish'); ?>" ><?php echo get_lang('Finish');?></button>
 <?php
-}
+}
 
-if ($origin != 'learnpath') {
-	//we are not in learnpath tool
-	Display::display_footer();
-} else {
+if ($origin != 'learnpath') {
+	//we are not in learnpath tool
+	Display::display_footer();
+} else {
 
-	if (!isset($_GET['fb_type'])) {
-		$lp_mode =  $_SESSION['lp_mode'];
-		$url = '../newscorm/lp_controller.php?cidReq='.api_get_course_id().'&action=view&lp_id='.$learnpath_id.'&lp_item_id='.$learnpath_item_id.'&exeId='.$exeId.'&fb_type='.$feedback_type;
+	if (!isset($_GET['fb_type'])) {
+		$lp_mode =  $_SESSION['lp_mode'];
+		$url = '../newscorm/lp_controller.php?cidReq='.api_get_course_id().'&action=view&lp_id='.$learnpath_id.'&lp_item_id='.$learnpath_item_id.'&exeId='.$exeId.'&fb_type='.$feedback_type;
 		$href = ($lp_mode == 'fullscreen')?' window.opener.location.href="'.$url.'" ':' top.location.href="'.$url.'" ';
-		echo '<script language="javascript" type="text/javascript">'.$href.'</script>'."\n";
-
-		//record the results in the learning path, using the SCORM interface (API)
-		echo '<script language="javascript" type="text/javascript">window.parent.API.void_save_asset('.$totalScore.','.$totalWeighting.');</script>'."\n";
-		echo '</body></html>';
-	} else {
-		Display::display_normal_message(get_lang('ExerciseFinished'));
-	}
-}
+		echo '<script language="javascript" type="text/javascript">'.$href.'</script>'."\n";
+
+		//record the results in the learning path, using the SCORM interface (API)
+		echo '<script language="javascript" type="text/javascript">window.parent.API.void_save_asset('.$totalScore.','.$totalWeighting.');</script>'."\n";
+		echo '</body></html>';
+	} else {
+		Display::display_normal_message(get_lang('ExerciseFinished'));
+	}
+}
 //destroying the session
-api_session_unregister('questionList');
-unset ($questionList);
-
-api_session_unregister('exerciseResult');
-unset ($exerciseResult);
+api_session_unregister('questionList');
+unset ($questionList);
+
+api_session_unregister('exerciseResult');
+unset ($exerciseResult);

+ 11 - 11
main/exercice/export/index.php

@@ -1,13 +1,13 @@
-<?php // $Id: $
-/**
- * @copyright (c) 2001-2006 Universite catholique de Louvain (UCL)
- *
- * @license http://www.gnu.org/copyleft/gpl.html (GPL) GENERAL PUBLIC LICENSE
- *
- * @author Claro Team <cvs@claroline.net>
- * @package dokeos.exercise
- *
- */
-header("Location: ../../../");
+<?php // $Id: $
+/**
+ * @copyright (c) 2001-2006 Universite catholique de Louvain (UCL)
+ *
+ * @license http://www.gnu.org/copyleft/gpl.html (GPL) GENERAL PUBLIC LICENSE
+ *
+ * @author Claro Team <cvs@claroline.net>
+ * @package dokeos.exercise
+ *
+ */
+header("Location: ../../../");
 exit();
 ?>

+ 94 - 94
main/exercice/feedback.php

@@ -1,96 +1,96 @@
-<?php
-/*
-    DOKEOS - elearning and course management software
-
-    For a full list of contributors, see documentation/credits.html
-
-    This program is free software; you can redistribute it and/or
-    modify it under the terms of the GNU General Public License
-    as published by the Free Software Foundation; either version 2
-    of the License, or (at your option) any later version.
-    See "documentation/licence.html" more details.
-
-    Contact:
-		Dokeos
-		Rue des Palais 44 Paleizenstraat
-		B-1030 Brussels - Belgium
-		Tel. +32 (2) 211 34 56
-*/
-
-// Note by Ivan Tcholakov, 14-JUL-2009: I can't see where this file is used. Is it obsolete?
-
-/**
-*	Feedback
-*	@package dokeos.exercise
-* 	@author
-* 	@version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $
-*/
-include('exercise.class.php');
-include('question.class.php');
-include('answer.class.php');
-
-include('exercise.lib.php');
-
-// name of the language file that needs to be included
-$language_file='exercice';
-
-include("../inc/global.inc.php");
-$this_section=SECTION_COURSES;
-
-include_once(api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
-include_once(api_get_path(LIBRARY_PATH).'document.lib.php');
-include_once(api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-$nameTools=get_lang('ExerciseManagement');
-
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+<?php
+/*
+    DOKEOS - elearning and course management software
+
+    For a full list of contributors, see documentation/credits.html
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+    See "documentation/licence.html" more details.
+
+    Contact:
+		Dokeos
+		Rue des Palais 44 Paleizenstraat
+		B-1030 Brussels - Belgium
+		Tel. +32 (2) 211 34 56
+*/
+
+// Note by Ivan Tcholakov, 14-JUL-2009: I can't see where this file is used. Is it obsolete?
+
+/**
+*	Feedback
+*	@package dokeos.exercise
+* 	@author
+* 	@version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $
+*/
+include('exercise.class.php');
+include('question.class.php');
+include('answer.class.php');
+
+include('exercise.lib.php');
+
+// name of the language file that needs to be included
+$language_file='exercice';
+
+include("../inc/global.inc.php");
+$this_section=SECTION_COURSES;
+
+include_once(api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
+include_once(api_get_path(LIBRARY_PATH).'document.lib.php');
+include_once(api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+$nameTools=get_lang('ExerciseManagement');
+
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-
-$interbreadcrumb[]=array("url" => "exercice.php","name" => get_lang('Exercices'));
-Display::display_header($nameTools,"Exercise");
-?>
-<table border="0" align="center" cellpadding="2" cellspacing="2" width="100%">
-<h4>
-  <?php echo "Add Feedback"; ?>
-</h4>
-<?php
-	$id = $_REQUEST['question'];
-	$objQuestionTmp = Question::read($id);
-	echo "<tr><td><b>".get_lang('Question')." : </b>";
-	echo $objQuestionTmp->selectTitle();
-	echo "</td></tr>";
-	echo " <br><tr><td><b><br>".get_lang('Answer')." : </b></td></tr>";
-	$objAnswerTmp=new Answer($id);
-	$num = $objAnswerTmp->selectNbrAnswers();
-	$objAnswerTmp->read();
-	for($i=1;$i<=$num;$i++)
-	{
-	echo "<tr><td width='10%'> ";
-	$ans =  $objAnswerTmp->answer[$i];
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
+
+$interbreadcrumb[]=array("url" => "exercice.php","name" => get_lang('Exercices'));
+Display::display_header($nameTools,"Exercise");
+?>
+<table border="0" align="center" cellpadding="2" cellspacing="2" width="100%">
+<h4>
+  <?php echo "Add Feedback"; ?>
+</h4>
+<?php
+	$id = $_REQUEST['question'];
+	$objQuestionTmp = Question::read($id);
+	echo "<tr><td><b>".get_lang('Question')." : </b>";
+	echo $objQuestionTmp->selectTitle();
+	echo "</td></tr>";
+	echo " <br><tr><td><b><br>".get_lang('Answer')." : </b></td></tr>";
+	$objAnswerTmp=new Answer($id);
+	$num = $objAnswerTmp->selectNbrAnswers();
+	$objAnswerTmp->read();
+	for($i=1;$i<=$num;$i++)
+	{
+	echo "<tr><td width='10%'> ";
+	$ans =  $objAnswerTmp->answer[$i];
 
-	$form = new FormValidator('feedbackform','post',api_get_self()."?modifyQuestion=".$modifyQuestion."&newQuestion=".$newQuestion);
-	$obj_registration_form = new HTML_QuickForm('frmRegistration', 'POST');
-	$renderer =& $obj_registration_form->defaultRenderer();
-	$renderer->setElementTemplate(
-'<tr>
-	<td align="left" style="" valign="top" width=30%>{label}
-		<!-- BEGIN required --><span style="color: #ff0000">*</span><!-- END required -->
-	</td>
-	<td align="left" width=70%>{element}
-		<!-- BEGIN error --><br /><span style="color: #ff0000;font-size:10px">{error}</span><!-- END error -->
-	</td>
-</tr>');
-	$form->add_html_editor('Feedback', $i.'.'.$ans, false, false, array('ToolbarSet' => 'TestAnswerFeedback', 'Width' => '600', 'Height' => '200'));
-	$form->display();
-	echo "</td>";
-	}?>
-	<form name="frm" action="javascript: void(0);" method="post">
-	 Click Ok to finish <input  type="submit" value="Ok" />
-	</form>
+	$form = new FormValidator('feedbackform','post',api_get_self()."?modifyQuestion=".$modifyQuestion."&newQuestion=".$newQuestion);
+	$obj_registration_form = new HTML_QuickForm('frmRegistration', 'POST');
+	$renderer =& $obj_registration_form->defaultRenderer();
+	$renderer->setElementTemplate(
+'<tr>
+	<td align="left" style="" valign="top" width=30%>{label}
+		<!-- BEGIN required --><span style="color: #ff0000">*</span><!-- END required -->
+	</td>
+	<td align="left" width=70%>{element}
+		<!-- BEGIN error --><br /><span style="color: #ff0000;font-size:10px">{error}</span><!-- END error -->
+	</td>
+</tr>');
+	$form->add_html_editor('Feedback', $i.'.'.$ans, false, false, array('ToolbarSet' => 'TestAnswerFeedback', 'Width' => '600', 'Height' => '200'));
+	$form->display();
+	echo "</td>";
+	}?>
+	<form name="frm" action="javascript: void(0);" method="post">
+	 Click Ok to finish <input  type="submit" value="Ok" />
+	</form>

+ 5 - 5
main/exercice/hotspot_actionscript.as.php

@@ -57,11 +57,11 @@ while ($hotspot = mysql_fetch_assoc($result))
 	if ($hotspot['hotspot_type'] == 'poly')
 	{
 		$output .= "&hotspot_".$hotspot['id']."_type=poly";
-	}
-	// Delineation
-	if ($hotspot['hotspot_type'] == 'delineation')
-	{
-		$output .= "&hotspot_".$hotspot['id']."_type=delineation";
+	}
+	// Delineation
+	if ($hotspot['hotspot_type'] == 'delineation')
+	{
+		$output .= "&hotspot_".$hotspot['id']."_type=delineation";
 	}
 
 	// This is a good answer, count + 1 for nmbr of clicks

+ 5 - 5
main/exercice/hotspot_actionscript_admin.as.php

@@ -66,11 +66,11 @@ for($i=1;$i <= $nbrAnswers;$i++)
 	if ($answers['hotspot_type'][$i] == 'poly')
 	{
 		$output .= "&hotspot_".$i."_type=poly";
-	}
-	// Delineation
-	if ($answers['hotspot_type'][$i] == 'delineation')
-	{
-		$output .= "&hotspot_".$i."_type=delineation";
+	}
+	// Delineation
+	if ($answers['hotspot_type'][$i] == 'delineation')
+	{
+		$output .= "&hotspot_".$i."_type=delineation";
 	}
 
 	// This is a good answer, count + 1 for nmbr of clicks

+ 226 - 226
main/exercice/mark_free_answer.php

@@ -1,227 +1,227 @@
-<?php
-/*
-    DOKEOS - elearning and course management software
-
-    For a full list of contributors, see documentation/credits.html
-
-    This program is free software; you can redistribute it and/or
-    modify it under the terms of the GNU General Public License
-    as published by the Free Software Foundation; either version 2
-    of the License, or (at your option) any later version.
-    See "documentation/licence.html" more details.
-
-    Contact:
-		Dokeos
-		Rue des Palais 44 Paleizenstraat
-		B-1030 Brussels - Belgium
-		Tel. +32 (2) 211 34 56
-*/
-
-
-/**
-*	Free answer marking script
-* 	This script allows a course tutor to mark a student's free answer.
-*	@package dokeos.exercise
-* 	@author Yannick Warnier <yannick.warnier@dokeos.com>
-* 	@version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $
-*
-* 	@todo respect coding guidelines
-*/
-
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
-*/
-// name of the language file that needs to be included
-$language_file='exercice';
-
-// name of the language file that needs to be included
-include('../inc/global.inc.php');
-
-// including additional libraries
-include('exercise.class.php');
-include('question.class.php');
-include('answer.class.php');
-include_once(api_get_library_path().'/text.lib.php');
-
-// answer types
-define('UNIQUE_ANSWER',	1);
-define('MULTIPLE_ANSWER',	2);
-define('FILL_IN_BLANKS',	3);
-define('MATCHING',		4);
-define('FREE_ANSWER', 5);
-
-
-
-
-/** @todo use the Database:: functions */
-$TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
-$TBL_EXERCICES         = Database::get_course_table(TABLE_QUIZ_TEST);
-$TBL_QUESTIONS         = Database::get_course_table(TABLE_QUIZ_QUESTION);
-$TBL_REPONSES          = Database::get_course_table(TABLE_QUIZ_ANSWER);
-
-//debug param. 0: no display - 1: debug display
-$debug=0;
-if($debug>0){echo str_repeat('&nbsp;',0).'Entered exercise_result.php'."<br />\n";var_dump($_POST);}
-
-// general parameters passed via POST/GET
-$my_course_code = $_GET['cid'];
-if(!empty($_REQUEST['exe'])){
-	$my_exe = $_REQUEST['exe'];
-}else{
-	$my_exe = null;
-}
-if(!empty($_REQUEST['qst'])){
-	$my_qst = $_REQUEST['qst'];
-}else{
-	$my_qst = null;
-}
-if(!empty($_REQUEST['usr'])){
-	$my_usr = $_REQUEST['usr'];
-}else{
-	$my_usr = null;
-}
-if(!empty($_REQUEST['cidReq'])){
-	$my_cid = $_REQUEST['cidReq'];
-}else{
-	$my_cid = null;
-}
-if(!empty($_POST['action'])){
-	$action = $_POST['action'];
-}else{
-	$action = '';
-}
-
-if (empty($my_qst) or empty($my_usr) or empty($my_cid) or empty($my_exe)){
-	header('Location: exercice.php');
-	exit();
-}
-
-if(!$is_courseTutor)
-{
-	api_not_allowed();
-}
-
-$obj_question = Question :: read($my_qst);
-
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+<?php
+/*
+    DOKEOS - elearning and course management software
+
+    For a full list of contributors, see documentation/credits.html
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+    See "documentation/licence.html" more details.
+
+    Contact:
+		Dokeos
+		Rue des Palais 44 Paleizenstraat
+		B-1030 Brussels - Belgium
+		Tel. +32 (2) 211 34 56
+*/
+
+
+/**
+*	Free answer marking script
+* 	This script allows a course tutor to mark a student's free answer.
+*	@package dokeos.exercise
+* 	@author Yannick Warnier <yannick.warnier@dokeos.com>
+* 	@version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $
+*
+* 	@todo respect coding guidelines
+*/
+
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
+*/
+// name of the language file that needs to be included
+$language_file='exercice';
+
+// name of the language file that needs to be included
+include('../inc/global.inc.php');
+
+// including additional libraries
+include('exercise.class.php');
+include('question.class.php');
+include('answer.class.php');
+include_once(api_get_library_path().'/text.lib.php');
+
+// answer types
+define('UNIQUE_ANSWER',	1);
+define('MULTIPLE_ANSWER',	2);
+define('FILL_IN_BLANKS',	3);
+define('MATCHING',		4);
+define('FREE_ANSWER', 5);
+
+
+
+
+/** @todo use the Database:: functions */
+$TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
+$TBL_EXERCICES         = Database::get_course_table(TABLE_QUIZ_TEST);
+$TBL_QUESTIONS         = Database::get_course_table(TABLE_QUIZ_QUESTION);
+$TBL_REPONSES          = Database::get_course_table(TABLE_QUIZ_ANSWER);
+
+//debug param. 0: no display - 1: debug display
+$debug=0;
+if($debug>0){echo str_repeat('&nbsp;',0).'Entered exercise_result.php'."<br />\n";var_dump($_POST);}
+
+// general parameters passed via POST/GET
+$my_course_code = $_GET['cid'];
+if(!empty($_REQUEST['exe'])){
+	$my_exe = $_REQUEST['exe'];
+}else{
+	$my_exe = null;
+}
+if(!empty($_REQUEST['qst'])){
+	$my_qst = $_REQUEST['qst'];
+}else{
+	$my_qst = null;
+}
+if(!empty($_REQUEST['usr'])){
+	$my_usr = $_REQUEST['usr'];
+}else{
+	$my_usr = null;
+}
+if(!empty($_REQUEST['cidReq'])){
+	$my_cid = $_REQUEST['cidReq'];
+}else{
+	$my_cid = null;
+}
+if(!empty($_POST['action'])){
+	$action = $_POST['action'];
+}else{
+	$action = '';
+}
+
+if (empty($my_qst) or empty($my_usr) or empty($my_cid) or empty($my_exe)){
+	header('Location: exercice.php');
+	exit();
+}
+
+if(!$is_courseTutor)
+{
+	api_not_allowed();
+}
+
+$obj_question = Question :: read($my_qst);
+
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-
-$nameTools=get_lang('Exercice');
-
-$interbreadcrumb[]=array("url" => "exercice.php","name" => get_lang('Exercices'));
-
-$my_msg = 'No change.';
-
-if($action == 'mark'){
-	if (!empty($_POST['score']) AND $_POST['score'] < $obj_question->selectWeighting() AND $_POST['score'] >= 0){
-
-		//mark the user mark into the database using something similar to the following function:
-		global $_configuration;
-
-		if($_configuration['tracking_enabled'])
-		{
-			$exercise_table = Database::get_statistic_table('track_e_exercices');
-			#$tbl_learnpath_user = Database::get_course_table('learnpath_user');
-			#global $origin, $tbl_learnpath_user, $learnpath_id, $learnpath_item_id;
-			$sql = "SELECT * FROM $exercise_table
-				WHERE exe_user_id = '".Database::escape_string($my_usr)."' AND exe_cours_id = '".Database::escape_string($my_cid)."' AND exe_exo_id = '".Database::escape_string($my_exe)."'
-				ORDER BY exe_date DESC";
-			#echo $sql;
-			$res = Database::query($sql,__FILE__,__LINE__);
-			if(mysql_num_rows($res)>0){
-				$row = mysql_fetch_array($res);
-				//@todo Check that just summing past score and the new free answer mark doesn't come up
-				// with a score higher than the possible score for that exercise
-				$my_score = $row['exe_result'] + $_POST['score'];
-				$sql = "UPDATE $exercise_table SET exe_result = '$my_score'
-					WHERE exe_id = '".$row['exe_id']."'";
-				#echo $sql;
-				$res = Database::query($sql,__FILE__,__LINE__);
-				$my_msg = get_lang('MarkIsUpdated');
-			}else{
-				$my_score = $_POST['score'];
-				$reallyNow = time();
-				$sql = "INSERT INTO $exercise_table
-						  (
-						   exe_user_id,
-						   exe_cours_id,
-						   exe_exo_id,
-						   exe_result,
-						   exe_weighting,
-						   exe_date
-						  )
-
-						  VALUES
-						  (
-						   '".Database::escape_string($my_usr)."',
-						   '".Database::escape_string($my_cid)."',
-						   '".Database::escape_string($my_exe)."',
-						   '".Database::escape_string($my_score)."',
-						   '".Database::escape_string($obj_question->selectWeighting())."',
-						   FROM_UNIXTIME(".$reallyNow.")
-						  )";
-				#if ($origin == 'learnpath')
-				#{
-				#	if ($user_id == "NULL")
-				#	{
-				#		$user_id = '0';
-				#	}
-				#	$sql2 = "update `$tbl_learnpath_user` set score='$score' where (user_id=$user_id and learnpath_id='$learnpath_id' and learnpath_item_id='$learnpath_item_id')";
-				#	$res2 = Database::query($sql2,__FILE__,__LINE__);
-				#}
-				$res = Database::query($sql,__FILE__,__LINE__);
-				$my_msg = get_lang('MarkInserted');
-			}
-			//$mysql_query($sql);
-			//return 0;
-		}
-	}else{
-		$my_msg .= get_lang('TotalScoreTooBig');
-	}
-}
-
-Display::display_header($nameTools,"Exercise");
-
-// Display simple marking interface
-
-// 1a - result of previous marking then exit suggestion
-// 1b - user answer and marking box + submit button
-$objAnswerTmp = new Answer();
-$objAnswerTmp->selectAnswer($answerId);
-
-if($action == 'mark'){
-	echo $my_msg.'<br />
-		<a href="exercice.php?cidReq='.$cidReq.'">'.get_lang('Back').'</a>';
-}else{
-
-
-	echo '<h2>'.$obj_question->question .':</h2>
-		'.$obj_question->selectTitle().'<br /><br />
-		'.get_lang('PleaseGiveAMark').
-		"<form action='' method='POST'>\n"
-		."<input type='hidden' name='exe' value='$my_exe'>\n"
-		."<input type='hidden' name='usr' value='$my_usr'>\n"
-		."<input type='hidden' name='cidReq' value='$my_cid'>\n"
-		."<input type='hidden' name='action' value='mark'>\n"
-		."<select name='score'>\n";
-		for($i=0 ; $i<$obj_question->selectWeighting() ; $i++){
-			echo '<option>'.$i.'</option>';
-		}
-		echo "</select>".
-		"<input type='submit' name='submit' value='".get_lang('Ok')."'>\n"
-		."</form>";
-}
-
-Display::display_footer();
-
-?>
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
+
+$nameTools=get_lang('Exercice');
+
+$interbreadcrumb[]=array("url" => "exercice.php","name" => get_lang('Exercices'));
+
+$my_msg = 'No change.';
+
+if($action == 'mark'){
+	if (!empty($_POST['score']) AND $_POST['score'] < $obj_question->selectWeighting() AND $_POST['score'] >= 0){
+
+		//mark the user mark into the database using something similar to the following function:
+		global $_configuration;
+
+		if($_configuration['tracking_enabled'])
+		{
+			$exercise_table = Database::get_statistic_table('track_e_exercices');
+			#$tbl_learnpath_user = Database::get_course_table('learnpath_user');
+			#global $origin, $tbl_learnpath_user, $learnpath_id, $learnpath_item_id;
+			$sql = "SELECT * FROM $exercise_table
+				WHERE exe_user_id = '".Database::escape_string($my_usr)."' AND exe_cours_id = '".Database::escape_string($my_cid)."' AND exe_exo_id = '".Database::escape_string($my_exe)."'
+				ORDER BY exe_date DESC";
+			#echo $sql;
+			$res = Database::query($sql,__FILE__,__LINE__);
+			if(mysql_num_rows($res)>0){
+				$row = mysql_fetch_array($res);
+				//@todo Check that just summing past score and the new free answer mark doesn't come up
+				// with a score higher than the possible score for that exercise
+				$my_score = $row['exe_result'] + $_POST['score'];
+				$sql = "UPDATE $exercise_table SET exe_result = '$my_score'
+					WHERE exe_id = '".$row['exe_id']."'";
+				#echo $sql;
+				$res = Database::query($sql,__FILE__,__LINE__);
+				$my_msg = get_lang('MarkIsUpdated');
+			}else{
+				$my_score = $_POST['score'];
+				$reallyNow = time();
+				$sql = "INSERT INTO $exercise_table
+						  (
+						   exe_user_id,
+						   exe_cours_id,
+						   exe_exo_id,
+						   exe_result,
+						   exe_weighting,
+						   exe_date
+						  )
+
+						  VALUES
+						  (
+						   '".Database::escape_string($my_usr)."',
+						   '".Database::escape_string($my_cid)."',
+						   '".Database::escape_string($my_exe)."',
+						   '".Database::escape_string($my_score)."',
+						   '".Database::escape_string($obj_question->selectWeighting())."',
+						   FROM_UNIXTIME(".$reallyNow.")
+						  )";
+				#if ($origin == 'learnpath')
+				#{
+				#	if ($user_id == "NULL")
+				#	{
+				#		$user_id = '0';
+				#	}
+				#	$sql2 = "update `$tbl_learnpath_user` set score='$score' where (user_id=$user_id and learnpath_id='$learnpath_id' and learnpath_item_id='$learnpath_item_id')";
+				#	$res2 = Database::query($sql2,__FILE__,__LINE__);
+				#}
+				$res = Database::query($sql,__FILE__,__LINE__);
+				$my_msg = get_lang('MarkInserted');
+			}
+			//$mysql_query($sql);
+			//return 0;
+		}
+	}else{
+		$my_msg .= get_lang('TotalScoreTooBig');
+	}
+}
+
+Display::display_header($nameTools,"Exercise");
+
+// Display simple marking interface
+
+// 1a - result of previous marking then exit suggestion
+// 1b - user answer and marking box + submit button
+$objAnswerTmp = new Answer();
+$objAnswerTmp->selectAnswer($answerId);
+
+if($action == 'mark'){
+	echo $my_msg.'<br />
+		<a href="exercice.php?cidReq='.$cidReq.'">'.get_lang('Back').'</a>';
+}else{
+
+
+	echo '<h2>'.$obj_question->question .':</h2>
+		'.$obj_question->selectTitle().'<br /><br />
+		'.get_lang('PleaseGiveAMark').
+		"<form action='' method='POST'>\n"
+		."<input type='hidden' name='exe' value='$my_exe'>\n"
+		."<input type='hidden' name='usr' value='$my_usr'>\n"
+		."<input type='hidden' name='cidReq' value='$my_cid'>\n"
+		."<input type='hidden' name='action' value='mark'>\n"
+		."<select name='score'>\n";
+		for($i=0 ; $i<$obj_question->selectWeighting() ; $i++){
+			echo '<option>'.$i.'</option>';
+		}
+		echo "</select>".
+		"<input type='submit' name='submit' value='".get_lang('Ok')."'>\n"
+		."</form>";
+}
+
+Display::display_footer();
+
+?>

+ 212 - 212
main/exercice/multiple_answer.class.php

@@ -1,220 +1,220 @@
-<?php // $Id: document.php 16494 2008-10-10 22:07:36Z yannoo $
-
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2008 Dokeos SPRL
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) various contributors
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
-==============================================================================
-*/
-
-/**
-*	File containing the MultipleAnswer class.
-*	@package dokeos.exercise
-* 	@author Eric Marguin
-* 	@version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $
-*/
-
-if(!class_exists('MultipleAnswer')):
-
-/**
-	CLASS MultipleAnswer
- *
- *	This class allows to instantiate an object of type MULTIPLE_ANSWER (MULTIPLE CHOICE, MULTIPLE ANSWER),
- *	extending the class question
- *
- *	@author Eric Marguin
- *	@package dokeos.exercise
- **/
-
-class MultipleAnswer extends Question {
-
-	static $typePicture = 'mcma.gif';
-	static $explanationLangVar = 'MultipleSelect';
-
-	/**
-	 * Constructor
-	 */
-	function MultipleAnswer(){
-		parent::question();
-		$this -> type = MULTIPLE_ANSWER;
-	}
-
-	/**
-	 * function which redifines Question::createAnswersForm
-	 * @param the formvalidator instance
-	 * @param the answers number to display
-	 */
-	function createAnswersForm ($form) {
-
-		$nb_answers = isset($_POST['nb_answers']) ? $_POST['nb_answers'] : 2;
-		$nb_answers += (isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0));
-
-		$html='
-		<div class="row">
-			<div class="label">
-			'.get_lang('Answers').'<br /><img src="../img/fill_field.png">
-			</div>
-			<div class="formw">
-				<table class="data_table">
-					<tr style="text-align: center;">
-						<th>
-							'.get_lang('Number').'
-						</th>
-						<th>
-							'.get_lang('True').'
-						</th>
-						<th>
-							'.get_lang('Answer').'
-						</th>
-						<th>
-							'.get_lang('Comment').'
-						</th>
-						<th>
-							'.get_lang('Weighting').'
+<?php // $Id: document.php 16494 2008-10-10 22:07:36Z yannoo $
+
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2008 Dokeos SPRL
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) various contributors
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+
+/**
+*	File containing the MultipleAnswer class.
+*	@package dokeos.exercise
+* 	@author Eric Marguin
+* 	@version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $
+*/
+
+if(!class_exists('MultipleAnswer')):
+
+/**
+	CLASS MultipleAnswer
+ *
+ *	This class allows to instantiate an object of type MULTIPLE_ANSWER (MULTIPLE CHOICE, MULTIPLE ANSWER),
+ *	extending the class question
+ *
+ *	@author Eric Marguin
+ *	@package dokeos.exercise
+ **/
+
+class MultipleAnswer extends Question {
+
+	static $typePicture = 'mcma.gif';
+	static $explanationLangVar = 'MultipleSelect';
+
+	/**
+	 * Constructor
+	 */
+	function MultipleAnswer(){
+		parent::question();
+		$this -> type = MULTIPLE_ANSWER;
+	}
+
+	/**
+	 * function which redifines Question::createAnswersForm
+	 * @param the formvalidator instance
+	 * @param the answers number to display
+	 */
+	function createAnswersForm ($form) {
+
+		$nb_answers = isset($_POST['nb_answers']) ? $_POST['nb_answers'] : 2;
+		$nb_answers += (isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0));
+
+		$html='
+		<div class="row">
+			<div class="label">
+			'.get_lang('Answers').'<br /><img src="../img/fill_field.png">
+			</div>
+			<div class="formw">
+				<table class="data_table">
+					<tr style="text-align: center;">
+						<th>
+							'.get_lang('Number').'
+						</th>
+						<th>
+							'.get_lang('True').'
+						</th>
+						<th>
+							'.get_lang('Answer').'
+						</th>
+						<th>
+							'.get_lang('Comment').'
 						</th>
-					</tr>';
-		$form -> addElement ('html', $html);
-
-		$defaults = array();
-		$correct = 0;
-		if(!empty($this -> id))	{
-			$answer = new Answer($this -> id);
-			$answer -> read();
-			if(count($answer->nbrAnswers)>0 && !$form->isSubmitted()) {
-				$nb_answers = $answer->nbrAnswers;
-			}
-		}
-
+						<th>
+							'.get_lang('Weighting').'
+						</th>
+					</tr>';
+		$form -> addElement ('html', $html);
+
+		$defaults = array();
+		$correct = 0;
+		if(!empty($this -> id))	{
+			$answer = new Answer($this -> id);
+			$answer -> read();
+			if(count($answer->nbrAnswers)>0 && !$form->isSubmitted()) {
+				$nb_answers = $answer->nbrAnswers;
+			}
+		}
+
 		$form -> addElement('hidden', 'nb_answers');
-		$boxes_names = array();
-
+		$boxes_names = array();
+
 		for($i = 1 ; $i <= $nb_answers ; ++$i) {
-			if(is_object($answer)) {
-				$defaults['answer['.$i.']'] = $answer -> answer[$i];
-				$defaults['comment['.$i.']'] = $answer -> comment[$i];
-				$defaults['weighting['.$i.']'] = float_format($answer -> weighting[$i], 1);
-				$defaults['correct['.$i.']'] = $answer -> correct[$i];
-			} else {
-				$defaults['answer[1]']  = get_lang('langDefaultMultipleAnswer2');
-				$defaults['comment[1]'] = get_lang('langDefaultMultipleComment2');
-				$defaults['correct[1]'] = true;
-				$defaults['weighting[1]'] = 10;
-
-				$defaults['answer[2]']  = get_lang('langDefaultMultipleAnswer1');
-				$defaults['comment[2]'] = get_lang('langDefaultMultipleComment1');
-				$defaults['correct[2]'] = false;
-				$defaults['weighting[2]'] = -5;
-			}
-			$renderer = & $form->defaultRenderer();
-			$renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>');
-
-			$answer_number=$form->addElement('text', null,null,'value="'.$i.'"');
+			if(is_object($answer)) {
+				$defaults['answer['.$i.']'] = $answer -> answer[$i];
+				$defaults['comment['.$i.']'] = $answer -> comment[$i];
+				$defaults['weighting['.$i.']'] = float_format($answer -> weighting[$i], 1);
+				$defaults['correct['.$i.']'] = $answer -> correct[$i];
+			} else {
+				$defaults['answer[1]']  = get_lang('langDefaultMultipleAnswer2');
+				$defaults['comment[1]'] = get_lang('langDefaultMultipleComment2');
+				$defaults['correct[1]'] = true;
+				$defaults['weighting[1]'] = 10;
+
+				$defaults['answer[2]']  = get_lang('langDefaultMultipleAnswer1');
+				$defaults['comment[2]'] = get_lang('langDefaultMultipleComment1');
+				$defaults['correct[2]'] = false;
+				$defaults['weighting[2]'] = -5;
+			}
+			$renderer = & $form->defaultRenderer();
+			$renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>');
+
+			$answer_number=$form->addElement('text', null,null,'value="'.$i.'"');
 			$answer_number->freeze();
 
-			$form->addElement('checkbox', 'correct['.$i.']', null, null, 'class="checkbox" style="margin-left: 0em;"');
-			$boxes_names[] = 'correct['.$i.']';
-
-			$form->addElement('html_editor', 'answer['.$i.']',null, 'style="vertical-align:middle"', array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '100'));
-			$form->addRule('answer['.$i.']', get_lang('ThisFieldIsRequired'), 'required');
-			$form->addElement('html_editor', 'comment['.$i.']',null, 'style="vertical-align:middle"', array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '100'));
-			$form->addElement('text', 'weighting['.$i.']',null, 'style="vertical-align:middle;margin-left: 0em;" size="5" value="10"');
-			$form -> addElement ('html', '</tr>');
-		}
-		$form -> addElement ('html', '</table>');
-		$form -> addElement ('html', '<br />');
-
-		$form -> add_multiple_required_rule ($boxes_names , get_lang('ChooseAtLeastOneCheckbox') , 'multiple_required');
-
-
-		$navigator_info = api_get_navigator();
+			$form->addElement('checkbox', 'correct['.$i.']', null, null, 'class="checkbox" style="margin-left: 0em;"');
+			$boxes_names[] = 'correct['.$i.']';
+
+			$form->addElement('html_editor', 'answer['.$i.']',null, 'style="vertical-align:middle"', array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '100'));
+			$form->addRule('answer['.$i.']', get_lang('ThisFieldIsRequired'), 'required');
+			$form->addElement('html_editor', 'comment['.$i.']',null, 'style="vertical-align:middle"', array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '100'));
+			$form->addElement('text', 'weighting['.$i.']',null, 'style="vertical-align:middle;margin-left: 0em;" size="5" value="10"');
+			$form -> addElement ('html', '</tr>');
+		}
+		$form -> addElement ('html', '</table>');
+		$form -> addElement ('html', '<br />');
+
+		$form -> add_multiple_required_rule ($boxes_names , get_lang('ChooseAtLeastOneCheckbox') , 'multiple_required');
+
+
+		$navigator_info = api_get_navigator();
 		global $text, $class;
 		//ie6 fix
-		if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
-			$form->addElement('submit', 'lessAnswers', get_lang('LessAnswer'),'class="minus"');
-			$form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'),'class="plus"');
+		if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
+			$form->addElement('submit', 'lessAnswers', get_lang('LessAnswer'),'class="minus"');
+			$form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'),'class="plus"');
 			$form->addElement('submit','submitQuestion',$text, 'class="'.$class.'"');
-		} else {
-			$form->addElement('style_submit_button', 'lessAnswers', get_lang('LessAnswer'),'class="minus"');
-			$form->addElement('style_submit_button', 'moreAnswers', get_lang('PlusAnswer'),'class="plus"');
-			// setting the save button here and not in the question class.php
-			$form->addElement('style_submit_button','submitQuestion',$text, 'class="'.$class.'"');
-		}
-
-		$renderer->setElementTemplate('{element}&nbsp;','lessAnswers');
-		$renderer->setElementTemplate('{element}&nbsp;','submitQuestion');
-		$renderer->setElementTemplate('{element}','moreAnswers');
-		$form -> addElement ('html', '</div></div>');
-
-		$defaults['correct'] = $correct;
-		$form -> setDefaults($defaults);
-
-		$form->setConstants(array('nb_answers' => $nb_answers));
-
-	}
-
-
-	/**
-	 * abstract function which creates the form to create / edit the answers of the question
-	 * @param the formvalidator instance
-	 * @param the answers number to display
-	 */
-	function processAnswersCreation($form) {
-
-		$questionWeighting = $nbrGoodAnswers = 0;
-
-		$objAnswer = new Answer($this->id);
-
-		$nb_answers = $form -> getSubmitValue('nb_answers');
-
-		for($i=1 ; $i <= $nb_answers ; $i++)
-        {
-        	$answer = trim($form -> getSubmitValue('answer['.$i.']'));
-            $comment = trim($form -> getSubmitValue('comment['.$i.']'));
-            $weighting = trim($form -> getSubmitValue('weighting['.$i.']'));
-            $goodAnswer = trim($form -> getSubmitValue('correct['.$i.']'));
-
-			if($goodAnswer){
-    			$weighting = abs($weighting);
-			} else {
-				$weighting = abs($weighting);
-				$weighting = -$weighting;
-			}
-    		if($weighting > 0)
-            {
-                $questionWeighting += $weighting;
-            }
-
-        	$objAnswer -> createAnswer($answer,$goodAnswer,$comment,$weighting,$i);
-
-        }
-
-    	// saves the answers into the data base
-        $objAnswer -> save();
-
-        // sets the total weighting of the question
-        $this -> updateWeighting($questionWeighting);
-        $this -> save();
-
-	}
-
-}
-
-endif;
-?>
+		} else {
+			$form->addElement('style_submit_button', 'lessAnswers', get_lang('LessAnswer'),'class="minus"');
+			$form->addElement('style_submit_button', 'moreAnswers', get_lang('PlusAnswer'),'class="plus"');
+			// setting the save button here and not in the question class.php
+			$form->addElement('style_submit_button','submitQuestion',$text, 'class="'.$class.'"');
+		}
+
+		$renderer->setElementTemplate('{element}&nbsp;','lessAnswers');
+		$renderer->setElementTemplate('{element}&nbsp;','submitQuestion');
+		$renderer->setElementTemplate('{element}','moreAnswers');
+		$form -> addElement ('html', '</div></div>');
+
+		$defaults['correct'] = $correct;
+		$form -> setDefaults($defaults);
+
+		$form->setConstants(array('nb_answers' => $nb_answers));
+
+	}
+
+
+	/**
+	 * abstract function which creates the form to create / edit the answers of the question
+	 * @param the formvalidator instance
+	 * @param the answers number to display
+	 */
+	function processAnswersCreation($form) {
+
+		$questionWeighting = $nbrGoodAnswers = 0;
+
+		$objAnswer = new Answer($this->id);
+
+		$nb_answers = $form -> getSubmitValue('nb_answers');
+
+		for($i=1 ; $i <= $nb_answers ; $i++)
+        {
+        	$answer = trim($form -> getSubmitValue('answer['.$i.']'));
+            $comment = trim($form -> getSubmitValue('comment['.$i.']'));
+            $weighting = trim($form -> getSubmitValue('weighting['.$i.']'));
+            $goodAnswer = trim($form -> getSubmitValue('correct['.$i.']'));
+
+			if($goodAnswer){
+    			$weighting = abs($weighting);
+			} else {
+				$weighting = abs($weighting);
+				$weighting = -$weighting;
+			}
+    		if($weighting > 0)
+            {
+                $questionWeighting += $weighting;
+            }
+
+        	$objAnswer -> createAnswer($answer,$goodAnswer,$comment,$weighting,$i);
+
+        }
+
+    	// saves the answers into the data base
+        $objAnswer -> save();
+
+        // sets the total weighting of the question
+        $this -> updateWeighting($questionWeighting);
+        $this -> save();
+
+	}
+
+}
+
+endif;
+?>

+ 166 - 166
main/exercice/question_create.php

@@ -1,176 +1,176 @@
-<?php // $Id: question_create.php 20569 2009-05-12 21:34:00Z pcool $
-
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2009 Dokeos SPRL
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) various contributors
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
-==============================================================================
-*/
-
-
-// name of the language file that needs to be included
-$language_file='exercice';
-
-// including global Dokeos file
-include("../inc/global.inc.php");
-
-// including additional libraries
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-require_once ('question.class.php');
-
-
-// the section (tabs)
-$this_section=SECTION_COURSES;
-
-// notice for unauthorized people.
-api_protect_course_script(true);
-
-// breadcrumbs
-$interbreadcrumb[]=array("url" => "exercice.php","name" => get_lang('Exercices'));
-
-// Tool name
-$nameTools=get_lang('AddQuestionToExercise');
-
-
-
-// The form
-$form = new FormValidator('add_question','post');
-// form title
-$form->addElement('header','',get_lang('AddQuestionToExercise'));
-
-// the question types (normal form element)
-/*
-foreach (Question::$questionTypes as $key=>$value)
-{
-	$question_types[] = get_lang($value[1]);
-}
-$form->addElement('select', 'question_type', get_lang('QuestionType'), $question_types);
-*/
-
-
-// the question types (jquery form element)
-$form->addElement('hidden', 'question_type_hidden', get_lang('QuestionType'), array('id'=>'question_type_hidden'));
-$form->addElement('static','','<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.js" type="text/javascript"></script>
-							<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.customselect.js" type="text/javascript"></script>');
-$form->addElement('static','select_question_type', get_lang('QuestionType'),'<div id="questiontypes"></div>');
-
-// the exercices
-$tbl_exercices = Database :: get_course_table(TABLE_QUIZ_TEST);
-$sql = "SELECT id,title,type,description, results_disabled FROM $tbl_exercices WHERE active<>'-1' ORDER BY title ASC";
-$result = Database::query($sql, __FILE__, __LINE__);
-$exercises['-'] = '-'.get_lang('SelectExercice').'-';
+<?php // $Id: question_create.php 20569 2009-05-12 21:34:00Z pcool $
+
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2009 Dokeos SPRL
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) various contributors
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+
+
+// name of the language file that needs to be included
+$language_file='exercice';
+
+// including global Dokeos file
+include("../inc/global.inc.php");
+
+// including additional libraries
+require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+require_once ('question.class.php');
+
+
+// the section (tabs)
+$this_section=SECTION_COURSES;
+
+// notice for unauthorized people.
+api_protect_course_script(true);
+
+// breadcrumbs
+$interbreadcrumb[]=array("url" => "exercice.php","name" => get_lang('Exercices'));
+
+// Tool name
+$nameTools=get_lang('AddQuestionToExercise');
+
+
+
+// The form
+$form = new FormValidator('add_question','post');
+// form title
+$form->addElement('header','',get_lang('AddQuestionToExercise'));
+
+// the question types (normal form element)
+/*
+foreach (Question::$questionTypes as $key=>$value)
+{
+	$question_types[] = get_lang($value[1]);
+}
+$form->addElement('select', 'question_type', get_lang('QuestionType'), $question_types);
+*/
+
+
+// the question types (jquery form element)
+$form->addElement('hidden', 'question_type_hidden', get_lang('QuestionType'), array('id'=>'question_type_hidden'));
+$form->addElement('static','','<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.js" type="text/javascript"></script>
+							<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.customselect.js" type="text/javascript"></script>');
+$form->addElement('static','select_question_type', get_lang('QuestionType'),'<div id="questiontypes"></div>');
+
+// the exercices
+$tbl_exercices = Database :: get_course_table(TABLE_QUIZ_TEST);
+$sql = "SELECT id,title,type,description, results_disabled FROM $tbl_exercices WHERE active<>'-1' ORDER BY title ASC";
+$result = Database::query($sql, __FILE__, __LINE__);
+$exercises['-'] = '-'.get_lang('SelectExercice').'-';
 while ($row = Database :: fetch_array($result))
-{
+{
 	$exercises[$row['id']] = $row['title'];
-}
-$form->addElement('select', 'exercice', get_lang('Exercice'), $exercises);
-
-// the submit button
-$form->addElement('style_submit_button', 'SubmitCreateQuestion', get_lang('CreateQuestion'), 'class="add"');
-
-// setting the rules
-// $form->addRule('question_type', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
-$form->addRule('exercice', '<span class="required">'.get_lang('ThisFieldIsRequired').'</span>', 'required');
-$form->addRule('exercice', '<span class="required">'.get_lang('YouHaveToSelectATest').'</span>', 'numeric');
-$form->registerRule('validquestiontype', 'callback', 'check_question_type');
-$form->addRule('question_type_hidden', get_lang('InvalidQuestionType'), 'validquestiontype');
-
-
-
-if ($form->validate())
-{
-	$values = $form->exportValues();
-	//echo 'form validates';
-	//print_r($values);
-
-	foreach (Question::$questionTypes as $question_type_id => $question_type_class_and_name)
-	{
-		if (get_lang($question_type_class_and_name[1]) == $values['question_type_hidden'])
-		{
-			$answer_type = $question_type_id;
-		}
-	}
-
-	header('Location: admin.php?exerciseId='.$values['exercice'].'&newQuestion=yes&answerType='.$answer_type);
-}
+}
+$form->addElement('select', 'exercice', get_lang('Exercice'), $exercises);
+
+// the submit button
+$form->addElement('style_submit_button', 'SubmitCreateQuestion', get_lang('CreateQuestion'), 'class="add"');
+
+// setting the rules
+// $form->addRule('question_type', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule('exercice', '<span class="required">'.get_lang('ThisFieldIsRequired').'</span>', 'required');
+$form->addRule('exercice', '<span class="required">'.get_lang('YouHaveToSelectATest').'</span>', 'numeric');
+$form->registerRule('validquestiontype', 'callback', 'check_question_type');
+$form->addRule('question_type_hidden', get_lang('InvalidQuestionType'), 'validquestiontype');
+
+
+
+if ($form->validate())
+{
+	$values = $form->exportValues();
+	//echo 'form validates';
+	//print_r($values);
+
+	foreach (Question::$questionTypes as $question_type_id => $question_type_class_and_name)
+	{
+		if (get_lang($question_type_class_and_name[1]) == $values['question_type_hidden'])
+		{
+			$answer_type = $question_type_id;
+		}
+	}
+
+	header('Location: admin.php?exerciseId='.$values['exercice'].'&newQuestion=yes&answerType='.$answer_type);
+}
 else
-{
-	// header
+{
+	// header
 	Display::display_header($nameTools);
 
-	// displaying the form
-	$form->display();
+	// displaying the form
+	$form->display();
 
-	// footer
+	// footer
 	Display::display_footer();
-}
-
-
-?>
-
-
-
-<script>
-var ddlObj1=$("#questiontypes").finalselect({id:"test",viewWidth:'260px', viewHeight:'150px', selectText:'<?php echo Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align:middle; cursor:hand'))."&nbsp;&nbsp;".get_lang('SelectQuestionType');?>',selectImage:'<?php echo api_get_path(WEB_IMG_PATH); ?>select.png', viewMouseoverColor: '#EFEFEF'});
-$("#test-select").bind('click',function(){
-	$("#question_type_hidden").val(ddlObj1.getText());
-});
-
-
-
+}
+
+
+?>
+
+
+
+<script>
+var ddlObj1=$("#questiontypes").finalselect({id:"test",viewWidth:'260px', viewHeight:'150px', selectText:'<?php echo Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align:middle; cursor:hand'))."&nbsp;&nbsp;".get_lang('SelectQuestionType');?>',selectImage:'<?php echo api_get_path(WEB_IMG_PATH); ?>select.png', viewMouseoverColor: '#EFEFEF'});
+$("#test-select").bind('click',function(){
+	$("#question_type_hidden").val(ddlObj1.getText());
+});
+
+
+
+<?php
+// defining the pictures of the question types
+$pictures_question_types[1] = 'mcua.gif';
+$pictures_question_types[2] = 'mcma.gif';
+$pictures_question_types[3] = 'fill_in_blanks.gif';
+$pictures_question_types[4] = 'matching.gif';
+$pictures_question_types[5] = 'open_answer.gif';
+$pictures_question_types[6] = 'hotspot.gif';
+
+foreach (Question::$questionTypes as $key=>$value)
+{
+	?>
+	ddlObj1.addItem('<table width="100%"><tr><td style="width: 37px;" valign="top"><?php Display::display_icon($pictures_question_types[$key],addslashes(get_lang($value[1])),array('height'=>'40px;', 'style' => 'vertical-align:top; cursor:hand;')); ?></td><td><span class="thistext" style="cursor:hand"><?php echo addslashes(get_lang($value[1])); ?></span><br/><sub><?php /*echo addslashes(get_lang($value[1].'Comment'));*/ ?></sub></td></tr></table>','');
+	<?php
+}
+?>
+</script>
+
+
+
 <?php
-// defining the pictures of the question types
-$pictures_question_types[1] = 'mcua.gif';
-$pictures_question_types[2] = 'mcma.gif';
-$pictures_question_types[3] = 'fill_in_blanks.gif';
-$pictures_question_types[4] = 'matching.gif';
-$pictures_question_types[5] = 'open_answer.gif';
-$pictures_question_types[6] = 'hotspot.gif';
-
-foreach (Question::$questionTypes as $key=>$value)
-{
-	?>
-	ddlObj1.addItem('<table width="100%"><tr><td style="width: 37px;" valign="top"><?php Display::display_icon($pictures_question_types[$key],addslashes(get_lang($value[1])),array('height'=>'40px;', 'style' => 'vertical-align:top; cursor:hand;')); ?></td><td><span class="thistext" style="cursor:hand"><?php echo addslashes(get_lang($value[1])); ?></span><br/><sub><?php /*echo addslashes(get_lang($value[1].'Comment'));*/ ?></sub></td></tr></table>','');
-	<?php
-}
-?>
-</script>
-
-
-
-<?php
-function check_question_type($parameter)
-{
-	foreach (Question::$questionTypes as $key=>$value)
-	{
-		$valid_question_types[] = get_lang($value[1]);
-		//$valid_question_types[] = trim($value[1]);
-	}
-	if (in_array($parameter, $valid_question_types))
-	{
-		return true;
-	}
+function check_question_type($parameter)
+{
+	foreach (Question::$questionTypes as $key=>$value)
+	{
+		$valid_question_types[] = get_lang($value[1]);
+		//$valid_question_types[] = trim($value[1]);
+	}
+	if (in_array($parameter, $valid_question_types))
+	{
+		return true;
+	}
 	else
-	{
-		return false;
-	}
-}
-
+	{
+		return false;
+	}
+}
+
 ?>

+ 293 - 293
main/exercice/unique_answer.class.php

@@ -1,381 +1,381 @@
-<?php
-/*
-    DOKEOS - elearning and course management software
-
-    For a full list of contributors, see documentation/credits.html
-
-    This program is free software; you can redistribute it and/or
-    modify it under the terms of the GNU General Public License
-    as published by the Free Software Foundation; either version 2
-    of the License, or (at your option) any later version.
-    See "documentation/licence.html" more details.
-
-    Contact:
-		Dokeos
-		Rue des Palais 44 Paleizenstraat
-		B-1030 Brussels - Belgium
-		Tel. +32 (2) 211 34 56
-*/
-
-
-/**
-*	File containing the UNIQUE_ANSWER class.
-*	@package dokeos.exercise
-* 	@author Eric Marguin
-* 	@version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $
-*/
-
-
-if(!class_exists('UniqueAnswer')):
-
-/**
-	CLASS UNIQUE_ANSWER
- *
- *	This class allows to instantiate an object of type UNIQUE_ANSWER (MULTIPLE CHOICE, UNIQUE ANSWER),
- *	extending the class question
- *
- *	@author Eric Marguin
+<?php
+/*
+    DOKEOS - elearning and course management software
+
+    For a full list of contributors, see documentation/credits.html
+
+    This program is free software; you can redistribute it and/or
+    modify it under the terms of the GNU General Public License
+    as published by the Free Software Foundation; either version 2
+    of the License, or (at your option) any later version.
+    See "documentation/licence.html" more details.
+
+    Contact:
+		Dokeos
+		Rue des Palais 44 Paleizenstraat
+		B-1030 Brussels - Belgium
+		Tel. +32 (2) 211 34 56
+*/
+
+
+/**
+*	File containing the UNIQUE_ANSWER class.
+*	@package dokeos.exercise
+* 	@author Eric Marguin
+* 	@version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $
+*/
+
+
+if(!class_exists('UniqueAnswer')):
+
+/**
+	CLASS UNIQUE_ANSWER
+ *
+ *	This class allows to instantiate an object of type UNIQUE_ANSWER (MULTIPLE CHOICE, UNIQUE ANSWER),
+ *	extending the class question
+ *
+ *	@author Eric Marguin
  *  @author Julio Montoya
- *	@package dokeos.exercise
- **/
-
-class UniqueAnswer extends Question {
-
-	static $typePicture = 'mcua.gif';
-	static $explanationLangVar = 'UniqueSelect';
-
-	/**
-	 * Constructor
-	 */
-	function UniqueAnswer(){
-		//this is highly important
-		parent::question();
-		$this -> type = UNIQUE_ANSWER;
-	}
-
-	/**
-	 * function which redifines Question::createAnswersForm
-	 * @param the formvalidator instance
-	 * @param the answers number to display
-	 */
-	function createAnswersForm ($form) {
+ *	@package dokeos.exercise
+ **/
+
+class UniqueAnswer extends Question {
+
+	static $typePicture = 'mcua.gif';
+	static $explanationLangVar = 'UniqueSelect';
+
+	/**
+	 * Constructor
+	 */
+	function UniqueAnswer(){
+		//this is highly important
+		parent::question();
+		$this -> type = UNIQUE_ANSWER;
+	}
+
+	/**
+	 * function which redifines Question::createAnswersForm
+	 * @param the formvalidator instance
+	 * @param the answers number to display
+	 */
+	function createAnswersForm ($form) {
 		// getting the exercise list
-		$obj_ex =$_SESSION['objExercise'];
-
-		$editor_config = array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '125');
-
-		//this line define how many question by default appear when creating a choice question
-		$nb_answers = isset($_POST['nb_answers']) ? (int) $_POST['nb_answers'] : 2;
-		$nb_answers += (isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0));
-
-		/*
-	 		Types of Feedback
-	 		$feedback_option[0]=get_lang('Feedback');
-			$feedback_option[1]=get_lang('DirectFeedback');
-			$feedback_option[2]=get_lang('NoFeedback');
-	 	*/
-
-		$feedback_title='';
-		$comment_title='';
-
-		if ($obj_ex->selectFeedbackType()==0) {
+		$obj_ex =$_SESSION['objExercise'];
+
+		$editor_config = array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '125');
+
+		//this line define how many question by default appear when creating a choice question
+		$nb_answers = isset($_POST['nb_answers']) ? (int) $_POST['nb_answers'] : 2;
+		$nb_answers += (isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0));
+
+		/*
+	 		Types of Feedback
+	 		$feedback_option[0]=get_lang('Feedback');
+			$feedback_option[1]=get_lang('DirectFeedback');
+			$feedback_option[2]=get_lang('NoFeedback');
+	 	*/
+
+		$feedback_title='';
+		$comment_title='';
+
+		if ($obj_ex->selectFeedbackType()==0) {
 			$comment_title = '<th>'.get_lang('Comment').'</th>';
 		} elseif ($obj_ex->selectFeedbackType()==1) {
-			$editor_config['Width'] = '250';
-			$editor_config['Height'] = '110';
-			$comment_title = '<th width="500" >'.get_lang('Comment').'</th>';
+			$editor_config['Width'] = '250';
+			$editor_config['Height'] = '110';
+			$comment_title = '<th width="500" >'.get_lang('Comment').'</th>';
 			$feedback_title = '<th width="350px" >'.get_lang('Scenario').'</th>';
 		}
 
-		$html='
-		<div class="row">
-			<div class="label">
-			'.get_lang('Answers').' <br /> <img src="../img/fill_field.png">
-			</div>
-			<div class="formw">
-				<table class="data_table">
-					<tr style="text-align: center;">
-						<th width="10px">
-							'.get_lang('Number').'
-						</th>
-						<th width="10px" >
-							'.get_lang('True').'
-						</th>
-						<th width="45%">
-							'.get_lang('Answer').'
-						</th>
+		$html='
+		<div class="row">
+			<div class="label">
+			'.get_lang('Answers').' <br /> <img src="../img/fill_field.png">
+			</div>
+			<div class="formw">
+				<table class="data_table">
+					<tr style="text-align: center;">
+						<th width="10px">
+							'.get_lang('Number').'
+						</th>
+						<th width="10px" >
+							'.get_lang('True').'
+						</th>
+						<th width="45%">
+							'.get_lang('Answer').'
+						</th>
 							'.$comment_title.'
 							'.$feedback_title.'
-						<th width="20px">
-							'.get_lang('Weighting').'
+						<th width="20px">
+							'.get_lang('Weighting').'
 						</th>
-					</tr>';
-
-		$form -> addElement ('html', $html);
-
-		$defaults = array();
-		$correct = 0;
-		if(!empty($this -> id)) {
-			$answer = new Answer($this -> id);
-			$answer -> read();
-			if(count($answer->nbrAnswers)>0 && !$form->isSubmitted())
-			{
-				$nb_answers = $answer->nbrAnswers;
-			}
-		}
-		$form -> addElement('hidden', 'nb_answers');
-
-		//Feedback SELECT
-		$question_list=$obj_ex->selectQuestionList();
-		$select_question=array();
-		$select_question[0]=get_lang('SelectTargetQuestion');
+					</tr>';
+
+		$form -> addElement ('html', $html);
+
+		$defaults = array();
+		$correct = 0;
+		if(!empty($this -> id)) {
+			$answer = new Answer($this -> id);
+			$answer -> read();
+			if(count($answer->nbrAnswers)>0 && !$form->isSubmitted())
+			{
+				$nb_answers = $answer->nbrAnswers;
+			}
+		}
+		$form -> addElement('hidden', 'nb_answers');
+
+		//Feedback SELECT
+		$question_list=$obj_ex->selectQuestionList();
+		$select_question=array();
+		$select_question[0]=get_lang('SelectTargetQuestion');
 		require_once('../newscorm/learnpathList.class.php');
-		require_once(api_get_path(LIBRARY_PATH).'text.lib.php');
+		require_once(api_get_path(LIBRARY_PATH).'text.lib.php');
 
-		if (is_array($question_list)) {
+		if (is_array($question_list)) {
 			foreach ($question_list as $key=>$questionid) {
 				$question = Question::read($questionid);
 				$select_question[$questionid]='Q'.$key.' :'.cut($question->selectTitle(),20);
-			}
-		}
+			}
+		}
 		$select_question[-1]=get_lang('ExitTest');
 
-		//LP SELECT
-		require_once('../newscorm/learnpathList.class.php');
-		//require_once('../newscorm/learnpath.class.php');
-		//require_once('../newscorm/learnpathItem.class.php');
-
-		$list = new LearnpathList(api_get_user_id());
-		$flat_list = $list->get_flat_list();
+		//LP SELECT
+		require_once('../newscorm/learnpathList.class.php');
+		//require_once('../newscorm/learnpath.class.php');
+		//require_once('../newscorm/learnpathItem.class.php');
+
+		$list = new LearnpathList(api_get_user_id());
+		$flat_list = $list->get_flat_list();
 		$select_lp_id=array();
-		$select_lp_id[0]=get_lang('SelectTargetLP');
+		$select_lp_id[0]=get_lang('SelectTargetLP');
 
-		foreach ($flat_list as $id => $details)
-		{
-			$select_lp_id[$id] = cut($details['lp_name'],20);
+		foreach ($flat_list as $id => $details)
+		{
+			$select_lp_id[$id] = cut($details['lp_name'],20);
 		}
 
 		$temp_scenario=array();
-		for($i = 1 ; $i <= $nb_answers ; ++$i)
-		{
-			$form -> addElement ('html', '<tr>');
-			if(is_object($answer))
-			{
-				if($answer -> correct[$i])
-				{
-					$correct = $i;
-				}
-
-				$defaults['answer['.$i.']'] = $answer -> answer[$i];
+		for($i = 1 ; $i <= $nb_answers ; ++$i)
+		{
+			$form -> addElement ('html', '<tr>');
+			if(is_object($answer))
+			{
+				if($answer -> correct[$i])
+				{
+					$correct = $i;
+				}
+
+				$defaults['answer['.$i.']'] = $answer -> answer[$i];
 				$defaults['comment['.$i.']'] = $answer -> comment[$i];
-				$defaults['weighting['.$i.']'] = float_format($answer -> weighting[$i], 1);
+				$defaults['weighting['.$i.']'] = float_format($answer -> weighting[$i], 1);
 
-				$item_list=explode('@@',$answer -> destination[$i]);
-				//echo '<pre>';	print_r($item_list);
+				$item_list=explode('@@',$answer -> destination[$i]);
+				//echo '<pre>';	print_r($item_list);
 
-				$try = $item_list[0];
-				$lp = $item_list[1];
-				$list_dest= $item_list[2];
-				$url=$item_list[3];
+				$try = $item_list[0];
+				$lp = $item_list[1];
+				$list_dest= $item_list[2];
+				$url=$item_list[3];
 
-				if ($try==0)
-					$try_result=0;
-				else
-					$try_result=1;
+				if ($try==0)
+					$try_result=0;
+				else
+					$try_result=1;
 
 				if ($url==0)
-					$url_result='';
-				else
-					$url_result=$url;
+					$url_result='';
+				else
+					$url_result=$url;
 
-				$temp_scenario['url'.$i]=$url_result;
+				$temp_scenario['url'.$i]=$url_result;
 				$temp_scenario['try'.$i]=$try_result;
-				$temp_scenario['lp'.$i]=$lp;
+				$temp_scenario['lp'.$i]=$lp;
 				$temp_scenario['destination'.$i]=$list_dest;
 
 
-				/*$pre_list_destination=explode(';',$list_dest);
+				/*$pre_list_destination=explode(';',$list_dest);
 				$list_destination=array();
-				foreach($pre_list_destination as $value)
-				{
+				foreach($pre_list_destination as $value)
+				{
 					$list_destination[]=$value;
-				}
-				$defaults['destination'.$i]=$list_destination;
-				*/
+				}
+				$defaults['destination'.$i]=$list_destination;
+				*/
 				//$defaults['destination'.$i] = $list_destination;
-			}else {
+			}else {
 				$defaults['answer[1]']  = get_lang('langDefaultUniqueAnswer1');
-				$defaults['weighting[1]'] = 10;
-				$defaults['answer[2]']  = get_lang('langDefaultUniqueAnswer2');
-				$defaults['weighting[2]'] = 0;
+				$defaults['weighting[1]'] = 10;
+				$defaults['answer[2]']  = get_lang('langDefaultUniqueAnswer2');
+				$defaults['weighting[2]'] = 0;
 
-				$temp_scenario['destination'.$i] = array('0');
-				$temp_scenario['lp'.$i] = array('0');
-				//$defaults['scenario']
+				$temp_scenario['destination'.$i] = array('0');
+				$temp_scenario['lp'.$i] = array('0');
+				//$defaults['scenario']
 			}
 			$defaults['scenario']=$temp_scenario;
 
 			$renderer = & $form->defaultRenderer();
 			$renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>');
-			$answer_number=$form->addElement('text', null,null,'value="'.$i.'"');
-			$answer_number->freeze();
+			$answer_number=$form->addElement('text', null,null,'value="'.$i.'"');
+			$answer_number->freeze();
 
-			$form->addElement('radio', 'correct', null, null, $i, 'class="checkbox" style="margin-left: 0em;"');
-			$form->addElement('html_editor', 'answer['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
-			$form->addRule('answer['.$i.']', get_lang('ThisFieldIsRequired'), 'required');
+			$form->addElement('radio', 'correct', null, null, $i, 'class="checkbox" style="margin-left: 0em;"');
+			$form->addElement('html_editor', 'answer['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
+			$form->addRule('answer['.$i.']', get_lang('ThisFieldIsRequired'), 'required');
 
-			if ($obj_ex->selectFeedbackType()==0) // feedback
-				$form->addElement('html_editor', 'comment['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
-			elseif ($obj_ex->selectFeedbackType()==1) // direct feedback
+			if ($obj_ex->selectFeedbackType()==0) // feedback
+				$form->addElement('html_editor', 'comment['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
+			elseif ($obj_ex->selectFeedbackType()==1) // direct feedback
 			{
-				$form->addElement('html_editor', 'comment['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
+				$form->addElement('html_editor', 'comment['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
 				//Adding extra feedback fields
 				$group = array();
 				$group['try'.$i] =&$form->createElement('checkbox', 'try'.$i,get_lang('TryAgain').': ' );
 				$group['lp'.$i] =&$form->createElement('select', 'lp'.$i,get_lang('SeeTheory').': ',$select_lp_id);
 				$group['destination'.$i]=&$form->createElement('select', 'destination'.$i, get_lang('GoToQuestion').': ' ,$select_question);
-				$group['url'.$i] =&$form->createElement('text', 'url'.$i,get_lang('Other').': ',array('size'=>'25px'));
+				$group['url'.$i] =&$form->createElement('text', 'url'.$i,get_lang('Other').': ',array('size'=>'25px'));
 
 				$form -> addGroup($group, 'scenario', 'scenario');
 				$renderer->setGroupElementTemplate('<div class="exercise_scenario_label">{label}</div><div class="exercise_scenario_element">{element}</div>','scenario');
-			}
+			}
 
-			//$form->addElement('select', 'destination'.$i, get_lang('SelectQuestion').' : ',$select_question,'multiple');
+			//$form->addElement('select', 'destination'.$i, get_lang('SelectQuestion').' : ',$select_question,'multiple');
 
-			$form->addElement('text', 'weighting['.$i.']',null, 'style="vertical-align:middle;margin-left: 0em;" size="5" value="10"');
-			$form -> addElement ('html', '</tr>');
-		}
+			$form->addElement('text', 'weighting['.$i.']',null, 'style="vertical-align:middle;margin-left: 0em;" size="5" value="10"');
+			$form -> addElement ('html', '</tr>');
+		}
 
-		$form -> addElement ('html', '</table>');
-		$form -> addElement ('html', '<br />');
-		$navigator_info = api_get_navigator();
+		$form -> addElement ('html', '</table>');
+		$form -> addElement ('html', '<br />');
+		$navigator_info = api_get_navigator();
 		global $text, $class;
-		//ie6 fix
-		if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
-			$form->addElement('submit', 'lessAnswers', get_lang('LessAnswer'),'class="minus"');
-			$form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'),'class="plus"');
-			$form->addElement('submit','submitQuestion',$text, 'class="'.$class.'"');
-		} else {
-			$form->addElement('style_submit_button', 'lessAnswers', get_lang('LessAnswer'),'class="minus"');
-			$form->addElement('style_submit_button', 'moreAnswers', get_lang('PlusAnswer'),'class="plus"');
-			// setting the save button here and not in the question class.php
+		//ie6 fix
+		if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
+			$form->addElement('submit', 'lessAnswers', get_lang('LessAnswer'),'class="minus"');
+			$form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'),'class="plus"');
+			$form->addElement('submit','submitQuestion',$text, 'class="'.$class.'"');
+		} else {
+			$form->addElement('style_submit_button', 'lessAnswers', get_lang('LessAnswer'),'class="minus"');
+			$form->addElement('style_submit_button', 'moreAnswers', get_lang('PlusAnswer'),'class="plus"');
+			// setting the save button here and not in the question class.php
 			$form->addElement('style_submit_button','submitQuestion',$text, 'class="'.$class.'"');
-		}
+		}
 
-		$renderer->setElementTemplate('{element}','submitQuestion');
-		$renderer->setElementTemplate('{element}&nbsp;','lessAnswers');
-		$renderer->setElementTemplate('{element}','moreAnswers');
+		$renderer->setElementTemplate('{element}','submitQuestion');
+		$renderer->setElementTemplate('{element}&nbsp;','lessAnswers');
+		$renderer->setElementTemplate('{element}','moreAnswers');
 
-		$form -> addElement ('html', '</div></div>');
+		$form -> addElement ('html', '</div></div>');
 
 		//We check the first radio button to be sure a radio button will be check
-		if($correct==0){
-			$correct=1;
-		}
-		$defaults['correct'] = $correct;
-		$form -> setDefaults($defaults);
-
-		$form->setConstants(array('nb_answers' => $nb_answers));
-
-	}
-
-
-	/**
-	 * abstract function which creates the form to create / edit the answers of the question
-	 * @param the formvalidator instance
-	 * @param the answers number to display
-	 */
-	function processAnswersCreation($form) {
-
+		if($correct==0){
+			$correct=1;
+		}
+		$defaults['correct'] = $correct;
+		$form -> setDefaults($defaults);
+
+		$form->setConstants(array('nb_answers' => $nb_answers));
+
+	}
+
+
+	/**
+	 * abstract function which creates the form to create / edit the answers of the question
+	 * @param the formvalidator instance
+	 * @param the answers number to display
+	 */
+	function processAnswersCreation($form) {
+
 		$questionWeighting = $nbrGoodAnswers = 0;
-		$correct = $form -> getSubmitValue('correct');
-		$objAnswer = new Answer($this->id);
-		$nb_answers = $form -> getSubmitValue('nb_answers');
-
-		for($i=1 ; $i <= $nb_answers ; $i++)
-        {
-        	$answer = trim($form -> getSubmitValue('answer['.$i.']'));
-            $comment = trim($form -> getSubmitValue('comment['.$i.']'));
-            $weighting = trim($form -> getSubmitValue('weighting['.$i.']'));
-
-            $scenario= $form -> getSubmitValue('scenario');
-
-            echo '<pre>';
-           	//$list_destination = $form -> getSubmitValue('destination'.$i);
-           	//$destination_str = $form -> getSubmitValue('destination'.$i);
-
- 		    $try = $scenario['try'.$i];
+		$correct = $form -> getSubmitValue('correct');
+		$objAnswer = new Answer($this->id);
+		$nb_answers = $form -> getSubmitValue('nb_answers');
+
+		for($i=1 ; $i <= $nb_answers ; $i++)
+        {
+        	$answer = trim($form -> getSubmitValue('answer['.$i.']'));
+            $comment = trim($form -> getSubmitValue('comment['.$i.']'));
+            $weighting = trim($form -> getSubmitValue('weighting['.$i.']'));
+
+            $scenario= $form -> getSubmitValue('scenario');
+
+            echo '<pre>';
+           	//$list_destination = $form -> getSubmitValue('destination'.$i);
+           	//$destination_str = $form -> getSubmitValue('destination'.$i);
+
+ 		    $try = $scenario['try'.$i];
             $lp= $scenario['lp'.$i];
  			$destination = $scenario['destination'.$i];
  			$url = trim($scenario['url'.$i]);
 
- 			/*
- 			How we are going to parse the destination value
+ 			/*
+ 			How we are going to parse the destination value
 
 			here we parse the destination value which is a string
-		 	1@@3@@2;4;4;@@http://www.dokeos.com
+		 	1@@3@@2;4;4;@@http://www.dokeos.com
 
 		 	where: try_again@@lp_id@@selected_questions@@url
 
-			try_again = is 1 || 0
-			lp_id = id of a learning path (0 if dont select)
+			try_again = is 1 || 0
+			lp_id = id of a learning path (0 if dont select)
 			selected_questions= ids of questions
 			url= an url
-			*/
+			*/
 			/*
- 			$destination_str='';
- 			foreach ($list_destination as $destination_id)
- 			{
- 				$destination_str.=$destination_id.';';
- 			}*/
-
-        	$goodAnswer= ($correct == $i) ? true : false;
-
-        	if($goodAnswer)
-        	{
-        		$nbrGoodAnswers++;
+ 			$destination_str='';
+ 			foreach ($list_destination as $destination_id)
+ 			{
+ 				$destination_str.=$destination_id.';';
+ 			}*/
+
+        	$goodAnswer= ($correct == $i) ? true : false;
+
+        	if($goodAnswer)
+        	{
+        		$nbrGoodAnswers++;
         		$weighting = abs($weighting);
-        		if($weighting > 0)
-                {
-                    $questionWeighting += $weighting;
-                }
-        	}
+        		if($weighting > 0)
+                {
+                    $questionWeighting += $weighting;
+                }
+        	}
+
+ 			if (empty($try))
+ 				$try=0;
 
- 			if (empty($try))
- 				$try=0;
+ 			if (empty($lp))
+ 			{
+ 				$lp=0;
+ 			}
 
- 			if (empty($lp))
- 			{
- 				$lp=0;
- 			}
+ 			if (empty($destination))
+ 			{
+ 				$destination=0;
+ 			}
 
- 			if (empty($destination))
- 			{
- 				$destination=0;
- 			}
 
 
+ 			if ($url=='')
+ 			{
+ 				$url=0;
+ 			}
 
- 			if ($url=='')
- 			{
- 				$url=0;
- 			}
+ 			//1@@1;2;@@2;4;4;@@http://www.dokeos.com
+			$dest= $try.'@@'.$lp.'@@'.$destination.'@@'.$url;
+        	$objAnswer -> createAnswer($answer,$goodAnswer,$comment,$weighting,$i,NULL,NULL,$dest);
 
- 			//1@@1;2;@@2;4;4;@@http://www.dokeos.com
-			$dest= $try.'@@'.$lp.'@@'.$destination.'@@'.$url;
-        	$objAnswer -> createAnswer($answer,$goodAnswer,$comment,$weighting,$i,NULL,NULL,$dest);
+        }
 
-        }
 
+    	// saves the answers into the data base
+        $objAnswer -> save();
 
-    	// saves the answers into the data base
-        $objAnswer -> save();
-
-        // sets the total weighting of the question
-        $this -> updateWeighting($questionWeighting);
-        $this -> save();
+        // sets the total weighting of the question
+        $this -> updateWeighting($questionWeighting);
+        $this -> save();
 
-	}
-}
-endif;
-?>
+	}
+}
+endif;
+?>

+ 258 - 258
main/forum/editpost.php

@@ -1,267 +1,267 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2008 Dokeos SPRL
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) various contributors
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
-==============================================================================
-*/
-
-/**
-*	These files are a complete rework of the forum. The database structure is
-*	based on phpBB but all the code is rewritten. A lot of new functionalities
-*	are added:
-* 	- forum categories and forums can be sorted up or down, locked or made invisible
-*	- consistent and integrated forum administration
-* 	- forum options: 	are students allowed to edit their post?
-* 						moderation of posts (approval)
-* 						reply only forums (students cannot create new threads)
-* 						multiple forums per group
-*	- sticky messages
-* 	- new view option: nested view
-* 	- quoting a message
-*
-*	@Author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*	@Copyright Ghent University
-*	@Copyright Patrick Cool
-*
-* 	@package dokeos.forum
-*/
-
-/**
- **************************************************************************
- *						IMPORTANT NOTICE
- * Please do not change anything is this code yet because there are still
- * some significant code that need to happen and I do not have the time to
- * merge files and test it all over again. So for the moment, please do not
- * touch the code
- * 							-- Patrick Cool <patrick.cool@UGent.be>
- **************************************************************************
- */
-
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
-*/
-// name of the language file that needs to be included
-$language_file = array (
-	'forum',
-	'group'
-);
-
-// including the global dokeos file
-require ('../inc/global.inc.php');
-require_once('../gradebook/lib/gradebook_functions.inc.php');
-require_once('../gradebook/lib/be/gradebookitem.class.php');
-require_once('../gradebook/lib/be/evaluation.class.php');
-require_once('../gradebook/lib/be/abstractlink.class.php');
-require_once('../gradebook/lib/gradebook_functions.inc.php');
-// the section (tabs)
-$this_section=SECTION_COURSES;
-// notice for unauthorized people.
-api_protect_course_script(true);
-
-// including additional library scripts
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-include_once (api_get_path(LIBRARY_PATH).'groupmanager.lib.php');
-
-$nameTools=get_lang('Forum');
-
-/*
------------------------------------------------------------
-	Including necessary files
------------------------------------------------------------
-*/
-include('forumconfig.inc.php');
-include('forumfunction.inc.php');
-
-// javascript
-$htmlHeadXtra[] = '<script>
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
-		function advanced_parameters() {
-			if(document.getElementById(\'id_qualify\').style.display == \'none\') {
-				document.getElementById(\'id_qualify\').style.display = \'block\';
-				document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_hide.gif',get_lang('Hide'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
-
-			} else {
-				document.getElementById(\'id_qualify\').style.display = \'none\';
-				document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
-			}
-		}
+	Copyright (c) 2004-2008 Dokeos SPRL
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) various contributors
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+
+/**
+*	These files are a complete rework of the forum. The database structure is
+*	based on phpBB but all the code is rewritten. A lot of new functionalities
+*	are added:
+* 	- forum categories and forums can be sorted up or down, locked or made invisible
+*	- consistent and integrated forum administration
+* 	- forum options: 	are students allowed to edit their post?
+* 						moderation of posts (approval)
+* 						reply only forums (students cannot create new threads)
+* 						multiple forums per group
+*	- sticky messages
+* 	- new view option: nested view
+* 	- quoting a message
+*
+*	@Author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*	@Copyright Ghent University
+*	@Copyright Patrick Cool
+*
+* 	@package dokeos.forum
+*/
+
+/**
+ **************************************************************************
+ *						IMPORTANT NOTICE
+ * Please do not change anything is this code yet because there are still
+ * some significant code that need to happen and I do not have the time to
+ * merge files and test it all over again. So for the moment, please do not
+ * touch the code
+ * 							-- Patrick Cool <patrick.cool@UGent.be>
+ **************************************************************************
+ */
+
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
+*/
+// name of the language file that needs to be included
+$language_file = array (
+	'forum',
+	'group'
+);
+
+// including the global dokeos file
+require ('../inc/global.inc.php');
+require_once('../gradebook/lib/gradebook_functions.inc.php');
+require_once('../gradebook/lib/be/gradebookitem.class.php');
+require_once('../gradebook/lib/be/evaluation.class.php');
+require_once('../gradebook/lib/be/abstractlink.class.php');
+require_once('../gradebook/lib/gradebook_functions.inc.php');
+// the section (tabs)
+$this_section=SECTION_COURSES;
+// notice for unauthorized people.
+api_protect_course_script(true);
+
+// including additional library scripts
+require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+include_once (api_get_path(LIBRARY_PATH).'groupmanager.lib.php');
+
+$nameTools=get_lang('Forum');
+
+/*
+-----------------------------------------------------------
+	Including necessary files
+-----------------------------------------------------------
+*/
+include('forumconfig.inc.php');
+include('forumfunction.inc.php');
+
+// javascript
+$htmlHeadXtra[] = '<script>
+
+		function advanced_parameters() {
+			if(document.getElementById(\'id_qualify\').style.display == \'none\') {
+				document.getElementById(\'id_qualify\').style.display = \'block\';
+				document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_hide.gif',get_lang('Hide'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
+
+			} else {
+				document.getElementById(\'id_qualify\').style.display = \'none\';
+				document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
+			}
+		}
 </script>';
-
-/*
-==============================================================================
-		MAIN DISPLAY SECTION
-==============================================================================
-*/
-/*
------------------------------------------------------------
-	Retrieving forum and forum categorie information
------------------------------------------------------------
-*/
-// we are getting all the information about the current forum and forum category.
-// note pcool: I tried to use only one sql statement (and function) for this
-// but the problem is that the visibility of the forum AND forum cateogory are stored in the item_property table
-$current_thread=get_thread_information($_GET['thread']); // note: this has to be validated that it is an existing thread
-$current_forum=get_forum_information($_GET['forum']); // note: this has to be validated that it is an existing forum.
-$current_forum_category=get_forumcategory_information($current_forum['forum_category']);
-$current_post=get_post_information($_GET['post']);
-/*
------------------------------------------------------------
-	Header and Breadcrumbs
------------------------------------------------------------
-*/
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+
+/*
+==============================================================================
+		MAIN DISPLAY SECTION
+==============================================================================
+*/
+/*
+-----------------------------------------------------------
+	Retrieving forum and forum categorie information
+-----------------------------------------------------------
+*/
+// we are getting all the information about the current forum and forum category.
+// note pcool: I tried to use only one sql statement (and function) for this
+// but the problem is that the visibility of the forum AND forum cateogory are stored in the item_property table
+$current_thread=get_thread_information($_GET['thread']); // note: this has to be validated that it is an existing thread
+$current_forum=get_forum_information($_GET['forum']); // note: this has to be validated that it is an existing forum.
+$current_forum_category=get_forumcategory_information($current_forum['forum_category']);
+$current_post=get_post_information($_GET['post']);
+/*
+-----------------------------------------------------------
+	Header and Breadcrumbs
+-----------------------------------------------------------
+*/
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-
-
-if (!empty($_SESSION['toolgroup'])) {
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
 
-	$_clean['toolgroup']=(int)$_SESSION['toolgroup'];
-	$group_properties  = GroupManager :: get_group_properties($_clean['toolgroup']);
-	$interbreadcrumb[] = array ("url" => "../group/group.php", "name" => get_lang('Groups'));
-	$interbreadcrumb[] = array ("url"=>"../group/group_space.php?gidReq=".$_SESSION['toolgroup'], "name"=> get_lang('GroupSpace').' ('.$group_properties['name'].')');
+
+if (!empty($_SESSION['toolgroup'])) {
+
+	$_clean['toolgroup']=(int)$_SESSION['toolgroup'];
+	$group_properties  = GroupManager :: get_group_properties($_clean['toolgroup']);
+	$interbreadcrumb[] = array ("url" => "../group/group.php", "name" => get_lang('Groups'));
+	$interbreadcrumb[] = array ("url"=>"../group/group_space.php?gidReq=".$_SESSION['toolgroup'], "name"=> get_lang('GroupSpace').' ('.$group_properties['name'].')');
 	$interbreadcrumb[] = array("url" => "viewforum.php?origin=".$origin."&amp;gidReq=".$_SESSION['toolgroup']."&amp;forum=".Security::remove_XSS($_GET['forum']),"name" => prepare4display($current_forum['forum_title']));
-	$interbreadcrumb[] = array("url" => "javascript: void (0);","name" => get_lang('EditPost'));
+	$interbreadcrumb[] = array("url" => "javascript: void (0);","name" => get_lang('EditPost'));
+
+} else {
+	$interbreadcrumb[]=array("url" => "index.php?gradebook=$gradebook","name" => $nameTools);
+	$interbreadcrumb[]=array("url" => "viewforumcategory.php?forumcategory=".$current_forum_category['cat_id'],"name" => prepare4display($current_forum_category['cat_title']));
+	$interbreadcrumb[]=array("url" => "viewforum.php?origin=".$origin."&amp;forum=".Security::remove_XSS($_GET['forum']),"name" => prepare4display($current_forum['forum_title']));
+	$interbreadcrumb[]=array("url" => "viewthread.php?gradebook=$gradebook&amp;origin=".$origin."&amp;forum=".Security::remove_XSS($_GET['forum'])."&amp;thread=".$_GET['thread'],"name" => prepare4display($current_thread['thread_title']));
+	$interbreadcrumb[]=array("url" => "javascript: void (0);","name" => get_lang('EditPost'));
+}
+/*
+-----------------------------------------------------------
+	Resource Linker
+-----------------------------------------------------------
+*/
+if (isset($_POST['add_resources']) AND $_POST['add_resources']==get_lang('Resources')) {
+	$_SESSION['formelements']=$_POST;
+	$_SESSION['origin']=$_SERVER['REQUEST_URI'];
+	$_SESSION['breadcrumbs']=$interbreadcrumb;
+	header("Location: ../resourcelinker/resourcelinker.php");
+}
+$table_link 			= Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+/*
+-----------------------------------------------------------
+	Header
+-----------------------------------------------------------
+*/
+//are we in a lp ?
+$origin = '';
+if (isset($_GET['origin'])) {
+	$origin =  Security::remove_XSS($_GET['origin']);
+}
+
+if ($origin=='learnpath') {
+	include(api_get_path(INCLUDE_PATH).'reduced_header.inc.php');
+} else {
+	Display :: display_header(null);
+	//api_display_tool_title($nameTools);
+}
+//echo '<link href="forumstyles.css" rel="stylesheet" type="text/css" />';
+/*
+-----------------------------------------------------------
+	Is the user allowed here?
+-----------------------------------------------------------
+*/
+// the user is not allowed here if
+// 1. the forumcategory, forum or thread is invisible (visibility==0)
+// 2. the forumcategory, forum or thread is locked (locked <>0)
+// 3. if anonymous posts are not allowed
+// 4. if editing of replies is not allowed
+// The only exception is the course manager
+// I have split this is several pieces for clarity.
+//if (!api_is_allowed_to_edit() AND (($current_forum_category['visibility']==0 OR $current_forum['visibility']==0) OR ($current_forum_category['locked']<>0 OR $current_forum['locked']<>0 OR $current_thread['locked']<>0)))
+if (!api_is_allowed_to_edit() AND (($current_forum_category['visibility']==0 OR $current_forum['visibility']==0))) {
+	forum_not_allowed_here();
+}
+if (!api_is_allowed_to_edit() AND ($current_forum_category['locked']<>0 OR $current_forum['locked']<>0 OR $current_thread['locked']<>0)) {
+	forum_not_allowed_here();
+}
+if (!$_user['user_id'] AND $current_forum['allow_anonymous']==0) {
+	forum_not_allowed_here();
+}
+if (!api_is_allowed_to_edit() AND $current_forum['allow_edit']==0) {
+	forum_not_allowed_here();
+}
+
+
+// action links
+if ($origin!='learnpath') {
+	echo '<div class="actions">';
+	echo '<span style="float:right;">'.search_link().'</span>';
+	echo '<a href="index.php?gradebook='.$gradebook.'">'.Display::return_icon('back.png').' '.get_lang('BackToForumOverview').'</a>';
+	echo '<a href="viewforum.php?forum='.Security::remove_XSS($_GET['forum']).'">'.Display::return_icon('forum.gif').' '.get_lang('BackToForum').'</a>';
+	echo '</div>';
+}
+
+/*
+-----------------------------------------------------------
+	Display Forum Category and the Forum information
+-----------------------------------------------------------
+*/
+echo "<table class=\"data_table\" width='100%'>\n";
+// the forum category
+echo "\t<tr>\n\t\t<th align=\"left\" colspan=\"2\">";
+echo '<a href="viewforum.php?&origin='.$origin.'&forum='.$current_forum['forum_id'].'" '.class_visible_invisible($current_forum['visibility']).'>'.prepare4display($current_forum['forum_title']).'</a><br />';
+echo '<span class="forum_description">'.prepare4display($current_forum['forum_comment']).'</span>';echo "</th>\n";
+echo "</th>\n";
+echo "\t</tr>\n";
+echo '</table>';
+
+// the form for the reply
+$values=show_edit_post_form($current_post, $current_thread, $current_forum, isset($_SESSION['formelements'])?$_SESSION['formelements']:'');
+
+if (!empty($values) and isset($_POST['SubmitPost'])) {
+	store_edit_post($values);
 
-} else {
-	$interbreadcrumb[]=array("url" => "index.php?gradebook=$gradebook","name" => $nameTools);
-	$interbreadcrumb[]=array("url" => "viewforumcategory.php?forumcategory=".$current_forum_category['cat_id'],"name" => prepare4display($current_forum_category['cat_title']));
-	$interbreadcrumb[]=array("url" => "viewforum.php?origin=".$origin."&amp;forum=".Security::remove_XSS($_GET['forum']),"name" => prepare4display($current_forum['forum_title']));
-	$interbreadcrumb[]=array("url" => "viewthread.php?gradebook=$gradebook&amp;origin=".$origin."&amp;forum=".Security::remove_XSS($_GET['forum'])."&amp;thread=".$_GET['thread'],"name" => prepare4display($current_thread['thread_title']));
-	$interbreadcrumb[]=array("url" => "javascript: void (0);","name" => get_lang('EditPost'));
-}
-/*
------------------------------------------------------------
-	Resource Linker
------------------------------------------------------------
-*/
-if (isset($_POST['add_resources']) AND $_POST['add_resources']==get_lang('Resources')) {
-	$_SESSION['formelements']=$_POST;
-	$_SESSION['origin']=$_SERVER['REQUEST_URI'];
-	$_SESSION['breadcrumbs']=$interbreadcrumb;
-	header("Location: ../resourcelinker/resourcelinker.php");
-}
-$table_link 			= Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
-/*
------------------------------------------------------------
-	Header
------------------------------------------------------------
-*/
-//are we in a lp ?
-$origin = '';
-if (isset($_GET['origin'])) {
-	$origin =  Security::remove_XSS($_GET['origin']);
-}
-
-if ($origin=='learnpath') {
-	include(api_get_path(INCLUDE_PATH).'reduced_header.inc.php');
-} else {
-	Display :: display_header(null);
-	//api_display_tool_title($nameTools);
-}
-//echo '<link href="forumstyles.css" rel="stylesheet" type="text/css" />';
-/*
------------------------------------------------------------
-	Is the user allowed here?
------------------------------------------------------------
-*/
-// the user is not allowed here if
-// 1. the forumcategory, forum or thread is invisible (visibility==0)
-// 2. the forumcategory, forum or thread is locked (locked <>0)
-// 3. if anonymous posts are not allowed
-// 4. if editing of replies is not allowed
-// The only exception is the course manager
-// I have split this is several pieces for clarity.
-//if (!api_is_allowed_to_edit() AND (($current_forum_category['visibility']==0 OR $current_forum['visibility']==0) OR ($current_forum_category['locked']<>0 OR $current_forum['locked']<>0 OR $current_thread['locked']<>0)))
-if (!api_is_allowed_to_edit() AND (($current_forum_category['visibility']==0 OR $current_forum['visibility']==0))) {
-	forum_not_allowed_here();
-}
-if (!api_is_allowed_to_edit() AND ($current_forum_category['locked']<>0 OR $current_forum['locked']<>0 OR $current_thread['locked']<>0)) {
-	forum_not_allowed_here();
-}
-if (!$_user['user_id'] AND $current_forum['allow_anonymous']==0) {
-	forum_not_allowed_here();
-}
-if (!api_is_allowed_to_edit() AND $current_forum['allow_edit']==0) {
-	forum_not_allowed_here();
-}
-
-
-// action links
-if ($origin!='learnpath') {
-	echo '<div class="actions">';
-	echo '<span style="float:right;">'.search_link().'</span>';
-	echo '<a href="index.php?gradebook='.$gradebook.'">'.Display::return_icon('back.png').' '.get_lang('BackToForumOverview').'</a>';
-	echo '<a href="viewforum.php?forum='.Security::remove_XSS($_GET['forum']).'">'.Display::return_icon('forum.gif').' '.get_lang('BackToForum').'</a>';
-	echo '</div>';
-}
-
-/*
------------------------------------------------------------
-	Display Forum Category and the Forum information
------------------------------------------------------------
-*/
-echo "<table class=\"data_table\" width='100%'>\n";
-// the forum category
-echo "\t<tr>\n\t\t<th align=\"left\" colspan=\"2\">";
-echo '<a href="viewforum.php?&origin='.$origin.'&forum='.$current_forum['forum_id'].'" '.class_visible_invisible($current_forum['visibility']).'>'.prepare4display($current_forum['forum_title']).'</a><br />';
-echo '<span class="forum_description">'.prepare4display($current_forum['forum_comment']).'</span>';echo "</th>\n";
-echo "</th>\n";
-echo "\t</tr>\n";
-echo '</table>';
-
-// the form for the reply
-$values=show_edit_post_form($current_post, $current_thread, $current_forum, isset($_SESSION['formelements'])?$_SESSION['formelements']:'');
-
-if (!empty($values) and isset($_POST['SubmitPost'])) {
-	store_edit_post($values);
-
-	$option_chek=isset($values['thread_qualify_gradebook'])?$values['thread_qualify_gradebook']:null;// values 1 or 0
-	if ( 1== $option_chek ) {
-			$id=$values['thread_id'];
-			$title_gradebook=$values['calification_notebook_title'];
-			$value_calification=$values['numeric_calification'];
-			$weight_calification=$values['weight_calification'];
-			$description="";
-			$session_id=api_get_session_id();
-			$link_id=is_resource_in_course_gradebook(api_get_course_id(),5,$id,$session_id);
-			if ($link_id==false) {
+	$option_chek=isset($values['thread_qualify_gradebook'])?$values['thread_qualify_gradebook']:null;// values 1 or 0
+	if ( 1== $option_chek ) {
+			$id=$values['thread_id'];
+			$title_gradebook=$values['calification_notebook_title'];
+			$value_calification=$values['numeric_calification'];
+			$weight_calification=$values['weight_calification'];
+			$description="";
+			$session_id=api_get_session_id();
+			$link_id=is_resource_in_course_gradebook(api_get_course_id(),5,$id,$session_id);
+			if ($link_id==false) {
 				add_resource_to_course_gradebook(api_get_course_id(), 5, $id, $title_gradebook,$weight_calification,$value_calification,$description,time(),1,api_get_session_id());
-			} else {
-				Database::query('UPDATE '.$table_link.' SET weight='.$weight_calification.' WHERE id='.$link_id.'');
-			}
+			} else {
+				Database::query('UPDATE '.$table_link.' SET weight='.$weight_calification.' WHERE id='.$link_id.'');
+			}
 
-	}
+	}
 
-}
-// footer
-if ($origin!='learnpath') {
-	Display :: display_footer();
-}
+}
+// footer
+if ($origin!='learnpath') {
+	Display :: display_footer();
+}

+ 301 - 301
main/forum/forumqualify.php

@@ -1,338 +1,338 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2008 Dokeos Latinoamerica SAC
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, 108 rue du Corbeau, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
-==============================================================================
-*/
-/**
-* 	@package dokeos.forum
-*/
-// name of the language file that needs to be included
-$language_file=array('admin','forum');
-require '../inc/global.inc.php';
-require_once 'forumconfig.inc.php';
-require_once 'forumfunction.inc.php';
-$nameTools = get_lang('Forum');
-$this_section = SECTION_COURSES;
-
-$allowed_to_edit = api_is_allowed_to_edit(true,true);
-if (!$allowed_to_edit) {
-	api_not_allowed(true);
-}
-
-$origin = '';
-$origin_string='';
-if (isset($_GET['origin'])) {
-	$origin =  Security::remove_XSS($_GET['origin']);
-}
-
-// including additional library scripts
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-include_once (api_get_path(LIBRARY_PATH).'groupmanager.lib.php');
-//require_once (api_get_path(LIBRARY_PATH).'resourcelinker.lib.php');
-$nameTools=get_lang('Forum');
-
-/*
------------------------------------------------------------
-	Including necessary files
------------------------------------------------------------
-*/
-
-$htmlHeadXtra[] = '<script type="text/javascript" src="'.api_get_path(WEB_CODE_PATH).'inc/lib/javascript/jquery.js" ></script>';
-$htmlHeadXtra[] = '<script type="text/javascript" language="javascript">
-										$(document).ready(function(){ $(\'.hide-me\').slideUp() });
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact address: Dokeos, 108 rue du Corbeau, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+/**
+* 	@package dokeos.forum
+*/
+// name of the language file that needs to be included
+$language_file=array('admin','forum');
+require '../inc/global.inc.php';
+require_once 'forumconfig.inc.php';
+require_once 'forumfunction.inc.php';
+$nameTools = get_lang('Forum');
+$this_section = SECTION_COURSES;
+
+$allowed_to_edit = api_is_allowed_to_edit(true,true);
+if (!$allowed_to_edit) {
+	api_not_allowed(true);
+}
+
+$origin = '';
+$origin_string='';
+if (isset($_GET['origin'])) {
+	$origin =  Security::remove_XSS($_GET['origin']);
+}
+
+// including additional library scripts
+require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+include_once (api_get_path(LIBRARY_PATH).'groupmanager.lib.php');
+//require_once (api_get_path(LIBRARY_PATH).'resourcelinker.lib.php');
+$nameTools=get_lang('Forum');
+
+/*
+-----------------------------------------------------------
+	Including necessary files
+-----------------------------------------------------------
+*/
+
+$htmlHeadXtra[] = '<script type="text/javascript" src="'.api_get_path(WEB_CODE_PATH).'inc/lib/javascript/jquery.js" ></script>';
+$htmlHeadXtra[] = '<script type="text/javascript" language="javascript">
+										$(document).ready(function(){ $(\'.hide-me\').slideUp() });
 									function hidecontent(content){ $(content).slideToggle(\'normal\'); }
-									</script>';
-
-//are we in a lp ?
-$origin = '';
-if (isset($_GET['origin'])) {
-	$origin =  Security::remove_XSS($_GET['origin']);
-}
-/*
-==============================================================================
-		MAIN DISPLAY SECTION
-==============================================================================
-*/
-/*
------------------------------------------------------------
-	Retrieving forum and forum categorie information
------------------------------------------------------------
-*/
-// we are getting all the information about the current forum and forum category.
-// note pcool: I tried to use only one sql statement (and function) for this
-// but the problem is that the visibility of the forum AND forum cateogory are stored in the item_property table
-$current_thread=get_thread_information($_GET['thread']); // note: this has to be validated that it is an existing thread
-$current_forum=get_forum_information($current_thread['forum_id']); // note: this has to be validated that it is an existing forum.
-$current_forum_category=get_forumcategory_information($current_forum['forum_category']);
-$whatsnew_post_info=$_SESSION['whatsnew_post_info'];
-/*
------------------------------------------------------------
-	Header and Breadcrumbs
------------------------------------------------------------
-*/
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+									</script>';
+
+//are we in a lp ?
+$origin = '';
+if (isset($_GET['origin'])) {
+	$origin =  Security::remove_XSS($_GET['origin']);
+}
+/*
+==============================================================================
+		MAIN DISPLAY SECTION
+==============================================================================
+*/
+/*
+-----------------------------------------------------------
+	Retrieving forum and forum categorie information
+-----------------------------------------------------------
+*/
+// we are getting all the information about the current forum and forum category.
+// note pcool: I tried to use only one sql statement (and function) for this
+// but the problem is that the visibility of the forum AND forum cateogory are stored in the item_property table
+$current_thread=get_thread_information($_GET['thread']); // note: this has to be validated that it is an existing thread
+$current_forum=get_forum_information($current_thread['forum_id']); // note: this has to be validated that it is an existing forum.
+$current_forum_category=get_forumcategory_information($current_forum['forum_category']);
+$whatsnew_post_info=$_SESSION['whatsnew_post_info'];
+/*
+-----------------------------------------------------------
+	Header and Breadcrumbs
+-----------------------------------------------------------
+*/
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-
-if ($origin=='learnpath') {
-	include(api_get_path(INCLUDE_PATH).'reduced_header.inc.php');
-} else {
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
+
+if ($origin=='learnpath') {
+	include(api_get_path(INCLUDE_PATH).'reduced_header.inc.php');
+} else {
 	if (!empty($_SESSION['toolgroup'])) {
 
-		$_clean['toolgroup']=(int)$_SESSION['toolgroup'];
-		$group_properties  = GroupManager :: get_group_properties($_clean['toolgroup']);
-		$interbreadcrumb[] = array ("url" => "../group/group.php", "name" => get_lang('Groups'));
-		$interbreadcrumb[] = array ("url"=>"../group/group_space.php?gidReq=".$_SESSION['toolgroup'], "name"=> get_lang('GroupSpace').' ('.$group_properties['name'].')');
-		$interbreadcrumb[]=array("url" => "viewforum.php?forum=".Security::remove_XSS($_GET['forum'])."&amp;origin=".$origin."&amp;search=".Security::remove_XSS(urlencode($_GET['search'])),"name" => prepare4display($current_forum['forum_title']));
-		if ($message<>'PostDeletedSpecial') {
-			$interbreadcrumb[]=array("url" => "viewthread.php?forum=".Security::remove_XSS($_GET['forum'])."&amp;gradebook=".$gradebook."&amp;thread=".Security::remove_XSS($_GET['thread']),"name" => prepare4display($current_thread['thread_title']));
-		}
-		$interbreadcrumb[]=array("url" => "#","name" => get_lang('QualifyThread'));
-		// the last element of the breadcrumb navigation is already set in interbreadcrumb, so give empty string
-		Display :: display_header('');
-		api_display_tool_title($nameTools);
-	} else {
-
-		$info_thread=get_thread_information(Security::remove_XSS($_GET['thread']));
-		$interbreadcrumb[]=array("url" => "index.php?gradebook=$gradebook&search=".Security::remove_XSS(urlencode($_GET['search'])),"name" => $nameTools);
-		$interbreadcrumb[]=array("url" => "viewforumcategory.php?forumcategory=".$current_forum_category['cat_id']."&amp;search=".Security::remove_XSS(urlencode($_GET['search'])),"name" => prepare4display($current_forum_category['cat_title']));
-
-		$interbreadcrumb[]=array("url" => "viewforum.php?forum=".Security::remove_XSS($_GET['forum'])."&amp;origin=".$origin."&amp;search=".Security::remove_XSS(urlencode($_GET['search'])),"name" => prepare4display($current_forum['forum_title']));
-
-		if ($message<>'PostDeletedSpecial') {
-			if (isset($_GET['gradebook']) and $_GET['gradebook']=='view') {
-				$info_thread=get_thread_information(Security::remove_XSS($_GET['thread']));
-				$interbreadcrumb[]=array("url" => "viewthread.php?forum=".$info_thread['forum_id']."&amp;gradebook=".$gradebook."&amp;thread=".Security::remove_XSS($_GET['thread']),"name" => prepare4display($current_thread['thread_title']));
-			} else {
-				$interbreadcrumb[]=array("url" => "viewthread.php?forum=".Security::remove_XSS($_GET['forum'])."&amp;gradebook=".$gradebook."&amp;thread=".Security::remove_XSS($_GET['thread']),"name" => prepare4display($current_thread['thread_title']));
-			}
-		}
-		// the last element of the breadcrumb navigation is already set in interbreadcrumb, so give empty string
-		$interbreadcrumb[]=array("url" => "#","name" => get_lang('QualifyThread'));
-		Display :: display_header('');
+		$_clean['toolgroup']=(int)$_SESSION['toolgroup'];
+		$group_properties  = GroupManager :: get_group_properties($_clean['toolgroup']);
+		$interbreadcrumb[] = array ("url" => "../group/group.php", "name" => get_lang('Groups'));
+		$interbreadcrumb[] = array ("url"=>"../group/group_space.php?gidReq=".$_SESSION['toolgroup'], "name"=> get_lang('GroupSpace').' ('.$group_properties['name'].')');
+		$interbreadcrumb[]=array("url" => "viewforum.php?forum=".Security::remove_XSS($_GET['forum'])."&amp;origin=".$origin."&amp;search=".Security::remove_XSS(urlencode($_GET['search'])),"name" => prepare4display($current_forum['forum_title']));
+		if ($message<>'PostDeletedSpecial') {
+			$interbreadcrumb[]=array("url" => "viewthread.php?forum=".Security::remove_XSS($_GET['forum'])."&amp;gradebook=".$gradebook."&amp;thread=".Security::remove_XSS($_GET['thread']),"name" => prepare4display($current_thread['thread_title']));
+		}
+		$interbreadcrumb[]=array("url" => "#","name" => get_lang('QualifyThread'));
+		// the last element of the breadcrumb navigation is already set in interbreadcrumb, so give empty string
+		Display :: display_header('');
 		api_display_tool_title($nameTools);
+	} else {
+
+		$info_thread=get_thread_information(Security::remove_XSS($_GET['thread']));
+		$interbreadcrumb[]=array("url" => "index.php?gradebook=$gradebook&search=".Security::remove_XSS(urlencode($_GET['search'])),"name" => $nameTools);
+		$interbreadcrumb[]=array("url" => "viewforumcategory.php?forumcategory=".$current_forum_category['cat_id']."&amp;search=".Security::remove_XSS(urlencode($_GET['search'])),"name" => prepare4display($current_forum_category['cat_title']));
+
+		$interbreadcrumb[]=array("url" => "viewforum.php?forum=".Security::remove_XSS($_GET['forum'])."&amp;origin=".$origin."&amp;search=".Security::remove_XSS(urlencode($_GET['search'])),"name" => prepare4display($current_forum['forum_title']));
+
+		if ($message<>'PostDeletedSpecial') {
+			if (isset($_GET['gradebook']) and $_GET['gradebook']=='view') {
+				$info_thread=get_thread_information(Security::remove_XSS($_GET['thread']));
+				$interbreadcrumb[]=array("url" => "viewthread.php?forum=".$info_thread['forum_id']."&amp;gradebook=".$gradebook."&amp;thread=".Security::remove_XSS($_GET['thread']),"name" => prepare4display($current_thread['thread_title']));
+			} else {
+				$interbreadcrumb[]=array("url" => "viewthread.php?forum=".Security::remove_XSS($_GET['forum'])."&amp;gradebook=".$gradebook."&amp;thread=".Security::remove_XSS($_GET['thread']),"name" => prepare4display($current_thread['thread_title']));
+			}
+		}
+		// the last element of the breadcrumb navigation is already set in interbreadcrumb, so give empty string
+		$interbreadcrumb[]=array("url" => "#","name" => get_lang('QualifyThread'));
+		Display :: display_header('');
+		api_display_tool_title($nameTools);
+
+	}
+}
+
+/*
+-----------------------------------------------------------
+	Is the user allowed here?
+-----------------------------------------------------------
+*/
+// if the user is not a course administrator and the forum is hidden
+// then the user is not allowed here.
+if (!api_is_allowed_to_edit(false,true) AND ($current_forum['visibility']==0 OR $current_thread['visibility']==0)) {
+	forum_not_allowed_here();
+}
+
 
-	}
-}
-
-/*
------------------------------------------------------------
-	Is the user allowed here?
------------------------------------------------------------
-*/
-// if the user is not a course administrator and the forum is hidden
-// then the user is not allowed here.
-if (!api_is_allowed_to_edit(false,true) AND ($current_forum['visibility']==0 OR $current_thread['visibility']==0)) {
-	forum_not_allowed_here();
-}
-
-
-/*
------------------------------------------------------------
-	Actions
------------------------------------------------------------
-*/
-if ($_GET['action']=='delete' && isset($_GET['content']) && isset($_GET['id']) && api_is_allowed_to_edit(false,true)) {
-	$message=delete_post($_GET['id']); // note: this has to be cleaned first
-}
-if (($_GET['action']=='invisible' || $_GET['action']=='visible') && isset($_GET['id']) && api_is_allowed_to_edit(false,true)) {
-	$message=approve_post($_GET['id'],$_GET['action']); // note: this has to be cleaned first
-}
-if ($_GET['action']=='move' and isset($_GET['post'])) {
-	$message=move_post_form();
-}
-
-/*
------------------------------------------------------------
-	Display the action messages
------------------------------------------------------------
-*/
-if (!empty($message)) {
-	Display :: display_confirmation_message(get_lang($message));
-}
-
-if ($message<>'PostDeletedSpecial') {// in this case the first and only post of the thread is removed
-	// this increases the number of times the thread has been viewed
-	increase_thread_view($_GET['thread']);
-
-	/*
-	-----------------------------------------------------------
-		Action Links
-	-----------------------------------------------------------
-	*/
-/*	echo '<div style="float:right;">';
-	$my_url = '<a href="viewthread.php?'.api_get_cidreq().'&amp;forum='.Security::remove_XSS($_GET['forum']).'&amp;thread='.Security::remove_XSS($_GET['thread']).'&amp;origin='.$origin.'&amp;search='.Security::remove_XSS(urlencode($_GET['search']));
-	echo $my_url.'&amp;view=flat&origin='.$origin.'">'.get_lang('FlatView').'</a> | ';
-	echo $my_url.'&amp;view=threaded&origin='.$origin.'">'.get_lang('ThreadedView').'</a> | ';
-	echo $my_url.'&amp;view=nested&origin='.$origin.'">'.get_lang('NestedView').'</a>';
-	$my_url = null;
-	echo '</div>';*/
-	// the reply to thread link should only appear when the forum_category is not locked AND the forum is not locked AND the thread is not locked.
-	// if one of the three levels is locked then the link should not be displayed
-	if ($current_forum_category['locked']==0 AND $current_forum['locked']==0 AND $current_thread['locked']==0 OR api_is_allowed_to_edit(false,true)) {
-		// The link should only appear when the user is logged in or when anonymous posts are allowed.
-		if ($_user['user_id'] OR ($current_forum['allow_anonymous']==1 AND !$_user['user_id'])) {
-			//reply link
-			/*echo '<a href="reply.php?'.api_get_cidreq().'&forum='.Security::remove_XSS($_GET['forum']).'&amp;thread='.Security::remove_XSS($_GET['thread']).'&amp;action=replythread&origin='.$origin.'">'.get_lang('ReplyToThread').'</a>';*/
-
-			//new thread link
-			if (api_is_allowed_to_edit(false,true) OR ($current_forum['allow_new_threads']==1 AND isset($_user['user_id'])) OR ($current_forum['allow_new_threads']==1 AND !isset($_user['user_id']) AND $current_forum['allow_anonymous']==1)) {
-				if ($current_forum['locked'] <> 1 AND $current_forum['locked'] <> 1) {
+/*
+-----------------------------------------------------------
+	Actions
+-----------------------------------------------------------
+*/
+if ($_GET['action']=='delete' && isset($_GET['content']) && isset($_GET['id']) && api_is_allowed_to_edit(false,true)) {
+	$message=delete_post($_GET['id']); // note: this has to be cleaned first
+}
+if (($_GET['action']=='invisible' || $_GET['action']=='visible') && isset($_GET['id']) && api_is_allowed_to_edit(false,true)) {
+	$message=approve_post($_GET['id'],$_GET['action']); // note: this has to be cleaned first
+}
+if ($_GET['action']=='move' and isset($_GET['post'])) {
+	$message=move_post_form();
+}
+
+/*
+-----------------------------------------------------------
+	Display the action messages
+-----------------------------------------------------------
+*/
+if (!empty($message)) {
+	Display :: display_confirmation_message(get_lang($message));
+}
+
+if ($message<>'PostDeletedSpecial') {// in this case the first and only post of the thread is removed
+	// this increases the number of times the thread has been viewed
+	increase_thread_view($_GET['thread']);
+
+	/*
+	-----------------------------------------------------------
+		Action Links
+	-----------------------------------------------------------
+	*/
+/*	echo '<div style="float:right;">';
+	$my_url = '<a href="viewthread.php?'.api_get_cidreq().'&amp;forum='.Security::remove_XSS($_GET['forum']).'&amp;thread='.Security::remove_XSS($_GET['thread']).'&amp;origin='.$origin.'&amp;search='.Security::remove_XSS(urlencode($_GET['search']));
+	echo $my_url.'&amp;view=flat&origin='.$origin.'">'.get_lang('FlatView').'</a> | ';
+	echo $my_url.'&amp;view=threaded&origin='.$origin.'">'.get_lang('ThreadedView').'</a> | ';
+	echo $my_url.'&amp;view=nested&origin='.$origin.'">'.get_lang('NestedView').'</a>';
+	$my_url = null;
+	echo '</div>';*/
+	// the reply to thread link should only appear when the forum_category is not locked AND the forum is not locked AND the thread is not locked.
+	// if one of the three levels is locked then the link should not be displayed
+	if ($current_forum_category['locked']==0 AND $current_forum['locked']==0 AND $current_thread['locked']==0 OR api_is_allowed_to_edit(false,true)) {
+		// The link should only appear when the user is logged in or when anonymous posts are allowed.
+		if ($_user['user_id'] OR ($current_forum['allow_anonymous']==1 AND !$_user['user_id'])) {
+			//reply link
+			/*echo '<a href="reply.php?'.api_get_cidreq().'&forum='.Security::remove_XSS($_GET['forum']).'&amp;thread='.Security::remove_XSS($_GET['thread']).'&amp;action=replythread&origin='.$origin.'">'.get_lang('ReplyToThread').'</a>';*/
+
+			//new thread link
+			if (api_is_allowed_to_edit(false,true) OR ($current_forum['allow_new_threads']==1 AND isset($_user['user_id'])) OR ($current_forum['allow_new_threads']==1 AND !isset($_user['user_id']) AND $current_forum['allow_anonymous']==1)) {
+				if ($current_forum['locked'] <> 1 AND $current_forum['locked'] <> 1) {
 					echo '&nbsp;&nbsp;';
-					/*echo '<a href="newthread.php?'.api_get_cidreq().'&forum='.Security::remove_XSS($_GET['forum']).$origin_string.'">'.Display::return_icon('forumthread_new.gif').' '.get_lang('NewTopic').'</a>';*/
-				} else {
-					echo get_lang('ForumLocked');
-				}
-			}
-		}
-	}
-	// note: this is to prevent that some browsers display the links over the table (FF does it but Opera doesn't)
-	echo '&nbsp;';
-
-	/*
-	-----------------------------------------------------------
-		Display Forum Category and the Forum information
-	-----------------------------------------------------------
-	*/
-	if (!$_SESSION['view']) {
-		$viewmode=$current_forum['default_view'];
-	} else {
-		$viewmode=$_SESSION['view'];
-	}
-
-	$viewmode_whitelist=array('flat', 'threaded', 'nested');
-	if (isset($_GET['view']) and in_array($_GET['view'],$viewmode_whitelist)) {
-		$viewmode=Database::escape_string($_GET['view']);
-		$_SESSION['view']=$viewmode;
+					/*echo '<a href="newthread.php?'.api_get_cidreq().'&forum='.Security::remove_XSS($_GET['forum']).$origin_string.'">'.Display::return_icon('forumthread_new.gif').' '.get_lang('NewTopic').'</a>';*/
+				} else {
+					echo get_lang('ForumLocked');
+				}
+			}
+		}
 	}
-	if (empty($viewmode)) {
-		$viewmode = 'flat';
-	}
-
-	/*
-	-----------------------------------------------------------
-		Display Forum Category and the Forum information
-	-----------------------------------------------------------
-	*/
-	// we are getting all the information about the current forum and forum category.
-	// note pcool: I tried to use only one sql statement (and function) for this
-	// but the problem is that the visibility of the forum AND forum cateogory are stored in the item_property table
-	echo "<table class=\"data_table\" width=\"100%\">\n";
-
+	// note: this is to prevent that some browsers display the links over the table (FF does it but Opera doesn't)
+	echo '&nbsp;';
+
+	/*
+	-----------------------------------------------------------
+		Display Forum Category and the Forum information
+	-----------------------------------------------------------
+	*/
+	if (!$_SESSION['view']) {
+		$viewmode=$current_forum['default_view'];
+	} else {
+		$viewmode=$_SESSION['view'];
+	}
+
+	$viewmode_whitelist=array('flat', 'threaded', 'nested');
+	if (isset($_GET['view']) and in_array($_GET['view'],$viewmode_whitelist)) {
+		$viewmode=Database::escape_string($_GET['view']);
+		$_SESSION['view']=$viewmode;
+	}
+	if (empty($viewmode)) {
+		$viewmode = 'flat';
+	}
+
+	/*
+	-----------------------------------------------------------
+		Display Forum Category and the Forum information
+	-----------------------------------------------------------
+	*/
+	// we are getting all the information about the current forum and forum category.
+	// note pcool: I tried to use only one sql statement (and function) for this
+	// but the problem is that the visibility of the forum AND forum cateogory are stored in the item_property table
+	echo "<table class=\"data_table\" width=\"100%\">\n";
+
 	// the thread
 	echo "\t<tr>\n\t\t<th style=\"padding-left:5px;\" align=\"left\" colspan=\"6\">";
-	echo '<span class="forum_title">'.prepare4display($current_thread['thread_title']).'</span><br />';
+	echo '<span class="forum_title">'.prepare4display($current_thread['thread_title']).'</span><br />';
 
 	if ($origin!='learnpath') {
 		echo '<span class="forum_low_description">'.prepare4display($current_forum_category['cat_title']).' - ';
-	}
+	}
 
 	echo prepare4display($current_forum['forum_title']).'<br />';
-	echo "</th>\n";
+	echo "</th>\n";
 	echo "\t</tr>\n";
 	echo '<span>'.prepare4display($current_thread['thread_comment']).'</span>';
-	echo "</table>";
-
-	include_once('viewpost.inc.php');
-} // if ($message<>'PostDeletedSpecial') // in this case the first and only post of the thread is removed
-
-
-$userinf=api_get_user_info(api_get_user_id());
-if ($allowed_to_edit) {
-	//echo "<strong>".get_lang('QualifyThread')."</strong>";
-	//echo "<br />";
-	$current_thread=get_thread_information($_GET['thread']);
-	$userid=(int)$_GET['user_id'];
-	$threadid=$current_thread['thread_id'];
-	//show current qualify in my form
-	$qualify=current_qualify_of_thread($threadid,api_get_session_id());
-	//show max qualify in my form
-	$max_qualify=show_qualify('2',$_GET['cidReq'],$_GET['forum'],$userid,$threadid);
-	require_once 'forumbody.inc.php';
-	$value_return = store_theme_qualify($userid,$threadid,$_REQUEST['idtextqualify'],api_get_user_id(),date("Y-m-d H:i:s"),api_get_session_id());
-	$url='cidReq='.Security::remove_XSS($_GET['cidReq']).'&forum='.Security::remove_XSS($_GET['forum']).'&thread='.Security::remove_XSS($_GET['thread']).'&post='.Security::remove_XSS($_GET['post']).'&origin='.$origin.'&user_id='.Security::remove_XSS($_GET['user_id']);
-	$current_qualify_thread=show_qualify('1',$_GET['cidReq'],$_GET['forum'],$userid,$threadid);
+	echo "</table>";
+
+	include_once('viewpost.inc.php');
+} // if ($message<>'PostDeletedSpecial') // in this case the first and only post of the thread is removed
+
+
+$userinf=api_get_user_info(api_get_user_id());
+if ($allowed_to_edit) {
+	//echo "<strong>".get_lang('QualifyThread')."</strong>";
+	//echo "<br />";
+	$current_thread=get_thread_information($_GET['thread']);
+	$userid=(int)$_GET['user_id'];
+	$threadid=$current_thread['thread_id'];
+	//show current qualify in my form
+	$qualify=current_qualify_of_thread($threadid,api_get_session_id());
+	//show max qualify in my form
+	$max_qualify=show_qualify('2',$_GET['cidReq'],$_GET['forum'],$userid,$threadid);
+	require_once 'forumbody.inc.php';
+	$value_return = store_theme_qualify($userid,$threadid,$_REQUEST['idtextqualify'],api_get_user_id(),date("Y-m-d H:i:s"),api_get_session_id());
+	$url='cidReq='.Security::remove_XSS($_GET['cidReq']).'&forum='.Security::remove_XSS($_GET['forum']).'&thread='.Security::remove_XSS($_GET['thread']).'&post='.Security::remove_XSS($_GET['post']).'&origin='.$origin.'&user_id='.Security::remove_XSS($_GET['user_id']);
+	$current_qualify_thread=show_qualify('1',$_GET['cidReq'],$_GET['forum'],$userid,$threadid);
 
 	if ($value_return[0]!=$_REQUEST['idtextqualify'] && $value_return[1]=='update') {
-		store_qualify_historical('1','',$_GET['forum'],$userid,$threadid,$_REQUEST['idtextqualify'],api_get_user_id());
-	}
+		store_qualify_historical('1','',$_GET['forum'],$userid,$threadid,$_REQUEST['idtextqualify'],api_get_user_id());
+	}
 
 	if (!empty($_REQUEST['idtextqualify']) && $_REQUEST['idtextqualify'] > $max_qualify) {
 		$return_message = get_lang('QualificationCanNotBeGreaterThanMaxScore');
-		Display :: display_error_message($return_message,false);
-	}
-	// show qualifications history
-	$user_id_thread = (int)$_GET['user_id'];
-	$opt=Database::escape_string($_GET['type']);
-	$qualify_historic = get_historical_qualify($user_id_thread, $threadid, $opt);
-	$counter= count($qualify_historic);
+		Display :: display_error_message($return_message,false);
+	}
+	// show qualifications history
+	$user_id_thread = (int)$_GET['user_id'];
+	$opt=Database::escape_string($_GET['type']);
+	$qualify_historic = get_historical_qualify($user_id_thread, $threadid, $opt);
+	$counter= count($qualify_historic);
 	$act_qualify = $_REQUEST['idtextqualify'];
-	if ($counter>0) {
-		if (isset($_GET['gradebook'])){
-			$view_gradebook='&gradebook=view';
-		}
+	if ($counter>0) {
+		if (isset($_GET['gradebook'])){
+			$view_gradebook='&gradebook=view';
+		}
 		echo '<h4>'.get_lang('QualificationChangesHistory').'</h4>';
-		if ($_GET['type'] == 'false') {
-
-			echo '<div style="float:left; clear:left">'.get_lang('OrderBy').'&nbsp;:<a href="forumqualify.php?'.api_get_cidreq().'&forum='.Security::remove_XSS($_GET['forum']).'&origin='.$origin.'&thread='.$threadid.'&user='.Security::remove_XSS($_GET['user']).'&user_id='.Security::remove_XSS($_GET['user_id']).'&type=true&idtextqualify='.$act_qualify.$view_gradebook.'#history">'.get_lang('MoreRecent').'</a>&nbsp;|
-					'.get_lang('Older').'
-				  </div>';
-		} else {
-			echo '<div style="float:left; clear:left">'.get_lang('OrderBy').'&nbsp;:'.get_lang('MoreRecent').' |
-					<a href="forumqualify.php?'.api_get_cidreq().'&forum='.Security::remove_XSS($_GET['forum']).'&origin='.$origin.'&thread='.$threadid.'&user='.Security::remove_XSS($_GET['user']).'&user_id='.Security::remove_XSS($_GET['user_id']).'&type=false&idtextqualify='.$act_qualify.$view_gradebook.'#history">'.get_lang('Older').'</a>&nbsp;
-				  </div>';
+		if ($_GET['type'] == 'false') {
+
+			echo '<div style="float:left; clear:left">'.get_lang('OrderBy').'&nbsp;:<a href="forumqualify.php?'.api_get_cidreq().'&forum='.Security::remove_XSS($_GET['forum']).'&origin='.$origin.'&thread='.$threadid.'&user='.Security::remove_XSS($_GET['user']).'&user_id='.Security::remove_XSS($_GET['user_id']).'&type=true&idtextqualify='.$act_qualify.$view_gradebook.'#history">'.get_lang('MoreRecent').'</a>&nbsp;|
+					'.get_lang('Older').'
+				  </div>';
+		} else {
+			echo '<div style="float:left; clear:left">'.get_lang('OrderBy').'&nbsp;:'.get_lang('MoreRecent').' |
+					<a href="forumqualify.php?'.api_get_cidreq().'&forum='.Security::remove_XSS($_GET['forum']).'&origin='.$origin.'&thread='.$threadid.'&user='.Security::remove_XSS($_GET['user']).'&user_id='.Security::remove_XSS($_GET['user_id']).'&type=false&idtextqualify='.$act_qualify.$view_gradebook.'#history">'.get_lang('Older').'</a>&nbsp;
+				  </div>';
 		}
 		$table_list.= '<a name="history" /><br /><br /><table class="data_table" style="width:100%">';
-		$table_list.= '<tr>';
-		$table_list.= '<th width="50%">'.get_lang('WhoChanged').'</th>';
+		$table_list.= '<tr>';
+		$table_list.= '<th width="50%">'.get_lang('WhoChanged').'</th>';
 		$table_list.= '<th width="10%">'.get_lang('NoteChanged').'</th>';
 		$table_list.= '<th width="40%">'.get_lang('DateChanged').'</th>';
-		$table_list.= '</tr>';
+		$table_list.= '</tr>';
 
-		for($i=0;$i<count($qualify_historic);$i++) {
-			    $my_user_info=api_get_user_info($qualify_historic[$i]['qualify_user_id']);
+		for($i=0;$i<count($qualify_historic);$i++) {
+			    $my_user_info=api_get_user_info($qualify_historic[$i]['qualify_user_id']);
 				$name = api_get_person_name($my_user_info['firstName'], $my_user_info['lastName']);
 				$table_list.= '<tr class="'.$class.'"><td>'.$name.'</td>';
-				$table_list.= '<td>'.$qualify_historic[$i]['qualify'].'</td>';
+				$table_list.= '<td>'.$qualify_historic[$i]['qualify'].'</td>';
 				$table_list.= '<td>'.$qualify_historic[$i]['qualify_time'].'</td></tr>';
 		}
-		$table_list.= '</table>';
-		echo $table_list;
+		$table_list.= '</table>';
+		echo $table_list;
 
-	} else {
-		echo get_lang('NotChanged');
+	} else {
+		echo get_lang('NotChanged');
 	}
-} else {
+} else {
 	api_not_allowed();
-}
-
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-if ($origin!='learnpath') {
-	Display :: display_footer();
+}
+
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+if ($origin!='learnpath') {
+	Display :: display_footer();
 }

+ 241 - 241
main/forum/newthread.php

@@ -1,245 +1,245 @@
-<?php
-
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2008 Dokeos SPRL
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) various contributors
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
-==============================================================================
-*/
-
-/**
-*	These files are a complete rework of the forum. The database structure is
-*	based on phpBB but all the code is rewritten. A lot of new functionalities
-*	are added:
-* 	- forum categories and forums can be sorted up or down, locked or made invisible
-*	- consistent and integrated forum administration
-* 	- forum options: 	are students allowed to edit their post?
-* 						moderation of posts (approval)
-* 						reply only forums (students cannot create new threads)
-* 						multiple forums per group
-*	- sticky messages
-* 	- new view option: nested view
-* 	- quoting a message
-*
-*	@Author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*	@Copyright Ghent University
-*	@Copyright Patrick Cool
-*
-* 	@package dokeos.forum
-*/
-
-// name of the language file that needs to be included
-$language_file = array('forum','document');
-
-// including the global dokeos file
-require_once '../inc/global.inc.php';
-require_once '../gradebook/lib/gradebook_functions.inc.php';
-// the section (tabs)
-$this_section=SECTION_COURSES;
-
-// notice for unauthorized people.
-api_protect_course_script(true);
-
-// including additional library scripts
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-include_once (api_get_path(LIBRARY_PATH).'groupmanager.lib.php');
-$nameTools=get_lang('Forum');
-
-
-/*
------------------------------------------------------------
-	Including necessary files
------------------------------------------------------------
-*/
-include('forumconfig.inc.php');
-include('forumfunction.inc.php');
-
-//are we in a lp ?
-$origin = '';
-if(isset($_GET['origin'])) {
-	$origin =  Security::remove_XSS($_GET['origin']);
-}
-
-// javascript
-$htmlHeadXtra[] = '<script>
-
-		function advanced_parameters() {
-				if(document.getElementById(\'id_qualify\').style.display == \'none\') {
-				document.getElementById(\'id_qualify\').style.display = \'block\';
-				document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_hide.gif',get_lang('Hide'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
-
-			} else {
-				document.getElementById(\'id_qualify\').style.display = \'none\';
-				document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
-			}
-		}
+<?php
+
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2008 Dokeos SPRL
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) various contributors
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+
+/**
+*	These files are a complete rework of the forum. The database structure is
+*	based on phpBB but all the code is rewritten. A lot of new functionalities
+*	are added:
+* 	- forum categories and forums can be sorted up or down, locked or made invisible
+*	- consistent and integrated forum administration
+* 	- forum options: 	are students allowed to edit their post?
+* 						moderation of posts (approval)
+* 						reply only forums (students cannot create new threads)
+* 						multiple forums per group
+*	- sticky messages
+* 	- new view option: nested view
+* 	- quoting a message
+*
+*	@Author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*	@Copyright Ghent University
+*	@Copyright Patrick Cool
+*
+* 	@package dokeos.forum
+*/
+
+// name of the language file that needs to be included
+$language_file = array('forum','document');
+
+// including the global dokeos file
+require_once '../inc/global.inc.php';
+require_once '../gradebook/lib/gradebook_functions.inc.php';
+// the section (tabs)
+$this_section=SECTION_COURSES;
+
+// notice for unauthorized people.
+api_protect_course_script(true);
+
+// including additional library scripts
+require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+include_once (api_get_path(LIBRARY_PATH).'groupmanager.lib.php');
+$nameTools=get_lang('Forum');
+
+
+/*
+-----------------------------------------------------------
+	Including necessary files
+-----------------------------------------------------------
+*/
+include('forumconfig.inc.php');
+include('forumfunction.inc.php');
+
+//are we in a lp ?
+$origin = '';
+if(isset($_GET['origin'])) {
+	$origin =  Security::remove_XSS($_GET['origin']);
+}
+
+// javascript
+$htmlHeadXtra[] = '<script>
+
+		function advanced_parameters() {
+				if(document.getElementById(\'id_qualify\').style.display == \'none\') {
+				document.getElementById(\'id_qualify\').style.display = \'block\';
+				document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_hide.gif',get_lang('Hide'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
+
+			} else {
+				document.getElementById(\'id_qualify\').style.display = \'none\';
+				document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
+			}
+		}
 </script>';
-/*
-==============================================================================
-		MAIN DISPLAY SECTION
-==============================================================================
-*/
-/*
------------------------------------------------------------
-	Retrieving forum and forum categorie information
------------------------------------------------------------
-*/
-$current_forum=get_forum_information($_GET['forum']); // note: this has to be validated that it is an existing forum.
-$current_forum_category=get_forumcategory_information($current_forum['forum_category']);
-
-/*
------------------------------------------------------------
-	Breadcrumbs
------------------------------------------------------------
-*/
-
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+/*
+==============================================================================
+		MAIN DISPLAY SECTION
+==============================================================================
+*/
+/*
+-----------------------------------------------------------
+	Retrieving forum and forum categorie information
+-----------------------------------------------------------
+*/
+$current_forum=get_forum_information($_GET['forum']); // note: this has to be validated that it is an existing forum.
+$current_forum_category=get_forumcategory_information($current_forum['forum_category']);
+
+/*
+-----------------------------------------------------------
+	Breadcrumbs
+-----------------------------------------------------------
+*/
+
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-
-if (!empty($_GET['gidReq'])) {
-	$toolgroup = Database::escape_string($_GET['gidReq']);
-	api_session_register('toolgroup');
-}
-
-if (!empty($_SESSION['toolgroup'])) {
-
-	$_clean['toolgroup']=(int)$_SESSION['toolgroup'];
-	$group_properties  = GroupManager :: get_group_properties($_clean['toolgroup']);
-	$interbreadcrumb[] = array ("url" => "../group/group.php", "name" => get_lang('Groups'));
-	$interbreadcrumb[] = array ("url"=>"../group/group_space.php?gidReq=".$_SESSION['toolgroup'], "name"=> get_lang('GroupSpace').' ('.$group_properties['name'].')');
-	$interbreadcrumb[]=array("url" => "viewforum.php?origin=".$origin."&amp;gidReq=".$_SESSION['toolgroup']."&forum=".Security::remove_XSS($_GET['forum']),"name" => $current_forum['forum_title']);
-	$interbreadcrumb[]=array("url" => "newthread.php?origin=".$origin."&forum=".Security::remove_XSS($_GET['forum']),"name" => get_lang('NewTopic'));
-} else {
-	$interbreadcrumb[]=array("url" => "index.php?gradebook=$gradebook","name" => $nameTools);
-	$interbreadcrumb[]=array("url" => "viewforumcategory.php?forumcategory=".$current_forum_category['cat_id'],"name" => $current_forum_category['cat_title']);
-	$interbreadcrumb[]=array("url" => "viewforum.php?origin=".$origin."&forum=".Security::remove_XSS($_GET['forum']),"name" => $current_forum['forum_title']);
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
+
+if (!empty($_GET['gidReq'])) {
+	$toolgroup = Database::escape_string($_GET['gidReq']);
+	api_session_register('toolgroup');
+}
+
+if (!empty($_SESSION['toolgroup'])) {
+
+	$_clean['toolgroup']=(int)$_SESSION['toolgroup'];
+	$group_properties  = GroupManager :: get_group_properties($_clean['toolgroup']);
+	$interbreadcrumb[] = array ("url" => "../group/group.php", "name" => get_lang('Groups'));
+	$interbreadcrumb[] = array ("url"=>"../group/group_space.php?gidReq=".$_SESSION['toolgroup'], "name"=> get_lang('GroupSpace').' ('.$group_properties['name'].')');
+	$interbreadcrumb[]=array("url" => "viewforum.php?origin=".$origin."&amp;gidReq=".$_SESSION['toolgroup']."&forum=".Security::remove_XSS($_GET['forum']),"name" => $current_forum['forum_title']);
 	$interbreadcrumb[]=array("url" => "newthread.php?origin=".$origin."&forum=".Security::remove_XSS($_GET['forum']),"name" => get_lang('NewTopic'));
-}
-/*
------------------------------------------------------------
-	Resource Linker
------------------------------------------------------------
-*/
-if (isset($_POST['add_resources']) AND $_POST['add_resources']==get_lang('Resources')) {
-	$_SESSION['formelements']=$_POST;
-	$_SESSION['origin']=$_SERVER['REQUEST_URI'];
-	$_SESSION['breadcrumbs']=$interbreadcrumb;
-	header("Location: ../resourcelinker/resourcelinker.php");
-}
-
-/*
------------------------------------------------------------
-	Header
------------------------------------------------------------
-*/
-if($origin=='learnpath') {
-	include(api_get_path(INCLUDE_PATH).'reduced_header.inc.php');
-} else {
-	Display :: display_header(null);
-	//api_display_tool_title($nameTools);
-}
-/*
------------------------------------------------------------
-	Is the user allowed here?
------------------------------------------------------------
-*/
-// the user is not allowed here if:
-// 1. the forumcategory or forum is invisible (visibility==0) and the user is not a course manager
-// 2. the forumcategory or forum is locked (locked <>0) and the user is not a course manager
-// 3. new threads are not allowed and the user is not a course manager
-// 4. anonymous posts are not allowed and the user is not logged in
-// I have split this is several pieces for clarity.
-
-if (!api_is_allowed_to_edit(false,true) && (($current_forum_category['visibility']==0 || $current_forum['visibility']==0))) {
-	forum_not_allowed_here();
-}
-// 2. the forumcategory or forum is locked (locked <>0) and the user is not a course manager
-if (!api_is_allowed_to_edit(false,true) AND ($current_forum_category['locked']<>0 OR $current_forum['locked']<>0)) {
-	forum_not_allowed_here();
-}
-// 3. new threads are not allowed and the user is not a course manager
-if (!api_is_allowed_to_edit(false,true) AND $current_forum['allow_new_threads']<>1) {
-	forum_not_allowed_here();
-}
-// 4. anonymous posts are not allowed and the user is not logged in
-if (!$_user['user_id']  AND $current_forum['allow_anonymous']<>1) {
-	forum_not_allowed_here();
-}
-
-/*
------------------------------------------------------------
-	Display forms / Feedback Messages
------------------------------------------------------------
-*/
-handle_forum_and_forumcategories();
-// action links
-echo '<div class="actions">';
-echo '<span style="float:right;">'.search_link().'</span>';
-echo '<a href="index.php?gradebook='.$gradebook.'">'.Display::return_icon('back.png',get_lang('BackToForumOverview')).' '.get_lang('BackToForumOverview').'</a>';
-echo '<a href="viewforum.php?forum='.Security::remove_XSS($_GET['forum']).'">'.Display::return_icon('forum.gif',get_lang('BackToForum')).' '.get_lang('BackToForum').'</a>';
-echo '</div>';
-
-/*
------------------------------------------------------------
-	Display Forum Category and the Forum information
------------------------------------------------------------
-*/
-echo "<table class=\"data_table\" width='100%'>\n";
-
-if ($origin != 'learnpath') {
-	echo "\t<tr>\n\t\t<th align=\"left\"  colspan=\"2\">";
-
-	echo '<span class="forum_title">'.prepare4display($current_forum['forum_title']).'</span>';
-
-	if (!empty ($current_forum['forum_comment'])) {
-		echo '<br><span class="forum_description">'.prepare4display($current_forum['forum_comment']).'</span>';
-	}
-
-	if (!empty ($current_forum_category['cat_title'])) {
-		echo '<br /><span class="forum_low_description">'.prepare4display($current_forum_category['cat_title'])."</span><br />";
-	}
-	echo "</th>\n";
-	echo "\t</tr>\n";
-}
-echo '</table>';
-
-$values=show_add_post_form('newthread','', isset($_SESSION['formelements'])?$_SESSION['formelements']:null);
-
-if (!empty($values) and isset($values['SubmitPost'])) {
-	//add new thread in table forum_thread
-	store_thread($values);
-}
-
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-if ($origin!='learnpath') {
-	Display :: display_footer();
+} else {
+	$interbreadcrumb[]=array("url" => "index.php?gradebook=$gradebook","name" => $nameTools);
+	$interbreadcrumb[]=array("url" => "viewforumcategory.php?forumcategory=".$current_forum_category['cat_id'],"name" => $current_forum_category['cat_title']);
+	$interbreadcrumb[]=array("url" => "viewforum.php?origin=".$origin."&forum=".Security::remove_XSS($_GET['forum']),"name" => $current_forum['forum_title']);
+	$interbreadcrumb[]=array("url" => "newthread.php?origin=".$origin."&forum=".Security::remove_XSS($_GET['forum']),"name" => get_lang('NewTopic'));
+}
+/*
+-----------------------------------------------------------
+	Resource Linker
+-----------------------------------------------------------
+*/
+if (isset($_POST['add_resources']) AND $_POST['add_resources']==get_lang('Resources')) {
+	$_SESSION['formelements']=$_POST;
+	$_SESSION['origin']=$_SERVER['REQUEST_URI'];
+	$_SESSION['breadcrumbs']=$interbreadcrumb;
+	header("Location: ../resourcelinker/resourcelinker.php");
+}
+
+/*
+-----------------------------------------------------------
+	Header
+-----------------------------------------------------------
+*/
+if($origin=='learnpath') {
+	include(api_get_path(INCLUDE_PATH).'reduced_header.inc.php');
+} else {
+	Display :: display_header(null);
+	//api_display_tool_title($nameTools);
+}
+/*
+-----------------------------------------------------------
+	Is the user allowed here?
+-----------------------------------------------------------
+*/
+// the user is not allowed here if:
+// 1. the forumcategory or forum is invisible (visibility==0) and the user is not a course manager
+// 2. the forumcategory or forum is locked (locked <>0) and the user is not a course manager
+// 3. new threads are not allowed and the user is not a course manager
+// 4. anonymous posts are not allowed and the user is not logged in
+// I have split this is several pieces for clarity.
+
+if (!api_is_allowed_to_edit(false,true) && (($current_forum_category['visibility']==0 || $current_forum['visibility']==0))) {
+	forum_not_allowed_here();
+}
+// 2. the forumcategory or forum is locked (locked <>0) and the user is not a course manager
+if (!api_is_allowed_to_edit(false,true) AND ($current_forum_category['locked']<>0 OR $current_forum['locked']<>0)) {
+	forum_not_allowed_here();
+}
+// 3. new threads are not allowed and the user is not a course manager
+if (!api_is_allowed_to_edit(false,true) AND $current_forum['allow_new_threads']<>1) {
+	forum_not_allowed_here();
+}
+// 4. anonymous posts are not allowed and the user is not logged in
+if (!$_user['user_id']  AND $current_forum['allow_anonymous']<>1) {
+	forum_not_allowed_here();
+}
+
+/*
+-----------------------------------------------------------
+	Display forms / Feedback Messages
+-----------------------------------------------------------
+*/
+handle_forum_and_forumcategories();
+// action links
+echo '<div class="actions">';
+echo '<span style="float:right;">'.search_link().'</span>';
+echo '<a href="index.php?gradebook='.$gradebook.'">'.Display::return_icon('back.png',get_lang('BackToForumOverview')).' '.get_lang('BackToForumOverview').'</a>';
+echo '<a href="viewforum.php?forum='.Security::remove_XSS($_GET['forum']).'">'.Display::return_icon('forum.gif',get_lang('BackToForum')).' '.get_lang('BackToForum').'</a>';
+echo '</div>';
+
+/*
+-----------------------------------------------------------
+	Display Forum Category and the Forum information
+-----------------------------------------------------------
+*/
+echo "<table class=\"data_table\" width='100%'>\n";
+
+if ($origin != 'learnpath') {
+	echo "\t<tr>\n\t\t<th align=\"left\"  colspan=\"2\">";
+
+	echo '<span class="forum_title">'.prepare4display($current_forum['forum_title']).'</span>';
+
+	if (!empty ($current_forum['forum_comment'])) {
+		echo '<br><span class="forum_description">'.prepare4display($current_forum['forum_comment']).'</span>';
+	}
+
+	if (!empty ($current_forum_category['cat_title'])) {
+		echo '<br /><span class="forum_low_description">'.prepare4display($current_forum_category['cat_title'])."</span><br />";
+	}
+	echo "</th>\n";
+	echo "\t</tr>\n";
+}
+echo '</table>';
+
+$values=show_add_post_form('newthread','', isset($_SESSION['formelements'])?$_SESSION['formelements']:null);
+
+if (!empty($values) and isset($values['SubmitPost'])) {
+	//add new thread in table forum_thread
+	store_thread($values);
+}
+
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+if ($origin!='learnpath') {
+	Display :: display_footer();
 }

Algunos archivos no se mostraron porque demasiados archivos cambiaron en este cambio