Browse Source

merged from Patrick

Yannick Warnier 15 years ago
parent
commit
2e123b2c4b
100 changed files with 18574 additions and 16344 deletions
  1. 7 1
      archive/.htaccess
  2. 91 61
      documentation/changelog.html
  3. 26 32
      documentation/credits.html
  4. 78 76
      documentation/default.css
  5. 6 6
      documentation/dependencies.html
  6. 3 3
      documentation/index.html
  7. 2 2
      documentation/install_red5.txt
  8. 688 688
      documentation/installation_guide.html
  9. 763 763
      documentation/installation_guide_es_ES.html
  10. 317 317
      documentation/license.html
  11. 340 340
      documentation/license.txt
  12. 18 18
      documentation/readme.html
  13. 0 0
      home/home_tabs.html
  14. 0 0
      home/register_top.html
  15. 241 236
      index.php
  16. 7 7
      main/WCAG/index.html
  17. 199 199
      main/admin/access_url_add_courses_to_url.php
  18. 201 201
      main/admin/access_url_add_sessions_to_url.php
  19. 201 200
      main/admin/access_url_add_users_to_url.php
  20. 145 145
      main/admin/access_url_edit.php
  21. 473 473
      main/admin/access_url_edit_courses_to_url.php
  22. 469 469
      main/admin/access_url_edit_sessions_to_url.php
  23. 469 467
      main/admin/access_url_edit_users_to_url.php
  24. 208 208
      main/admin/access_urls.php
  25. 0 27
      main/admin/add_by_ajax_sub_language.inc.php
  26. 538 538
      main/admin/add_courses_to_session.php
  27. 320 0
      main/admin/add_many_session_to_category.php
  28. 145 141
      main/admin/add_users_to_session.php
  29. 3116 3116
      main/admin/calendar.lib.php
  30. 409 409
      main/admin/calendar.php
  31. 10 10
      main/admin/calendar_ical_export.php
  32. 1 1
      main/admin/calendar_tbl_change.js
  33. 8 8
      main/admin/calendar_view.php
  34. 2 2
      main/admin/calendar_view_print.php
  35. 18 23
      main/admin/class_add.php
  36. 18 24
      main/admin/class_edit.php
  37. 48 59
      main/admin/class_import.php
  38. 57 60
      main/admin/class_information.php
  39. 49 54
      main/admin/class_list.php
  40. 212 216
      main/admin/class_user_import.php
  41. 559 559
      main/admin/configure_extensions.php
  42. 93 57
      main/admin/configure_homepage.php
  43. 519 0
      main/admin/configure_inscription.php
  44. 25 43
      main/admin/course_add.php
  45. 51 51
      main/admin/course_category.php
  46. 13 13
      main/admin/course_create_content.php
  47. 53 49
      main/admin/course_edit.php
  48. 229 249
      main/admin/course_import.php
  49. 36 19
      main/admin/course_information.php
  50. 30 31
      main/admin/course_list.php
  51. 242 263
      main/admin/course_user_import.php
  52. 1 1
      main/admin/course_user_list.php
  53. 71 71
      main/admin/course_virtual.php
  54. 1 1
      main/admin/example_session.xml
  55. 1 1
      main/admin/exemple.xml
  56. 31 27
      main/admin/index.php
  57. 57 57
      main/admin/languages.php
  58. 17 5
      main/admin/ldap_form_add_users_group.php
  59. 12 12
      main/admin/ldap_import_students.php
  60. 10 10
      main/admin/ldap_import_students_to_session.php
  61. 17 17
      main/admin/ldap_synchro.php
  62. 27 11
      main/admin/ldap_users_list.php
  63. 1 1
      main/admin/ldap_users_synchro.php
  64. 41 41
      main/admin/legal_add.php
  65. 6 6
      main/admin/legal_list.php
  66. 0 297
      main/admin/register_sub_language.php
  67. 90 38
      main/admin/resume_session.php
  68. 102 80
      main/admin/session_add.php
  69. 241 0
      main/admin/session_category_add.php
  70. 238 0
      main/admin/session_category_edit.php
  71. 232 0
      main/admin/session_category_list.php
  72. 51 22
      main/admin/session_course_edit.php
  73. 101 111
      main/admin/session_course_list.php
  74. 310 0
      main/admin/session_course_user.php
  75. 171 200
      main/admin/session_course_user_list.php
  76. 362 340
      main/admin/session_edit.php
  77. 332 332
      main/admin/session_export.php
  78. 912 898
      main/admin/session_import.php
  79. 332 324
      main/admin/session_list.php
  80. 295 253
      main/admin/settings.php
  81. 286 0
      main/admin/special_exports.php
  82. 3 3
      main/admin/statistics.php
  83. 143 143
      main/admin/statistics/index.php
  84. 458 440
      main/admin/statistics/statistics.lib.php
  85. 164 164
      main/admin/style_preview.php
  86. 53 46
      main/admin/sub_language.class.php
  87. 291 0
      main/admin/sub_language.php
  88. 44 49
      main/admin/sub_language_add.php
  89. 30 0
      main/admin/sub_language_ajax.inc.php
  90. 11 11
      main/admin/subscribe_class2course.php
  91. 21 17
      main/admin/subscribe_user2class.php
  92. 85 83
      main/admin/subscribe_user2course.php
  93. 6 6
      main/admin/system_announcements.php
  94. 219 297
      main/admin/user_add.php
  95. 206 284
      main/admin/user_edit.php
  96. 32 32
      main/admin/user_export.php
  97. 417 417
      main/admin/user_fields.php
  98. 35 35
      main/admin/user_fields_add.php
  99. 32 32
      main/admin/user_fields_options.php
  100. 223 195
      main/admin/user_import.php

+ 7 - 1
archive/.htaccess

@@ -1,2 +1,8 @@
 order deny,allow
-deny from all
+deny from all
+
+# pChart generated files should be allowed
+<FilesMatch "^[0-9a-f]+$">
+	order allow,deny
+	allow from all
+</FilesMatch>

+ 91 - 61
documentation/changelog.html

@@ -1,7 +1,7 @@
 <!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 Changelog</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">
@@ -16,44 +16,74 @@
 <div id="header1">
 <h1>Dokeos&nbsp;Changelog</h1>
 </div>
-<a href="index.html">Documentation</a> &gt; Changelog 
+<a href="index.html">Documentation</a> &gt; Changelog
 <div id="outerframe">
 <div id="main">
+<h1>Dokeos 1.8.6.2 - .............</h1>
+<h3>Release notes - summary</h3>
+<p>....</p>
+<h3>New Features</h3>
+<ul>
+  <li>...</li>
+</li>
+</ul>
+<h3>Debugging</h3>
+<ul>
+  <li>Online editor: A upgrade from FCKEditor 2.6.4.1 to <strong>FCKEditor 2.6.5, Build 23959</strong> has been implemented. (#2867)</li>
+  <li>...</li>
+</ul>
+<br />
+<h3>CSS changes</h3>
+<ul>
+  <li>...</li>
+</ul>
+<h3>Known issues</h3>
+<ul>
+  <li>...</li>
+</ul>
+<h3>Deprecated files</h3>
+<ul>
+  <li>...</li>
+</ul>
 <br />
-<h1>Dokeos 1.8.6.1 <span style="font-style: italic;">(Babel?)</span> - August 2009</h1>
+<h1>Dokeos 1.8.6.1 - August 2009</h1>
 <h3>Release notes - summary</h3>
-<p>Dokeos 1.8.6.1 is a minor&nbsp;release including just a few new features, mostly focused on internationalization.&nbsp;</p>
+<p>Dokeos 1.8.6.1 is a minor&nbsp;release including just a few new features, mostly focused on internationalization, and several bugfixes.</p>
 <h3>New Features</h3>
 <ul>
+  <li>Implemented new sub-language feature by which language terms redefinition becomes possible through the admin section (FS#4321)</li>
+  <li>Admin: Terms and conditions added DT#4320</li>
   <li>Improvements in document tool, allow seeing glossary terms (FS#4337)</li>
-  <li>Improvements in SCORM export(FS#4300)</li>
-  <li>At the beginning of the installation script an imperative check for PHP 5 has been added. (FS#4296)</li>
+  <li>Small improvements in SCORM export(FS#4300)</li>
+  <li>At the beginning of the installation script, added an imperative check for PHP 5 has been added. (FS#4296)</li>
   <li>When the system Dokeos is switched into "Test server" mode, a clickable indicator appears in the footer. This indicator is visible by platform administrators only. (FS#4341)</li>
   <li>A transliteration function has been added. Currently, it is used in uploading files. Files with non-English names get names that contain ASCII letters only, remaining readable in the corresponding language. Rationale: The PHP5 run-time environment does not manage file name encodings, adding such a non-native feature involves too much work. For avoiding character encoding problems, transliteration of file names is the possible solution. (FS#306)</li>
   <li>An internationalization option has been added for improving sorting in arbitrary language. When the <a href="http://php.net/manual/en/book.intl.php" target="_blank">intl</a> php-extension has been installed, various sorting routines exploit it for better sorting. Rationale: The PHP5 run-time environment does not provide native and reliable way of sorting UTF-8 strings. (FS#306)</li>
-  <li>The installation sript: The page about system requilements has been updated. Also, at the very beginning, a check has been added whether the <a href="http://php.net/manual/en/book.mbstring.php" target="_blank">mbstring</a> php-extension is installed - see <a href="http://dokeos.com/forum/viewtopic.php?t=29548" target="_blank">the related forum topic</a>. (FS#306)</li>
+  <li>Installation script: The page about system requilements has been updated. Also, at the very beginning, a check has been added whether the <a href="http://php.net/manual/en/book.mbstring.php" target="_blank">mbstring</a> php-extension is installed - see <a href="http://dokeos.com/forum/viewtopic.php?t=29548" target="_blank">the related forum topic</a>. (FS#306)</li>
   <li>A new php-based configuration for the online editor has been implemented, see <i>dokeos/main/inc/lib/fckeditor/myconfig.php</i>. Also, toolbar definitions have been split in separate php-files within the directory <i>dokeos/main/inc/lib/fckeditor/toolbars/</i> . Customization of the editor is more convenient and flexible now. (FS#2867)</li>
-  <li>Online editor: A upgrade from FCKEditor 2.6.4 to <b>FCKEditor 2.6.4.1</b> has been implemented. (FS#4383)</li>
-  <li>Online editor: Several known bug-fixes from FCKEditor 2.6.5 SVN have been implemented, tickets <a href="http://dev.fckeditor.net/ticket/1537" target="_blank">#1537</a>, <a href="http://dev.fckeditor.net/ticket/2156" target="_blank">#2156</a>, <a href="http://dev.fckeditor.net/ticket/2689" target="_blank">#2689</a>, <a href="http://dev.fckeditor.net/ticket/2821" target="_blank">#2821</a>, <a href="http://dev.fckeditor.net/ticket/2856" target="_blank">#2856</a>, <a href="http://dev.fckeditor.net/ticket/2874" target="_blank">#2874</a>, <a href="http://dev.fckeditor.net/ticket/2915" target="_blank">#2915</a>, <a href="http://dev.fckeditor.net/ticket/3120" target="_blank">#3120</a>, <a href="http://dev.fckeditor.net/ticket/3181" target="_blank">#3181</a>, <a href="http://dev.fckeditor.net/ticket/3427" target="_blank">#3427</a>, <a href="http://dev.fckeditor.net/ticket/3429" target="_blank">#3429</a>, <a href="http://dev.fckeditor.net/ticket/3439" target="_blank">#3439</a>, <a href="http://dev.fckeditor.net/ticket/3446" target="_blank">#3446</a>, <a href="http://dev.fckeditor.net/ticket/3481" target="_blank">#3481</a>, <a href="http://dev.fckeditor.net/ticket/3677" target="_blank">#3677</a>, <a href="http://dev.fckeditor.net/ticket/3818" target="_blank">#3818</a>, <a href="http://dev.fckeditor.net/ticket/3880" target="_blank">#3880</a>, <a href="http://dev.fckeditor.net/ticket/3925" target="_blank">#3925</a>. (FS#2867)</li>
-  <li>Online editor: The simple file manager, the advanced file manager and the image manager have been integrated by default with the editor's dialog system. Thus, they work faster and in a more secure way. (FS#2867)</li>
+  <li>Online editor: A upgrade from FCKEditor 2.6.4 to <strong>FCKEditor 2.6.4.1</strong> has been implemented. (FS#4383)</li>
   <li>Online editor: Blocking copy/paste for trainees has been added. The feature is configurable through editing the toolbar definition files within the directory <i>dokeos/main/inc/lib/fckeditor/toolbars/</i> . (FS#2867)</li>
   <li>Online editor: Preview tabs have been added to the dialogs for inserting video, flv-video, and YouTube video. (FS#2867)</li>
-  <li>Online editor: The <b>audio</b> plugin has been activated by default as an implementation of the "Insert audio / Audio properties" dialog. This new plugin is intended to replace the "MP3" plugin. (FS#2867)</li>
-  <li>Online editor: Configuration of the <b>mimetex</b> plugin has been reworked to gain simplicity. The procedure for configuration has been updated, see <a href="http://www.dokeos.com/forum/viewtopic.php?t=29594" target="_blank">the related forum topic</a>. (FS#2867)</li>
-  <li>Online editor: A new <b>asciimath</b> plugin for inserting mathematical formulas has been added. It is based on the <a href="http://mathcs.chapman.edu/~jipsen/mathml/asciimath.html" target="_blank">ASCIIMathML.js</a> library. (FS#2867)</li>
+  <li>Online editor: The <strong>audio</strong> plugin has been activated by default as an implementation of the "Insert audio / Audio properties" dialog. This new plugin is intended to replace the "MP3" plugin. (FS#2867)</li>
+  <li>Online editor: The simple file manager, the advanced file manager and the image manager have been integrated by default with the editor's dialog system. Thus, they work faster and in a more secure way. (FS#2867)</li>
+  <li>Online editor: Configuration of the <strong>mimetex</strong> plugin has been reworked to gain simplicity. The procedure for configuration has been updated, see <a href="http://www.dokeos.com/forum/viewtopic.php?t=29594" target="_blank">the related forum topic</a>. (FS#2867)</li>
+  <li>Online editor: A new <strong>asciimath</strong> plugin for inserting mathematical formulas has been added. It is based on the <a href="http://mathcs.chapman.edu/~jipsen/mathml/asciimath.html" target="_blank">ASCIIMathML.js</a> library. (FS#2867)</li>
+  <li>Social: Added possibility to define RSS feeds inside personal page of social network (need to define an 'rssfeeds' extra user text field)</li>
+</ul>
+<h3>Debugging</h3>
+<ul>
+  <li>Online editor: Several known bug-fixes from FCKEditor 2.6.5 SVN have been implemented, tickets <a href="http://dev.fckeditor.net/ticket/1537" target="_blank">#1537</a>, <a href="http://dev.fckeditor.net/ticket/2156" target="_blank">#2156</a>, <a href="http://dev.fckeditor.net/ticket/2689" target="_blank">#2689</a>, <a href="http://dev.fckeditor.net/ticket/2821" target="_blank">#2821</a>, <a href="http://dev.fckeditor.net/ticket/2856" target="_blank">#2856</a>, <a href="http://dev.fckeditor.net/ticket/2874" target="_blank">#2874</a>, <a href="http://dev.fckeditor.net/ticket/2915" target="_blank">#2915</a>, <a href="http://dev.fckeditor.net/ticket/3120" target="_blank">#3120</a>, <a href="http://dev.fckeditor.net/ticket/3181" target="_blank">#3181</a>, <a href="http://dev.fckeditor.net/ticket/3427" target="_blank">#3427</a>, <a href="http://dev.fckeditor.net/ticket/3429" target="_blank">#3429</a>, <a href="http://dev.fckeditor.net/ticket/3439" target="_blank">#3439</a>, <a href="http://dev.fckeditor.net/ticket/3446" target="_blank">#3446</a>, <a href="http://dev.fckeditor.net/ticket/3481" target="_blank">#3481</a>, <a href="http://dev.fckeditor.net/ticket/3677" target="_blank">#3677</a>, <a href="http://dev.fckeditor.net/ticket/3818" target="_blank">#3818</a>, <a href="http://dev.fckeditor.net/ticket/3880" target="_blank">#3880</a>, <a href="http://dev.fckeditor.net/ticket/3925" target="_blank">#3925</a>. (FS#2867)</li>
   <li>Online editor: The toolbar icons have been upgraded to those from FCKEditor 3.0. (FS#2867)</li>
   <li>A solution has been implemented for fixing the <a href="http://bugs.adobe.com/jira/browse/FP-529" target="_blank">"__flash__removeCallback" bug</a>, which affects the media player on Internet Explorer browser. (FS#4378 and FS#2867)</li>
-  <li>Implement new sub-language feature by which language terms redefinition becomes possible through the admin section (FS#4321)</li>
-  <li>Social: Added possibility to define RSS feeds inside personal page of social network (need to define an 'rssfeeds' extra user text field)</li>
+  <li>Quiz: fixed bug in multiple-choice/single-answer questions results (whereby the wrong answer was saved)</li>
   <li>Admin: Added courses from sessions inside AJAX popup of courses list in users list (SVN#22398)</li>
   <li>Admin: Showing full-length course titles in list of courses while adding to sessions(SVN#22399)</li>
   <li>Admin: Added session name in title of session edition pages(SVN#22400)</li>
-  <li>Admin: Terms and conditions added DT#4320</li>  
 </ul>
 <br />
 <h3>CSS changes</h3>
 <ul>
-  <li>Sticky footer now available in all Dokeos stylesheets. If you own a custom stylesheet you must update it see <a href="https://bts.dokeos.com/issues/show/3549">DT#3549</a> for further details.</li>
+  <li>Sticky footer now available in all Dokeos stylesheets. If you own a custom stylesheet you will need to update it, see <a href="https://bts.dokeos.com/issues/show/3549">DT#3549</a> for further details.</li>
 </ul>
 
 <br />
@@ -61,7 +91,7 @@
 <br />
 <h3>Deprecated files</h3>
 <ul>
-  <li>The whole main/inc/lib/fckeditor/editor/filemanager/browser/default/connectors/ directory should be removed for security reasons</li> 
+  <li>The whole main/inc/lib/fckeditor/editor/filemanager/browser/default/connectors/ directory should be removed for security reasons</li>
 </ul>
 <br />
 <h1>Dokeos 1.8.6 <span style="font-style: italic;">Svalbard</span> - June 2009</h1>
@@ -94,7 +124,7 @@
   <li>Documents tool: The document-type icons have been made clickable (FS#3296)</li>
   <li>Documents tool: Online editor has been disabled for HotPotatoes tests in order their functionality to be preserved (FS#3345)</li>
   <li>Allow ZIP export of assignments for teacher and tutor </li>
-  <li>Added attach documents to Agenda</li> 
+  <li>Added attach documents to Agenda</li>
   <li>Added Web Services Interface (SOAP)</li>
   <li>Added Google Maps support</li>
   <li>Added Imagemap editor</li>
@@ -108,7 +138,7 @@
   <li>Added link create course message to go directly to the course(SVN#17497)</li>
   <li>Added ability to take partial surveys and finish them later (FS#2510)</li>
   <li>New Survey Feature: Surveys without invitation mail (FS#3403)</li>
-  <li>Added Booking system (a.k.a Reservation 2 Extension) (FS#821)</li> 
+  <li>Added Booking system (a.k.a Reservation 2 Extension) (FS#821)</li>
   <li>Added user profiling fields in auto-registration page (FS#2666)</li>
   <li>Added check for writeable status of session save path in installation directory (FS#2970)</li>
   <li>Allow forum threads to be moved (FS#3460)</li>
@@ -123,7 +153,7 @@
   <li>Added Question difficulty level in Exercises (FS#3515)</li>
   <li>Added Removed buggy audio recorder and added new MP3 player with easy upload (FS#3515)</li>
   <li>Improved Survey export (SVN#17927)</li>
-  <li>Students can now view their uploaded works in Work tool (FS#3486)</li>  
+  <li>Students can now view their uploaded works in Work tool (FS#3486)</li>
   <li>Implemented
 add to calendar an assignment with the date when it is completely
 closed, also when you remove it from assignment tool, it's removed into
@@ -138,10 +168,10 @@ calendar_event table, instead this value is 0.</li>
   <li>Added pChart v1.1.2 library to manage charts in Gradebook tool(FS#3718) and the Access details of a user </li>
   <li>Added SHA1 as a possibility to encrypt user passwords (FS#3798)</li>
   <li>Added global templates to use between courses (SVN#18955)</li>
-  <li>Added To change your password, you must enter your current password (SVN#19225)</li>   
+  <li>Added To change your password, you must enter your current password (SVN#19225)</li>
   <li>Added New Dokeos stylesheets </li>
   <li>Improvements to the User profile</li>
-  <li>Improvements to the Learning path display view (no more frames)</li>     
+  <li>Improvements to the Learning path display view (no more frames)</li>
   <li>Added HTML Purifier</li>
   <li>Added tracking/logging of admin activity FS#842</li>
 </ul>
@@ -233,7 +263,7 @@ PCLZIP_OPT_REMOVE_PATH on Windows (FS#3243)</li>
   <li>Fixed various HTTPS + IE related bugs, related to caching in general (SVN#17795)</li>
   <li>Fixed 31 bugs in file/image/sounds/flash uploads/delete/permissions in profile/homepage/agenda edition pages</li>
   <li>Fixed a bug in migration for several versions at once whereby new course tools were repeated several times (SVN#17935)</li>
-  <li>Fixed security issue allowing users to upload php files on the server through FCKEditor (FS#2970)</li> 
+  <li>Fixed security issue allowing users to upload php files on the server through FCKEditor (FS#2970)</li>
   <li>Fixed folders by default into document tool must not be removed - see FS#3611</li>
   <li>Fixed qualification of themes into forum tool - see FS#3609</li>
   <li>allow show results with floating point,in exercice tool - (partial FS#3630) - SVN#18367</li>
@@ -261,7 +291,7 @@ irvienhooi</li>
   <li>Changed many things in the public-admin style (Dokeos default) to improve
 design - will probably affect other styles a little despite efforts not to</li>
   <li>Added new styles</li>
-  
+
 </ul>
 <br />
 <h3>Important language changes</h3>
@@ -274,7 +304,7 @@ if you are willing to keep that change.</li>
   <li>Changed and unified work/assignment/student publications tool as "assignments"</li>
   <li>Changed "Dropbox" tool to "Documents sharing" (or "Documents sharing space" when referring to one's own space in the tool)</li>
   <li>Changed "Student View" link to "Teacher view" and vice-versa</li>
-  <li>Many buttons now have more defined action names</li>   
+  <li>Many buttons now have more defined action names</li>
 </ul>
 <br />
 <h3>Known issues</h3>
@@ -284,7 +314,7 @@ if you are willing to keep that change.</li>
 <br />
 <h3>Deprecated files</h3>
 <ul>
-  <li>The whole main/inc/lib/xajax/tests/ should be removed</li> 
+  <li>The whole main/inc/lib/xajax/tests/ should be removed</li>
 </ul>
 <br />
 <h1>Dokeos 1.8.5 <span style="font-style: italic;">Valparaiso</span>, June 2008</h1>
@@ -406,7 +436,7 @@ quickly after recording a sound track</li>
     <li>When migrating from 1.6 to 1.8, some SCORM learning paths might need to be re-imported, which means their tracking is lost</li>
 </ul>
 <hr style="width: 100%; height: 2px;" />
-	
+
 <h1>Dokeos 1.8.4 - September 2007</h1>
 <h3>Release notes - summary</h3>
 <p>Dokeos
@@ -506,22 +536,22 @@ UTF-8 and russian and asian fonts)</li>
 <h1>Dokeos 1.8 - May 2007</h1>
 
 
-    
+
 <h3>Release notes - summary</h3>
 
 
-    
+
 <p>Dokeos 1.8 is a major release. The software becomes a complete suite
 including not only a learning management system and a learners
 administration dashboard, but also an easy-to-use authoring system and
 a simple videoconferencing interface.</p>
 
 
-    
+
 <h3>New Features</h3>
 
 
-    
+
 <ul>
 
 
@@ -576,37 +606,37 @@ a simple videoconferencing interface.</p>
       <li>Platform Statistics so you can boast with your campus. </li>
 
 
-    
+
 </ul>
 
 
-    
+
 <h1></h1>
 
 <hr style="width: 100%; height: 2px;" />
 <h1>Dokeos 1.6.5 - July 2006 </h1>
 
 
-    
+
 <h3>Release notes - summary</h3>
 
 
-    
+
 <p>Security Release. 1 bug has been fixed. Click the link below to see the complete list of bugfixes<br />
 
 
       <a href="http://www.dokeos.com/wiki/index.php/Dokeos_1.6.5_release_notes_and_changelog">http://www.dokeos.com/wiki/index.php/Dokeos_1.6.5_release_notes_and_changelog</a></p>
 
 
-    
+
 <h1>Dokeos 1.6.4 April 2006 </h1>
 
 
-    
+
 <h3>Release notes - summary</h3>
 
 
-    
+
 <p>Bugfix release. 2 bugs have been fixed. One security hole has been fixed <br />
 
 
@@ -616,60 +646,60 @@ a simple videoconferencing interface.</p>
     <a href="http://www.dokeos.com/wiki/index.php/Dokeos_1.6.4_release_notes_and_changelog">http://www.dokeos.com/wiki/index.php/Dokeos_1.6.4_release_notes_and_changelog</a></p>
 
 
-    
+
 <h1>Dokeos 1.6.3 February 2006 </h1>
 
 
-    
+
 <h3>Release notes - summary</h3>
 
 
-    
+
 <p>Bugfix release. 44 bugs have been fixed. Click the link below to see the complete list of bugfixes<br />
 
 
     <a href="http://www.dokeos.com/wiki/index.php/Dokeos_1.6.3_release_notes_and_changelog">http://www.dokeos.com/wiki/index.php/Dokeos_1.6.3_release_notes_and_changelog</a> </p>
 
 
-    
+
 <h1>Dokeos 1.6.2 - September 2005</h1>
 
 
-    
+
 <h3>Release notes - summary</h3>
 
 
-    
+
 <p>Bugfix release. 14 bugs have been fixed. Click the link below to see the complete list of bugfixes<br />
 
 
     <a href="http://www.dokeos.com/wiki/index.php/Dokeos_1.6.2_release_notes_and_changelog">http://www.dokeos.com/wiki/index.php/Dokeos_1.6.2_release_notes_and_changelog</a></p>
 
 
-    
+
 <h1>Dokeos 1.6.1 - August 2005</h1>
 
 
-    
+
 <h3>Release notes - summary</h3>
 
 
-    
+
 <p>Bugfix release. 31 bugs have been fixed. Click the link below to see the complete list of bugfixes<br />
 
 
     <a href="http://www.dokeos.com/wiki/index.php/Dokeos_1.6.1_release_notes_and_changelog">http://www.dokeos.com/wiki/index.php/Dokeos_1.6.1_release_notes_and_changelog</a></p>
 
 
-    
+
 <h1>Dokeos 1.6 - July 2005</h1>
 
 
-    
+
 <h3>Release notes - summary</h3>
 
 
-    
+
 <p>In Dokeos 1.6, security and interoperability have been improved. Protection<br />
 
 
@@ -685,11 +715,11 @@ a simple videoconferencing interface.</p>
     <a href="http://www.dokeos.com/wiki/index.php/Dokeos_1.6_release_notes">http://www.dokeos.com/wiki/index.php/Dokeos_1.6_release_notes </a></p>
 
 
-    
+
 <h3>New Features</h3>
 
 
-    
+
 <ul>
 
 
@@ -723,7 +753,7 @@ a simple videoconferencing interface.</p>
         configure many options through the web interface instead of by digging through the code. </li>
 
 
-      <li> Improved course management - completely rewritten course import/export 
+      <li> Improved course management - completely rewritten course import/export
         functions, easily copy content from one course to another</li>
 
 
@@ -734,28 +764,28 @@ a simple videoconferencing interface.</p>
 
 
       <li>Interoperability: support for SCORM import/export, XML import/export for
-        some features, IEEE LOM Metadata support in documents and groups, import of 
-        Hotpotatoes, connection with QuestionMark (this last one will be available 
+        some features, IEEE LOM Metadata support in documents and groups, import of
+        Hotpotatoes, connection with QuestionMark (this last one will be available
         as plugin).</li>
 
 
-    
+
 </ul>
 
 
-    
+
 <h3>Roadmap</h3>
 
 
-    
+
 <p><a href="http://www.dokeos.com/wiki/index.php/Roadmap_1.6">http://www.dokeos.com/wiki/index.php/Roadmap_1.6</a></p>
 
 
-    
+
 <h1>Dokeos 1.5.5   </h1>
 
 
-    
+
 <ul>
 
 

+ 26 - 32
documentation/credits.html

@@ -1,7 +1,7 @@
 <!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 Credits</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">
@@ -23,23 +23,22 @@ Thomas De Praetere (thomas.depraetere@dokeos.com)
 
 <h1>Core developers</h1>
 <ol>
-  <li>Dokeos.com  
+  <li>Dokeos.com
   <ul>
-    <li>Olivier Brouckaert (oli.brouckaert@dokeos.com)</li>
-    <li>Yannick Warnier (yannick.warnier@dokeos.com)</li>
-    <li>Eric Marguin (eric.marguin@elixir-interactive.com)</li>
-    <li>Julian Prud'homme (j.prudhomme@elixir-interactive.com)</li>
-    <li>Arnaud Ligot (arnaud.ligot@dokeos.com)</li>
+    <li>Yannick Warnier (ywarnier@beeznest.org)</li>
+    <li>Arnaud Ligot (arnaud@cblue.be)</li>
+    <li>Noel Dieschburg (noel@cblue.be)</li>
+    <li>Frédéric Burlet (fburlet@cblue.be)</li>
+    <li>Toon Keppens (toon@develop-it.be)</li>
+    <li>Luk Van Landuyt (luk@develop-it.be)</li>
     <li>Sebastian Wagner (seba.wagner@gmail.com)</li>
+    <li>Julian Prud'homme (j.prudhomme@elixir-interactive.com)</li>
+    <li>Eric Marguin (eric.marguin@elixir-interactive.com)</li>
     <li>Alexandre Pelissard (a.pellissard@elixir-interactive.com)</li>
-    <li>Denes Nagy (denes.nagy@dokeos.com)</li>
-    <li>Luk Van Landuyt (luk@develop-it.be)</li>
-    <li>Toon Keppens (toon@develop-it.be)</li>
-    <li>Priya Siani (priya@ballisticlearning.com)</li>
     <li>Ravin Minocha (ravin@comprointertech.com)</li>
-	<li>Frédéric Burlet (fburlet@cblue.be)</li>
-	<li>Julio Allen Montoya Armas (gugli100@gmail.com)</li>
-	<li>Noel Dieschburg (noel@cblue.be)</li>
+    <li>Priya Siani (priya@ballisticlearning.com)</li>
+    <li>Denes Nagy (denes.nagy@dokeos.com)</li>
+    <li>Olivier Brouckaert (oli.brouckaert@dokeos.com)</li>
   </ul>
   </li>
 
@@ -54,24 +53,23 @@ Thomas De Praetere (thomas.depraetere@dokeos.com)
 
   <li>Hogeschool Gent
   <ul>
-    <li> Bart Mollet (bart.mollet@hogent.be)</li>  
+    <li> Bart Mollet (bart.mollet@hogent.be)</li>
   </ul>
   </li>
-  
+
   <li>Independent
   <ul>
-  <li>
-Juan Carlos Raña Trabado - considerable work on the wiki integration
-and improvements, and the FCKEditor/Mimetex extension as well as *many*
-FCKEditor's file manager and other modules improvements, as well as a
-continuous stream of recommendations that helped shape 1.8.5 and 1.8.6</li>
-  <li>
-Ivan Tcholakov - various bugfixes in 1.8.6, very accurate bug reporting
-contributions and a considerable work in the integration of a new
-version of FCKEditor, along with a bunch of useful plugins</li>
+    <li> Juan Carlos Raña Trabado - considerable work on the wiki integration and improvements, and the FCKEditor/Mimetex extension as well as *many* FCKEditor's file manager and other modules improvements, as well as a continuous stream of recommendations that helped shape 1.8.5 and 1.8.6.*</li>
+    <li> Ivan Tcholakov - various bugfixes in 1.8.6.*, very accurate bug reporting contributions and a considerable work in the integration of a new version of FCKEditor, along with a bunch of useful plugins and an exceptional work on internationalization</li>
+  </ul>
+  </li>
+  <li>Dokeos Latinoamerica
+  <ul>
+    <li>Julio Allen Montoya Armas (gugli100@gmail.com)</li>
+    <li>Isaac Flores (florespaz_isaac@hotmail.com)</li>
+    <li>Christian Fasanando (christian534@hotmail.com)</li>
   </ul>
   </li>
-
 </ol>
 
 
@@ -463,17 +461,13 @@ technical documentation and his thorough testing of 1.8.6 features and implement
 of Dokeos in the Latin American area, patiently answering crazy amounts
 of information requests and organizing great community events</li>
   <li> Jhon Rhoos Hinojosa Portuguez, for various bugfixes in 1.8.6</li>
-  <li> Christian Fasanando, for a huge amount of bugfixes and new features in
-1.8.6, including important improvements in the web services tool, and
-the development of the notebook and glossary tools</li>
   <li> Carlos Vargas, for a huge amount of bugfixes in 1.8.6</li>
-  <li> Isaac Flores, for a huge amount of bugfixes in 1.8.6 and the development of the social tool and revision of the messaging tool</li>
   <li> Jan Derriks, for various bugfixes and suggestions</li>
   <li> Ronny Velasquez, for a series of bugfixes and improvements in 1.8.6</li>
   <li> Ricardo Rodriguez, for implementing the first set of unit tests in 1.8.6, and manual testing and reporting</li>
   <li> Franco Cedillo, for minor bugfixes in 1.8.6</li>
   <li> Ruben Pereira, Ana Elena Olivera and all the kids from the Joaquin Sant'Anna school for being an inspiration to all of us.</li>
-  
+
 </ul>
 
 <h1>Removed developments</h1>
@@ -494,4 +488,4 @@ the development of the notebook and glossary tools</li>
 	<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>
+</body></html>

+ 78 - 76
documentation/default.css

@@ -3,7 +3,7 @@
    (info@ws-webservice.de / webmaster@bibelcenter.de)
    updated on 2005-02-25 by Olivier Brouckaert
    (oli.brouckaert@dokeos.com)
-   update on 2005-03-01 by Wolfgang Schneider   
+   update on 2005-03-01 by Wolfgang Schneider
    update on 2005-05-27 by Patrick Cool
    */
 
@@ -15,13 +15,13 @@ body {
 	padding: 0;
 	background-color: #fff;
 }
-img {	
-	border: none; 
+img {
+	border: none;
 }
 
 #outerframe {
 	position: relative;  /* do not remove, fixes a bug in IE */
-	border: 1px solid #fff; 
+	border: 1px solid #fff;
 	background-color: #fff;
 }
 
@@ -29,7 +29,7 @@ img {
 * html #outerframe {height: 1%;}
 /* End hide from IE5-mac */
 
-/***************************************************** 
+/*****************************************************
  *  HEADER STYLES                                    *
  *****************************************************/
 #header {
@@ -41,8 +41,10 @@ img {
 #header1 {
 	font-size: 12px;
 	padding: 4px;
-	background-color: #264269; 
-	color: #fff; 
+	/*background-color: #264269; */
+	color: #fff;
+	background-color: #4171b5;
+	/*color: #264269;*/
 	border-bottom: 1px solid white;
 }
 #header1 a {
@@ -52,53 +54,53 @@ img {
 #header1 a:hover{
 	text-decoration: underline;
 }
-#sitename { 
-	margin: 0; 
+#sitename {
+	margin: 0;
 	font-weight: bold;
 }
 #institution {
-	float: left; 
+	float: left;
 	font-weight: bold;
 }
 #my_courses {
-	float: right; 
+	float: right;
 	font-weight: bold;
 }
 /* Header 2: Containing My Courses, My Profile,... */
 #header2 {
 	font-size: 12px;
 	padding: 4px;
-	background-color: #4271B5; 
-	color: #fff; 
+	background-color: #4271B5;
+	color: #fff;
 	border-bottom: 1px solid white;
 }
 #header2 .banner_links {
-	margin: 0; 
+	margin: 0;
 }
-#header2 a { 
+#header2 a {
 	text-decoration: none;
-	color: #fff; 
+	color: #fff;
 	background: transparent;
 	font-weight:normal;
 	font-size: 12px;
 }
-#header2 input.logout { 
- 	/* makes an input appear like a link in this header */	
-	margin: 0; 
-	padding: 0; 
-	background-color: transparent; 
+#header2 input.logout {
+ 	/* makes an input appear like a link in this header */
+	margin: 0;
+	padding: 0;
+	background-color: transparent;
 	border: none;
-	color: #fff; 
+	color: #fff;
 	font-size: 12px;
 	font-weight:normal;
-	font-family: verdana, arial, helvetica, sans-serif; 
+	font-family: verdana, arial, helvetica, sans-serif;
 }
 #header2 a:hover, #header2 input.logout:hover {
 	border-bottom: 1px solid #fff;
 }
 #logout {
-	float: right; 
-	width:20%; 
+	float: right;
+	width:20%;
 	text-align:right;
 }
 /* Header 3: Containing breadcrumbs, online users, student/teacher view, help */
@@ -129,12 +131,12 @@ img {
 	list-style-type: none;
 	text-align: right;
 }
-#Header3Right ul li { 
-	display: inline; 
+#Header3Right ul li {
+	display: inline;
 }
 #Header3Right ul li a {
-	padding: 4px 6px 4px 4px; 
-	color:#fff; 
+	padding: 4px 6px 4px 4px;
+	color:#fff;
 }
 /* Header 4: not used */
 #header4 {
@@ -155,7 +157,7 @@ img {
 	text-align: right;
 }
 
-/***************************************************** 
+/*****************************************************
  *  FOOTER STYLES                                    *
  *****************************************************/
 #footer {
@@ -168,7 +170,7 @@ img {
 	float: right;
 }
 
-/***************************************************** 
+/*****************************************************
  *  MAIN STYLES                                      *
  *****************************************************/
 #main {
@@ -207,7 +209,7 @@ img {
  background-color: #fff; font-size: 12px; color: #f00;}
 
 
-/*** layout divs for course and tool pages (being tested in some pages) ****/  
+/*** layout divs for course and tool pages (being tested in some pages) ****/
 #contentfloatholder {/* also makes the right "sliding" tab  */
 /*background: url(../pics/sidebar-r.gif) repeat-y 100% 0;
 background: url(../pics/bg_fountain.jpg) no-repeat 100% 0; */
@@ -218,26 +220,26 @@ position: relative;
 
 #contentfloatholder:after {
  /* this is for NN6 to clear floats */
-content: "."; 
-display: block; 
+content: ".";
+display: block;
 height: 0px;
-clear: both; 
+clear: both;
 visibility: hidden;
 }
 
 #centerwrap {
   float: left;
-  width: 100%; 
-  margin-right: -95%; 
-	/* this needs to be less than 100% for Moz/Mac which thinks 
-         it's empty otherwise. The difference is made up by putting a 
+  width: 100%;
+  margin-right: -95%;
+	/* this needs to be less than 100% for Moz/Mac which thinks
+         it's empty otherwise. The difference is made up by putting a
          negative left margin on the left float:
-	   Note IE/Mac doesn't like this method ~ it wants the 100% so it can 
-	   be fed in using IE only CSS below becasue IE/Win also works with the 100% method.  
+	   Note IE/Mac doesn't like this method ~ it wants the 100% so it can
+	   be fed in using IE only CSS below becasue IE/Win also works with the 100% method.
 	*/
 }
 
-#center { margin: 0 0 0 180px; padding: 10px 0 40px 0;  
+#center { margin: 0 0 0 180px; padding: 10px 0 40px 0;
  min-height: 300px; }
 
 #left { float: left; width: 180px; padding: 20px 0 0 0;
@@ -247,8 +249,8 @@ visibility: hidden;
 #leftnavbox {	margin: 0; padding: 0; float:left;}
 #leftnavbox dl { width: 160px; margin: 12px auto 4px auto; padding: 0 0 10px 0;
 background: transparent; font-size: 12px; text-align: center; }
-#leftnavbox dt { margin: 0; padding: 1px 2px; font-weight: bold; font-size: 12px; 
- text-align: center; color: #000; 
+#leftnavbox dt { margin: 0; padding: 1px 2px; font-weight: bold; font-size: 12px;
+ text-align: center; color: #000;
  border-bottom: 1px solid #fff; background: transparent; }
 #leftnavbox dd { margin: 0; padding: 0; color: #009; text-align: left;
 border-bottom:1px solid #fff; background: #ccf; }
@@ -258,10 +260,10 @@ border-bottom:1px solid #fff; background: #ccf; }
 #leftnavlist a:visited {color:#eee; text-decoration: none; display: block; padding: 2px 5px 2px 10px;
  background: #4171B5; color: #eee; width:140px; }
 #leftnavlist a:hover { background: #fff; color:#4171B5; display: block;}
-/* --- end of left side definition list menu section  --- */ 
+/* --- end of left side definition list menu section  --- */
 
 
- 
+
 /* various sections in course-home.php file  */
 #toolremove {width: 40%; color: #f00; font-weight: bold;
  margin: 10px auto; padding: 10px; border: 2px solid #f00;}
@@ -309,20 +311,20 @@ border-bottom:1px solid #fff; background: #ccf; }
 -----------------------------------------------------*/
 #agenda_list {width: 100%; margin: 0 auto; border: 1px solid #fff;
  border-collapse: collapse;}
- 
-/*The caption of the calendar (displays the month and the << and >> links*/ 
+
+/*The caption of the calendar (displays the month and the << and >> links*/
 #agenda_list #title {background-color: #4171B5; font-weight: bold;
  font-size: 12px; color: #fff; text-align: left; padding: 2px 10px; text-align: center; border: 1px solid #264269;}
 #agenda_list #title a:link, #agenda_list #title a:visited {background-color: #4171B5; font-weight: bold;
  font-size: 12px; color: #fff; text-align: left; padding: 2px 10px;text-align: center;}
 #agenda_list #title a:hover {background-color: #4171B5; font-weight: bold;
  font-size: 12px; color: #ff0000; text-align: left; padding: 2px 10px;text-align: center;}
- 
+
 /* The cells with the name of the days of the weeks (mon->sun)*/
 #agenda_list .weekdays {background-color: #D3DFF1; text-align: center;
  font-weight: bold; border: 1px solid #264269; border-collapse: collapse;}
- 
-/* The cells for the days (1->31) */ 
+
+/* The cells for the days (1->31) */
 #agenda_list .days_week {height: 40px; width: 12%; text-align: left; vertical-align: top;
  border: 1px solid #264269; border-collapse: collapse; background-color: #f5f5f5;}
 #agenda_list .days_weekend {height: 40px; width: 12%; text-align: left; vertical-align: top;
@@ -334,29 +336,29 @@ border-bottom:1px solid #fff; background: #ccf; }
 #agenda_list .data {background-color: #eee; text-align: left; padding: 2px 10px;
  font-weight: bold; border: 0px solid #4171B5; border-collapse: collapse;}
 #agenda_list .datanotbold {background-color: #eee; text-align: left; padding: 2px 10px;
- font-weight: normal; border: 0px solid #4171B5; border-collapse: collapse;} 
+ font-weight: normal; border: 0px solid #4171B5; border-collapse: collapse;}
 #agenda_list .text {background-color: #fff; text-align: left; padding: 2px 10px;
  font-weight: normal; border: 0px solid #4171B5; border-collapse: collapse;}
 
-/*text in the cells: display of agenda items (invisible)*/   
+/*text in the cells: display of agenda items (invisible)*/
 #agenda_list .data_hidden {background-color: #eee; text-align: left; padding: 2px 10px;
  font-weight: bold; border: 0px solid #4171B5; border-collapse: collapse; color: #999999;}
 #agenda_list .datanotbold_hidden {background-color: #eee; text-align: left; padding: 2px 10px;
- font-weight: normal; border: 0px solid #4171B5; border-collapse: collapse; color: #999999;} 
+ font-weight: normal; border: 0px solid #4171B5; border-collapse: collapse; color: #999999;}
 #agenda_list .text_hidden {background-color: #fff; text-align: left; padding: 2px 10px;
  font-weight: normal; border: 0px solid #4171B5; border-collapse: collapse; color: #999999;}
- 
-/*text in the cells: display of agenda items (highlighted)*/    
+
+/*text in the cells: display of agenda items (highlighted)*/
 #agenda_list .datanow {background-color: #FFCC00; text-align: left; padding: 2px 10px;
  font-weight: bold; border: 0px solid #4171B5; border-collapse: collapse;}
 #agenda_list .datanotboldnow {background-color: #FFCC00; text-align: left; padding: 2px 10px;
- font-weight: normal; border: 0px solid #4171B5; border-collapse: collapse;} 
+ font-weight: normal; border: 0px solid #4171B5; border-collapse: collapse;}
 #agenda_list .textnow {background-color: #fff; text-align: left; padding: 2px 10px;
- font-weight: normal; border: 0px solid #4171B5; border-collapse: collapse;} 
- 
+ font-weight: normal; border: 0px solid #4171B5; border-collapse: collapse;}
+
 /* ---------------------------------------------------
 	styles for the mini agenda
------------------------------------------------------*/ 
+-----------------------------------------------------*/
 #smallcalendar {width: 100%; margin: 0 auto; border: 1px solid #fff;
  border-collapse: collapse;}
 #smallcalendar .weekdays {background-color: #D3DFF1; text-align: center;
@@ -366,15 +368,15 @@ border-bottom:1px solid #fff; background: #ccf; }
 #smallcalendar .days_weekend {background-color: #e6e6e6; text-align: center;
  font-size: 11px; border: 1px solid #fff; border-collapse: collapse;}
 #smallcalendar .days_today {width: 12%; text-align: center;
- font-size: 11px;  border: 1px solid #FA8500; border-collapse: collapse; background-color: #FFCA8D;} 
-   
+ font-size: 11px;  border: 1px solid #FA8500; border-collapse: collapse; background-color: #FFCA8D;}
+
 /* ---------------------------------------------------
 	styles for the personal agenda
 -----------------------------------------------------*/
 .personal_agenda {color: #008000; }
-.personal_agenda a:link, .personal_agenda a:visited {color: #008000; } 
+.personal_agenda a:link, .personal_agenda a:visited {color: #008000; }
 a.personal_agenda:link, a.personal_agenda:visited {color: #008000; }
-.personal_agenda a:hover, .personal_agenda a:hover {color: #666666; } 
+.personal_agenda a:hover, .personal_agenda a:hover {color: #666666; }
 a.personal_agenda:hover, a.personal_agenda:hover {color: #666666; }
 
 
@@ -392,12 +394,12 @@ a.personal_agenda:hover, a.personal_agenda:hover {color: #666666; }
 }
 .normal-message {
 	border: 1px solid #FF8001;
-	color: #000; 
+	color: #000;
 	background-color: #FDC77E;
 }
 .error-message {
 	border: 1px solid #3F70AC;
-	color: #000; 
+	color: #000;
 	background-color: #FDC273;
 }
 
@@ -483,7 +485,7 @@ input.liteoption {font-weight : normal;} /* None-bold submit button */
 select,
 input[type=checkbox],
 input[type=radio],
-input[type=button], 
+input[type=button],
 input[type=submit] {cursor:	pointer; font-size: 12px;}
 input[text] {font-size: 12px; }
 
@@ -512,14 +514,14 @@ padding-top: 0px;	padding-right: 0px;	padding-bottom: 0px;	padding-left: 0px;}
 .xxsmall {  font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9px}
 
 
-/***************************************************** 
+/*****************************************************
  *  DATA TABLE STYLES                                *
  *****************************************************/
 .cell_header {background-color: #EEEEFF;font-weight:bold;text-align:left;padding-left:5px;}   /* header cell in data table in tools */
 
 .data_table{
   	border-collapse: collapse;
-	width: 100%; 
+	width: 100%;
 	padding: 5px;
 }
 .data_table th{
@@ -540,7 +542,7 @@ padding-top: 0px;	padding-right: 0px;	padding-bottom: 0px;	padding-left: 0px;}
   	padding: 5px;
 	  vertical-align: top;
   	border-bottom: 1px solid #b0b0b0;
-  	border-right: 1px dotted #e1e1e1; 
+  	border-right: 1px dotted #e1e1e1;
   	border-left: 1px dotted #e1e1e1;
 }
 
@@ -549,12 +551,12 @@ padding-top: 0px;	padding-right: 0px;	padding-bottom: 0px;	padding-left: 0px;}
 .tool_list dd { margin: 0; padding: 4px 0 0 10px;}
 
 /* divs for category list / platform news on home page */
-.home_cats {width: 45%; float: left; 
+.home_cats {width: 45%; float: left;
 	margin: 0; padding: 8px; background: #fff;}
 
-.home_news {width: 45%; float: right; 
+.home_news {width: 45%; float: right;
 	margin: 0; padding: 8px; background: #fff;}
- 
+
 
 label.left { float: left; width: 15em; margin: 0 0 0.5em 0; }
 form br { clear: both; }
@@ -576,7 +578,7 @@ div.admin_section {
 	padding: 5px;
 	margin: 10px 20px;
 }
-div.admin_section h4 { 
+div.admin_section h4 {
   margin: 0;
 	border-bottom: 1px solid gray;
 	width: 100%;
@@ -615,7 +617,7 @@ div.admin_section h4 {
 
 /* New Announcements Tool */
 .announcements_datum
-{ 
+{
    font-size: 12px;
    font-style: italic;
    color: #666666;
@@ -635,4 +637,4 @@ div.system_announcement_content{
 	margin-left: 20px;
 	border-left: 1px solid gray;
 	padding-left: 5px;
-}
+}

+ 6 - 6
documentation/dependencies.html

@@ -1,7 +1,7 @@
 <!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 Server Dependencies</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">
@@ -18,15 +18,15 @@
 </div>
 <a href="index.html">Documentation</a> &gt;Dependencies
 <h2>Introduction</h2>
-<p>In the ever-evoluting web environment, Dokeos has to rely on state-of-the-art third-party 
+<p>In the ever-evoluting web environment, Dokeos has to rely on state-of-the-art third-party
   software in order to provide you with useful and practical features. Some of this third-party software
   usually come bundled with your operating system, but some don't. This means that if that software is
   not installed on your Dokeos server, along with Dokeos, you might not enjoy the best possible
-  experience with your Dokeos platform. To avoid this problem, most of the sofware we used is bundled 
+  experience with your Dokeos platform. To avoid this problem, most of the sofware we used is bundled
   into a typical Dokeos install.</p><p>
-  However, if such a third-party software is too big to be included, or if it doesn't make sense to 
-  includ it for whatever reason, you must make sure it is installed on your system. 
-  This is the goal of this list: to help you keep a track of what software is needed and, 
+  However, if such a third-party software is too big to be included, or if it doesn't make sense to
+  includ it for whatever reason, you must make sure it is installed on your system.
+  This is the goal of this list: to help you keep a track of what software is needed and,
   as much as possible, where to get the required information to install it.</p>
 
 <a name="dependencies"></a>

+ 3 - 3
documentation/index.html

@@ -1,7 +1,7 @@
 <!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</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">
@@ -18,7 +18,7 @@
 </div>
 
 <div id="outerframe">
-<div id="main">    
+<div id="main">
 <h1>About Dokeos</h1>
 <p><a href="readme.html">About Dokeos</a>     </p>
 <h1>Installing and upgrading</h1>
@@ -29,7 +29,7 @@ for the latest version – there may be updates to the guide since
 this version was released – and send new translations off to the <a href="mailto:translation@dokeos.com">translation@dokeos.com</a> email address. </p>
 
 <h1>License</h1>
-<a href="license.html">GNU General Public License Version 2</a>    
+<a href="license.html">GNU General Public License Version 2</a>
 <h1>Credits</h1>
 <p><a href="credits.html">Credits</a></p>
 <h1>Dependencies</h1>

+ 2 - 2
documentation/install_red5.txt

@@ -5,7 +5,7 @@ Table of contents
 -----------------
 1. Installation
 1.1. Red5
-1.2. Dokeos Red5 Application 
+1.2. Dokeos Red5 Application
 
 2. Configuration
 
@@ -23,7 +23,7 @@ Table of contents
 
 1.1. Red5
 
-To install red5, please check the documentation related to your platform on the red5 website[1]. Below, we will suppose that red5 home 
+To install red5, please check the documentation related to your platform on the red5 website[1]. Below, we will suppose that red5 home
 directory is /opt/red5. If you run red5 under MS-Windows, change /opt/red5 by your installation directory, for example: D:\applications\red5.
 From now on, we will refer to red5 home directory by $RED5_HOME.
 

+ 688 - 688
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 />
-
-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>
-
-<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>
-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 />
-
-<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.
- 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>
-
-
-<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>
-  <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>
-  <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>
-  <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>
-  <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 />
-
-<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>
-
-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>
+<!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>
+
+<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>
+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 />
+
+<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.
+ 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>
+
+
+<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>
+  <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>
+  <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>
+  <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>
+  <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 />
+
+<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>
+
+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>
 </body></html>

+ 763 - 763
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
-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 />
-
-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>
-
-<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>
-
-  <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>
-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.
-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
-(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
-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
- 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>
-
-
-<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>
-  <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>
-  <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>
-  <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 />
-
-<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
-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
-el nuevo. Usted puede remover la ruta antigua, cuando la actualizacion sea finalizada satisfactoriamente. 
-</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>
-
-
-<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
-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 />
-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
-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>
-
-
-<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>
-	
-<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 />
-  
-  Correo: 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>
+<!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 />
+
+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>
+
+<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>
+
+  <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>
+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.
+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
+(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
+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
+ 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>
+
+
+<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>
+  <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>
+  <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>
+  <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 />
+
+<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
+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
+el nuevo. Usted puede remover la ruta antigua, cuando la actualizacion sea finalizada satisfactoriamente.
+</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>
+
+
+<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
+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 />
+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
+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>
+
+
+<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>
+
+<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 />
+
+  Correo: 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>

+ 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.

+ 18 - 18
documentation/readme.html

@@ -1,18 +1,18 @@
 <!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 Information</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 }
@@ -37,7 +37,7 @@
 
       SCORM compliant, and light and flexible.</p>
 
-    
+
 <p>Dokeos supports many different kinds of learning and collaboration activities.<br />
 
       Teachers/trainers can create, manage and publish their courses through the web.<br />
@@ -46,30 +46,30 @@
 
       through groups, forums, chat.</p>
 
-    
+
 <p>Technically, Dokeos is a web application written in PHP that stores data in a <br />
 
       MySQL database. Users access it using a web browser.</p>
 
-    
+
 <p>If you would like to know more or help develop this software, please visit<br />
 
       our homepage at <a href="http://www.dokeos.com">http://www.dokeos.com</a></p>
 
-    
+
 <h1>SCORM</h1>
 
     Dokeos FREE imports Scorm 1.2 contents.<br />
 
     For more information on Scorm normalisation, see http://www.adlnet.org<br />
-    
+
 <h1>Licence</h1>
-    
+
 <p>Dokeos is distributed under the GNU General Public license (GPL).<br />
 
       Read the <a href="licence.html">GNU General Public license (GPL)</a> .</p>
 
-    
+
 <h1>Portability</h1>
 
 <p>Dokeos is an AMP software. This means it should work on any platform running Apache<br />
@@ -92,7 +92,7 @@
 
 <p>It has been tested on </p>
 
-    
+
 <ul>
 
       <li> Fedora, Mandrake, Red Hat Enterprise Server, Ubuntu, Debian </li>
@@ -100,14 +100,14 @@
       <li> Windows XP, Windows 2000</li>
 
       <li> Mac OS X 10.3</li>
-    
+
 </ul>
-    
+
 <p>Email functions remain silent on systems where there is no mail sending software<br />
 
       (Sendmail, Postfix, Hamster...), which is the case by default on a Windows machine.</p>
 
-    
+
 <h1>Interoperability</h1>
 
 <p>Dokeos imports Scorm compliant learning contents. It imports then "On the shelve"<br />
@@ -147,7 +147,7 @@
 
       Tel. +32 (2) 669 69 55<br />
 
-      Mail: <a href="mailto:info@dokeos.com">info@dokeos.com</a> 
+      Mail: <a href="mailto:info@dokeos.com">info@dokeos.com</a>
 </p>
 
 </div>

+ 0 - 0
home/home_tabs.html


+ 0 - 0
home/register_top.html


+ 241 - 236
index.php

@@ -1,5 +1,5 @@
 <?php // $Id: index.php 22368 2009-07-24 23:25:57Z iflorespaz $
- 
+
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
@@ -25,23 +25,22 @@
 */
 
 /**
-*	@package dokeos.main
-* 	@author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Refactoring
-* 	@version $Id: index.php 22368 2009-07-24 23:25:57Z iflorespaz $
-*   @todo check the different @todos in this page and really do them
-* 	@todo check if the news management works as expected
-*/
-
+ *	@package dokeos.main
+ *	@author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Refactoring
+ *	@version $Id: index.php 22368 2009-07-24 23:25:57Z iflorespaz $
+ *	@todo check the different @todos in this page and really do them
+ *	@todo check if the news management works as expected
+ */
 
 // only this script should have this constant defined. This is used to activate the javascript that
 // gives the login name automatic focus in header.inc.html.
-/** @todo  Couldn't this be done using the $HtmlHeadXtra array? */
+/** @todo Couldn't this be done using the $HtmlHeadXtra array? */
 define('DOKEOS_HOMEPAGE', true);
 
 // the language file
 $language_file = array ('courses', 'index');
 
-/* Flag forcing the 'current course' reset, as we're not inside a course anymore  */
+/* Flag forcing the 'current course' reset, as we're not inside a course anymore */
 // maybe we should change this into an api function? an example: Coursemanager::unset();
 $cidReset = true;
 
@@ -51,35 +50,40 @@ $cidReset = true;
 	Included libraries
 -----------------------------------------------------------
 */
+
 /** @todo make all the library files consistent, use filename.lib.php and not filename.lib.inc.php */
-require_once ('main/inc/global.inc.php');
-include_once (api_get_path(LIBRARY_PATH).'course.lib.php');
-include_once (api_get_path(LIBRARY_PATH).'debug.lib.inc.php');
-include_once (api_get_path(LIBRARY_PATH).'events.lib.inc.php');
-include_once (api_get_path(LIBRARY_PATH).'system_announcements.lib.php');
-include_once (api_get_path(LIBRARY_PATH).'groupmanager.lib.php');
-include_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+require_once 'main/inc/global.inc.php';
+include_once api_get_path(LIBRARY_PATH).'course.lib.php';
+include_once api_get_path(LIBRARY_PATH).'debug.lib.inc.php';
+include_once api_get_path(LIBRARY_PATH).'events.lib.inc.php';
+include_once api_get_path(LIBRARY_PATH).'system_announcements.lib.php';
+include_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
+include_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 require_once 'main/chat/chat_functions.lib.php';
+
 $loginFailed = isset($_GET['loginFailed']) ? true : isset($loginFailed);
-$setting_show_also_closed_courses = (api_get_setting('show_closed_courses')=='true') ? true : false;
+$setting_show_also_closed_courses = api_get_setting('show_closed_courses') == 'true';
 
 // the section (for the tabs)
 $this_section = SECTION_CAMPUS;
+
 /*
 -----------------------------------------------------------
 	Action Handling
 -----------------------------------------------------------
 */
-/** @todo 	wouldn't it make more sense if this would be done in local.inc.php so that local.inc.php become the only place where authentication is done?
+
+/** @todo 	Wouldn't it make more sense if this would be done in local.inc.php so that local.inc.php become the only place where authentication is done?
  * 			by doing this you could logout from any page instead of only from index.php. From the moment there is a logout=true in the url you will be logged out
  * 			this can be usefull when you are on an open course and you need to log in to edit something and you immediately want to check how anonymous users
  * 			will see it.
  */
- $my_user_id=api_get_user_id();
+$my_user_id = api_get_user_id();
 
 if (!empty($_GET['logout'])) {
 	logout();
 }
+
 /*
 -----------------------------------------------------------
 	Table definitions
@@ -103,12 +107,12 @@ if (isset($_user['user_id'])) {
 	$nameTools = api_get_setting('siteName');
 }
 
-
 /*
 ==============================================================================
 		LOGIN
 ==============================================================================
 */
+
 /**
  * @todo This piece of code should probably move to local.inc.php where the actual login / logout procedure is handled.
  * @todo consider removing this piece of code because does nothing.
@@ -119,11 +123,13 @@ if (isset($_GET['submitAuth']) && $_GET['submitAuth'] == 1) {
 	session_destroy();
 	die();
 }
+
 //Delete session neccesary for legal terms
-if (get_setting('allow_terms_conditions')=='true') {
+if (api_get_setting('allow_terms_conditions')=='true') {
 	unset($_SESSION['update_term_and_condition']);
 	unset($_SESSION['info_current_user']);
 }
+
 /**
  * @todo This piece of code should probably move to local.inc.php where the actual login procedure is handled.
  * @todo check if this code is used. I think this code is never executed because after clicking the submit button
@@ -131,31 +137,32 @@ if (get_setting('allow_terms_conditions')=='true') {
  * 		 on api_get_setting('page_after_login')
  */
 
-if (!empty($_POST["submitAuth"])) {
+if (!empty($_POST['submitAuth'])) {
 	// the user is already authenticated, we now find the last login of the user.
 	if (isset ($_user['user_id'])) {
 		$sql_last_login = "SELECT UNIX_TIMESTAMP(login_date)
 								FROM $track_login_table
 								WHERE login_user_id = '".$_user['user_id']."'
 								ORDER BY login_date DESC LIMIT 1";
-		$result_last_login = api_sql_query($sql_last_login, __FILE__, __LINE__);
-		if (!$result_last_login)
+		$result_last_login = Database::query($sql_last_login, __FILE__, __LINE__);
+		if (!$result_last_login) {
 			if (Database::num_rows($result_last_login) > 0) {
 				$user_last_login_datetime = Database::fetch_array($result_last_login);
 				$user_last_login_datetime = $user_last_login_datetime[0];
 				api_session_register('user_last_login_datetime');
 			}
+		}
 		mysql_free_result($result_last_login);
 
 		//event_login();
 		if (api_is_platform_admin()) {
 			// decode all open event informations and fill the track_c_* tables
-			include (api_get_path(LIBRARY_PATH)."stats.lib.inc.php");
+			include api_get_path(LIBRARY_PATH).'stats.lib.inc.php';
 			decodeOpenInfos();
 		}
 	}
 
-} // end login -- if($_POST["submitAuth"])
+} // end login -- if ($_POST['submitAuth'])
 else {
 	// only if login form was not sent because if the form is sent the user was already on the page.
 
@@ -170,6 +177,7 @@ Display :: display_header('', 'dokeos');
 		MAIN CODE
 ==============================================================================
 */
+
 echo '<div class="maincontent" id="content">';
 
 // Plugins for loginpage_main AND campushomepage_main
@@ -179,17 +187,17 @@ if (!api_get_user_id()) {
 	api_plugin('campushomepage_main');
 }
 
-$home= 'home/';
-if ($_configuration['multiple_access_urls']==true) {
-	$access_url_id = api_get_current_access_url_id();										 
-	if ($access_url_id != -1){						
+$home = 'home/';
+if ($_configuration['multiple_access_urls']) {
+	$access_url_id = api_get_current_access_url_id();
+	if ($access_url_id != -1){
 		$url_info = api_get_access_url($access_url_id);
-		// "http://" and the final "/" replaced						
-		$url = substr($url_info['url'],7,strlen($url_info['url'])-8);						
+		// "http://" and the final "/" replaced
+		$url = substr($url_info['url'], 7, strlen($url_info['url']) - 8);
 		$clean_url = replace_dangerous_char($url);
-		$clean_url = str_replace('/','-',$clean_url);
+		$clean_url = str_replace('/', '-', $clean_url);
 		$clean_url = $clean_url.'/';
-		$home_old  = 'home/'; 
+		$home_old = 'home/';
 		$home= 'home/'.$clean_url;
 	}
 }
@@ -197,35 +205,35 @@ if ($_configuration['multiple_access_urls']==true) {
 // Including the page for the news
 $page_included = false;
 
-if (!empty ($_GET['include']) && preg_match('/^[a-zA-Z0-9_-]*\.html$/',$_GET['include'])) {
-	include ('./'.$home.$_GET['include']);
+if (!empty($_GET['include']) && preg_match('/^[a-zA-Z0-9_-]*\.html$/', $_GET['include'])) {
+	include './'.$home.$_GET['include'];
 	$page_included = true;
 } else {
-	
+
 	if (!empty($_SESSION['user_language_choice'])) {
-		$user_selected_language=$_SESSION['user_language_choice'];
-	} elseif(!empty($_SESSION['_user']['language'])) {
-		$user_selected_language=$_SESSION['_user']['language'];
+		$user_selected_language = $_SESSION['user_language_choice'];
+	} elseif (!empty($_SESSION['_user']['language'])) {
+		$user_selected_language = $_SESSION['_user']['language'];
 	} else {
-		$user_selected_language=get_setting('platformLanguage');
+		$user_selected_language = api_get_setting('platformLanguage');
 	}
-	
-	if(!file_exists($home.'home_news_'.$user_selected_language.'.html')) {
-		if (file_exists($home.'home_top.html'))
-			$home_top_temp=file($home.'home_top.html');
-		else {
-			$home_top_temp=file($home_old.'home_top.html');
-		} 
-		$home_top_temp=implode('',$home_top_temp);
-		$open=str_replace('{rel_path}',api_get_path(REL_PATH),$home_top_temp);
+
+	if (!file_exists($home.'home_news_'.$user_selected_language.'.html')) {
+		if (file_exists($home.'home_top.html')) {
+			$home_top_temp = file($home.'home_top.html');
+		} else {
+			$home_top_temp = file($home_old.'home_top.html');
+		}
+		$home_top_temp = implode('', $home_top_temp);
+		$open = str_replace('{rel_path}', api_get_path(REL_PATH), $home_top_temp);
 		echo $open;
 	} else {
-		if(file_exists($home.'home_top_'.$user_selected_language.'.html')) {
+		if (file_exists($home.'home_top_'.$user_selected_language.'.html')) {
 			$home_top_temp = file_get_contents($home.'home_top_'.$user_selected_language.'.html');
 		} else {
 			$home_top_temp = file_get_contents($home.'home_top.html');
 		}
-		$open=str_replace('{rel_path}',api_get_path(REL_PATH),$home_top_temp);
+		$open = str_replace('{rel_path}', api_get_path(REL_PATH), $home_top_temp);
 		echo $open;
 	}
 }
@@ -268,14 +276,14 @@ Display :: display_footer();
  *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  */
-function logout() 
+function logout()
 {
 	global $_configuration, $extAuthSource;
 	// variable initialisation
-	$query_string='';
+	$query_string = '';
 
 	if (!empty($_SESSION['user_language_choice'])) {
-		$query_string='?language='.$_SESSION['user_language_choice'];
+		$query_string = '?language='.$_SESSION['user_language_choice'];
 	}
 
 	// Database table definition
@@ -283,30 +291,30 @@ function logout()
 
 	// selecting the last login of the user
 	$uid = intval($_GET['uid']);
-	$sql_last_connection="SELECT login_id, login_date FROM $tbl_track_login WHERE login_user_id='$uid' ORDER BY login_date DESC LIMIT 0,1";
-	$q_last_connection=api_sql_query($sql_last_connection);
-	if (Database::num_rows($q_last_connection)>0) {
-		$i_id_last_connection=Database::result($q_last_connection,0,"login_id");
+	$sql_last_connection = "SELECT login_id, login_date FROM $tbl_track_login WHERE login_user_id='$uid' ORDER BY login_date DESC LIMIT 0,1";
+	$q_last_connection = Database::query($sql_last_connection, __FILE__, __LINE__);
+	if (Database::num_rows($q_last_connection) > 0) {
+		$i_id_last_connection = Database::result($q_last_connection, 0, 'login_id');
 	}
-	
+
 	if (!isset($_SESSION['login_as'])) {
-		$current_date=date('Y-m-d H:i:s',time());
-		$s_sql_update_logout_date="UPDATE $tbl_track_login SET logout_date='".$current_date."' WHERE login_id='$i_id_last_connection'";
-		api_sql_query($s_sql_update_logout_date);
+		$current_date = date('Y-m-d H:i:s', time());
+		$s_sql_update_logout_date = "UPDATE $tbl_track_login SET logout_date='".$current_date."' WHERE login_id='$i_id_last_connection'";
+		Database::query($s_sql_update_logout_date, __FILE__, __LINE__);
 	}
 	LoginDelete($uid, $_configuration['statistics_database']); //from inc/lib/online.inc.php - removes the "online" status
-	
+
 	//the following code enables the use of an external logout function.
 	//example: define a $extAuthSource['ldap']['logout']="file.php" in configuration.php
-	// then a function called ldap_logout() inside that file 
-	// (using *authent_name*_logout as the function name) and the following code 
-	// will find and execute it 
+	// then a function called ldap_logout() inside that file
+	// (using *authent_name*_logout as the function name) and the following code
+	// will find and execute it
 	$uinfo = api_get_user_info($uid);
 	if (($uinfo['auth_source'] != PLATFORM_AUTH_SOURCE) && is_array($extAuthSource)) {
 		if (is_array($extAuthSource[$uinfo['auth_source']])) {
 			$subarray = $extAuthSource[$uinfo['auth_source']];
 			if (!empty($subarray['logout']) && file_exists($subarray['logout'])) {
-				include_once($subarray['logout']);
+				include_once ($subarray['logout']);
 				$logout_function = $uinfo['auth_source'].'_logout';
 				if (function_exists($logout_function)) {
 					$logout_function($uinfo);
@@ -328,22 +336,22 @@ function logout()
  */
 function category_has_open_courses($category) {
 	global $setting_show_also_closed_courses;
-	
-	$user_identified = (api_get_user_id()>0 && !api_is_anonymous());
+
+	$user_identified = (api_get_user_id() > 0 && !api_is_anonymous());
 	$main_course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
 	$sql_query = "SELECT * FROM $main_course_table WHERE category_code='$category'";
-	$sql_result = api_sql_query($sql_query, __FILE__, __LINE__);
+	$sql_result = Database::query($sql_query, __FILE__, __LINE__);
 	while ($course = Database::fetch_array($sql_result)) {
-		if ($setting_show_also_closed_courses == false) {
-			if ((api_get_user_id()>0 
-				and $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
-				or ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD)) {
+		if (!$setting_show_also_closed_courses) {
+			if ((api_get_user_id() > 0
+				&& $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
+				|| ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD)) {
 				return true; //at least one open course
 			}
-		} else  {
-			if(isset($course['visibility'])){
+		} else {
+			if (isset($course['visibility'])){
 				return true; //at least one course (does not matter weither it's open or not because $setting_show_also_closed_courses = true
-			}			
+			}
 		}
 	}
 	return false;
@@ -369,7 +377,7 @@ function display_anonymous_right_menu() {
 
 	$platformLanguage = api_get_setting('platformLanguage');
 
-	if ( !($_user['user_id']) or api_is_anonymous($_user['user_id']) ) {  // only display if the user isn't logged in
+	if (!($_user['user_id']) || api_is_anonymous($_user['user_id']) ) { // only display if the user isn't logged in
 		api_display_language_form(true);
 		echo '<br />';
 		display_login_form();
@@ -378,12 +386,12 @@ function display_anonymous_right_menu() {
 			echo '<br />';
 			handle_login_failed();
 		}
-		if (api_get_setting('allow_lostpassword') == 'true' OR api_get_setting('allow_registration') == 'true') {
+		if (api_get_setting('allow_lostpassword') == 'true' || api_get_setting('allow_registration') == 'true') {
 			echo '<div class="menusection"><span class="menusectioncaption">'.get_lang('MenuUser').'</span><ul class="menulist">';
-			if (get_setting('allow_registration') <> 'false') {
+			if (api_get_setting('allow_registration') <> 'false') {
 				echo '<li><a href="main/auth/inscription.php">'.get_lang('Reg').'</a></li>';
 			}
-			if (get_setting('allow_lostpassword') == 'true') {
+			if (api_get_setting('allow_lostpassword') == 'true') {
 				display_lost_password_info();
 			}
 			echo '</ul></div>';
@@ -397,50 +405,51 @@ function display_anonymous_right_menu() {
 
 
 	// My Account section
-	if (isset($_SESSION['_user']['user_id']) && $_SESSION['_user']['user_id']!=0) {
+	if (isset($_SESSION['_user']['user_id']) && $_SESSION['_user']['user_id'] != 0) {
 		// tabs that are deactivated are added here
 
+		$show_menu = false;
+		$show_create_link = false;
+		$show_course_link = false;
 
-		$show_menu=false;
-		$show_create_link=false;
-		$show_course_link=false;	
-		
 		$display_add_course_link = api_is_allowed_to_create_course() && ($_SESSION["studentview"] != "studentenview");
-		
+
 		if ($display_add_course_link) {
 			//display_create_course_link();
-			$show_menu=true;
-			$show_create_link=true;			
+			$show_menu = true;
+			$show_create_link = true;
 		}
-				
+
 		if (api_is_platform_admin() || api_is_course_admin() || api_is_allowed_to_create_course()) {
-				$show_menu=true;
-				$show_course_link=true;		
-		} else {	
-			if (api_get_setting('allow_students_to_browse_courses')=='true') {			
-				$show_menu=true;
-				$show_course_link=true;				
-			}	
+				$show_menu = true;
+				$show_course_link = true;
+		} else {
+			if (api_get_setting('allow_students_to_browse_courses') == 'true') {
+				$show_menu = true;
+				$show_course_link = true;
+			}
 		}
-				
+
 		if ($show_menu){
 			echo "<div class=\"menusection\">";
 			echo "<span class=\"menusectioncaption\">".get_lang("MenuUser")."</span>";
 			echo "<ul class=\"menulist\">";
-			if ($show_create_link)
+			if ($show_create_link) {
 				display_create_course_link();
-			if ($show_course_link)
-				display_edit_course_list_links();			
+			}
+			if ($show_course_link) {
+				display_edit_course_list_links();
+			}
 			echo "</ul>";
-			echo "</div>";			
+			echo "</div>";
 		}
-		
+
 		if (!empty($menu_navigation)) {
 			echo "<div class=\"menusection\">";
 			echo "<span class=\"menusectioncaption\">".get_lang("MainNavigation")."</span>";
 			echo "<ul class=\"menulist\">";
-			foreach($menu_navigation as $section => $navigation_info) {
-				$current = ($section == $GLOBALS['this_section'] ? ' id="current"' : '');
+			foreach ($menu_navigation as $section => $navigation_info) {
+				$current = $section == $GLOBALS['this_section'] ? ' id="current"' : '';
 				echo '<li'.$current.'>';
 				echo '<a href="'.$navigation_info['url'].'" target="_self">'.$navigation_info['title'].'</a>';
 				echo '</li>';
@@ -450,60 +459,57 @@ function display_anonymous_right_menu() {
 			echo '</div>';
 		}
 	}
-	
+
 	// help section
-	/*** hide right menu "general" and other parts on anonymous right menu  *****/
-	 
+	/*** hide right menu "general" and other parts on anonymous right menu *****/
+
 	$user_selected_language = api_get_interface_language();
 	global $home, $home_old;
-	if (!isset ($user_selected_language))
-	{
+	if (!isset($user_selected_language)) {
 		$user_selected_language = $platformLanguage;
-	} 
+	}
 
-	if (!file_exists($home.'home_menu_'.$user_selected_language.'.html') && file_exists($home.'home_menu.html') && file_get_contents($home.'home_menu.html')!='')
-	{
+	if (!file_exists($home.'home_menu_'.$user_selected_language.'.html') && file_exists($home.'home_menu.html') && file_get_contents($home.'home_menu.html') != '') {
 		echo "<div class=\"menusection\">", "<span class=\"menusectioncaption\">".get_lang("MenuGeneral")."</span>";
 	 	echo "<ul class=\"menulist\">";
-		if (file_exists($home.'home_menu.html'))
+		if (file_exists($home.'home_menu.html')) {
 			include ($home.'home_menu.html');
-		else {
+		} else {
 			include ($home_old.'home_menu.html');
 		}
 		echo '</ul>';
 		echo '</div>';
 	}
-
-	elseif(file_exists($home.'home_menu_'.$user_selected_language.'.html') && file_get_contents($home.'home_menu_'.$user_selected_language.'.html')!='')
-	{	
+	elseif(file_exists($home.'home_menu_'.$user_selected_language.'.html') && file_get_contents($home.'home_menu_'.$user_selected_language.'.html') != '') {
 		echo "<div class=\"menusection\">", "<span class=\"menusectioncaption\">".get_lang("MenuGeneral")."</span>";
 	 	echo "<ul class=\"menulist\">";
-		include($home.'home_menu_'.$user_selected_language.'.html');
+		include ($home.'home_menu_'.$user_selected_language.'.html');
 		echo '</ul>';
 		echo '</div>';
-	}	
-	
+	}
+
 	if ($_user['user_id'] && api_number_of_plugins('campushomepage_menu') > 0) {
 		echo '<div class="note" style="background: none">';
 		api_plugin('campushomepage_menu');
 		echo '</div>';
 	}
-			
+
 	// includes for any files to be displayed below anonymous right menu
-	
-	if (!file_exists($home.'home_notice_'.$user_selected_language.'.html') && file_exists($home.'home_notice.html') && file_get_contents($home.'home_notice.html')!='') {
+
+	if (!file_exists($home.'home_notice_'.$user_selected_language.'.html') && file_exists($home.'home_notice.html') && file_get_contents($home.'home_notice.html') != '') {
 		echo '<div class="note">';
-		if (file_exists($home.'home_notice.html'))
+		if (file_exists($home.'home_notice.html')) {
 			include ($home.'home_notice.html');
-		else {
+		} else {
 			include ($home_old.'home_notice.html');
 		}
 		echo '</div>';
-	} elseif(file_exists($home.'home_notice_'.$user_selected_language.'.html') && file_get_contents($home.'home_notice_'.$user_selected_language.'.html')!='') {
+	}
+	elseif(file_exists($home.'home_notice_'.$user_selected_language.'.html') && file_get_contents($home.'home_notice_'.$user_selected_language.'.html') != '') {
 		echo '<div class="note">';
-		include($home.'home_notice_'.$user_selected_language.'.html'); 
+		include($home.'home_notice_'.$user_selected_language.'.html');
 		echo '</div>';
-	}	
+	}
 }
 
 /**
@@ -528,16 +534,16 @@ function handle_login_failed() {
 				}
 				break;
 			case 'account_expired':
-				$message=get_lang('AccountExpired');
+				$message = get_lang('AccountExpired');
 				break;
 			case 'account_inactive':
-				$message=get_lang('AccountInactive');
+				$message = get_lang('AccountInactive');
 				break;
 			case 'user_password_incorrect':
-				$message=get_lang('InvalidId');
+				$message = get_lang('InvalidId');
 				break;
 			case 'access_url_inactive':
-				$message=get_lang('AccountURLInactive');
+				$message = get_lang('AccountURLInactive');
 				break;
 		}
 	}
@@ -548,20 +554,20 @@ function handle_login_failed() {
 *	Adds a form to let users login
 *	@version 1.1
 */
-function display_login_form() 
-{
+function display_login_form() {
 	$form = new FormValidator('formLogin');
-	$form->addElement('text','login',get_lang('UserName'),array('size'=>17));
-	$form->addElement('password','password',get_lang('Pass'),array('size'=>17));
-	$form->addElement('style_submit_button','submitAuth',get_lang('langEnter'), array('class'=>'login'));
+	$form->addElement('text', 'login', get_lang('UserName'), array('size' => 17));
+	$form->addElement('password', 'password', get_lang('Pass'), array('size' => 17));
+	$form->addElement('style_submit_button','submitAuth', get_lang('langEnter'), array('class' => 'login'));
 	$renderer =& $form->defaultRenderer();
 	$renderer->setElementTemplate('<div><label>{label}</label></div><div>{element}</div>');
 	$form->display();
-	if (api_get_setting('openid_authentication')=='true') {
-		include_once('main/auth/openid/login.php');
+	if (api_get_setting('openid_authentication') == 'true') {
+		include_once 'main/auth/openid/login.php';
 		echo '<div>'.openid_form().'</div>';
 	}
 }
+
 /**
  * Displays a link to the lost password section
  */
@@ -578,10 +584,10 @@ function display_lost_password_info() {
 */
 function display_anonymous_course_list() {
 	$ctok = $_SESSION['sec_token'];
-	$stok = Security::get_token();	
-	
+	$stok = Security::get_token();
+
 	//init
-	$user_identified = (api_get_user_id()>0 && !api_is_anonymous());
+	$user_identified = (api_get_user_id() > 0 && !api_is_anonymous());
 	$web_course_path = api_get_path(WEB_COURSE_PATH);
 	$category = Database::escape_string($_GET['category']);
 	global $setting_show_also_closed_courses;
@@ -596,21 +602,21 @@ function display_anonymous_course_list() {
 	$sql_get_course_list = "SELECT * FROM $main_course_table cours
 								WHERE category_code = '".Database::escape_string($_GET["category"])."'
 								ORDER BY title, UPPER(visual_code)";
-								
-	//showing only the courses of the current access_url_id								
+
+	//showing only the courses of the current access_url_id
 	global $_configuration;
-	if ($_configuration['multiple_access_urls']==true) {
+	if ($_configuration['multiple_access_urls'] == true) {
 		$url_access_id = api_get_current_access_url_id();
 		if ($url_access_id !=-1) {
-			$tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);			
-			$sql_get_course_list="SELECT * FROM $main_course_table as course INNER JOIN $tbl_url_rel_course as url_rel_course 
+			$tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+			$sql_get_course_list = "SELECT * FROM $main_course_table as course INNER JOIN $tbl_url_rel_course as url_rel_course
 					ON (url_rel_course.course_code=course.code)
 					WHERE access_url_id = $url_access_id AND category_code = '".Database::escape_string($_GET["category"])."' ORDER BY title, UPPER(visual_code)";
 		}
 	}
-	
+
 	//removed: AND cours.visibility='".COURSE_VISIBILITY_OPEN_WORLD."'
-	$sql_result_courses = api_sql_query($sql_get_course_list, __FILE__, __LINE__);
+	$sql_result_courses = Database::query($sql_get_course_list, __FILE__, __LINE__);
 
 	while ($course_result = Database::fetch_array($sql_result_courses)) {
 		$course_list[] = $course_result;
@@ -621,15 +627,15 @@ function display_anonymous_course_list() {
 	if($user_identified) {
 		if ($setting_show_also_closed_courses) {
 			$platform_visible_courses = '';
-		} else  {
-			$platform_visible_courses = "  AND (t3.visibility='".COURSE_VISIBILITY_OPEN_WORLD."' OR t3.visibility='".COURSE_VISIBILITY_OPEN_PLATFORM."' )";	
+		} else {
+			$platform_visible_courses = "  AND (t3.visibility='".COURSE_VISIBILITY_OPEN_WORLD."' OR t3.visibility='".COURSE_VISIBILITY_OPEN_PLATFORM."' )";
 		}
 	} else {
 		if ($setting_show_also_closed_courses) {
 			$platform_visible_courses = '';
-		} else  {
-			$platform_visible_courses = "  AND (t3.visibility='".COURSE_VISIBILITY_OPEN_WORLD."' )";	
-		}				
+		} else {
+			$platform_visible_courses = "  AND (t3.visibility='".COURSE_VISIBILITY_OPEN_WORLD."' )";
+		}
 	}
 	$sqlGetSubCatList = "
 				SELECT t1.name,t1.code,t1.parent_id,t1.children_count,COUNT(DISTINCT t3.code) AS nbCourse
@@ -638,27 +644,27 @@ function display_anonymous_course_list() {
 				LEFT JOIN $main_course_table t3 ON (t3.category_code=t1.code $platform_visible_courses)
 				WHERE t1.parent_id ". (empty ($category) ? "IS NULL" : "='$category'")."
 				GROUP BY t1.name,t1.code,t1.parent_id,t1.children_count ORDER BY t1.tree_pos, t1.name";
-				
-					
-	//showing only the category of courses of the current access_url_id								
+
+
+	//showing only the category of courses of the current access_url_id
 	global $_configuration;
-	if ($_configuration['multiple_access_urls']==true) {
+	if ($_configuration['multiple_access_urls'] == true) {
 		$url_access_id = api_get_current_access_url_id();
-		if ($url_access_id !=-1) {
-			$tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);	
+		if ($url_access_id != -1) {
+			$tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 			$sqlGetSubCatList = "
 				SELECT t1.name,t1.code,t1.parent_id,t1.children_count,COUNT(DISTINCT t3.code) AS nbCourse
 				FROM $main_category_table t1
 				LEFT JOIN $main_category_table t2 ON t1.code=t2.parent_id
 				LEFT JOIN $main_course_table t3 ON (t3.category_code=t1.code $platform_visible_courses)
-				INNER JOIN $tbl_url_rel_course as url_rel_course 
+				INNER JOIN $tbl_url_rel_course as url_rel_course
 					ON (url_rel_course.course_code=t3.code)
-				WHERE access_url_id = $url_access_id AND t1.parent_id ". (empty ($category) ? "IS NULL" : "='$category'")."				
+				WHERE access_url_id = $url_access_id AND t1.parent_id ".(empty($category) ? "IS NULL" : "='$category'")."
 				GROUP BY t1.name,t1.code,t1.parent_id,t1.children_count ORDER BY t1.tree_pos, t1.name";
 		}
 	}
-	
-	$resCats = api_sql_query($sqlGetSubCatList, __FILE__, __LINE__);
+
+	$resCats = Database::query($sqlGetSubCatList, __FILE__, __LINE__);
 	$thereIsSubCat = false;
 	if (Database::num_rows($resCats) > 0) {
 		$htmlListCat = "<h4 style=\"margin-top: 0px;\">".get_lang("CatList")."</h4>"."<ul>";
@@ -690,14 +696,14 @@ function display_anonymous_course_list() {
 					$htmlListCat .= $catLine['name'];
 					$htmlListCat .= "</li>\n";
 					$thereIsSubCat = true;
-				}//else don't set thereIsSubCat to true to avoid printing things if not requested
+				} //else don't set thereIsSubCat to true to avoid printing things if not requested
 			} else {
 				$htmlTitre = "<p>";
 				if (api_get_setting('show_back_link_on_top_of_tree') == 'true') {
 					$htmlTitre .= "<a href=\"".api_get_self()."\">"."&lt;&lt; ".get_lang("BackToHomePage")."</a>";
 				}
 				if (!is_null($catLine['parent_id']) || (api_get_setting('show_back_link_on_top_of_tree') <> 'true' && !is_null($catLine['code']))) {
-					$htmlTitre .= "<a href=\"".api_get_self()."?category=".$catLine['parent_id']."\">"."&lt;&lt; ".get_lang("Up")."</a>";
+					$htmlTitre .= "<a href=\"".api_get_self()."?category=".$catLine['parent_id']."\">"."&lt;&lt; ".get_lang('Up')."</a>";
 				}
 				$htmlTitre .= "</p>\n";
 				if ($category != "" && !is_null($catLine['code'])) {
@@ -724,32 +730,32 @@ function display_anonymous_course_list() {
 			$courses_list_string .= "<hr size=\"1\" noshade=\"noshade\">\n";
 		}
 		$courses_list_string .= "<h4 style=\"margin-top: 0px;\">".get_lang("CourseList")."</h4>\n"."<ul>\n";
-		
+
 		if (api_get_user_id()) {
 			$courses_of_user = get_courses_of_user(api_get_user_id());
 		}
-		
-		foreach ($course_list AS $course) {
+
+		foreach ($course_list as $course) {
 			// $setting_show_also_closed_courses
-			
-			if ($setting_show_also_closed_courses==false) {
-				// if we do not show the closed courses 
+
+			if ($setting_show_also_closed_courses == false) {
+				// if we do not show the closed courses
 				// we only show the courses that are open to the world (to everybody)
 				// and the courses that are open to the platform (if the current user is a registered user
-				if( ($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM) OR ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD)) {
+				if( ($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM) || ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD)) {
 					$courses_shown++;
 					$courses_list_string .= "<li>\n";
 				$courses_list_string .= "<a href=\"".$web_course_path.$course['directory']."/\">".$course['title']."</a><br />";
-				if (get_setting("display_coursecode_in_courselist") == "true") {
+				if (api_get_setting('display_coursecode_in_courselist') == 'true') {
 					$courses_list_string .= $course['visual_code'];
 				}
-				if (get_setting("display_coursecode_in_courselist") == "true" AND get_setting("display_teacher_in_courselist") == "true") {
-					$courses_list_string .= " - ";
+				if (api_get_setting('display_coursecode_in_courselist') == 'true' && api_get_setting('display_teacher_in_courselist') == 'true') {
+					$courses_list_string .= ' - ';
 				}
-				if (get_setting("display_teacher_in_courselist") == "true") {
+				if (api_get_setting('display_teacher_in_courselist') == 'true') {
 					$courses_list_string .= $course['tutor_name'];
-				}				
-					if (api_get_setting('show_different_course_language') == 'true' && $course['course_language'] <> api_get_setting('platformLanguage')) {
+				}
+					if (api_get_setting('show_different_course_language') == 'true' && $course['course_language'] != api_get_setting('platformLanguage')) {
 						$courses_list_string .= ' - '.$course['course_language'];
 					}
 					$courses_list_string .= "</li>\n";
@@ -762,54 +768,53 @@ function display_anonymous_course_list() {
 			// 3. the user is logged in and the user is subscribed to the course and the course visibility is not COURSE_VISIBILITY_CLOSED
 			// 4. the user is logged in and the user is course admin of te course (regardless of the course visibility setting)
 			// 5. the user is the platform admin api_is_platform_admin()
-			// 
+			//
 			else {
 				$courses_shown++;
 				$courses_list_string .= "<li>\n";
-					if ( $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD
-							OR ($user_identified AND $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM) 
-							OR ($user_identified AND key_exists($course['code'],$courses_of_user) AND $course['visibility'] <> COURSE_VISIBILITY_CLOSED) 
-							OR $courses_of_user[$course['code']]['status'] == '1'
-							OR api_is_platform_admin()) {
-						$courses_list_string .= "<a href=\"".$web_course_path.$course['directory']."/\">";
-					}
-					$courses_list_string .= $course['title'];
-					if ( $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD
-							OR ($user_identified AND $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM) 
-							OR ($user_identified AND key_exists($course['code'],$courses_of_user) AND $course['visibility'] <> COURSE_VISIBILITY_CLOSED) 
-							OR $courses_of_user[$course['code']]['status'] == '1'
-							OR api_is_platform_admin()) {
-						$courses_list_string .="</a><br />";
-					}
-					if (get_setting("display_coursecode_in_courselist") == "true") {
-						$courses_list_string .= $course['visual_code'];
-					}
-					if (get_setting("display_coursecode_in_courselist") == "true" AND get_setting("display_teacher_in_courselist") == "true") {
-						$courses_list_string .= " - ";
-					}
-					if (get_setting("display_teacher_in_courselist") == "true")
-					{
-						$courses_list_string .= $course['tutor_name'];
-					}				
-				if (api_get_setting('show_different_course_language') == 'true' && $course['course_language'] <> api_get_setting('platformLanguage')) {
+				if ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD
+						|| ($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
+						|| ($user_identified && key_exists($course['code'], $courses_of_user) && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
+						|| $courses_of_user[$course['code']]['status'] == '1'
+						|| api_is_platform_admin()) {
+					$courses_list_string .= "<a href=\"".$web_course_path.$course['directory']."/\">";
+				}
+				$courses_list_string .= $course['title'];
+				if ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD
+						|| ($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
+						|| ($user_identified && key_exists($course['code'], $courses_of_user) && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
+						|| $courses_of_user[$course['code']]['status'] == '1'
+						|| api_is_platform_admin()) {
+					$courses_list_string .= "</a><br />";
+				}
+				if (api_get_setting('display_coursecode_in_courselist') == 'true') {
+					$courses_list_string .= $course['visual_code'];
+				}
+				if (api_get_setting('display_coursecode_in_courselist') == 'true' && api_get_setting('display_teacher_in_courselist') == 'true') {
+					$courses_list_string .= ' - ';
+				}
+				if (api_get_setting('display_teacher_in_courselist') == 'true') {
+					$courses_list_string .= $course['tutor_name'];
+				}
+				if (api_get_setting('show_different_course_language') == 'true' && $course['course_language'] != api_get_setting('platformLanguage')) {
 					$courses_list_string .= ' - '.$course['course_language'];
 				}
-					if (api_get_setting('show_different_course_language') == 'true' && $course['course_language'] <> api_get_setting('platformLanguage')) {
-						$courses_list_string .= ' - '.$course['course_language'];
-					}
-					// We display a subscription link if 
-					// 1. it is allowed to register for the course and if the course is not already in the courselist of the user and if the user is identiefied
-					// 2
-					if ($user_identified AND !key_exists($course['code'],$courses_of_user)) {
-						if ($course['subscribe'] == '1') {
-							$courses_list_string .= "<form action=\"main/auth/courses.php?action=subscribe&category=".$_GET['category']."\" method=\"post\">";
-							$courses_list_string .= '<input type="hidden" name="sec_token" value="'.$stok.'">';
-							$courses_list_string .= "<input type=\"hidden\" name=\"subscribe\" value=\"".$course['code']."\" />";
-							$courses_list_string .= "<input type=\"image\" name=\"unsub\" src=\"main/img/enroll.gif\" alt=\"".get_lang("Subscribe")."\" />".get_lang("Subscribe")."</form>";
-						} else {
-							$courses_list_string .= '<br />'.get_lang("SubscribingNotAllowed");
-						}
+				if (api_get_setting('show_different_course_language') == 'true' && $course['course_language'] != api_get_setting('platformLanguage')) {
+					$courses_list_string .= ' - '.$course['course_language'];
+				}
+				// We display a subscription link if
+				// 1. it is allowed to register for the course and if the course is not already in the courselist of the user and if the user is identiefied
+				// 2
+				if ($user_identified && !key_exists($course['code'], $courses_of_user)) {
+					if ($course['subscribe'] == '1') {
+						$courses_list_string .= "<form action=\"main/auth/courses.php?action=subscribe&category=".$_GET['category']."\" method=\"post\">";
+						$courses_list_string .= '<input type="hidden" name="sec_token" value="'.$stok.'">';
+						$courses_list_string .= "<input type=\"hidden\" name=\"subscribe\" value=\"".$course['code']."\" />";
+						$courses_list_string .= "<input type=\"image\" name=\"unsub\" src=\"main/img/enroll.gif\" alt=\"".get_lang("Subscribe")."\" />".get_lang("Subscribe")."</form>";
+					} else {
+						$courses_list_string .= '<br />'.get_lang("SubscribingNotAllowed");
 					}
+				}
 				$courses_list_string .= "</li>\n";
 			}
 		}
@@ -818,11 +823,11 @@ function display_anonymous_course_list() {
 		// echo "<blockquote>",get_lang('_No_course_publicly_available'),"</blockquote>\n";
 	}
 	if ($courses_shown > 0) { //only display the list of courses and categories if there was more than
-	  // 0 courses visible to the world (we're in the anonymous list here)
+		// 0 courses visible to the world (we're in the anonymous list here)
 		echo $courses_list_string;
 	}
-	if ($category != "") {
-		echo "<p>", "<a href=\"".api_get_self()."\"><b></b> ", Display :: return_icon('back.png', get_lang('BackToHomePage')),get_lang("BackToHomePage"), "</a>", "</p>\n";
+	if ($category != '') {
+		echo "<p>", "<a href=\"".api_get_self()."\"> ", Display :: return_icon('back.png', get_lang('BackToHomePage')), get_lang("BackToHomePage"), "</a>", "</p>\n";
 	}
 }
 
@@ -836,20 +841,20 @@ function get_courses_of_user($user_id) {
 	$table_course		= Database::get_main_table(TABLE_MAIN_COURSE);
 	$table_course_user	= Database::get_main_table(TABLE_MAIN_COURSE_USER);
 
-	// Secondly we select the courses that are in a category (user_course_cat<>0) and sort these according to the sort of the category
+	// Secondly we select the courses that are in a category (user_course_cat <> 0) and sort these according to the sort of the category
 	$user_id = intval($user_id);
-	$sql_select_courses="SELECT course.code k, course.visual_code  vc, course.subscribe subscr, course.unsubscribe unsubscr,
+	$sql_select_courses = "SELECT course.code k, course.visual_code  vc, course.subscribe subscr, course.unsubscribe unsubscr,
 								course.title i, course.tutor_name t, course.db_name db, course.directory dir, course_rel_user.status status,
 								course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
-		                        FROM    $table_course       course,
+								FROM    $table_course       course,
 										$table_course_user  course_rel_user
-		                        WHERE course.code = course_rel_user.course_code
-		                        AND   course_rel_user.user_id = '".$user_id."'
-		                        ORDER BY course_rel_user.sort ASC";
-	$result = api_sql_query($sql_select_courses,__FILE__,__LINE__);
-	while ($row=Database::fetch_array($result)) {
+								WHERE course.code = course_rel_user.course_code
+								AND   course_rel_user.user_id = '".$user_id."'
+								ORDER BY course_rel_user.sort ASC";
+	$result = Database::query($sql_select_courses, __FILE__, __LINE__);
+	while ($row = Database::fetch_array($result)) {
 		// we only need the database name of the course
-		$courses[$row['k']] = array("db"=> $row['db'], "code" => $row['k'], "visual_code" => $row['vc'], "title" => $row['i'], "directory" => $row['dir'], "status" => $row['status'], "tutor" => $row['t'], "subscribe" => $row['subscr'], "unsubscribe" => $row['unsubscr'], "sort" => $row['sort'], "user_course_category" => $row['user_course_cat']);
+		$courses[$row['k']] = array('db' => $row['db'], 'code' => $row['k'], 'visual_code' => $row['vc'], 'title' => $row['i'], 'directory' => $row['dir'], 'status' => $row['status'], 'tutor' => $row['t'], 'subscribe' => $row['subscr'], 'unsubscribe' => $row['unsubscr'], 'sort' => $row['sort'], 'user_course_category' => $row['user_course_cat']);
 	}
 	return $courses;
 }

+ 7 - 7
main/WCAG/index.html

@@ -1,7 +1,7 @@
-<html>
-<head>
-<meta http-equiv="refresh" content="0; url=../gradebook.php">
-</head>
-<body>
-</body>
-</html>
+<html>
+<head>
+<meta http-equiv="refresh" content="0; url=../gradebook.php">
+</head>
+<body>
+</body>
+</html>

+ 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 = api_sql_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 '".strtolower($first_letter_course)."%'
-		ORDER BY title, code DESC ";
-		
-$result = api_sql_query($sql, __FILE__, __LINE__);
-$db_courses = api_store_result($result);
-unset($result);
-
-$sql = "SELECT id, url FROM $tbl_access_url  WHERE active=1 ORDER BY url";
-$result = api_sql_query($sql, __FILE__, __LINE__);
-$db_urls = api_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 = api_sql_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 '".strtolower($first_letter_session)."%'
-		ORDER BY name DESC ";
-		
-$result = api_sql_query($sql, __FILE__, __LINE__);
-$db_sessions = api_store_result($result);
-unset($result);
-
-$sql = "SELECT id, url FROM $tbl_access_url  WHERE active=1 ORDER BY url";
-$result = api_sql_query($sql, __FILE__, __LINE__);
-$db_urls = api_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 - 200
main/admin/access_url_add_users_to_url.php

@@ -1,201 +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 = api_sql_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);
-
-$sql = "SELECT user_id,lastname,firstname,username FROM $tbl_user 
-	    WHERE lastname LIKE '".$first_letter_user."%' OR lastname LIKE '".strtolower($first_letter_user)."%' 
-		ORDER BY ". (count($users) > 0 ? "(user_id IN(".implode(',', $users).")) DESC," : "")." lastname";
-$result = api_sql_query($sql, __FILE__, __LINE__);
-$db_users = api_store_result($result);
-unset($result);
-
-$sql = "SELECT id, url FROM $tbl_access_url  WHERE active=1 ORDER BY url"; 
-$result = api_sql_query($sql, __FILE__, __LINE__);
-$db_urls = api_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 $user['lastname'].' '.$user['firstname'].' ('.$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 = api_sql_query($sql, __FILE__, __LINE__);		
-        $i=0;        
-		while ($course = Database :: fetch_array($rs)) {
-			$i++;
-            if ($i<=10) {
-			     $return .= '<a href="#" onclick="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=api_sql_query($sql,__FILE__,__LINE__);	
-	$courses=api_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 = api_sql_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=api_sql_query($sql,__FILE__,__LINE__);	
-	$sessions=api_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 - 467
main/admin/access_url_edit_users_to_url.php

@@ -1,467 +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
-		$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 BY lastname, firstname, username
-				LIMIT 11';
-				
-		$rs = api_sql_query($sql, __FILE__, __LINE__);		
-        $i=0;
-        
-		while ($user = Database :: fetch_array($rs)) {
-			$i++;
-            if ($i<=10) {
-			     $return .= '<a href="#" onclick="add_user_to_url(\''.addslashes($user['user_id']).'\',\''.addslashes($user['lastname']).' '.addslashes($user['firstname']).' ('.addslashes($user['username']).')'.'\')">'.$user['lastname'].' '.$user['firstname'].' ('.$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 ;
-		}
-	}	
-	$sql="SELECT u.user_id, lastname, firstname, username
-	  	  	FROM $tbl_user u	
-			ORDER BY lastname,firstname,username";	
-	$result=api_sql_query($sql,__FILE__,__LINE__);	
-	$Users=api_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 $enreg['lastname'].' '.$enreg['firstname'].' ('.$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 $enreg['lastname'].' '.$enreg['firstname'].' ('.$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();
+?>

+ 0 - 27
main/admin/add_by_ajax_sub_language.inc.php

@@ -1,27 +0,0 @@
-<?php
-/* For licensing terms, see /dokeos_license.txt */
-
-// including the global dokeos file
-require_once '../inc/global.inc.php';
-require_once 'sub_language.class.php';
-/*
- * search a term and return description from a glossary
- */
-global $charset;
-$new_language		= Security::remove_XSS($_POST['new_language']);
-$language_variable	= Security::remove_XSS($_POST['variable_language']);
-$file_language		= Security::remove_XSS($_POST['file_language']);
-$id_language		= Security::remove_XSS($_POST['id']);
-$sub_language_id	= Security::remove_XSS($_POST['sublanguage_id']);
- 
-$all_data_of_language=SubLanguageManager::get_all_information_of_sub_language($id_language,$sub_language_id);
-$dokeos_path_folder=api_get_path('SYS_LANG_PATH').$all_data_of_language['dokeos_folder'].'/'.$file_language;
-$all_file_of_directory=SubLanguageManager::get_all_language_variable_in_file($dokeos_path_folder);
-SubLanguageManager::add_file_in_language_directory ($dokeos_path_folder);
-
-//update variable language
-$all_file_of_directory[$language_variable]="\"".mb_convert_encoding($new_language,$charset,'UTF-8')."\";";
-
-foreach ($all_file_of_directory as $key_value=>$value_info) {
-	SubLanguageManager::write_data_in_file ($dokeos_path_folder,$value_info,$key_value);
-}

+ 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 = api_sql_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 = api_sql_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 = api_sql_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="#" onclick="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 = api_sql_query("SELECT id_coach FROM $tbl_session WHERE id=$id_session");
-	$id_coach = Database::fetch_array($id_coach);
-	$id_coach = $id_coach[0];
-
-	$rs = api_sql_query("SELECT course_code FROM $tbl_session_rel_course WHERE id_session=$id_session");
-	$existingCourses = api_store_result($rs);
-
-	$sql="SELECT id_user
-		FROM $tbl_session_rel_user
-		WHERE id_session = $id_session";
-	$result=api_sql_query($sql,__FILE__,__LINE__);
-	$UserList=api_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')";
-			api_sql_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')";
-				api_sql_query($sql_insert,__FILE__,__LINE__);
-				if(Database::affected_rows()) {
-					$nbr_users++;
-				}
-			}
-			api_sql_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)){
-			api_sql_query("DELETE FROM $tbl_session_rel_course WHERE course_code='".$existingCourse['course_code']."' AND id_session=$id_session");
-			api_sql_query("DELETE FROM $tbl_session_rel_course_rel_user WHERE course_code='".$existingCourse['course_code']."' AND id_session=$id_session");
-
-		}
-	}
-	$nbr_courses=count($CourseList);
-	api_sql_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 = api_sql_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=api_sql_query($sql,__FILE__,__LINE__);	
-	$Courses=api_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=api_sql_query($sql,__FILE__,__LINE__);	
-	$Courses=api_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 $_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 = Database::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();
+?>

+ 320 - 0
main/admin/add_many_session_to_category.php

@@ -0,0 +1,320 @@
+<?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 -> 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_category				= Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
+
+$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('SubscribeSessionsToCategory');
+$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, $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');
+
+		$sql = 'SELECT * FROM '.$tbl_session.' WHERE name LIKE "'.$needle.'%" ORDER BY id';
+
+		$rs = Database::query($sql, __FILE__, __LINE__);
+		$course_list = array();
+
+		$return .= '<select id="origin" name="NoSessionCategoryList[]" multiple="multiple" size="20" style="width:340px;">';
+		while($course = Database :: fetch_array($rs)) {
+			$course_list[] = $course['id'];
+			$return .= '<option value="'.$course['id'].'" title="'.htmlspecialchars($course['name'],ENT_QUOTES).'">'.$course['name'].'</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 send() {
+	if (document.formulaire.CategorySessionId.value!=0) {
+		//alert(document.formulaire.CategorySessionId.value);
+		document.formulaire.formSent.value=0;
+		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>';
+
+$formSent=0;
+$errorMsg = $firstLetterCourse = $firstLetterSession='';
+$CourseList=$SessionList=array();
+$courses=$sessions=array();
+$noPHP_SELF=true;
+
+if ($_POST['formSent']) {
+	$formSent=$_POST['formSent'];
+	$SessionCategoryList = $_POST['SessionCategoryList'];
+	$Categoryid = intval($_POST['CategorySessionId']);
+	if($Categoryid != 0 && count($SessionCategoryList)>0 ){
+		$session_id = join(',', $SessionCategoryList);
+		$sql = "UPDATE $tbl_session SET session_category_id = $Categoryid WHERE id in ($session_id) ";
+		Database::query($sql,__FILE__,__LINE__);
+		header('Location: session_list.php?id_category='.$Categoryid);
+	} else {
+		header('Location: add_many_session_to_category.php?msg=error');
+	}
+}
+
+if(isset($_GET['msg']) && $_GET['msg']=='error'){
+	$errorMsg = get_lang('MsgErrorSessionCategory');
+}
+// display the dokeos header
+Display::display_header($tool_name);
+
+echo '<div class="row"><div class="form_header">'.$tool_name.' </div></div><br />';
+
+// *******************
+$where ='';
+$rows_category_session = array();
+if(isset($_POST['CategorySessionId']) && $_POST['formSent'] == 0 ){
+	$where = 'WHERE session_category_id !='.intval($_POST['CategorySessionId']);
+	$sql = 'SELECT id, name  FROM '.$tbl_session .' WHERE session_category_id ='.intval($_POST['CategorySessionId']).' ORDER BY name';
+	$result=Database::query($sql,__FILE__,__LINE__);
+	$rows_category_session = Database::store_result($result);
+}
+
+$sql = "SELECT id, name  FROM $tbl_session_category ORDER BY name";
+$result=Database::query($sql,__FILE__,__LINE__);
+$rows_session_category = Database::store_result($result);
+
+$sql = "SELECT id, name  FROM $tbl_session $where ORDER BY name";
+$result=Database::query($sql,__FILE__,__LINE__);
+$rows_session = Database::store_result($result);
+?>
+<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>?page=<?php echo $_GET['page']; 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_error_message($errorMsg); //main API
+}
+?>
+<table border="0" cellpadding="5" cellspacing="0" width="100%" align="center">
+<tr>
+	<td align="left"></td>
+	<td align="left"></td>
+	<td width="" align="center"> <b><?php echo get_lang('SessionCategoryName') ?> :</b><br />
+	<select name="CategorySessionId" style="width: 320px;" onchange="javascript:send();" >
+		<option value="0" selected> </option>
+		<?php
+		foreach($rows_session_category as $category) {
+			if($category['id'] == $_POST['CategorySessionId'])
+  			echo '<option value="'.$category['id'].'" selected>'.$category['name'].'</option>';
+  			else
+  			echo '<option value="'.$category['id'].'">'.$category['name'].'</option>';
+		}
+  		?>
+  	</select>
+	</td>
+</tr>
+<tr>
+  <td width="45%" align="center"><b><?php echo get_lang('SessionListInPlatform') ?> :</b></td>
+
+  <td width="10%">&nbsp;</td>
+  <td align="center" width="45%"><b><?php echo get_lang('SessionListInCategory') ?> :</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">
+	<div id="ajax_list_courses_multiple">
+	<select id="origin" name="NoSessionCategoryList[]" multiple="multiple" size="20" style="width:320px;">
+	<?php
+	foreach($rows_session as $enreg) {
+	?>
+		<option value="<?php echo $enreg['id']; ?>" <?php echo 'title="'.htmlspecialchars($enreg['name'],ENT_QUOTES).'"'; if(in_array($enreg['id'],$CourseList)) echo 'selected="selected"'; ?>><?php echo $enreg['name']; ?></option>
+	<?php } ?>
+	</select></div>
+<?php unset($nosessionCourses); ?>
+  </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
+		echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('SubscribeSessionsToCategory').'</button>';
+	?>
+  </td>
+  <td width="45%" align="center">
+  <select id='destination' name="SessionCategoryList[]" multiple="multiple" size="20" style="width:320px;">
+	<?php
+	foreach($rows_category_session as $enreg) {
+	?>
+		<option value="<?php echo $enreg['id']; ?>" <?php echo 'title="'.htmlspecialchars($enreg['name'],ENT_QUOTES).'"'; if(in_array($enreg['id'],$CourseList)) echo 'selected="selected"'; ?>><?php echo $enreg['name']; ?></option>
+	<?php } ?>
+  </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();
+?>

+ 145 - 141
main/admin/add_users_to_session.php

@@ -53,7 +53,7 @@ if(isset($_REQUEST['add_type']) && $_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 = api_sql_query($sql,__FILE__,__LINE__);
+	$rs = Database::query($sql,__FILE__,__LINE__);
 	if(Database::result($rs,0,0)!=$_user['user_id']) {
 		api_not_allowed(true);
 	}
@@ -71,96 +71,99 @@ if (is_array($extra_field_list)) {
 			$new_field_list[] = array('name'=> $extra_field[3], 'variable'=>$extra_field[1], 'data'=> $extra_field[9]);
 		}
 	}
-}	
-	
+}
+
 function search_users($needle,$type)
 {
 	global $tbl_user,$tbl_session_rel_user,$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 = Database::escape_string($needle);
 		$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';
 		$cond_user_id = '';
 		if (!empty($id_session)) {
 		$id_session = Database::escape_string($id_session);
 			// check id_user from session_rel_user table
 			$sql = 'SELECT id_user FROM '.$tbl_session_rel_user.' WHERE id_session ="'.(int)$id_session.'"';
-			$res = api_sql_query($sql,__FILE__,__LINE__);
+			$res = Database::query($sql,__FILE__,__LINE__);
 			$user_ids = array();
 			if (Database::num_rows($res) > 0) {
 				while ($row = Database::fetch_row($res)) {
-					$user_ids[] = (int)$row[0];  
+					$user_ids[] = (int)$row[0];
 				}
 			}
-			if (count($user_ids) > 0){	
+			if (count($user_ids) > 0){
 				$cond_user_id = ' AND user_id NOT IN('.implode(",",$user_ids).')';
-			}				
-		} 
-		
+			}
+		}
+
 		if ($type == 'single') {
 			// search users where username or firstname or lastname begins likes $needle
 			$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 BY lastname, firstname, username
-					LIMIT 11';
-		} else {						
+				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 lastname LIKE "'.$needle.'%" AND user_id<>"'.$user_anonymous.'"'.$cond_user_id.' 
-					ORDER BY lastname, firstname, username';	
+					WHERE '.(api_sort_by_first_name() ? 'firstname' : 'lastname').' LIKE "'.$needle.'%" AND user_id<>"'.$user_anonymous.'"'.$cond_user_id.
+					$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);	
+
+		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){
-				if ($type == 'single') {		
-					$sql = 'SELECT user.user_id, username, lastname, firstname FROM '.$tbl_user.' user 
+				if ($type == 'single') {
+					$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 (username LIKE "'.$needle.'%"
 					OR firstname LIKE "'.$needle.'%"
-					OR lastname LIKE "'.$needle.'%") AND user.user_id<>"'.$user_anonymous.'" 
-					ORDER BY lastname, firstname, username
-					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 
+					$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 lastname LIKE "'.$needle.'%" AND user.user_id<>"'.$user_anonymous.'"'.$cond_user_id.'  
-					ORDER BY lastname, firstname, username';					
-				}				
-				
+					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;
+				}
+
 			}
 		}
-				
-		$rs = api_sql_query($sql, __FILE__, __LINE__);		
-        $i=0;		
-		if ($type=='single') {			
+
+		$rs = Database::query($sql, __FILE__, __LINE__);
+        $i=0;
+		if ($type=='single') {
 			while ($user = Database :: fetch_array($rs)) {
 	            $i++;
 	            if ($i<=10) {
-				     $return .= '<a href="#" onclick="add_user_to_session(\''.$user['user_id'].'\',\''.$user['lastname'].' '.$user['firstname'].' ('.$user['username'].')'.'\')">'.$user['lastname'].' '.$user['firstname'].' ('.$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 />';
 	            }
 			}
-			
+
 			$xajax_response -> addAssign('ajax_list_users_single','innerHTML',api_utf8_encode($return));
-				
+
 		} else {
 			global $nosessionUsersList;
 			$return .= '<select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:360px;">';
-			while ($user = Database :: fetch_array($rs)) {				
-	            $return .= '<option value="'.$user['user_id'].'">'.$user['lastname'].' '.$user['firstname'].' ('.$user['username'].')</option>';				     	            
+			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>';
 			}
 			$return .= '</select>';
 			$xajax_response -> addAssign('ajax_list_users_multiple','innerHTML',api_utf8_encode($return));
@@ -179,19 +182,19 @@ function add_user_to_session (code, content) {
 
 	document.getElementById("user_to_add").value = "";
 	document.getElementById("ajax_list_users_single").innerHTML = "";
-	
+
 	destination = document.getElementById("destination_users");
-			
+
 	for (i=0;i<destination.length;i++) {
 		if(destination.options[i].text == content) {
 				return false;
-		} 
-	}		
-			
-	destination.options[destination.length] = new Option(content,code);	
+		}
+	}
+
+	destination.options[destination.length] = new Option(content,code);
 	destination.selectedIndex = -1;
 	sortOptions(destination.options);
-	
+
 }
 function remove_item(origin)
 {
@@ -204,15 +207,15 @@ function remove_item(origin)
 }
 
 function validate_filter() {
-	
+
 		document.formulaire.add_type.value = \''.$add_type.'\';
-		document.formulaire.form_sent.value=0;				
+		document.formulaire.form_sent.value=0;
 		document.formulaire.submit();
-		
+
 }
-			
 
-	
+
+
 </script>';
 
 
@@ -233,18 +236,18 @@ if($_POST['form_sent']) {
 	}
 
 	if ($form_sent == 1) {
-		
+
 		SessionManager::suscribe_users_to_session($id_session,$UserList,true);
-		
+
 		//adding the session to the access_url_rel_session table
 		global $_configuration;
-		require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');	
-		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();			
-			UrlManager::add_session_to_url($id_session,$access_url_id);			
+		require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
+		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();
+			UrlManager::add_session_to_url($id_session,$access_url_id);
 		} else {
-			// we are filling by default the access_url_rel_session table 
+			// we are filling by default the access_url_rel_session table
 			UrlManager::add_session_to_url($id_session,1);
 		}
 		//if(empty($_GET['add']))
@@ -261,120 +264,121 @@ Display::display_header($tool_name);
 
 $nosessionUsersList = $sessionUsersList = array();
 /*$sql = 'SELECT COUNT(1) FROM '.$tbl_user;
-$rs = api_sql_query($sql, __FILE__, __LINE__);
+$rs = Database::query($sql, __FILE__, __LINE__);
 $count_courses = Database::result($rs, 0, 0);*/
 $ajax_search = $add_type == 'unique' ? true : false;
-global $_configuration;	
+global $_configuration;
 
+$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 BY lastname,firstname,username";
+				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);	
+	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){				
+		if ($access_url_id != -1){
 			$sql="SELECT u.user_id, lastname, firstname, username, id_session
-			FROM $tbl_user u 
+			FROM $tbl_user u
 			INNER JOIN $tbl_session_rel_user
 				ON $tbl_session_rel_user.id_user = u.user_id
 				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 BY lastname,firstname,username";
+				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";
 		}
-	}		
-	$result=api_sql_query($sql,__FILE__,__LINE__);	
-	$Users=api_store_result($result);	
+	}
+	$result=Database::query($sql,__FILE__,__LINE__);
+	$Users=Database::store_result($result);
 	foreach ($Users as $user) {
 		$sessionUsersList[$user['user_id']] = $user ;
 	}
 
 } else {
 		//Filter by Extra Fields
-		$use_extra_fields = false;		
+		$use_extra_fields = false;
 		if (is_array($extra_field_list)) {
-			if (is_array($new_field_list) && count($new_field_list)>0 ) {			
+			if (is_array($new_field_list) && count($new_field_list)>0 ) {
 				$result_list=array();
 				foreach ($new_field_list as $new_field) {
-					$varname = 'field_'.$new_field['variable'];				
+					$varname = 'field_'.$new_field['variable'];
 					if (Usermanager::is_extra_field_available($new_field['variable'])) {
-						if (isset($_POST[$varname]) && $_POST[$varname]!='0') {		
-							$use_extra_fields = true;																	
+						if (isset($_POST[$varname]) && $_POST[$varname]!='0') {
+							$use_extra_fields = true;
 							$extra_field_result[]= Usermanager::get_extra_user_data_by_value($new_field['variable'], $_POST[$varname]);
-						}								
+						}
 					}
-				}									
+				}
 			}
-		}	
+		}
 		if ($use_extra_fields) {
 			$final_result = array();
 			if (count($extra_field_result)>1) {
 				for($i=0;$i<count($extra_field_result)-1;$i++) {
 					if (is_array($extra_field_result[$i+1])) {
-						$final_result  = array_intersect($extra_field_result[$i],$extra_field_result[$i+1]);				
+						$final_result  = array_intersect($extra_field_result[$i],$extra_field_result[$i+1]);
 					}
 				}
-			} else {				
+			} else {
 				$final_result = $extra_field_result[0];
 			}
-					
+
 			$where_filter ='';
 			if ($_configuration['multiple_access_urls']==true) {
 				if (is_array($final_result) && count($final_result)>0) {
 					$where_filter = " AND u.user_id IN  ('".implode("','",$final_result)."') ";
 				} else {
 					//no results
-					$where_filter = " AND u.user_id  = -1"; 
+					$where_filter = " AND u.user_id  = -1";
 				}
-			} else {			
+			} else {
 				if (is_array($final_result) && count($final_result)>0) {
 					$where_filter = " WHERE u.user_id IN  ('".implode("','",$final_result)."') ";
 				} else {
 					//no results
-					$where_filter = " WHERE u.user_id  = -1"; 
+					$where_filter = " WHERE u.user_id  = -1";
 				}
-			}		
+			}
 		}
-		
-		if ($use_extra_fields) {		
+
+		if ($use_extra_fields) {
 			$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'
 				$where_filter
-				ORDER BY lastname,firstname,username";
-				
+			$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 BY lastname,firstname,username";
-		}			
-		if ($_configuration['multiple_access_urls']==true) {		
-			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
+				ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$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);
 			$access_url_id = api_get_current_access_url_id();
-			if ($access_url_id != -1){				
+			if ($access_url_id != -1){
 				$sql="SELECT  u.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'			 
-				INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id) 
+					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 BY lastname,firstname,username";			
+			$order_clause";
 			}
 		}
-		
-		$result=api_sql_query($sql,__FILE__,__LINE__);	
-		$Users=api_store_result($result);
+
+		$result=Database::query($sql,__FILE__,__LINE__);
+		$Users=Database::store_result($result);
 		//var_dump($_REQUEST['id_session']);
 		foreach ($Users as $user) {
-			if($user['id_session'] != $id_session)			
+			if($user['id_session'] != $id_session)
 				$nosessionUsersList[$user['user_id']] = $user ;
 		}
 		$user_anonymous=api_get_anonymous_id();
@@ -387,31 +391,31 @@ if ($ajax_search) {
 		$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 BY lastname,firstname,username";
-		
-		if ($_configuration['multiple_access_urls']==true) {		
-			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
+			ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$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);
 			$access_url_id = api_get_current_access_url_id();
-			if ($access_url_id != -1){				
+			if ($access_url_id != -1){
 				$sql="SELECT  u.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'			 
-				INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id) 
+					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 BY lastname,firstname,username";			
+				$order_clause";
 			}
-		}		
-	$result=api_sql_query($sql,__FILE__,__LINE__);	
-	$Users=api_store_result($result);
+		}
+	$result=Database::query($sql,__FILE__,__LINE__);
+	$Users=Database::store_result($result);
 
 	foreach($Users as $key_user_list =>$value_user_list) {
 		if ($Users[$key_user_list]['user_id']==$user_anonymous) {
 			unset($Users[$key_user_list]);
 			}
 		}
-		
+
 	foreach ($Users as $user) {
 		if($user['id_session'] == $id_session){
 			$sessionUsersList[$user['user_id']] = $user;
@@ -442,30 +446,30 @@ if ($add_type == 'multiple') {
 <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();"';}?>>
 
 <?php
-if ($add_type=='multiple') {	
+if ($add_type=='multiple') {
 	if (is_array($extra_field_list)) {
 		if (is_array($new_field_list) && count($new_field_list)>0 ) {
 			echo '<h3>'.get_lang('FilterUsers').'</h3>';
 			foreach ($new_field_list as $new_field) {
 				echo $new_field['name'];
-				$varname = 'field_'.$new_field['variable'];						
+				$varname = 'field_'.$new_field['variable'];
 				echo '&nbsp;<select name="'.$varname.'">';
-				echo '<option value="0">--'.get_lang('Select').'--</option>';	
+				echo '<option value="0">--'.get_lang('Select').'--</option>';
 				foreach	($new_field['data'] as $option) {
 					$checked='';
 					if (isset($_POST[$varname])) {
 						if ($_POST[$varname]==$option[1]) {
-							$checked = 'selected="true"'; 
+							$checked = 'selected="true"';
 						}
-					}							
-					echo '<option value="'.$option[1].'" '.$checked.'>'.$option[1].'</option>';		
+					}
+					echo '<option value="'.$option[1].'" '.$checked.'>'.$option[1].'</option>';
 				}
-				echo '</select>';	
+				echo '</select>';
 				echo '&nbsp;&nbsp;';
 			}
 			echo '<input type="button" value="'.get_lang('Filter').'" onclick="validate_filter()" />';
 			echo '<br /><br />';
-		}	
+		}
 	}
 }
 ?>
@@ -492,11 +496,11 @@ if(!empty($errorMsg)) {
 <tr>
 <td align="center">
 
-<?php echo get_lang('FirstLetterUser'); ?> : 
+<?php echo get_lang('FirstLetterUser'); ?> :
      <select name="firstLetterUser" onchange = "xajax_search_users(this.value,'multiple')" >
       <option value = "%">--</option>
       <?php
-        echo Display :: get_alphabet_options();        
+        echo Display :: get_alphabet_options();
       ?>
      </select>
 </td>
@@ -515,15 +519,15 @@ if(!empty($errorMsg)) {
 		<div id="ajax_list_users_single"></div>
 		<?php
   	  } else {
-  	  ?>  	
-  	  <div id="ajax_list_users_multiple">    	 	  
+  	  ?>
+  	  <div id="ajax_list_users_multiple">
 	  <select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:360px;">
 		<?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 $enreg['lastname'].' '.$enreg['firstname'].' ('.$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
-		}	
+		}
 		?>
 	  </select>
 	  </div>
@@ -544,8 +548,8 @@ if(!empty($errorMsg)) {
   	<button class="arrowr" type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))"></button>
 	<br /><br />
 	<button class="arrowl" type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))"></button>
-	<?php 
-  } 
+	<?php
+  }
   ?>
 	<br /><br /><br /><br /><br /><br />
   </td>
@@ -555,7 +559,7 @@ if(!empty($errorMsg)) {
 <?php
 foreach($sessionUsersList as $enreg) {
 ?>
-	<option value="<?php echo $enreg['user_id']; ?>"><?php echo $enreg['lastname'].' '.$enreg['firstname'].' ('.$enreg['username'].')'; ?></option>
+	<option value="<?php echo $enreg['user_id']; ?>"><?php echo $enreg['firstname'].' '.$enreg['lastname'].' ('.$enreg['username'].')'; ?></option>
 
 <?php
 }
@@ -573,8 +577,8 @@ unset($sessionUsersList);
 			echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('FinishSessionCreation').'</button>';
         } else {
             //@todo see that the call to "valide()" doesn't duplicate the onsubmit of the form (necessary to avoid delete on "enter" key pressed)
-			echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('SubscribeUsersToSession').'</button>'; 
-			
+			echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('SubscribeUsersToSession').'</button>';
+
         }
 		?>
 	</td>

+ 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 = array (get_lang("SundayShort"), get_lang("MondayShort"), get_lang("TuesdayShort"), get_lang("WednesdayShort"), get_lang("ThursdayShort"), get_lang("FridayShort"), get_lang("SaturdayShort"));
-// Defining the days of the week to allow translation of the days
-$DaysLong = array (get_lang("SundayLong"), get_lang("MondayLong"), get_lang("TuesdayLong"), get_lang("WednesdayLong"), get_lang("ThursdayLong"), get_lang("FridayLong"), get_lang("SaturdayLong"));
-// Defining the months of the year to allow translation of the months
-$MonthsLong = array (get_lang("JanuaryLong"), get_lang("FebruaryLong"), get_lang("MarchLong"), get_lang("AprilLong"), get_lang("MayLong"), get_lang("JuneLong"), get_lang("JulyLong"), get_lang("AugustLong"), get_lang("SeptemberLong"), get_lang("OctoberLong"), get_lang("NovemberLong"), get_lang("DecemberLong"));
-
-/*
-==============================================================================
-		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 = api_sql_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					= api_sql_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 = api_sql_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 = api_sql_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=api_sql_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=api_sql_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 = api_sql_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 = api_sql_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=api_sql_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 = api_sql_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 = api_sql_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 = api_sql_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 = api_sql_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 = api_sql_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 = api_sql_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 = api_sql_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 = api_sql_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=api_sql_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 = api_sql_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 = array (get_lang("SundayShort"), get_lang("MondayShort"), get_lang("TuesdayShort"), get_lang("WednesdayShort"), get_lang("ThursdayShort"), get_lang("FridayShort"), get_lang("SaturdayShort"));
-// Defining the days of the week to allow translation of the days. We use camelcase because these are arrays of language variables
-$DaysLong = array (get_lang("SundayLong"), get_lang("MondayLong"), get_lang("TuesdayLong"), get_lang("WednesdayLong"), get_lang("ThursdayLong"), get_lang("FridayLong"), get_lang("SaturdayLong"));
-// Defining the months of the year to allow translation of the months. We use camelcase because these are arrays of language variables
-$MonthsLong = array (get_lang("JanuaryLong"), get_lang("FebruaryLong"), get_lang("MarchLong"), get_lang("AprilLong"), get_lang("MayLong"), get_lang("JuneLong"), get_lang("JulyLong"), get_lang("AugustLong"), get_lang("SeptemberLong"), get_lang("OctoberLong"), get_lang("NovemberLong"), get_lang("DecemberLong"));
-
-// 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(Database::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();
+
+}
 ?>

+ 10 - 10
main/admin/calendar_ical_export.php

@@ -4,7 +4,7 @@
 ==============================================================================
 *	@package dokeos.admin
 *	@author Carlos Vargas
-*	This file is the calendar/ical_export.php 
+*	This file is the calendar/ical_export.php
 ==============================================================================
 */
 /**
@@ -32,11 +32,11 @@ $nameTools = get_lang('MyAgenda');
 
 // the variables for the days and the months
 // Defining the shorts for the days
-$DaysShort = array (get_lang("SundayShort"), get_lang("MondayShort"), get_lang("TuesdayShort"), get_lang("WednesdayShort"), get_lang("ThursdayShort"), get_lang("FridayShort"), get_lang("SaturdayShort"));
+$DaysShort = api_get_week_days_short();
 // Defining the days of the week to allow translation of the days
-$DaysLong = array (get_lang("SundayLong"), get_lang("MondayLong"), get_lang("TuesdayLong"), get_lang("WednesdayLong"), get_lang("ThursdayLong"), get_lang("FridayLong"), get_lang("SaturdayLong"));
+$DaysLong = api_get_week_days_long();
 // Defining the months of the year to allow translation of the months
-$MonthsLong = array (get_lang("JanuaryLong"), get_lang("FebruaryLong"), get_lang("MarchLong"), get_lang("AprilLong"), get_lang("MayLong"), get_lang("JuneLong"), get_lang("JulyLong"), get_lang("AugustLong"), get_lang("SeptemberLong"), get_lang("OctoberLong"), get_lang("NovemberLong"), get_lang("DecemberLong"));
+$MonthsLong = api_get_months_long();
 
 if(!empty($_GET['id']) && $_GET['id']==strval(intval($_GET['id'])))
 {
@@ -51,7 +51,7 @@ if(!empty($_GET['id']) && $_GET['id']==strval(intval($_GET['id'])))
 		switch($_GET['class'])
 		{
 			case 'public':
-				$vevent->setClass('PUBLIC');			
+				$vevent->setClass('PUBLIC');
 				break;
 			case 'private':
 				$vevent->setClass('PRIVATE');
@@ -60,7 +60,7 @@ if(!empty($_GET['id']) && $_GET['id']==strval(intval($_GET['id'])))
 				$vevent->setClass('CONFIDENTIAL');
 				break;
 			default:
-				$vevent->setClass('PRIVATE');				
+				$vevent->setClass('PRIVATE');
 				break;
 		}
 
@@ -74,7 +74,7 @@ if(!empty($_GET['id']) && $_GET['id']==strval(intval($_GET['id'])))
 				list($y,$m,$d,$h,$M,$s) = preg_split('/[\s:-]/',$ai['date']);
 				$vevent->setProperty('dtstart',array('year'=>$y,'month'=>$m,'day'=>$d,'hour'=>$h,'min'=>$M,'sec'=>$s));
 				if(empty($ai['enddate']))
-				{	
+				{
 					$y2=$y;$m2=$m;$d2=$d;$h2=$h;$M2=$M+15;$s2=$s;
 					if($M2>60){$M2=$M2-60;$h2+=1;}
 				}
@@ -104,7 +104,7 @@ if(!empty($_GET['id']) && $_GET['id']==strval(intval($_GET['id'])))
 				list($y,$m,$d,$h,$M,$s) = preg_split('/[\s:-]/',$ai['start_date']);
 				$vevent->setProperty('dtstart',array('year'=>$y,'month'=>$m,'day'=>$d,'hour'=>$h,'min'=>$M,'sec'=>$s));
 				if(empty($ai['end_date']))
-				{	
+				{
 					$y2=$y;$m2=$m;$d2=$d;$h2=$h;$M2=$M+15;$s2=$s;
 					if($M2>60){$M2=$M2-60;$h2+=1;}
 				}
@@ -134,13 +134,13 @@ if(!empty($_GET['id']) && $_GET['id']==strval(intval($_GET['id'])))
 				break;
 			default:
 				header('location:'.$_SERVER['REFERER_URI']);
-				die();	
+				die();
 		}
 	}
 }
 else
 {
 	header('location:'.$_SERVER['REFERER_URI']);
-	die();	
+	die();
 }
 ?>

+ 1 - 1
main/admin/calendar_tbl_change.js

@@ -60,7 +60,7 @@ function initCalendar() {
     if (!year && !month && !day) {
         day = window.opener.day;
         month = window.opener.month;
-        year  = window.opener.year;   
+        year  = window.opener.year;
         if (isNaN(year) || isNaN(month) || isNaN(day) || day == 0) {
             dt      = new Date();
             year    = dt.getFullYear();

+ 8 - 8
main/admin/calendar_view.php

@@ -22,12 +22,12 @@
 ==============================================================================
 *	@package dokeos.admin
 *	@author Carlos Vargas
-*	This file is the calendar/calendar.php 
+*	This file is the calendar/calendar.php
 ==============================================================================
 */
 // name of the language file that needs to be included
 $language_file = 'agenda';
-// including the claroline global 
+// including the claroline global
 include('../inc/global.inc.php');
 
 //session
@@ -36,11 +36,11 @@ if(isset($_GET['id_session']))
 
 // the variables for the days and the months
 // Defining the shorts for the days
-$DaysShort = array(get_lang("SundayShort"), get_lang("MondayShort"), get_lang("TuesdayShort"), get_lang("WednesdayShort"), get_lang("ThursdayShort"), get_lang("FridayShort"), get_lang("SaturdayShort")); 
+$DaysShort = api_get_week_days_short();
 // Defining the days of the week to allow translation of the days
-$DaysLong = array(get_lang("SundayLong"), get_lang("MondayLong"), get_lang("TuesdayLong"), get_lang("WednesdayLong"), get_lang("ThursdayLong"), get_lang("FridayLong"), get_lang("SaturdayLong")); 
+$DaysLong = api_get_week_days_long();
 // Defining the months of the year to allow translation of the months
-$MonthsLong = array(get_lang("JanuaryLong"), get_lang("FebruaryLong"), get_lang("MarchLong"), get_lang("AprilLong"), get_lang("MayLong"), get_lang("JuneLong"), get_lang("JulyLong"), get_lang("AugustLong"), get_lang("SeptemberLong"), get_lang("OctoberLong"), get_lang("NovemberLong"), get_lang("DecemberLong")); 
+$MonthsLong = api_get_months_long();
 
 ?>
 <html>
@@ -60,7 +60,7 @@ $MonthsLong = array(get_lang("JanuaryLong"), get_lang("FebruaryLong"), get_lang(
 }
 table.calendar
 {
-	width: 100%;	
+	width: 100%;
 	font-size: 11px;
 	font-family: verdana, arial, helvetica, sans-serif;
 }
@@ -79,12 +79,12 @@ table.calendar td
 {
 	width: 25px;
 	height: 25px;
-	background-color: #f5f5f5;	
+	background-color: #f5f5f5;
 	text-align: center;
 }
 table.calendar td.selected
 {
-	border: 1px solid #ff0000; 
+	border: 1px solid #ff0000;
 	background-color: #FFCECE;
 }
 table.calendar td a

+ 2 - 2
main/admin/calendar_view_print.php

@@ -22,7 +22,7 @@
 ==============================================================================
 *	@package dokeos.admin
 *	@author Carlos Vargas
-*	This file is the calendar/print.php 
+*	This file is the calendar/print.php
 ==============================================================================
 */
 // name of the language file that needs to be included
@@ -48,7 +48,7 @@ require('../inc/global.inc.php');
 $TABLEAGENDA 		= Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
 
 $sql 			= "SELECT * FROM $TABLEAGENDA WHERE id IN($id) ORDER BY start_date DESC";
-$result			= api_sql_query($sql,__FILE__,__LINE__);
+$result			= Database::query($sql,__FILE__,__LINE__);
 ?>
 
 <html>

+ 18 - 23
main/admin/class_add.php

@@ -29,48 +29,43 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
+// Language files that should be included.
 $language_file = 'admin';
 
-// resetting the course id
+// Resetting the course id.
 $cidReset = true;
 
-// including some necessary dokeos files
-require_once('../inc/global.inc.php');
-require_once (api_get_path(LIBRARY_PATH).'classmanager.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+// Including some necessary dokeos files.
+require_once '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'classmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 
-// setting the section (for the tabs)
+// Setting the section (for the tabs).
 $this_section = SECTION_PLATFORM_ADMIN;
 
-// Access restrictions
+// Access restrictions.
 api_protect_admin_script();
 
-// setting breadcrumbs
+// Setting breadcrumbs.
 $interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 
-// setting the name of the tool
+// Setting the name of the tool.
 $tool_name = get_lang("AddClasses");
 
 $form = new FormValidator('add_class');
-$form->add_textfield('name',get_lang('ClassName'));
-$form->addElement('submit','submit',get_lang('Ok'));
-if($form->validate())
-{
+$form->add_textfield('name', get_lang('ClassName'));
+$form->addElement('style_submit_button', 'submit', get_lang('Ok'), 'class="add"');
+if ($form->validate()) {
 	$values = $form->exportValues();
-	ClassManager :: create_class($values['name']);
+	ClassManager::create_class($values['name']);
 	header('Location: class_list.php');
 }
 
-// Displaying the header
+// Displaying the header.
 Display :: display_header($tool_name);
 
-// Displaying the form
+// Displaying the form.
 $form->display();
-/*
-==============================================================================
-		FOOTER 
-==============================================================================
-*/
+
+// Displaying the footer.
 Display :: display_footer();
-?>

+ 18 - 24
main/admin/class_edit.php

@@ -29,37 +29,36 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
+// Language files that should be included.
 $language_file = 'admin';
 
-// resetting the course id
+// Resetting the course id.
 $cidReset = true;
 
-// including some necessary dokeos files
-include ('../inc/global.inc.php');
-require_once(api_get_path(LIBRARY_PATH).'classmanager.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+// Including some necessary dokeos files.
+include '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'classmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 
-// setting the section (for the tabs)
-$this_section=SECTION_PLATFORM_ADMIN;
+// Setting the section (for the tabs).
+$this_section = SECTION_PLATFORM_ADMIN;
 
-// Access restrictions
+// Access restrictions.
 api_protect_admin_script();
 
-// setting breadcrumbs
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ("url" => "class_list.php", "name" => get_lang('AdminClasses'));
-
-// setting the name of the tool
-$tool_name = get_lang("AddClasses");
+// Setting breadcrumbs.
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'class_list.php', 'name' => get_lang('AdminClasses'));
 
+// Setting the name of the tool.
+$tool_name = get_lang('AddClasses');
 
 $tool_name = get_lang('ModifyClassInfo');
 $class_id = intval($_GET['idclass']);
 $class = ClassManager :: get_class_info($class_id);
-$form = new FormValidator('edit_class','post','class_edit.php?idclass='.$class_id);
+$form = new FormValidator('edit_class', 'post', 'class_edit.php?idclass='.$class_id);
 $form->add_textfield('name',get_lang('ClassName'));
-$form->addElement('submit','submit',get_lang('Ok'));
+$form->addElement('style_submit_button', 'submit', get_lang('Ok'), 'class="add"');
 $form->setDefaults(array('name'=>$class['name']));
 if($form->validate())
 {
@@ -68,14 +67,9 @@ if($form->validate())
 	header('Location: class_list.php');
 }
 
-
 Display :: display_header($tool_name);
 //api_display_tool_title($tool_name);
 $form->display();
-/*
-==============================================================================
-		FOOTER 
-==============================================================================
-*/
+
+// Displaying the footer.
 Display :: display_footer();
-?>

+ 48 - 59
main/admin/class_import.php

@@ -30,100 +30,91 @@
 *	@package dokeos.admin
 ==============================================================================
 */
+
 /**
- * Validate the imported data
+ * Validates imported data.
  */
-function validate_data($classes)
-{
+function validate_data($classes) {
 	$errors = array();
-	foreach($classes as $index => $class)
-	{
-		//1. Check if ClassName is available
-		if(!isset($class['ClassName']) || strlen(trim($class['ClassName'])) == 0)
-		{
-			$class['line'] = $index+2;
+	foreach ($classes as $index => $class) {
+		// 1. Check wheter ClassName is available.
+		if (!isset($class['ClassName']) || strlen(trim($class['ClassName'])) == 0) {
+			$class['line'] = $index + 2;
 			$class['error'] = get_lang('MissingClassName');
 			$errors[] = $class;
-		}	
-		//2. Check if class doesn't exist yet
-		else
-		{
-			if(ClassManager::class_name_exists($class['ClassName']))
-			{
-				$class['line'] = $index+2;
-				$class['error'] = get_lang('ClassNameExists');
-				$errors[] = $class;					
-			}	
+		}
+		// 2. Check whether class doesn't exist yet.
+		else {
+			if (ClassManager::class_name_exists($class['ClassName'])) {
+				$class['line'] = $index + 2;
+				$class['error'] = get_lang('ClassNameExists').' <strong>'.$class['ClassName'].'</strong>';
+				$errors[] = $class;
+			}
 		}
 	}
 	return $errors;
 }
+
 /**
  * Save imported class data to database
  */
-function save_data($classes)
-{
+function save_data($classes) {
 	$number_of_added_classes = 0;
-	foreach($classes as $index => $class)
-	{
-		if(ClassManager::create_class($class['ClassName']))
-		{
-			$number_of_added_classes++;	
-		}	
+	foreach ($classes as $index => $class) {
+		if (ClassManager::create_class($class['ClassName'])) {
+			$number_of_added_classes++;
+		}
 	}
 	return $number_of_added_classes;
 }
 
-
-
-// name of the language file that needs to be included 
+// Language files that should be included.
 $language_file = array ('admin', 'registration');
 
-// resetting the course id
+// Resetting the course id.
 $cidReset = true;
 
-// including some necessary dokeos files
-include ('../inc/global.inc.php');
-require_once (api_get_path(LIBRARY_PATH).'fileManage.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'classmanager.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'import.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+// Including some necessary dokeos files.
+include '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+require_once api_get_path(LIBRARY_PATH).'classmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'import.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 
-// setting the section (for the tabs)
+// Setting the section (for the tabs).
 $this_section = SECTION_PLATFORM_ADMIN;
 
-// Access restrictions
+// Access restrictions.
 api_protect_admin_script();
 
 // setting breadcrumbs
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 
 // Database Table Definitions
 
-// setting the name of the tool
+// Setting the name of the tool.
 $tool_name = get_lang('ImportClassListCSV');
 
-// Displaying the header
+// Displaying the header.
 Display :: display_header($tool_name);
 //api_display_tool_title($tool_name);
+
+set_time_limit(0);
+
 $form = new FormValidator('import_classes');
-$form->addElement('file','import_file',get_lang('ImportCSVFileLocation'));
-$form->addElement('submit','submit',get_lang('Ok'));
-if( $form->validate())
-{
+$form->addElement('file', 'import_file', get_lang('ImportCSVFileLocation'));
+$form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
+
+if ($form->validate()) {
 	$classes = Import::csv_to_array($_FILES['import_file']['tmp_name']);
 	$errors = validate_data($classes);
-	if (count($errors) == 0)
-	{
+	if (count($errors) == 0) {
 		$number_of_added_classes = save_data($classes);
 		Display::display_normal_message($number_of_added_classes.' '.get_lang('ClassesCreated'));
-	}		
-	else
-	{
+	} else {
 		$error_message = get_lang('ErrorsWhenImportingFile');
 		$error_message .= '<ul>';
-		foreach ($errors as $index => $error_class)
-		{
+		foreach ($errors as $index => $error_class) {
 			$error_message .= '<li>'.$error_class['error'].' ('.get_lang('Line').' '.$error_class['line'].')';
 			$error_message .= '</li>';
 		}
@@ -132,7 +123,9 @@ if( $form->validate())
 		Display :: display_error_message($error_message);
 	}
 }
+
 $form->display();
+
 ?>
 <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
 <blockquote>
@@ -145,10 +138,6 @@ $form->display();
  </pre>
 </blockquote>
 <?php
-/*
-==============================================================================
-		FOOTER 
-==============================================================================
-*/
+
+// Displaying the footer.
 Display :: display_footer();
-?>

+ 57 - 60
main/admin/class_information.php

@@ -22,86 +22,89 @@
 ==============================================================================
 */
 /**
-============================================================================== 
+==============================================================================
 *	@author	 Bart Mollet
 *	@package dokeos.admin
-============================================================================== 
-*/
-
-/*
-==============================================================================
-		INIT SECTION
 ==============================================================================
-*/ 
+*/
 
-// name of the language file that needs to be included 
-$language_file='admin';
+// Language files that should be included.
+$language_file = 'admin';
 
-$cidReset=true;
+$cidReset = true;
 
-require('../inc/global.inc.php');
-$this_section=SECTION_PLATFORM_ADMIN;
+require '../inc/global.inc.php';
+$this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
-require(api_get_path(LIBRARY_PATH).'classmanager.lib.php');
-if( !isset($_GET['id']))
-{
-	api_not_allowed();	
+
+require api_get_path(LIBRARY_PATH).'classmanager.lib.php';
+
+if (!isset($_GET['id'])) {
+	api_not_allowed();
 }
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ("url" => 'class_list.php', "name" => get_lang('AdminClasses'));
+
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'class_list.php', 'name' => get_lang('AdminClasses'));
+
 $class_id = $_GET['id'];
 $class = ClassManager::get_class_info($class_id);
 
 $tool_name = $class['name'];
 Display::display_header($tool_name);
 //api_display_tool_title($tool_name);
+
 /**
- * Show all users subscribed in this class
+ * Show all users subscribed in this class.
  */
 echo '<h4>'.get_lang('Users').'</h4>';
 echo '<blockquote>';
-
 $users = ClassManager::get_users($class_id);
-if( count($users) > 0)
-{
-$table_header[] = array (get_lang('OfficialCode'), true);
-$table_header[] = array (get_lang('FirstName'), true);
-$table_header[] = array (get_lang('LastName'), true);
-$table_header[] = array (get_lang('Email'), true);
-$table_header[] = array (get_lang('Status'), true);
-$table_header[] = array ('', false);
-$data = array();
-foreach($users as $index => $user)
-{
-	$row = array ();
-	$row[] = $user['official_code'];
-	$row[] = $user['firstname'];
-	$row[] = $user['lastname'];
-	$row[] = Display :: encrypted_mailto_link($user['email'], $user['email']);
-	$row[] = $user['status'] == 5 ? get_lang('Student') : get_lang('Teacher');
-	$row[] = '<a href="user_information.php?user_id='.$user['user_id'].'">'.Display::return_icon('synthese_view.gif').'</a>';
-	$data[] = $row;
-}
-Display::display_sortable_table($table_header,$data,array(),array(),array('id'=>$_GET['id']));
-}
-else
-{
-	echo get_lang('NoUsersInClass');	
+if (count($users) > 0) {
+	$is_western_name_order = api_is_western_name_order();
+	$table_header[] = array (get_lang('OfficialCode'), true);
+	if ($is_western_name_order) {
+		$table_header[] = array (get_lang('FirstName'), true);
+		$table_header[] = array (get_lang('LastName'), true);
+	} else {
+		$table_header[] = array (get_lang('LastName'), true);
+		$table_header[] = array (get_lang('FirstName'), true);
+	}
+	$table_header[] = array (get_lang('Email'), true);
+	$table_header[] = array (get_lang('Status'), true);
+	$table_header[] = array ('', false);
+	$data = array();
+	foreach($users as $index => $user) {
+		$row = array ();
+		$row[] = $user['official_code'];
+		if ($is_western_name_order) {
+			$row[] = $user['firstname'];
+			$row[] = $user['lastname'];
+		} else {
+			$row[] = $user['lastname'];
+			$row[] = $user['firstname'];
+		}
+		$row[] = Display :: encrypted_mailto_link($user['email'], $user['email']);
+		$row[] = $user['status'] == 5 ? get_lang('Student') : get_lang('Teacher');
+		$row[] = '<a href="user_information.php?user_id='.$user['user_id'].'">'.Display::return_icon('synthese_view.gif').'</a>';
+		$data[] = $row;
+	}
+	Display::display_sortable_table($table_header,$data,array(),array(),array('id'=>$_GET['id']));
+} else {
+	echo get_lang('NoUsersInClass');
 }
 echo '</blockquote>';
+
 /**
- * Show all courses in which this class is subscribed
+ * Show all courses in which this class is subscribed.
  */
 $courses = ClassManager::get_courses($class_id);
-if (count($courses) > 0)
-{
+if (count($courses) > 0) {
 	$header[] = array (get_lang('Code'), true);
 	$header[] = array (get_lang('Title'), true);
 	$header[] = array ('', false);
 	$data = array ();
-	foreach( $courses as $index=>$course)
-	{
+	foreach( $courses as $index => $course) {
 		$row = array ();
 		$row[] = $course['visual_code'];
 		$row[] = $course['title'];
@@ -114,15 +117,9 @@ if (count($courses) > 0)
 	echo '<blockquote>';
 	Display :: display_sortable_table($header, $data, array (), array (), array('id'=>$_GET['id']));
 	echo '</blockquote>';
-}
-else
-{
+} else {
 	echo '<p>'.get_lang('NoCoursesForThisClass').'</p>';
 }
-/*
-==============================================================================
-		FOOTER 
-==============================================================================
-*/ 
+
+// Displaying the footer.
 Display::display_footer();
-?> 

+ 49 - 54
main/admin/class_list.php

@@ -28,92 +28,86 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
 $language_file = 'admin';
+
 $cidReset = true;
-require ('../inc/global.inc.php');
+require '../inc/global.inc.php';
+
 $this_section = SECTION_PLATFORM_ADMIN;
+api_protect_admin_script();
 
 /**
- * Gets the total number of classes
+ * Gets the total number of classes.
  */
-function get_number_of_classes()
-{
+function get_number_of_classes() {
 	$tbl_class = Database :: get_main_table(TABLE_MAIN_CLASS);
 	$sql = "SELECT COUNT(*) AS number_of_classes FROM $tbl_class";
-	if (isset ($_GET['keyword']))
-	{
+	if (isset ($_GET['keyword'])) {
 		$sql .= " WHERE (name LIKE '%".Database::escape_string(trim($_GET['keyword']))."%')";
 	}
-	$res = api_sql_query($sql, __FILE__, __LINE__);
+	$res = Database::query($sql, __FILE__, __LINE__);
 	$obj = Database::fetch_object($res);
 	return $obj->number_of_classes;
 }
+
 /**
- * Gets the information about some classes
+ * Gets the information about some classes.
  * @param int $from
  * @param int $number_of_items
  * @param string $direction
  */
-function get_class_data($from, $number_of_items, $column, $direction)
-{
-	$tbl_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
+function get_class_data($from, $number_of_items, $column, $direction) {
+	$tbl_class_user = Database::get_main_table(TABLE_MAIN_CLASS_USER);
 	$tbl_class = Database :: get_main_table(TABLE_MAIN_CLASS);
 	$from 				= Database::escape_string($from);
 	$number_of_items 	= Database::escape_string($number_of_items);
 	$column 			= Database::escape_string($column);
 	$direction 			= Database::escape_string($direction);
-	
+
 	$sql = "SELECT 	id AS col0, name AS col1, COUNT(user_id) AS col2, id AS col3
-				FROM $tbl_class
-				LEFT JOIN $tbl_class_user ON id=class_id ";
-	if (isset ($_GET['keyword']))
-	{
+		FROM $tbl_class
+			LEFT JOIN $tbl_class_user ON id=class_id ";
+	if (isset ($_GET['keyword'])) {
 		$sql .= " WHERE (name LIKE '%".Database::escape_string(trim($_GET['keyword']))."%')";
 	}
-	$sql .= "GROUP BY id,name ORDER BY col$column $direction LIMIT $from,$number_of_items";
-	$res = api_sql_query($sql, __FILE__, __LINE__);
+	$sql .= " GROUP BY id,name ORDER BY col$column $direction LIMIT $from,$number_of_items";
+	$res = Database::query($sql, __FILE__, __LINE__);
 	$classes = array ();
-	while ($class = Database::fetch_row($res))
-	{
+	while ($class = Database::fetch_row($res)) {
 		$classes[] = $class;
 	}
 	return $classes;
 }
+
 /**
  * Filter for sortable table to display edit icons for class
  */
-function modify_filter($class_id)
-{
-	global $charset;
+function modify_filter($class_id) {
 	$class_id = Security::remove_XSS($class_id);
 	$result = '<a href="class_information.php?id='.$class_id.'">'.Display::return_icon('synthese_view.gif', get_lang('Info')).'</a>';
 	$result .= '<a href="class_edit.php?idclass='.$class_id.'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
-	$result .= '<a href="class_list.php?action=delete_class&amp;class_id='.$class_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>';
+	$result .= '<a href="class_list.php?action=delete_class&amp;class_id='.$class_id.'" onclick="javascript: if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES))."'".')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
 	$result .= '<a href="subscribe_user2class.php?idclass='.$class_id.'">'.Display::return_icon('add_multiple_users.gif', get_lang('AddUsersToAClass')).'</a>';
 	return $result;
 }
 
-api_protect_admin_script();
-require (api_get_path(LIBRARY_PATH).'fileManage.lib.php');
-require (api_get_path(LIBRARY_PATH).'classmanager.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+require api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+require api_get_path(LIBRARY_PATH).'classmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+
 $tool_name = get_lang('ClassList');
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 
 Display :: display_header($tool_name);
 //api_display_tool_title($tool_name);
-if (isset ($_POST['action']))
-{
-	switch ($_POST['action'])
-	{
+
+if (isset($_POST['action'])) {
+	switch ($_POST['action']) {
 		// Delete selected classes
 		case 'delete_classes' :
 			$classes = $_POST['class'];
-			if (count($classes) > 0)
-			{
-				foreach ($classes as $index => $class_id)
-				{
+			if (count($classes) > 0) {
+				foreach ($classes as $index => $class_id) {
 					ClassManager :: delete_class($class_id);
 				}
 				Display :: display_normal_message(get_lang('ClassesDeleted'));
@@ -121,36 +115,37 @@ if (isset ($_POST['action']))
 			break;
 	}
 }
-if (isset ($_GET['action']))
-{
-	switch ($_GET['action'])
-	{
-		case 'delete_class' :
+
+if (isset($_GET['action'])) {
+	switch ($_GET['action']) {
+		case 'delete_class':
 			ClassManager :: delete_class($_GET['class_id']);
 			Display :: display_normal_message(get_lang('ClassDeleted'));
+			break;
+		case 'show_message':
+			Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
+			break;
 	}
 }
+
 // Create a search-box
-$form = new FormValidator('search_simple','get','','',null,false);
+$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('submit','submit',get_lang('Search'));
+$form->addElement('text', 'keyword', get_lang('keyword'));
+$form->addElement('submit', 'submit', get_lang('Search'));
 $form->display();
+
 // Create the sortable table with class information
 $table = new SortableTable('classes', 'get_number_of_classes', 'get_class_data', 1);
-$table->set_additional_parameters(array('keyword'=>$_GET['keyword']));
+$table->set_additional_parameters(array('keyword' => $_GET['keyword']));
 $table->set_header(0, '', false);
 $table->set_header(1, get_lang('ClassName'));
 $table->set_header(2, get_lang('NumberOfUsers'));
 $table->set_header(3, '', false);
 $table->set_column_filter(3, 'modify_filter');
-$table->set_form_actions(array ('delete_classes' => get_lang('DeleteSelectedClasses')),'class');
+$table->set_form_actions(array ('delete_classes' => get_lang('DeleteSelectedClasses')), 'class');
 $table->display();
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
+
+// Displaying the footer.
 Display :: display_footer();
-?>

+ 212 - 216
main/admin/class_user_import.php

@@ -1,216 +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
-==============================================================================
-*/
-/**
- * validate the imported data
- */
-function validate_data($user_classes)
-{
-	$errors = array ();
-	$classcodes = array ();
-	foreach ($user_classes as $index => $user_class)
-	{
-		$user_class['line'] = $index +1;
-		//1. check if 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 if classcode exists
-		if (isset ($user_class['ClassName']) && strlen($user_class['ClassName']) != 0)
-		{
-			//2.1 check if code allready used in this CVS-file
-			if (!isset ($classcodes[$user_class['ClassName']]))
-			{
-				//2.1.1 check if 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 = api_sql_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 if username exists
-		if (isset ($user_class['UserName']) && strlen($user_class['UserName']) != 0)
-		{
-			if (UserManager :: is_username_available($user_class['UserName']))
-			{
-				$user_class['error'] = get_lang('UnknownUser').":".$user_class['UserName'];
-				$errors[] = $user_class;
-			}
-		}
-	}
-	return $errors;
-}
-
-/**
- * Save the imported data
- */
-function save_data($users_classes)
-{
-	// 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);
-	
-	$csv_data = array ();
-	foreach ($users_classes as $index => $user_class)
-	{
-		$sql = "SELECT * FROM $class_table WHERE name = '".mysql_real_escape_string($user_class['ClassName'])."'";
-		$res = api_sql_query($sql, __FILE__, __LINE__);
-		$obj = mysql_fetch_object($res);
-		$csv_data[$user_class['UserName']][$obj->id] = 1;
-	}
-	foreach ($csv_data as $username => $csv_subscriptions)
-	{
-		$user_id = 0;
-		$sql = "SELECT * FROM $user_table u WHERE u.username = '".mysql_real_escape_string($username)."'";
-		$res = api_sql_query($sql, __FILE__, __LINE__);
-		$obj = mysql_fetch_object($res);
-		$user_id = $obj->user_id;
-		$sql = "SELECT * FROM $class_user_table cu WHERE cu.user_id = $user_id";
-		$res = api_sql_query($sql, __FILE__, __LINE__);
-		$db_subscriptions = array ();
-		while ($obj = mysql_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));
-		if ($_POST['subscribe'])
-		{
-			foreach ($to_subscribe as $index => $class_id)
-			{
-				ClassManager :: add_user($user_id, $class_id);
-				//echo get_lang('Subscription').' : '.$course_code.'<br />';
-			}
-		}
-		if ($_POST['unsubscribe'])
-		{
-			foreach ($to_unsubscribe as $index => $class_id)
-			{
-				ClassManager :: unsubscribe_user($user_id, $class_id);
-				//echo get_lang('Unsubscription').' : '.$course_code.'<br />';
-			}
-		}
-	}
-}
-/**
- * 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;
-}
-
-// name of the language file that needs to be included 
-$language_file = array ('admin', 'registration');
-
-$cidReset = true;
-
-include ('../inc/global.inc.php');
-
-
-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');
-$formSent = 0;
-$errorMsg = '';
-
-$tool_name = get_lang('AddUsersToAClass').' CSV';
-
-$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-
-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('submit', 'submit', get_lang('Ok'));
-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
-a.dam;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 = api_sql_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 = api_sql_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 = api_sql_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"';
-							api_sql_query($sql, __FILE__, __LINE__);		
-						}
-						$select = "SELECT id FROM $tool_table WHERE name='".TOOL_VISIO_CLASSROOM."'";
-						$selectres = api_sql_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"';
-							api_sql_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 = api_sql_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 = api_sql_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 = api_sql_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 = api_sql_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 = api_sql_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"';
-			api_sql_query($sql, __FILE__, __LINE__);
-			
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="'.addslashes($_POST['port']).'"
-					WHERE variable="service_ppt2lp"
-					AND subkey="port"';
-			api_sql_query($sql, __FILE__, __LINE__);
-			
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="'.addslashes($_POST['ftp_password']).'"
-					WHERE variable="service_ppt2lp"
-					AND subkey="ftp_password"';
-			api_sql_query($sql, __FILE__, __LINE__);
-			
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="'.addslashes($_POST['user']).'"
-					WHERE variable="service_ppt2lp"
-					AND subkey="user"';
-			api_sql_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"';
-			api_sql_query($sql, __FILE__, __LINE__);
-			
-			$sql = 'UPDATE '.$tbl_settings_current.' SET
-					selected_value="'.addslashes($_POST['size']).'"
-					WHERE variable="service_ppt2lp"
-					AND subkey="size"';
-			api_sql_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 = api_sql_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 = api_sql_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 = api_sql_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();
+?>

+ 93 - 57
main/admin/configure_homepage.php

@@ -1,6 +1,6 @@
 <?php // $Id: configure_homepage.php 22243 2009-07-20 15:08:31Z ivantcholakov $
 /*
-===== =========================================================================
+==============================================================================
 	Dokeos - elearning and course management software
 
 	Copyright (c) 2004-2009 Dokeos SPRL
@@ -32,6 +32,7 @@ include('../inc/global.inc.php');
 
 $this_section=SECTION_PLATFORM_ADMIN;
 $_SESSION['this_section']=$this_section;
+$this_page = '';
 
 api_protect_admin_script();
 require_once(api_get_path(LIBRARY_PATH).'WCAG/WCAG_rendering.php');
@@ -63,6 +64,12 @@ if(!empty($action)){
 		case "edit_link":
 			$tool_name=get_lang("EditLink");
 			break;
+		case "insert_tabs":
+			$tool_name=get_lang("InsertTabs");
+			break;
+		case "edit_tabs":
+			$tool_name=get_lang("EditTabs");
+			break;
 	}
 }
 
@@ -90,34 +97,34 @@ if(!empty($_SESSION['user_language_choice'])) {
 } elseif(!empty($_SESSION['_user']['language'])) {
 	$lang=$_SESSION['_user']['language'];
 } else {
-	$lang=get_setting('platformLanguage');
+	$lang=api_get_setting('platformLanguage');
 }
 
 // ----- Ensuring availability of main files in the corresponding language -----
 
 if ($_configuration['multiple_access_urls']==true) {
-	$access_url_id = api_get_current_access_url_id();										 
-	if ($access_url_id != -1){						
+	$access_url_id = api_get_current_access_url_id();
+	if ($access_url_id != -1){
 		$url_info = api_get_access_url($access_url_id);
-		// "http://" and the final "/" replaced						
-		$url = substr($url_info['url'],7,strlen($url_info['url'])-8);						
+		// "http://" and the final "/" replaced
+		$url = substr($url_info['url'],7,strlen($url_info['url'])-8);
 		$clean_url = replace_dangerous_char($url);
 		$clean_url = str_replace('/','-',$clean_url);
 		$clean_url = $clean_url.'/';
-		
-		$homep = '../../home/'; //homep for Home Path			
-		$homep_new = '../../home/'.$clean_url; //homep for Home Path added the url				
+
+		$homep = '../../home/'; //homep for Home Path
+		$homep_new = '../../home/'.$clean_url; //homep for Home Path added the url
 		$new_url_dir = api_get_path(SYS_PATH).'home/'.$clean_url;
 		//we create the new dir for the new sites
-		if (!is_dir($new_url_dir)){		
+		if (!is_dir($new_url_dir)){
 			umask(0);
 			$perm = api_get_setting('permissions_for_new_directories');
 			$perm = octdec(!empty($perm)?$perm:'0755');
 			mkdir($new_url_dir, $perm);
-		}							
+		}
 	}
-} else {			
-	$homep_new ='';		
+} else {
+	$homep_new ='';
 	$homep = '../../home/'; //homep for Home Path
 }
 
@@ -126,9 +133,10 @@ $menuf	 = 'home_menu'; //menuf for Menu File
 $newsf	 = 'home_news'; //newsf for News File
 $topf 	 = 'home_top'; //topf for Top File
 $noticef = 'home_notice'; //noticef for Notice File
+$menutabs= 'home_tabs'; //menutabs for tabs Menu
 $ext 	 = '.html'; //ext for HTML Extension - when used frequently, variables are
 				// faster than hardcoded strings
-$homef = array($menuf,$newsf,$topf,$noticef);
+$homef = array($menuf,$newsf,$topf,$noticef,$menutabs);
 
 // If language-specific file does not exist, create it by copying default file
 foreach($homef as $my_file) {
@@ -179,11 +187,11 @@ if(!empty($action)) {
 					$home_top=WCAG_Rendering::prepareXHTML();
 				} else {
 					$home_top=trim(stripslashes($_POST['home_top']));
-				}				
-					
+				}
+
 				// Write
 				if (file_exists($homep.$topf.'_'.$lang.$ext)) {
-					if(is_writable($homep.$topf.'_'.$lang.$ext)) {						
+					if(is_writable($homep.$topf.'_'.$lang.$ext)) {
 						$fp=fopen($homep.$topf.'_'.$lang.$ext,"w");
 						fputs($fp,$home_top);
 						fclose($fp);
@@ -191,12 +199,12 @@ if(!empty($action)) {
 						$errorMsg=get_lang('HomePageFilesNotWritable');
 					}
 				} else {
-					//File does not exist					
+					//File does not exist
 					$fp=fopen($homep.$topf.'_'.$lang.$ext,"w");
 					fputs($fp,$home_top);
 					fclose($fp);
-				}				
-				
+				}
+
 				break;
 			case 'edit_notice':
 				// Filter
@@ -288,6 +296,8 @@ if(!empty($action)) {
 					}
 				}
 				break;
+			case 'insert_tabs':
+			case 'edit_tabs':
 			case 'insert_link':
 			case 'edit_link':
 				$link_index=intval($_POST['link_index']);
@@ -309,7 +319,7 @@ if(!empty($action)) {
 				elseif(!empty($link_url) && !strstr($link_url,'://')) {
 					$link_url='http://'.$link_url;
 				}
-
+				$menuf = ($action == 'insert_tabs' || $action == 'edit_tabs')? $menutabs : $menuf;
 				if(!is_writable($homep.$menuf.'_'.$lang.$ext)) {
 					$errorMsg=get_lang('HomePageFilesNotWritable');
 				}
@@ -317,7 +327,7 @@ if(!empty($action)) {
 					$errorMsg=get_lang('PleaseEnterLinkName');
 				} else {
 					// New links are added as new files in the home/ directory
-					if($action == 'insert_link' || empty($filename) || strstr($filename,'/') || !strstr($filename,'.html')) {
+					if($action == 'insert_link' || $action == 'insert_tabs' || empty($filename) || strstr($filename,'/') || !strstr($filename,'.html')) {
 						$filename=replace_dangerous_char($link_name,'strict').'.html';
 					}
 					// "home_" prefix for links are renamed to "user_" prefix (to avoid name clash with existing home page files)
@@ -368,7 +378,7 @@ if(!empty($action)) {
 					// If the requested action is to create a link, make some room
 					// for the new link in the home_menu array at the requested place
 					// and insert the new link there
-					if($action == 'insert_link') {
+					if($action == 'insert_link' || $action == 'insert_tabs') {
 						for($i=sizeof($home_menu);$i;$i--) {
 							if($i > $insert_where) {
 								$home_menu[$i]=$home_menu[$i-1];
@@ -398,7 +408,7 @@ if(!empty($action)) {
 									fclose($fpo);
 								}
 							}
-								
+
 						} else {
 							$errorMsg=get_lang('HomePageFilesNotWritable');
 						}
@@ -424,11 +434,12 @@ if(!empty($action)) {
 				// Previously, filtering of GET['link'] was done here but it left
 				// a security threat. Filtering has now been moved outside conditions
 				break;
+			case 'delete_tabs':
 			case 'delete_link':
 				// A link is deleted by getting the file into an array, removing the
 				// link and re-writing the array to the file
 				$link_index=intval($_GET['link_index']);
-
+				$menuf = ($action == 'delete_tabs')? $menutabs : $menuf;
 				$home_menu=file($homep.$menuf.'_'.$lang.$ext);
 
 				foreach($home_menu as $key=>$enreg) {
@@ -454,14 +465,14 @@ if(!empty($action)) {
 				break;
 			case 'edit_top':
 				// This request is only the preparation for the update of the home_top
-				$home_top = '';			
+				$home_top = '';
 				if(is_file($homep.$topf.'_'.$lang.$ext) && is_readable($homep.$topf.'_'.$lang.$ext)) {
 					$home_top=file_get_contents($homep.$topf.'_'.$lang.$ext);
 				} elseif(is_file($homep.$topf.$lang.$ext) && is_readable($homep.$topf.$lang.$ext)) {
 					$home_top=file_get_contents($homep.$topf.$lang.$ext);
 				} else {
 					$errorMsg=get_lang('HomePageFilesNotReadable');
-				}		
+				}
 				break;
 			case 'edit_notice':
 				// This request is only the preparation for the update of the home_notice
@@ -506,6 +517,7 @@ if(!empty($action)) {
 			case 'insert_link':
 				// This request is the preparation for the addition of an item in home_menu
 				$home_menu = '';
+				$menuf = ($action == 'edit_tabs')? $menutabs : $menuf;
 				if(is_file($homep.$menuf.'_'.$lang.$ext)
 					&& is_readable($homep.$menuf.'_'.$lang.$ext))
 				{
@@ -521,9 +533,29 @@ if(!empty($action)) {
 					$errorMsg=get_lang('HomePageFilesNotReadable');
 				}
 				break;
+			case 'insert_tabs':
+				// This request is the preparation for the addition of an item in home_menu
+				$home_menu = '';
+				if(is_file($homep.$menutabs.'_'.$lang.$ext)
+					&& is_readable($homep.$menutabs.'_'.$lang.$ext))
+				{
+					$home_menu=file($homep.$menutabs.'_'.$lang.$ext);
+				}
+				elseif(is_file($homep.$menutabs.$lang.$ext)
+					&& is_readable($homep.$menutabs.$lang.$ext))
+				{
+					$home_menu=file($homep.$menutabs.$lang.$ext);
+				}
+				else
+				{
+					$errorMsg=get_lang('HomePageFilesNotReadable');
+				}
+				break;
+			case 'edit_tabs':
 			case 'edit_link':
 				// This request is the preparation for the edition of the links array
 				$home_menu = '';
+				$menuf = ($action == 'edit_tabs')? $menutabs : $menuf;
 				if(is_file($homep.$menuf.'_'.$lang.$ext)
 					&& is_readable($homep.$menuf.'_'.$lang.$ext))
 				{
@@ -587,8 +619,8 @@ if(!empty($action)) {
 }
 else //if $action is empty, then prepare a list of the course categories to display (?)
 {
-	$result=api_sql_query("SELECT name FROM $tbl_category WHERE parent_id IS NULL ORDER BY tree_pos",__FILE__,__LINE__);
-	$Categories=api_store_result($result);
+	$result=Database::query("SELECT name FROM $tbl_category WHERE parent_id IS NULL ORDER BY tree_pos",__FILE__,__LINE__);
+	$Categories=Database::store_result($result);
 }
 
 // -------------------------
@@ -622,7 +654,7 @@ switch($action){
 		}
 
 		?>
-		
+
 		<table border="0" cellpadding="5" cellspacing="0">
 		<tr><td colspan="2"><?php echo '<span style="font-style: italic;">'.get_lang('LetThoseFieldsEmptyToHideTheNotice').'</span>'; ?></tr>
 		<tr>
@@ -641,6 +673,8 @@ switch($action){
 		</form>
 		<?php
 		break;
+	case 'insert_tabs':
+	case 'edit_tabs':
 	case 'insert_link':
 	case 'edit_link':
 
@@ -656,24 +690,26 @@ switch($action){
 		$renderer->setRequiredNoteTemplate('');
 		$form->addElement('header', '', $tool_name);
 		$form->addElement('hidden', 'formSent', '1');
-		$form->addElement('hidden', 'link_index', $action == 'edit_link' ? $link_index : '0');
-		$form->addElement('hidden', 'filename', $action == 'edit_link' ? $filename : '');
+		$form->addElement('hidden', 'link_index', ($action == 'edit_link' || $action == 'edit_tabs') ? $link_index : '0');
+		$form->addElement('hidden', 'filename', ($action == 'edit_link' || $action == 'edit_tabs') ? $filename : '');
 
 		$form->addElement('html', '<tr><td nowrap="nowrap" style="width: 15%;">'.get_lang('LinkName').' :</td><td>');
 		$default['link_name'] = api_htmlentities($link_name, ENT_QUOTES, $charset);
 		$form->addElement('text', 'link_name', get_lang('LinkName'), array('size' => '30', 'maxlength' => '50'));
 		$form->addElement('html', '</td></tr>');
-		
+
 		$form->addElement('html', '<tr><td nowrap="nowrap">'.get_lang('LinkURL').' ('.get_lang('Optional').') :</td><td>');
-		$default['link_url'] = empty($link_url) ? 'http://' : api_htmlentities($link_url, ENT_QUOTES, $charset); 
+		$default['link_url'] = empty($link_url) ? 'http://' : api_htmlentities($link_url, ENT_QUOTES, $charset);
 		$form->addElement('text', 'link_url', get_lang('LinkName'), array('size' => '30', 'maxlength' => '100', 'style' => 'width: 350px;'));
 		$form->addElement('html', '</td></tr>');
-		
-		if($action == 'insert_link') {
+
+		if($action == 'insert_link' || $action == 'insert_tabs') {
 			$form->addElement('html', '<tr><td nowrap="nowrap">'.get_lang('InsertThisLink').' :</td>');
 			$form->addElement('html', '<td><select name="insert_where"><option value="-1">'.get_lang('FirstPlace').'</option>');
-			foreach($home_menu as $key=>$enreg) {
-				$form->addElement('html', '<option value="'.$key.'" '.($formSent && $insert_where == $key ? 'selected="selected"' : '').' >'.get_lang('After').' &quot;'.trim(strip_tags($enreg)).'&quot;</option>');
+			if(is_array($home_menu)){
+				foreach($home_menu as $key=>$enreg) {
+					$form->addElement('html', '<option value="'.$key.'" '.($formSent && $insert_where == $key ? 'selected="selected"' : '').' >'.get_lang('After').' &quot;'.trim(strip_tags($enreg)).'&quot;</option>');
+				}
 			}
 			$form->addElement('html', '</select></td></tr>');
 		}
@@ -729,7 +765,7 @@ switch($action){
 		$renderer->setElementTemplate('<tr><td>{element}</td></tr>');
 		$renderer->setRequiredNoteTemplate('');
 		$form->addElement('hidden', 'formSent', '1');
-		
+
 		if($action == 'edit_news'){
 			$_languages=api_get_languages();
 			$html = '<tr><td>'.get_lang('ChooseNewsLanguage').' : ';
@@ -764,14 +800,14 @@ switch($action){
 		break;
 	default: // When no action applies, default page to update campus homepage
 		?>
-		<table border="0" cellpadding="5" cellspacing="0" width="100%">	
+		<table border="0" cellpadding="5" cellspacing="0" width="100%">
 		<tr>
 		  <td width="80%" colspan="2" valign="top">
 		  	<div class="actions">
 			<a href="<?php echo api_get_self(); ?>?action=edit_top"><?php Display::display_icon('edit.gif', get_lang('EditHomePage')); ?></a>
 			<a href="<?php echo api_get_self(); ?>?action=edit_top"><?php echo get_lang('EditHomePage'); ?></a>
 		  	</div>
-		  	
+
 			<table border="0" cellpadding="5" cellspacing="0" width="100%">
 			<tr>
 			  <td colspan="2">
@@ -788,26 +824,26 @@ switch($action){
 			  </td>
 			</tr>
 			<tr>
-			<?php 
+			<?php
 			$access_url_id =1;
 			// we only show the category options for the main Dokeos installation
-			if ($_configuration['multiple_access_urls']==true) {					
-				$access_url_id = api_get_current_access_url_id();					
-			}			
-			echo '<td width="50%">';				
+			if ($_configuration['multiple_access_urls']==true) {
+				$access_url_id = api_get_current_access_url_id();
+			}
+			echo '<td width="50%">';
 			if ($access_url_id ==1) {
 				echo '<div class="actions">';
 				echo '<a href="course_category.php">'.Display::display_icon('edit.gif', get_lang('Edit')).'</a>
 					  <a href="course_category.php">'.get_lang('EditCategories').'</a>';
 				echo '</div>';
-			}			
+			}
 			echo '</td>
 				  <td width="50%">
-				  <br />';								
+				  <br />';
 			/* <!--<a href="<?php echo api_get_self(); ?>?action=edit_news"><?php Display::display_icon('edit.gif', get_lang('Edit')); ?></a> <a href="<?php echo api_get_self(); ?>?action=edit_news"><?php echo get_lang('EditNews'); ?></a>--> */
 			echo '</td></tr>
 				<tr>
-				<td width="50%" valign="top">				  	
+				<td width="50%" valign="top">
 				<table border="0" cellpadding="5" cellspacing="0" width="100%">';
 				if ($access_url_id ==1) {
 					if(sizeof($Categories)) {
@@ -818,19 +854,19 @@ switch($action){
 					} else {
 						echo get_lang('NoCategories');
 					}
-				}				
-				
+				}
+
 				echo '</table>';
 				?>
 			  </td>
 			  <!--<td width="50%" valign="top">
-				<?php				
+				<?php
 				if(file_exists($homep.$newsf.'_'.$lang.$ext)) {
 					include ($homep.$newsf.'_'.$lang.$ext);
 				} else {
 					include ($homep.$newsf.$ext);
 				}
-				
+
 			?>
 			  </td>-->
 			</tr>
@@ -852,7 +888,7 @@ switch($action){
 						<td><input type="password" id="password" size="15" disabled="disabled" /></td>
 					</tr>
 				</table>
-				<input type="button" value="<?php echo get_lang('Ok'); ?>" disabled="disabled" />
+				<button class="login" type="button" name="submitAuth" value="<?php echo get_lang('Ok'); ?>" disabled="disabled"><?php echo get_lang('Ok'); ?></button>
 			</form>
 			<div class="menusection">
 				<span class="menusectioncaption"><?php echo get_lang('User'); ?></span>
@@ -861,12 +897,12 @@ switch($action){
 				<li><span style="color: #9D9DA1; font-weight: bold;"><?php echo api_ucfirst(get_lang('LostPassword')); ?></span></li>
 				</ul>
 			</div>
-			
-			
+
+
 			<br />
 			<a href="<?php echo api_get_self(); ?>?action=insert_link"><?php Display::display_icon('insert_row.png', get_lang('InsertLink')); ?></a>
 			<a href="<?php echo api_get_self(); ?>?action=insert_link"/><?php echo get_lang('InsertLink'); ?></a>
-			
+
 			<div class="menusection">
 				<span class="menusectioncaption"><?php echo api_ucfirst(get_lang('General')); ?></span>
 				<ul class="menulist">

+ 519 - 0
main/admin/configure_inscription.php

@@ -0,0 +1,519 @@
+<?php
+/* For licensing terms, see /dokeos_license.txt */
+/**
+==============================================================================
+*	This script displays a form for registering new users.
+*	@package	 dokeos.auth
+==============================================================================
+*/
+// name of the language file that needs to be included
+$language_file = array('registration','admin');
+$cidReset = true;
+include ("../inc/global.inc.php");
+
+require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
+require_once (api_get_path(CONFIGURATION_PATH).'profile.conf.php');
+require_once(api_get_path(INCLUDE_PATH).'lib/mail.lib.inc.php');
+require_once(api_get_path(INCLUDE_PATH).'lib/legal.lib.php');
+
+//require_once(api_get_path(LIBRARY_PATH).'fileManage.lib.php');
+//require_once(api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
+//require_once (api_get_path(LIBRARY_PATH).'image.lib.php');
+
+// Load terms & conditions from the current lang
+if (get_setting('allow_terms_conditions')=='true') {	
+	$get = array_keys($_GET);
+	if (isset($get)) {
+		if ($get[0]=='legal'){				
+			//$language = api_get_setting('platformLanguage');
+			$language = api_get_interface_language();
+			$language = api_get_language_id($language);
+			$term_preview= LegalManager::get_last_condition($language);
+			if ($term_preview==false) {
+				//look for the default language
+				$language = api_get_setting('platformLanguage');				
+				$language = api_get_language_id($language);
+				$term_preview= LegalManager::get_last_condition($language);
+			}					
+			$tool_name = get_lang('TermsAndConditions');
+			Display :: display_header('');
+			echo '<div class="actions-title">';
+			echo $tool_name;
+			echo '</div>';
+			if (!empty($term_preview['content']))
+				echo $term_preview['content'];
+			else 
+				echo get_lang('ComingSoon');
+			Display :: display_footer();
+			exit;
+		}
+	}
+}
+
+$action=Security::remove_XSS($_GET['action']);
+$interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
+$tool_name = get_lang('ConfigureInscription');
+if(!empty($action)){
+	$interbreadcrumb[]=array('url' => 'configure_inscription.php',"name" => get_lang('ConfigureInscription'));
+	switch($action){
+		case "edit_top":
+			$tool_name=get_lang("EditTopRegister");
+			break;
+	}
+}
+
+$lang = ''; //el for "Edit Language"
+if(!empty($_SESSION['user_language_choice'])) {
+	$lang=$_SESSION['user_language_choice'];
+} elseif(!empty($_SESSION['_user']['language'])) {
+	$lang=$_SESSION['_user']['language'];
+} else {
+	$lang=get_setting('platformLanguage');
+}
+
+// ----- Ensuring availability of main files in the corresponding language -----
+if ($_configuration['multiple_access_urls']==true) {
+	$access_url_id = api_get_current_access_url_id();										 
+	if ($access_url_id != -1){						
+		$url_info = api_get_access_url($access_url_id);
+		// "http://" and the final "/" replaced						
+		$url = substr($url_info['url'],7,strlen($url_info['url'])-8);						
+		$clean_url = replace_dangerous_char($url);
+		$clean_url = str_replace('/','-',$clean_url);
+		$clean_url = $clean_url.'/';
+		
+		$homep = '../../home/'; //homep for Home Path			
+		$homep_new = '../../home/'.$clean_url; //homep for Home Path added the url				
+		$new_url_dir = api_get_path(SYS_PATH).'home/'.$clean_url;
+		//we create the new dir for the new sites
+		if (!is_dir($new_url_dir)){		
+			umask(0);
+			$perm = api_get_setting('permissions_for_new_directories');
+			$perm = octdec(!empty($perm)?$perm:'0755');
+			mkdir($new_url_dir, $perm);
+		}							
+	}
+} else {			
+	$homep_new ='';		
+	$homep = '../../home/'; //homep for Home Path
+}
+
+
+
+$topf 	 = 'register_top'; //topf for Top File
+$ext 	 = '.html'; //ext for HTML Extension - when used frequently, variables are
+$homef = array($topf);
+
+// If language-specific file does not exist, create it by copying default file
+foreach($homef as $my_file) {
+	if ($_configuration['multiple_access_urls']==true) {
+		if (!file_exists($homep_new.$my_file.'_'.$lang.$ext)) {
+			copy($homep.$my_file.$ext,$homep_new.$my_file.'_'.$lang.$ext);
+		}		
+	} else {	
+		if (!file_exists($homep.$my_file.'_'.$lang.$ext)) {
+			copy($homep.$my_file.$ext,$homep.$my_file.'_'.$lang.$ext);
+		}
+	}
+}
+
+if(!empty($action)) {
+	if($_POST['formSent']) {
+		switch($action) {
+			case 'edit_top':
+				// Filter
+				$home_top='';
+				if (api_get_setting('wcag_anysurfer_public_pages')=='true') {
+					$home_top=WCAG_Rendering::prepareXHTML();
+				} else {
+					$home_top=trim(stripslashes($_POST['register_top']));
+				}
+				// Write
+				if (file_exists($homep.$topf.'_'.$lang.$ext)) {
+					if(is_writable($homep.$topf.'_'.$lang.$ext)) {						
+						$fp=fopen($homep.$topf.'_'.$lang.$ext,"w");
+						fputs($fp,$home_top);
+						fclose($fp);
+					} else {
+						$errorMsg=get_lang('HomePageFilesNotWritable');
+					}
+				} else {
+					//File does not exist					
+					$fp=fopen($homep.$topf.'_'.$lang.$ext,"w");
+					fputs($fp,$home_top);
+					fclose($fp);
+				}
+				break;
+		}
+		if(empty($errorMsg)) {
+			header('Location: '.api_get_self());
+			exit();
+		}
+	} else {
+		switch($action) {
+			case 'edit_top':
+				// This request is only the preparation for the update of the home_top
+				$home_top = '';
+				if(is_file($homep.$topf.'_'.$lang.$ext) && is_readable($homep.$topf.'_'.$lang.$ext)) {
+					$home_top=file_get_contents($homep.$topf.'_'.$lang.$ext);
+				} elseif(is_file($homep.$topf.$lang.$ext) && is_readable($homep.$topf.$lang.$ext)) {
+					$home_top=file_get_contents($homep.$topf.$lang.$ext);
+				} else {
+					$errorMsg=get_lang('HomePageFilesNotReadable');
+				}		
+				break;
+		}
+	}
+}
+
+Display :: display_header($tool_name);
+
+echo '<div class="actions-title">';
+echo $tool_name;
+echo '</div>';
+
+// Forbidden to self-register
+if (get_setting('allow_registration') == 'false') {
+	api_not_allowed();
+}
+//api_display_tool_title($tool_name);
+if (get_setting('allow_registration')=='approval') {
+	Display::display_normal_message(get_lang('YourAccountHasToBeApproved'));
+}
+//if openid was not found
+if (!empty($_GET['openid_msg']) && $_GET['openid_msg'] == 'idnotfound') {
+	Display::display_warning_message(get_lang('OpenIDCouldNotBeFoundPleaseRegister'));	
+}
+
+$form = new FormValidator('registration');
+if (get_setting('allow_terms_conditions')=='true') {
+	if (!isset($_SESSION['update_term_and_condition'][1])) {
+		$display_all_form=true;
+	} else {
+		$display_all_form=false;
+	}
+} else {
+	$display_all_form=true;
+}
+if ($display_all_form===true) {
+	
+//	LAST NAME and FIRST NAME
+$form->addElement('text', 'lastname',  get_lang('LastName'),  array('size' => 40, 'disabled' => 'disabled'));
+$form->applyFilter('lastname','trim');
+$form->addElement('text', 'firstname', get_lang('FirstName'), array('size' => 40, 'disabled' => 'disabled'));
+$form->applyFilter('firstname','trim');
+$form->addRule('lastname',  get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
+//	EMAIL
+$form->addElement('text', 'email', get_lang('Email'), array('size' => 40, 'disabled' => 'disabled'));
+if (api_get_setting('registration', 'email') == 'true')
+	$form->addRule('email', get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule('email', get_lang('EmailWrong'), 'email');
+if (api_get_setting('openid_authentication')=='true') {
+	$form->addElement('text', 'openid', get_lang('OpenIDURL'), array('size' => 40, 'disabled' => 'disabled'));	
+}
+
+//	USERNAME
+$form->addElement('text', 'username', get_lang('UserName'), array('size' => 20, 'disabled' => 'disabled'));
+$form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule('username', get_lang('UsernameWrong'), 'username');
+$form->addRule('username', get_lang('UserTaken'), 'username_available');
+$form->addRule('username', sprintf(get_lang('UsernameMaxXCharacters'),'20'), 'maxlength',20);
+//	PASSWORD
+$form->addElement('password', 'pass1', get_lang('Pass'),         array('size' => 40, 'disabled' => 'disabled'));
+$form->addElement('password', 'pass2', get_lang('Confirmation'), array('size' => 40, 'disabled' => 'disabled'));
+$form->addRule('pass1', get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule('pass2', get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule(array('pass1', 'pass2'), get_lang('PassTwo'), 'compare');
+if (CHECK_PASS_EASY_TO_FIND)
+	$form->addRule('password1', get_lang('PassTooEasy').': '.api_generate_password(), 'callback', 'api_check_password');
+
+//	PHONE
+$form->addElement('text', 'phone', get_lang('Phone'), array('size' => 40, 'disabled' => 'disabled'));
+if (api_get_setting('registration', 'phone') == 'true')
+	$form->addRule('phone', get_lang('ThisFieldIsRequired'), 'required');
+
+//	LANGUAGE
+if (get_setting('registration', 'language') == 'true') {
+	$form->addElement('select_language', 'language', get_lang('Language'), '', array('disabled' => 'disabled'));
+}
+//	STUDENT/TEACHER
+if (get_setting('allow_registration_as_teacher') <> 'false') {
+	$form->addElement('radio', 'status', get_lang('Status'), get_lang('RegStudent'), STUDENT, array('disabled' => 'disabled'));
+	$form->addElement('radio', 'status', null, get_lang('RegAdmin'), COURSEMANAGER, array('disabled' => 'disabled'));
+}
+
+//	EXTENDED FIELDS
+if (api_get_setting('extended_profile') == 'true' AND api_get_setting('extendedprofile_registration','mycomptetences') == 'true')
+{
+	$form->add_html_editor('competences', get_lang('MyCompetences'), false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130'));
+}
+if (api_get_setting('extended_profile') == 'true' AND api_get_setting('extendedprofile_registration','mydiplomas') == 'true')
+{
+	$form->add_html_editor('diplomas', get_lang('MyDiplomas'), false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130'));
+}
+if (api_get_setting('extended_profile') == 'true' AND api_get_setting('extendedprofile_registration','myteach') == 'true')
+{
+	$form->add_html_editor('teach', get_lang('MyTeach'), false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130'));
+}
+if (api_get_setting('extended_profile') == 'true' AND api_get_setting('extendedprofile_registration','mypersonalopenarea') == 'true')
+{
+	$form->add_html_editor('openarea', get_lang('MyPersonalOpenArea'), false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130'));
+}
+if (api_get_setting('extended_profile') == 'true')
+{
+	if (api_get_setting('extendedprofile_registrationrequired','mycomptetences') == 'true')
+	{
+		$form->addRule('competences', get_lang('ThisFieldIsRequired'), 'required');
+	}
+	if (api_get_setting('extendedprofile_registrationrequired','mydiplomas') == 'true')
+	{
+		$form->addRule('diplomas', get_lang('ThisFieldIsRequired'), 'required');
+	}
+	if (api_get_setting('extendedprofile_registrationrequired','myteach') == 'true')
+	{
+		$form->addRule('teach', get_lang('ThisFieldIsRequired'), 'required');
+	}
+	if (api_get_setting('extendedprofile_registrationrequired','mypersonalopenarea') == 'true')
+	{
+		$form->addRule('openarea', get_lang('ThisFieldIsRequired'), 'required');
+	}
+}
+// EXTRA FIELDS
+$extra = UserManager::get_extra_fields(0,50,5,'ASC');
+$extra_data = UserManager::get_extra_user_data(api_get_user_id(),true);
+foreach ($extra as $id => $field_details) {
+	if ($field_details[6] == 0) {
+		continue;
+	}
+	switch($field_details[2]) {
+		case USER_FIELD_TYPE_TEXT:
+			$form->addElement('text', 'extra_'.$field_details[1], $field_details[3], array('size' => 40));
+			$form->applyFilter('extra_'.$field_details[1], 'stripslashes');
+			$form->applyFilter('extra_'.$field_details[1], 'trim');
+			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+			break;
+		case USER_FIELD_TYPE_TEXTAREA:
+			$form->add_html_editor('extra_'.$field_details[1], $field_details[3], false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130'));
+			//$form->addElement('textarea', 'extra_'.$field_details[1], $field_details[3], array('size' => 80));
+			$form->applyFilter('extra_'.$field_details[1], 'stripslashes');
+			$form->applyFilter('extra_'.$field_details[1], 'trim');
+			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+			break;
+		case USER_FIELD_TYPE_RADIO:
+			$group = array();
+			foreach ($field_details[9] as $option_id => $option_details) {
+				$options[$option_details[1]] = $option_details[2];
+				$group[] =& HTML_QuickForm::createElement('radio', 'extra_'.$field_details[1], $option_details[1],$option_details[2].'<br />',$option_details[1]);
+			}
+			$form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '');
+			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);	
+			break;
+		case USER_FIELD_TYPE_SELECT:
+			$options = array();
+			foreach($field_details[9] as $option_id => $option_details) {
+				$options[$option_details[1]] = $option_details[2];
+			}
+			$form->addElement('select','extra_'.$field_details[1],$field_details[3],$options,'');	
+			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);			
+			break;
+		case USER_FIELD_TYPE_SELECT_MULTIPLE:
+			$options = array();
+			foreach ($field_details[9] as $option_id => $option_details) {
+				$options[$option_details[1]] = $option_details[2];
+			}
+			$form->addElement('select','extra_'.$field_details[1],$field_details[3],$options,array('multiple' => 'multiple'));
+			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);	
+			break;
+		case USER_FIELD_TYPE_DATE:
+			$form->addElement('datepickerdate', 'extra_'.$field_details[1], $field_details[3],array('form_name'=>'registration'));
+			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear',1900);
+			$defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
+			$form -> setDefaults($defaults);
+			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+			$form->applyFilter('theme', 'trim');
+			break;
+		case USER_FIELD_TYPE_DATETIME:
+			$form->addElement('datepicker', 'extra_'.$field_details[1], $field_details[3],array('form_name'=>'registration'));
+			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear',1900);
+			$defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
+			$form -> setDefaults($defaults);
+			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+			$form->applyFilter('theme', 'trim');
+			break;
+		case USER_FIELD_TYPE_DOUBLE_SELECT:
+			foreach ($field_details[9] as $key=>$element) {
+				if ($element[2][0] == '*') {
+					$values['*'][$element[0]] = str_replace('*','',$element[2]);
+				} else {
+					$values[0][$element[0]] = $element[2];
+				}
+			}
+			
+			$group='';
+			$group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1],'',$values[0],'');
+			$group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1].'*','',$values['*'],'');
+			$form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '&nbsp;');
+			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+
+			// recoding the selected values for double : if the user has selected certain values, we have to assign them to the correct select form
+			if (key_exists('extra_'.$field_details[1], $extra_data)) {
+				// exploding all the selected values (of both select forms)
+				$selected_values = explode(';',$extra_data['extra_'.$field_details[1]]);
+				$extra_data['extra_'.$field_details[1]]  =array();
+				
+				// looping through the selected values and assigning the selected values to either the first or second select form
+				foreach ($selected_values as $key=>$selected_value) {
+					if (key_exists($selected_value,$values[0])) {
+						$extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1]] = $selected_value;
+					} else {
+						$extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1].'*'] = $selected_value;
+					}
+				}
+			}
+			break;
+		case USER_FIELD_TYPE_DIVIDER:
+			$form->addElement('static',$field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
+			break;
+	}
+}
+
+}
+//------------ Terms and conditions
+if (get_setting('allow_terms_conditions')=='true') {	
+	//$language = api_get_setting('platformLanguage');
+	$language = api_get_interface_language();
+	$language = api_get_language_id($language);
+	$term_preview= LegalManager::get_last_condition($language);	
+	
+	if ($term_preview==false) { 
+		//we load from the platform
+		$language = api_get_setting('platformLanguage');
+		$language = api_get_language_id($language);
+		$term_preview= LegalManager::get_last_condition($language);
+		//if is false we load from english
+		if ($term_preview==false){
+			$language = api_get_language_id('english'); //this must work
+			$term_preview= LegalManager::get_last_condition($language);	
+		}					
+	}	
+	// Version and language //password
+	$form->addElement('hidden', 'legal_accept_type',$term_preview['version'].':'.$term_preview['language_id']);
+	$form->addElement('hidden', 'legal_info',$term_preview['legal_id'].':'.$term_preview['language_id']);	
+	if (isset($_SESSION['info_current_user'][1]) && isset($_SESSION['info_current_user'][2])) {
+		$form->addElement('hidden', 'login',$_SESSION['info_current_user'][1]);
+		$form->addElement('hidden', 'password',$_SESSION['info_current_user'][2]);	
+	}
+	if($term_preview['type'] == 1) {
+		$form->addElement('checkbox', 'legal_accept', null, get_lang('IHaveReadAndAgree').'&nbsp;<a href="inscription.php?legal" target="_blank">'.get_lang('TermsAndConditions').'</a>');		
+		$form->addRule('extra_legal_accept',  get_lang('ThisFieldIsRequired'), 'required');
+	} else {
+		if (!empty($term_preview['content'])) {			
+			$preview = LegalManager::show_last_condition($term_preview);
+			$term_preview  = '<div class="row">
+					<div class="label">'.get_lang('TermsAndConditions').'</div>
+					<div class="formw">
+					'.$preview.'
+					<br />				
+					</div>
+					</div>';		
+			$form->addElement('html', $term_preview);
+		}		
+	}
+}
+
+$form->addElement('style_submit_button', 'submit', get_lang('RegisterUser'),array('class' => 'save', 'disabled' => 'disabled'));
+$defaults['status'] = STUDENT;
+$form->setDefaults($defaults);
+if(isset($_SESSION["user_language_choice"]) && $_SESSION["user_language_choice"]!=""){
+	$defaults['language'] = $_SESSION["user_language_choice"];
+}
+else{
+	$defaults['language'] = api_get_setting('platformLanguage');
+}
+if(!empty($_GET['username']))
+{
+	$defaults['username'] = Security::remove_XSS($_GET['username']);
+}
+if(!empty($_GET['email']))
+{
+	$defaults['email'] = Security::remove_XSS($_GET['email']);
+}
+
+if(!empty($_GET['phone']))
+{
+	$defaults['phone'] = Security::remove_XSS($_GET['phone']);
+}
+
+if (api_get_setting('openid_authentication')=='true' && !empty($_GET['openid']))
+{
+	$defaults['openid'] = Security::remove_XSS($_GET['openid']);	
+}
+
+switch($action){
+	case 'edit_top':
+		if($action == 'edit_top') {
+			$name= $topf;
+			$open = $home_top;
+		} else {
+			$name = $newsf;
+			$open=@file_get_contents($homep.$newsf.'_'.$lang.$ext);
+
+		}
+
+		if(!empty($errorMsg)) {
+			Display::display_normal_message($errorMsg); //main API
+		}
+
+		$default = array();
+		$form = new FormValidator('configure_homepage_'.$action, 'post', api_get_self().'?action='.$action, '', array('style' => 'margin: 0px;'));
+		$renderer =& $form->defaultRenderer();
+		$renderer->setHeaderTemplate('');
+		$renderer->setFormTemplate('<form{attributes}><table border="0" cellpadding="5" cellspacing="0" width="100%">{content}</table></form>');
+		$renderer->setElementTemplate('<tr><td>{element}</td></tr>');
+		$renderer->setRequiredNoteTemplate('');
+		$form->addElement('hidden', 'formSent', '1');
+		if (api_get_setting('wcag_anysurfer_public_pages')=='true') {
+			//TODO: review these lines
+			// Print WCAG-specific HTML editor
+			$html = '<tr><td>';
+			$html .= WCAG_Rendering::create_xhtml($open);
+			$html .= '</td></tr>';
+			$form->addElement('html', $html);
+		} else {
+			$default[$name] = str_replace('{rel_path}', api_get_path(REL_PATH), $open);
+			$form->add_html_editor($name, '', true, false, array('ToolbarSet' => 'PortalHomePage', 'Width' => '100%', 'Height' => '400'));
+		}
+		$form->addElement('style_submit_button', null, get_lang('Save'), 'class="save"');
+		$form->setDefaults($default);
+		$form->display();
+		break;
+	default:
+		/*******************************/
+		//Form of language
+		api_display_language_form();
+		
+		echo '&nbsp;&nbsp;<a href="'.api_get_self().'?action=edit_top">'.Display::display_icon('edit.gif', get_lang('Edit')).'</a> <a href="'.api_get_self().'?action=edit_top">'.get_lang('EditNotice').'</a>';
+		echo '<div class="note">';
+		$home_notice = '';
+		if(file_exists($homep.$topf.'_'.$lang.$ext)) {
+		$home_notice = @file_get_contents($homep.$topf.'_'.$lang.$ext);
+		} else {
+			$home_notice = @file_get_contents($homep.$topf.$ext);
+		}
+		echo $home_notice;
+		echo '</div>'; 
+		/*******************************/
+		$form->display();
+		break;
+}
+
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+
+Display :: display_footer();
+?>

+ 25 - 43
main/admin/course_add.php

@@ -1,29 +1,6 @@
 <?php
 // $Id: course_add.php 20441 2009-05-10 07:39:15Z ivantcholakov $
-/*
-==============================================================================
-	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) 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, rue du Corbeau, 108, B-1030 Brussels
-		 Belgium, info@dokeos.com
-==============================================================================
-*/
+/* For licensing terms, see /dokeos_license.txt */
 /**
 ==============================================================================
 *	@package dokeos.admin
@@ -35,7 +12,7 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
+// name of the language file that needs to be included
 $language_file = array('admin','create_course');
 $cidReset = true;
 require_once ('../inc/global.inc.php');
@@ -60,22 +37,23 @@ $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAd
 global $_configuration;
 
 // Get all possible teachers
+$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
 $table_user = Database :: get_main_table(TABLE_MAIN_USER);
-$sql = "SELECT user_id,lastname,firstname FROM $table_user WHERE status=1 ORDER BY lastname,firstname";
+$sql = "SELECT user_id,lastname,firstname FROM $table_user WHERE status=1".$order_clause;
 //filtering teachers when creating a course
 if ($_configuration['multiple_access_urls']==true){
-	$access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);   	
+	$access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 	$sql = "SELECT u.user_id,lastname,firstname FROM $table_user as u
-			INNER JOIN $access_url_rel_user_table url_rel_user 
-			ON (u.user_id=url_rel_user.user_id) WHERE url_rel_user.access_url_id=".api_get_current_access_url_id()." AND status=1 ORDER BY lastname,firstname ";  
+			INNER JOIN $access_url_rel_user_table url_rel_user
+			ON (u.user_id=url_rel_user.user_id) WHERE url_rel_user.access_url_id=".api_get_current_access_url_id()." AND status=1".$order_clause;
 }
 
-$res = api_sql_query($sql,__FILE__,__LINE__);
+$res = Database::query($sql,__FILE__,__LINE__);
 $teachers = array();
 $teachers[0] = '-- '.get_lang('NoManager').' --';
-while($obj = mysql_fetch_object($res))
+while($obj = Database::fetch_object($res))
 {
-	$teachers[$obj->user_id] = $obj->lastname.' '.$obj->firstname;
+	$teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
 }
 
 
@@ -84,8 +62,15 @@ $dbnamelength = strlen($_configuration['db_prefix']);
 $maxlength = 40 - $dbnamelength;
 
 // Build the form
-$form = new FormValidator('update_course'); 
+$form = new FormValidator('update_course');
 $form->addElement('header', '', $tool_name);
+
+//Title
+$form->add_textfield('title', get_lang('Title'),true, array ('size' => '60'));
+$form->applyFilter('title','html_filter');
+$form->applyFilter('title','trim');
+
+// code
 $form->add_textfield( 'visual_code', get_lang('CourseCode'),false,array('size'=>'20','maxlength'=>20));
 $form->applyFilter('visual_code','api_strtoupper');
 $form->applyFilter('visual_code','html_filter');
@@ -97,10 +82,7 @@ $form->applyFilter('tutor_id','html_filter');
 $form->addElement('select', 'course_teachers', get_lang('CourseTeachers'), $teachers, 'multiple=multiple size=5');
 $form->applyFilter('course_teachers','html_filter');
 
-//Title
-$form->add_textfield('title', get_lang('Title'),true, array ('size' => '60'));
-$form->applyFilter('title','html_filter');
-$form->applyFilter('title','trim');
+
 
 $categories_select = $form->addElement('select', 'category_code', get_lang('CourseFaculty'), $categories);
 $form->applyFilter('category_code','html_filter');
@@ -110,7 +92,7 @@ $form->add_textfield('department_name', get_lang('CourseDepartment'),false, arra
 $form->applyFilter('department_name','html_filter');
 $form->applyFilter('department_name','trim');
 
-//Department URL 
+//Department URL
 $form->add_textfield('department_url', get_lang('CourseDepartmentURL'),false, array ('size' => '60'));
 $form->applyFilter('department_url','html_filter');
 
@@ -131,8 +113,8 @@ $form->addRule('disk_quota',get_lang('ThisFieldShouldBeNumeric'),'numeric');
 $form->add_progress_bar();
 $form->addElement('style_submit_button','submit', get_lang('CreateCourse'),'class="add"');
 // Set some default values
-$values['course_language'] = get_setting('platformLanguage');
-$values['disk_quota'] = get_setting('default_document_quotum');
+$values['course_language'] = api_get_setting('platformLanguage');
+$values['disk_quota'] = api_get_setting('default_document_quotum');
 $values['visibility'] = COURSE_VISIBILITY_OPEN_PLATFORM;
 $values['subscribe'] = 1;
 $values['unsubscribe'] = 0;
@@ -147,7 +129,7 @@ if( $form->validate()) {
 	$teacher_id = $course['tutor_id'];
 	$course_teachers = $course['course_teachers'];
 	$test=false;
-	
+
 	//The course tutor has been selected in the teachers list so we must remove him to avoid double records in the database
 	foreach($course_teachers as $key=>$value){
 		if($value==$teacher_id){
@@ -181,8 +163,8 @@ if( $form->validate()) {
 		$pictures_array=fill_course_repository($currentCourseRepository);
 		fill_Db_course($currentCourseDbName, $currentCourseRepository, $course_language,$pictures_array);
 		register_course($currentCourseId, $currentCourseCode, $currentCourseRepository, $currentCourseDbName, $tutor_name, $category, $title, $course_language, $teacher_id, $expiration_date,$course_teachers);
-		$sql = "UPDATE $table_course SET disk_quota = '".$disk_quota."', visibility = '".mysql_real_escape_string($course['visibility'])."', subscribe = '".mysql_real_escape_string($course['subscribe'])."', unsubscribe='".mysql_real_escape_string($course['unsubscribe'])."' WHERE code = '".$currentCourseId."'";
-		api_sql_query($sql,__FILE__,__LINE__);
+		$sql = "UPDATE $table_course SET disk_quota = '".$disk_quota."', visibility = '".Database::escape_string($course['visibility'])."', subscribe = '".Database::escape_string($course['subscribe'])."', unsubscribe='".Database::escape_string($course['unsubscribe'])."' WHERE code = '".$currentCourseId."'";
+		Database::query($sql,__FILE__,__LINE__);
 		header('Location: course_list.php');
 		exit ();
 	}

+ 51 - 51
main/admin/course_category.php

@@ -28,7 +28,7 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
+// name of the language file that needs to be included
 $language_file='admin';
 
 $cidReset=true;
@@ -90,7 +90,7 @@ if(!empty($action))
 	{
 		$categoryCode=Database::escape_string($_GET['id']);
 
-		$result=api_sql_query("SELECT name,auth_course_child FROM $tbl_category WHERE code='$categoryCode'",__FILE__,__LINE__);
+		$result=Database::query("SELECT name,auth_course_child FROM $tbl_category WHERE code='$categoryCode'",__FILE__,__LINE__);
 
 		list($categoryName,$canHaveCourses)=Database::fetch_row($result);
 
@@ -117,7 +117,7 @@ Display::display_header($tool_name);
 if(!empty($category))
 {
 	$myquery = "SELECT * FROM $tbl_category WHERE code ='$category'";
-	$result	= api_sql_query($myquery,__FILE__,__LINE__);
+	$result	= Database::query($myquery,__FILE__,__LINE__);
 	if(Database::num_rows($result)==0)
 	{
 		$category = '';
@@ -127,59 +127,59 @@ if(!empty($category))
 if(empty($action))
 {
 	$myquery="SELECT t1.name,t1.code,t1.parent_id,t1.tree_pos,t1.children_count,COUNT(DISTINCT t3.code) AS nbr_courses FROM $tbl_category t1 LEFT JOIN $tbl_category t2 ON t1.code=t2.parent_id LEFT JOIN $tbl_course t3 ON t3.category_code=t1.code WHERE t1.parent_id ".(empty($category)?"IS NULL":"='$category'")." GROUP BY t1.name,t1.code,t1.parent_id,t1.tree_pos,t1.children_count ORDER BY t1.tree_pos";
-	$result=api_sql_query($myquery,__FILE__,__LINE__);
+	$result=Database::query($myquery,__FILE__,__LINE__);
 
-	$Categories=api_store_result($result);
+	$Categories=Database::store_result($result);
 }
 
-	
-	
+
+
 
 if($action == 'add' || $action == 'edit')
 {
 	?>
 	<div class="actions">
 	<a href="<?php echo api_get_self(); ?>?category=<?php echo Security::remove_XSS($category); ?>"><?php echo Display::return_icon('folder_up.gif').get_lang("Back"); if(!empty($category)) echo ' ('.Security::remove_XSS($category).')'; ?></a>
-	</div>	
-	
-	
+	</div>
+
 
-	<?php 
-	$form_title = ($action == 'add')?get_lang('AddACategory'):get_lang('EditNode'); 
+
+	<?php
+	$form_title = ($action == 'add')?get_lang('AddACategory'):get_lang('EditNode');
 	if(!empty($category))
 	{
-		$form_title .= ' '.get_lang('Into').' '.Security::remove_XSS($category); 
+		$form_title .= ' '.get_lang('Into').' '.Security::remove_XSS($category);
 	}
-	
+
 	$form = new FormValidator('course_category');
 	$form->addElement('header', '', $form_title);
 	$form->display();
-	
+
 	?>
-	
+
 	<form method="post" action="<?php echo api_get_self(); ?>?action=<?php echo Security::remove_XSS($action); ?>&category=<?php echo Security::remove_XSS($category); ?>&amp;id=<?php echo Security::remove_XSS($_GET['id']); ?>">
 	<input type="hidden" name="formSent" value="1" />
 	<table border="0" cellpadding="5" cellspacing="0">
-	
+
 	<?php
 	if(!empty($errorMsg))
 	{
 	?>
-	
+
 	<tr>
 	  <td colspan="2">
-	
+
 	<?php
 		Display::display_normal_message($errorMsg); //main API
 	?>
-	
+
 	  </td>
 	</tr>
-	
+
 	<?php
 	}
 	?>
-	
+
 	<tr>
 	  <td nowrap="nowrap"><?php echo get_lang("CategoryCode"); ?> :</td>
 	  <td><input type="text" name="categoryCode" size="20" maxlength="20" value="<?php echo api_htmlentities(stripslashes($categoryCode),ENT_QUOTES,$charset); ?>" /></td>
@@ -203,36 +203,36 @@ if($action == 'add' || $action == 'edit')
 			$text=get_lang('CategoryMod');
 		} else {
 			$class="add";
-			$text=get_lang('AddCategory'); 
+			$text=get_lang('AddCategory');
 		}
 	  ?>
 	  <td><button type="submit" class="<?php echo $class; ?>" value="<?php echo $text; ?>" ><?php echo $text; ?></button></td>
 	</tr>
 	</table>
 	</form>
-	
+
 	<?php
 }
 else
 {
 ?>
 <div class="actions">
-<?php 
+<?php
 if(!empty($category) && empty($action))
 {
 	$myquery = "SELECT parent_id FROM $tbl_category WHERE code='$category'";
-	$result=api_sql_query($myquery,__FILE__,__LINE__);
+	$result=Database::query($myquery,__FILE__,__LINE__);
 	$parent_id = 0;
 	if(Database::num_rows($result)>0){
 		$parent_id=Database::fetch_array($result);
 	}
-	
+
 	$parent_id['parent_id']?$link=' ('.$parent_id['parent_id'].')':$link='';
 	?>
 
 	<a href="<?php echo api_get_self(); ?>?category=<?php echo $parent_id['parent_id']; ?>"><?php echo Display::return_icon('folder_up.gif').get_lang("Back"); if(!empty($parent_id)) echo $link ?></a>
 
-	<?php 
+	<?php
 }
 ?>
 <a href="<?php echo api_get_self(); ?>?category=<?php echo Security::remove_XSS($category); ?>&amp;action=add"><?php echo Display::return_icon('folder_new.gif').get_lang("AddACategory"); if(!empty($category)) echo ' '.get_lang('Into').' '.Security::remove_XSS($category); ?></a>
@@ -271,9 +271,9 @@ else
 
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
-*/ 
+*/
 Display::display_footer();
 
 /******** Functions ********/
@@ -283,23 +283,23 @@ function deleteNode($node)
 	global $tbl_category, $tbl_course;
 	$node = Database::escape_string($node);
 
-	$result=api_sql_query("SELECT parent_id,tree_pos FROM $tbl_category WHERE code='$node'",__FILE__,__LINE__);
+	$result=Database::query("SELECT parent_id,tree_pos FROM $tbl_category WHERE code='$node'",__FILE__,__LINE__);
 
 	if($row=Database::fetch_array($result))
 	{
 		if(!empty($row['parent_id']))
 		{
-			api_sql_query("UPDATE $tbl_course SET category_code='".$row['parent_id']."' WHERE category_code='$node'",__FILE__,__LINE__);
-			api_sql_query("UPDATE $tbl_category SET parent_id='".$row['parent_id']."' WHERE parent_id='$node'",__FILE__,__LINE__);
+			Database::query("UPDATE $tbl_course SET category_code='".$row['parent_id']."' WHERE category_code='$node'",__FILE__,__LINE__);
+			Database::query("UPDATE $tbl_category SET parent_id='".$row['parent_id']."' WHERE parent_id='$node'",__FILE__,__LINE__);
 		}
 		else
 		{
-			api_sql_query("UPDATE $tbl_course SET category_code='' WHERE category_code='$node'",__FILE__,__LINE__);
-			api_sql_query("UPDATE $tbl_category SET parent_id=NULL WHERE parent_id='$node'",__FILE__,__LINE__);
+			Database::query("UPDATE $tbl_course SET category_code='' WHERE category_code='$node'",__FILE__,__LINE__);
+			Database::query("UPDATE $tbl_category SET parent_id=NULL WHERE parent_id='$node'",__FILE__,__LINE__);
 		}
 
-		api_sql_query("UPDATE $tbl_category SET tree_pos=tree_pos-1 WHERE tree_pos > '".$row['tree_pos']."'",__FILE__,__LINE__);
-		api_sql_query("DELETE FROM $tbl_category WHERE code='$node'",__FILE__,__LINE__);
+		Database::query("UPDATE $tbl_category SET tree_pos=tree_pos-1 WHERE tree_pos > '".$row['tree_pos']."'",__FILE__,__LINE__);
+		Database::query("DELETE FROM $tbl_category WHERE code='$node'",__FILE__,__LINE__);
 
 		if(!empty($row['parent_id']))
 		{
@@ -315,22 +315,22 @@ function addNode($code,$name,$canHaveCourses,$parent_id)
 	$canHaveCourses=$canHaveCourses?'TRUE':'FALSE';
 	$code 			= Database::escape_string($code);
 	$name 			= Database::escape_string($name);
-	$parent_id		= Database::escape_string($parent_id);	
+	$parent_id		= Database::escape_string($parent_id);
 
-	$result=api_sql_query("SELECT 1 FROM $tbl_category WHERE code='$code'",__FILE__,__LINE__);
+	$result=Database::query("SELECT 1 FROM $tbl_category WHERE code='$code'",__FILE__,__LINE__);
 
 	if(Database::num_rows($result))
 	{
 		return false;
 	}
 
-	$result=api_sql_query("SELECT MAX(tree_pos) AS maxTreePos FROM $tbl_category",__FILE__,__LINE__);
+	$result=Database::query("SELECT MAX(tree_pos) AS maxTreePos FROM $tbl_category",__FILE__,__LINE__);
 
 	$row=Database::fetch_array($result);
 
 	$tree_pos=$row['maxTreePos']+1;
 
-	api_sql_query("INSERT INTO $tbl_category(name,code,parent_id,tree_pos,children_count,auth_course_child) VALUES('$name','$code',".(empty($parent_id)?"NULL":"'$parent_id'").",'$tree_pos','0','$canHaveCourses')",__FILE__,__LINE__);
+	Database::query("INSERT INTO $tbl_category(name,code,parent_id,tree_pos,children_count,auth_course_child) VALUES('$name','$code',".(empty($parent_id)?"NULL":"'$parent_id'").",'$tree_pos','0','$canHaveCourses')",__FILE__,__LINE__);
 
 	updateFils($parent_id);
 
@@ -348,7 +348,7 @@ function editNode($code,$name,$canHaveCourses,$old_code)
 
 	if($code != $old_code)
 	{
-		$result=api_sql_query("SELECT 1 FROM $tbl_category WHERE code='$code'",__FILE__,__LINE__);
+		$result=Database::query("SELECT 1 FROM $tbl_category WHERE code='$code'",__FILE__,__LINE__);
 
 		if(Database::num_rows($result))
 		{
@@ -356,7 +356,7 @@ function editNode($code,$name,$canHaveCourses,$old_code)
 		}
 	}
 
-	api_sql_query("UPDATE $tbl_category SET name='$name',code='$code',auth_course_child='$canHaveCourses' WHERE code='$old_code'",__FILE__,__LINE__);
+	Database::query("UPDATE $tbl_category SET name='$name',code='$code',auth_course_child='$canHaveCourses' WHERE code='$old_code'",__FILE__,__LINE__);
 
 	return true;
 }
@@ -367,12 +367,12 @@ function moveNodeUp($code,$tree_pos,$parent_id)
 	$code 		= Database::escape_string($code);
 	$tree_pos 	= Database::escape_string($tree_pos);
 	$parent_id	= Database::escape_string($parent_id);
-	
-	$result=api_sql_query("SELECT code,tree_pos FROM $tbl_category WHERE parent_id ".(empty($parent_id)?"IS NULL":"='$parent_id'")." AND tree_pos<'$tree_pos' ORDER BY tree_pos DESC LIMIT 0,1",__FILE__,__LINE__);
+
+	$result=Database::query("SELECT code,tree_pos FROM $tbl_category WHERE parent_id ".(empty($parent_id)?"IS NULL":"='$parent_id'")." AND tree_pos<'$tree_pos' ORDER BY tree_pos DESC LIMIT 0,1",__FILE__,__LINE__);
 
 	if(!$row=Database::fetch_array($result))
 	{
-		$result=api_sql_query("SELECT code,tree_pos FROM $tbl_category WHERE parent_id ".(empty($parent_id)?"IS NULL":"='$parent_id'")." AND tree_pos>'$tree_pos' ORDER BY tree_pos DESC LIMIT 0,1",__FILE__,__LINE__);
+		$result=Database::query("SELECT code,tree_pos FROM $tbl_category WHERE parent_id ".(empty($parent_id)?"IS NULL":"='$parent_id'")." AND tree_pos>'$tree_pos' ORDER BY tree_pos DESC LIMIT 0,1",__FILE__,__LINE__);
 
 		if(!$row=Database::fetch_array($result))
 		{
@@ -380,15 +380,15 @@ function moveNodeUp($code,$tree_pos,$parent_id)
 		}
 	}
 
-	api_sql_query("UPDATE $tbl_category SET tree_pos='".$row['tree_pos']."' WHERE code='$code'",__FILE__,__LINE__);
-	api_sql_query("UPDATE $tbl_category SET tree_pos='$tree_pos' WHERE code='$row[code]'",__FILE__,__LINE__);
+	Database::query("UPDATE $tbl_category SET tree_pos='".$row['tree_pos']."' WHERE code='$code'",__FILE__,__LINE__);
+	Database::query("UPDATE $tbl_category SET tree_pos='$tree_pos' WHERE code='$row[code]'",__FILE__,__LINE__);
 }
 
 function updateFils($category)
 {
 	global $tbl_category;
 	$category = Database::escape_string($category);
-	$result=api_sql_query("SELECT parent_id FROM $tbl_category WHERE code='$category'",__FILE__,__LINE__);
+	$result=Database::query("SELECT parent_id FROM $tbl_category WHERE code='$category'",__FILE__,__LINE__);
 
 	if($row=Database::fetch_array($result))
 	{
@@ -397,14 +397,14 @@ function updateFils($category)
 
 	$children_count=compterFils($category,0)-1;
 
-	api_sql_query("UPDATE $tbl_category SET children_count='$children_count' WHERE code='$category'",__FILE__,__LINE__);
+	Database::query("UPDATE $tbl_category SET children_count='$children_count' WHERE code='$category'",__FILE__,__LINE__);
 }
 
 function compterFils($pere,$cpt)
 {
 	global $tbl_category;
 	$pere = Database::escape_string($pere);
-	$result=api_sql_query("SELECT code FROM $tbl_category WHERE parent_id='$pere'",__FILE__,__LINE__);
+	$result=Database::query("SELECT code FROM $tbl_category WHERE parent_id='$pere'",__FILE__,__LINE__);
 
 	while($row=Database::fetch_array($result))
 	{

+ 13 - 13
main/admin/course_create_content.php

@@ -1,32 +1,32 @@
 <?php
 // $Id: course_create_content.php 10811 2007-01-22 08:26:40Z elixir_julian $
 /*
-============================================================================== 
+==============================================================================
 	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) 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 address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
-============================================================================== 
+==============================================================================
 */
 /**
  * ==============================================================================
  * This script allows a platform admin to add dummy content to a course.
- * 
+ *
  * @author Bart Mollet <bart.mollet@hogent.be>
  * @package dokeos.admin
  * ==============================================================================
@@ -35,9 +35,9 @@
 ==============================================================================
 		INIT SECTION
 ==============================================================================
-*/ 
+*/
 
-// name of the language file that needs to be included 
+// name of the language file that needs to be included
 $language_file = 'admin';
 include ('../inc/global.inc.php');
 $this_section=SECTION_PLATFORM_ADMIN;
@@ -47,9 +47,9 @@ $tool_name = get_lang('DummyCourseCreator');
 $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
 Display::display_header($tool_name);
 //api_display_tool_title($tool_name);
-if( get_setting('server_type') != 'test')
+if(api_get_setting('server_type') != 'test')
 {
-	echo get_lang('DummyCourseOnlyOnTestServer');	
+	echo get_lang('DummyCourseOnlyOnTestServer');
 }
 elseif( isset($_POST['action']))
 {
@@ -65,7 +65,7 @@ else
 }
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display::display_footer();

+ 53 - 49
main/admin/course_edit.php

@@ -11,7 +11,7 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
+// name of the language file that needs to be included
 $language_file = 'admin';
 $cidReset = true;
 include ('../inc/global.inc.php');
@@ -51,7 +51,7 @@ $table_user = Database :: get_main_table(TABLE_MAIN_USER);
 
 //Get the course infos
 $sql = "SELECT * FROM $course_table WHERE code='".Database::escape_string($course_code)."'";
-$result = api_sql_query($sql, __FILE__, __LINE__);
+$result = Database::query($sql, __FILE__, __LINE__);
 if (Database::num_rows($result) != 1)
 {
 	header('Location: course_list.php');
@@ -61,38 +61,39 @@ $course = Database::fetch_array($result,'ASSOC');
 
 // Get course teachers
 $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-$sql = "SELECT user.user_id,lastname,firstname FROM $table_user as user,$table_course_user as course_user WHERE course_user.status='1' AND course_user.user_id=user.user_id AND course_user.course_code='".$course_code."' ORDER BY lastname,firstname";
-$res = api_sql_query($sql,__FILE__,__LINE__);
+$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
+$sql = "SELECT user.user_id,lastname,firstname FROM $table_user as user,$table_course_user as course_user WHERE course_user.status='1' AND course_user.user_id=user.user_id AND course_user.course_code='".$course_code."'".$order_clause;
+$res = Database::query($sql,__FILE__,__LINE__);
 $course_teachers = array();
 while($obj = Database::fetch_object($res))
 {
-		$course_teachers[$obj->user_id] = $obj->lastname.' '.$obj->firstname;
+	$course_teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
 }
 
 // Get all possible teachers without the course teachers
-$sql = "SELECT user_id,lastname,firstname FROM $table_user WHERE status='1' ORDER BY lastname,firstname";
-$res = api_sql_query($sql,__FILE__,__LINE__);
+$sql = "SELECT user_id,lastname,firstname FROM $table_user WHERE status='1'".$order_clause;
+$res = Database::query($sql,__FILE__,__LINE__);
 $teachers = array();
 
 $platform_teachers[0] = '-- '.get_lang('NoManager').' --';
 while($obj = Database::fetch_object($res))
-{		
+{
 	if(!array_key_exists($obj->user_id,$course_teachers)){
-		$teachers[$obj->user_id] = $obj->lastname.' '.$obj->firstname;
+		$teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
 	}
-	
+
 
 	if($course['tutor_name']==$course_teachers[$obj->user_id]){
 		$course['tutor_name']=$obj->user_id;
 	}
-	//We add in the array platform teachers 
-	$platform_teachers[$obj->user_id] = $obj->lastname.' '.$obj->firstname;
+	//We add in the array platform teachers
+	$platform_teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
 }
 
 //Case where there is no teacher in the course
 if(count($course_teachers)==0){
 	$sql='SELECT tutor_name FROM '.$course_table.' WHERE code="'.$course_code.'"';
-	$res = api_sql_query($sql,__FILE__,__LINE__);
+	$res = Database::query($sql,__FILE__,__LINE__);
 	$tutor_name=Database::result($res,0,0);
 	$course['tutor_name']=array_search($tutor_name,$platform_teachers);
 }
@@ -100,6 +101,12 @@ if(count($course_teachers)==0){
 // Build the form
 $form = new FormValidator('update_course');
 $form->addElement('hidden','code',$course_code);
+
+//title
+$form->add_textfield( 'title', get_lang('Title'),true, array ('size' => '60'));
+$form->applyFilter('title','html_filter');
+$form->applyFilter('title','trim');
+// code
 $form->add_textfield('visual_code', get_lang('CourseCode'));
 $form->applyFilter('visual_code','strtoupper');
 $form->applyFilter('visual_code','html_filter');
@@ -127,14 +134,11 @@ $element_template = <<<EOT
 		</div>
 	</div>
 EOT;
-	
+
 $renderer = $form->defaultRenderer();
 $renderer -> setElementTemplate($element_template, 'group');
 $form -> addGroup($group,'group',get_lang('CourseTeachers'),'</td><td width="50" align="center"><input type="button" onclick="moveItem(document.getElementById(\'platform_teachers\'), document.getElementById(\'course_teachers\'))" value=">>"><br><br><input type="button" onclick="moveItem(document.getElementById(\'course_teachers\'), document.getElementById(\'platform_teachers\'))" value="<<"></td><td>');
-//title 
-$form->add_textfield( 'title', get_lang('Title'),true, array ('size' => '60'));
-$form->applyFilter('title','html_filter');
-$form->applyFilter('title','trim');
+
 
 $categories_select = $form->addElement('select', 'category_code', get_lang('CourseFaculty'), $categories);
 CourseManager::select_and_sort_categories($categories_select);
@@ -165,7 +169,7 @@ $form->addElement('style_submit_button', 'button', get_lang('ModifyCourseInfo'),
 // Set some default values
 
 $course_db_name = $course['db_name'];
-$course['title']=api_html_entity_decode($course['title'],ENT_QUOTES,$charset);
+$course['title'] = api_html_entity_decode($course['title'], ENT_QUOTES, $charset);
 $form->setDefaults($course);
 // Validate form
 if( $form->validate())
@@ -174,7 +178,7 @@ if( $form->validate())
 	$dbName = $_POST['dbName'];
 	$course_code = $course['code'];
 	$visual_code = $course['visual_code'];
-    
+
     // Check if the visual code is already used by *another* course
     $visual_code_is_used = false;
     error_log($visual_code);
@@ -190,12 +194,12 @@ if( $form->validate())
         }
         $warn = substr($warn,0,-1);
     }
-	
+
 	$tutor_id = $course['tutor_name'];
 	$tutor_name=$platform_teachers[$tutor_id];
-	
+
 	$teachers = $course['group']['course_teachers'];
-	
+
 	$title = $course['title'];
 	$category_code = $course['category_code'];
 	$department_name = $course['department_name'];
@@ -217,27 +221,27 @@ if( $form->validate())
 								department_name='".Database::escape_string($department_name)."',
 								department_url='".Database::escape_string($department_url)."',
 								disk_quota='".Database::escape_string($disk_quota)."',
-								visibility = '".Database::escape_string($visibility)."', 
+								visibility = '".Database::escape_string($visibility)."',
 								subscribe = '".Database::escape_string($subscribe)."',
 								unsubscribe='".Database::escape_string($unsubscribe)."'
 							WHERE code='".Database::escape_string($course_code)."'";
-	api_sql_query($sql, __FILE__, __LINE__);
-	
+	Database::query($sql, __FILE__, __LINE__);
+
 	//Delete only teacher relations that doesn't match the selected teachers
 	$cond='';
 	if(count($teachers)>0){
 		foreach($teachers as $key) $cond.=" AND user_id<>'".$key."'";
-	}	
+	}
 	$sql='DELETE FROM '.$course_user_table.' WHERE course_code="'.Database::escape_string($course_code).'" AND status="1"'.$cond;
-	api_sql_query($sql, __FILE__, __LINE__);
-	
+	Database::query($sql, __FILE__, __LINE__);
+
 	if(count($teachers)>0){
 		foreach($teachers as $key){
-			
-			//We check if the teacher is already subscribed in this course 
+
+			//We check if the teacher is already subscribed in this course
 			$sql_select_teacher = 'SELECT 1 FROM '.$course_user_table.' WHERE user_id = "'.$key.'" AND course_code = "'.$course_code.'"';
-			$result = api_sql_query($sql_select_teacher, __FILE__, __LINE__);
-			
+			$result = Database::query($sql_select_teacher, __FILE__, __LINE__);
+
 			if(Database::num_rows($result) == 1){
 				$sql = 'UPDATE '.$course_user_table.' SET status = "1" WHERE course_code = "'.$course_code.'" AND user_id = "'.$key.'"';
 			}
@@ -251,12 +255,12 @@ if( $form->validate())
 					sort='0',
 					user_course_cat='0'";
 			}
-			api_sql_query($sql, __FILE__, __LINE__);
-			
+			Database::query($sql, __FILE__, __LINE__);
+
 		}
-		
+
 	}
-	
+
 	$sql = "INSERT IGNORE INTO ".$course_user_table . " SET
 				course_code = '".Database::escape_string($course_code). "',
 				user_id = '".$tutor_id . "',
@@ -265,12 +269,12 @@ if( $form->validate())
 				tutor_id='0',
 				sort='0',
 				user_course_cat='0'";
-	api_sql_query($sql, __FILE__, __LINE__);
-	
+	Database::query($sql, __FILE__, __LINE__);
+
 	$forum_config_table = Database::get_course_table(TOOL_FORUM_CONFIG_TABLE,$course_db_name);
 	$sql = "UPDATE ".$forum_config_table." SET default_lang='".Database::escape_string($course_language)."'";
 	if ($visual_code_is_used == true) {
-	    header('Location: course_list.php?action=show_msg&warn='.urlencode($warn));	
+	    header('Location: course_list.php?action=show_msg&warn='.urlencode($warn));
 	} else {
         header('Location: course_list.php');
 	}
@@ -280,30 +284,30 @@ Display::display_header($tool_name);
 
 echo "<script>
 function moveItem(origin , destination){
-	
+
 	for(var i = 0 ; i<origin.options.length ; i++) {
-		if(origin.options[i].selected) {	
+		if(origin.options[i].selected) {
 			destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
-			origin.options[i]=null;	
+			origin.options[i]=null;
 			i = i-1;
 		}
 	}
 	destination.selectedIndex = -1;
 	sortOptions(destination.options);
-	
+
 }
 
-function sortOptions(options) { 
+function sortOptions(options) {
 
 	newOptions = new Array();
 	for (i = 0 ; i<options.length ; i++)
 		newOptions[i] = options[i];
-		
-	newOptions = newOptions.sort(mysort);	
+
+	newOptions = newOptions.sort(mysort);
 	options.length = 0;
 	for(i = 0 ; i < newOptions.length ; i++)
 		options[i] = newOptions[i];
-	
+
 }
 
 function mysort(a, b){
@@ -328,7 +332,7 @@ function valide(){
 $form->display();
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 229 - 249
main/admin/course_import.php

@@ -1,249 +1,229 @@
-<?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
-==============================================================================
-*/
-/**
- * validate the imported data
- */
-function validate_data($courses) {
-	global $_configuration;	
-	$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 if mandatory fields are set
-		$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;
-			}
-		}
-		//2. check if code isn't in use
-		if (isset ($course['Code']) && strlen($course['Code']) != 0) {
-			//2.1 check if code allready used in this CVS-file
-			if (isset ($coursecodes[$course['Code']])) {
-				$course['error'] = get_lang('CodeTwiceInFile');
-				$errors[] = $course;
-			} elseif (api_strlen($course['Code']) > $maxlength) {
-				$course['error'] = get_lang('Max');
-				$errors[] = $course;
-			}
-			//2.3 check if code allready used in DB
-			else {
-				$course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
-				$sql = "SELECT * FROM $course_table WHERE code = '".Database::escape_string($course['Code'])."'";
-				$res = api_sql_query($sql, __FILE__, __LINE__);
-				if (Database::num_rows($res) > 0) {
-					$course['error'] = get_lang('CodeExists');
-					$errors[] = $course;
-				}
-			}
-			$coursecodes[$course['Code']] = 1;
-		}
-		//3. check if teacher exists
-		if (isset ($course['Teacher']) && strlen($course['Teacher']) != 0)
-		{
-			if (UserManager :: is_username_available($course['Teacher']))
-			{
-				$course['error'] = get_lang('UnknownTeacher');
-				$errors[] = $course;
-			}
-		}
-		//4. check if category exists
-		if (isset ($course['CourseCategory']) && strlen($course['CourseCategory']) != 0)
-		{
-			$category_table = Database :: get_main_table(TABLE_MAIN_CATEGORY);
-			$sql = "SELECT * FROM $category_table WHERE code = '".mysql_real_escape_string($course['CourseCategory'])."'";
-			$res = api_sql_query($sql, __FILE__, __LINE__);
-			if (mysql_num_rows($res) == 0)
-			{
-				$course['error'] = get_lang('UnkownCategory');
-				$errors[] = $course;
-			}
-		}
-	}
-	return $errors;
-}
-
-/**
- * Save the imported data
- * @param   array   List of courses info
- */
-function save_data($courses)
-{
-	global $_configuration, $firstExpirationDelay;
-	$msg = '';
-	$enabled_languages = api_get_languages();
-	$enabled_languages = $enabled_languages["folder"];
-	foreach($courses as $index => $course)
-	{
-		$course_language = $course['Language'];
-		if (empty($course_language) || !in_array($course_language, $enabled_languages))
-		{
-			$course_language = api_get_setting('platformLanguage');
-		}
-		$keys = define_course_keys($course['Code'], "", $_configuration['db_prefix']);
-		$user_table = Database::get_main_table(TABLE_MAIN_USER);
-		$sql = "SELECT user_id, CONCAT(lastname,' ',firstname) AS name FROM $user_table WHERE username = '".Database::escape_string($course['Teacher'])."'";
-		$res = api_sql_query($sql,__FILE__,__LINE__);
-		$teacher = mysql_fetch_object($res);
-		$visual_code = $keys["currentCourseCode"];
-		$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
- */
-function parse_csv_data($file)
-{
-	$courses = Import :: csv_to_array($file);
-	return $courses;
-}
-
-$language_file = array ('admin', 'registration','create_course', 'document');
-
-$cidReset = true;
-
-include ('../inc/global.inc.php');
-api_protect_admin_script();
-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(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');
-$formSent = 0;
-$errorMsg = '';
-$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';
-
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
-
-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);
-	}
-	else
-	{
-		$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 ();
-		}
-	}
-}
-
-if (count($errors) != 0)
-{
-	$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
-
-
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display :: display_footer();
-?>
+<?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;
+	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;
+		// 1. Check whether mandatory fields are set.
+		$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;
+			}
+		}
+		// 2. Check current course code.
+		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;
+			}
+			// 2.2 Check course code length.
+			elseif (api_strlen($course['Code']) > $maxlength) {
+				$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'])."'";
+				$res = Database::query($sql, __FILE__, __LINE__);
+				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;
+			}
+		}
+		// 4. Check whether course category exists.
+		if (isset ($course['CourseCategory']) && strlen($course['CourseCategory']) != 0) {
+			$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;
+}
+
+/**
+ * Saves imported data.
+ * @param   array   List of courses
+ */
+function save_data($courses) {
+	global $_configuration, $firstExpirationDelay;
+	global $purification_option_for_usernames;
+	$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);
+		$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);
+		$visual_code = $keys['currentCourseCode'];
+		$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
+ */
+function parse_csv_data($file) {
+	$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();
+
+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(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;
+if (is_array($extAuthSource)) {
+	$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);
+
+if ($_POST['formSent']) {
+	if (empty($_FILES['import_file']['tmp_name'])) {
+		$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);
+		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 ();
+		}
+	}
+}
+
+if (count($errors) != 0) {
+	$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();

+ 36 - 19
main/admin/course_information.php

@@ -11,7 +11,7 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
+// name of the language file that needs to be included
 $language_file = 'admin';
 $cidReset = true;
 require ('../inc/global.inc.php');
@@ -20,15 +20,15 @@ $this_section=SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
 /**
- * 
+ *
  */
 function get_course_usage($course_code)
 {
 	$table = Database::get_main_table(TABLE_MAIN_COURSE);
     $course_code = Database::escape_string($course_code);
 	$sql = "SELECT * FROM $table WHERE code='".$course_code."'";
-	$res = api_sql_query($sql,__FILE__,__LINE__);
-	$course = mysql_fetch_object($res);
+	$res = Database::query($sql,__FILE__,__LINE__);
+	$course = Database::fetch_object($res);
 	// Learnpaths
 	$table = Database :: get_course_table(TABLE_LP_MAIN, $course->db_name);
 	$usage[] = array (get_lang(ucfirst(TOOL_LEARNPATH)), Database::count_rows($table));
@@ -65,8 +65,8 @@ $interbreadcrumb[] = array ("url" => 'course_list.php', "name" => get_lang('Cour
 $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
 $code = Database::escape_string($_GET['code']);
 $sql = "SELECT * FROM $table_course WHERE code = '".$code."'";
-$res = api_sql_query($sql,__FILE__,__LINE__);
-$course = mysql_fetch_object($res);
+$res = Database::query($sql,__FILE__,__LINE__);
+$course = Database::fetch_object($res);
 $tool_name = $course->title.' ('.$course->visual_code.')';
 Display::display_header($tool_name);
 //api_display_tool_title($tool_name);
@@ -75,7 +75,7 @@ Display::display_header($tool_name);
 <a href="<?php echo api_get_path(WEB_COURSE_PATH).$course->directory; ?>"><?php Display::display_icon('course_home.gif'); ?> <?php echo api_get_path(WEB_COURSE_PATH).$course->directory; ?></a>
 <br/>
 <?php
-if( get_setting('server_type') == 'test')
+if(api_get_setting('server_type') == 'test')
 {
 	?>
 	<a href="course_create_content.php?course_code=<?php echo $course->code ?>"><?php echo get_lang('AddDummyContentToCourse') ?></a>
@@ -102,16 +102,25 @@ echo '<blockquote>';
 $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 $table_user = Database :: get_main_table(TABLE_MAIN_USER);
 $sql = "SELECT *,cu.status as course_status FROM $table_course_user cu, $table_user u WHERE cu.user_id = u.user_id AND cu.course_code = '".$code."'";
-$res = api_sql_query($sql,__FILE__,__LINE__);
-if (mysql_num_rows($res) > 0)
+$res = Database::query($sql,__FILE__,__LINE__);
+$is_western_name_order = api_is_western_name_order();
+if (Database::num_rows($res) > 0)
 {
 	$users = array ();
-	while ($obj = mysql_fetch_object($res))
+	while ($obj = Database::fetch_object($res))
 	{
 		$user = array ();
 		$user[] = $obj->official_code;
-		$user[] = $obj->firstname;
-		$user[] = $obj->lastname;
+		if ($is_western_name_order)
+		{
+			$user[] = $obj->firstname;
+			$user[] = $obj->lastname;
+		}
+		else
+		{
+			$user[] = $obj->lastname;
+			$user[] = $obj->firstname;
+		}
 		$user[] = Display :: encrypted_mailto_link($obj->email, $obj->email);
 		$user[] = $obj->course_status == 5 ? get_lang('Student') : get_lang('Teacher');
 		$user[] = '<a href="user_information.php?user_id='.$obj->user_id.'">'.Display::return_icon('synthese_view.gif',get_lang('UserInfo')).'</a>';
@@ -121,8 +130,16 @@ if (mysql_num_rows($res) > 0)
 	$table->set_additional_parameters(array ('code' => $code));
 	$table->set_other_tables(array('usage_table','class_table'));
 	$table->set_header(0,get_lang('OfficialCode'), true);
-	$table->set_header(1,get_lang('FirstName'), true);
-	$table->set_header(2,get_lang('LastName'), true);
+	if ($is_western_name_order)
+	{
+		$table->set_header(1,get_lang('FirstName'), true);
+		$table->set_header(2,get_lang('LastName'), true);
+	}
+	else
+	{
+		$table->set_header(1,get_lang('LastName'), true);
+		$table->set_header(2,get_lang('FirstName'), true);
+	}
 	$table->set_header(3,get_lang('Email'), true);
 	$table->set_header(4,get_lang('Status'), true);
 	$table->set_header(5,'', false);
@@ -139,11 +156,11 @@ echo '</blockquote>';
 $table_course_class = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
 $table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
 $sql = "SELECT * FROM $table_course_class cc, $table_class c WHERE cc.class_id = c.id AND cc.course_code = '".$code."'";
-$res = api_sql_query($sql,__FILE__,__LINE__);
-if (mysql_num_rows($res) > 0)
+$res = Database::query($sql,__FILE__,__LINE__);
+if (Database::num_rows($res) > 0)
 {
 	$data = array ();
-	while ($class = mysql_fetch_object($res))
+	while ($class = Database::fetch_object($res))
 	{
 		$row = array ();
 		$row[] = $class->name;
@@ -166,8 +183,8 @@ else
 }
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
-*/ 
+*/
 Display::display_footer();
 ?>

+ 30 - 31
main/admin/course_list.php

@@ -11,7 +11,7 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
+// name of the language file that needs to be included
 $language_file = array('admin','courses');
 $cidReset = true;
 require ('../inc/global.inc.php');
@@ -25,18 +25,18 @@ require_once '../gradebook/lib/be/gradebookitem.class.php';
 require_once '../gradebook/lib/be/category.class.php';
 /**
  * Get the number of courses which will be displayed
- */ 
+ */
 function get_number_of_courses()
 {
 	$course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
 	$sql = "SELECT COUNT(code) AS total_number_of_items FROM $course_table";
-	
+
 	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_course_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-    	$sql.= " INNER JOIN $access_url_rel_course_table url_rel_course ON (code=url_rel_course.course_code)";    		
+    	$sql.= " INNER JOIN $access_url_rel_course_table url_rel_course ON (code=url_rel_course.course_code)";
     }
-    
+
 	if (isset ($_GET['keyword']))
 	{
 		$keyword = Database::escape_string($_GET['keyword']);
@@ -53,13 +53,13 @@ function get_number_of_courses()
 		$keyword_unsubscribe = Database::escape_string($_GET['keyword_unsubscribe']);
 		$sql .= " WHERE (code LIKE '%".$keyword_code."%' OR visual_code LIKE '%".$keyword_code."%') AND title LIKE '%".$keyword_title."%' AND category_code LIKE '%".$keyword_category."%'  AND course_language LIKE '%".$keyword_language."%'   AND visibility LIKE '%".$keyword_visibility."%'    AND subscribe LIKE '".$keyword_subscribe."'AND unsubscribe LIKE '".$keyword_unsubscribe."'";
 	}
-	
+
 	 // 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_course.access_url_id=".api_get_current_access_url_id();   	  
+	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_course.access_url_id=".api_get_current_access_url_id();
     }
-    
-	$res = api_sql_query($sql, __FILE__, __LINE__);
+
+	$res = Database::query($sql, __FILE__, __LINE__);
 	$obj = Database::fetch_object($res);
 	return $obj->total_number_of_items;
 }
@@ -71,15 +71,15 @@ function get_course_data($from, $number_of_items, $column, $direction)
 	$course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
 	$users_table = Database :: get_main_table(TABLE_MAIN_USER);
 	$course_users_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-	
+
 	$sql = "SELECT code AS col0, visual_code AS col1, title AS col2, course_language AS col3, category_code AS col4, subscribe AS col5, unsubscribe AS col6, code AS col7, tutor_name as col8, code AS col9, visibility AS col10,directory as col11 FROM $course_table";
-	
+
 	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_course_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-    	$sql.= " INNER JOIN $access_url_rel_course_table url_rel_course ON (code=url_rel_course.course_code)";    		
-    }    
-    
+    	$sql.= " INNER JOIN $access_url_rel_course_table url_rel_course ON (code=url_rel_course.course_code)";
+    }
+
 	if (isset ($_GET['keyword']))
 	{
 		$keyword = Database::escape_string($_GET['keyword']);
@@ -96,20 +96,19 @@ function get_course_data($from, $number_of_items, $column, $direction)
 		$keyword_unsubscribe = Database::escape_string($_GET['keyword_unsubscribe']);
 		$sql .= " WHERE (code LIKE '%".$keyword_code."%' OR visual_code LIKE '%".$keyword_code."%') AND title LIKE '%".$keyword_title."%' AND category_code LIKE '%".$keyword_category."%'  AND course_language LIKE '%".$keyword_language."%'   AND visibility LIKE '%".$keyword_visibility."%'    AND subscribe LIKE '".$keyword_subscribe."'AND unsubscribe LIKE '".$keyword_unsubscribe."'";
 	}
-	
+
 	 // 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_course.access_url_id=".api_get_current_access_url_id();   	  
+	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_course.access_url_id=".api_get_current_access_url_id();
     }
 
 	$sql .= " ORDER BY col$column $direction ";
 	$sql .= " LIMIT $from,$number_of_items";
-	$res = api_sql_query($sql, __FILE__, __LINE__);
+	$res = Database::query($sql, __FILE__, __LINE__);
 	$courses = array ();
 	while ($course = Database::fetch_row($res))
 	{
 		//place colour icons in front of courses
-		//$course[1] = get_course_visibility_icon($course[10]).'<a href="../course_home/course_home.php?cidReq='.$course[0].'">'.$course[1].'</a>'; // This is not the preferable way to go to the homepage.
 		$course[1] = get_course_visibility_icon($course[10]).'<a href="'.api_get_path(WEB_COURSE_PATH).$course[11].'/index.php">'.$course[1].'</a>';
 
 		$course[5] = $course[5] == SUBSCRIBE_ALLOWED ? get_lang('Yes') : get_lang('No');
@@ -242,10 +241,10 @@ else
 	{
 
 		CourseManager :: delete_course($_GET['delete_course']);
-		
+
 		$obj_cat=new Category();
 		$obj_cat->update_category_delete($_GET['delete_course']);
-		
+
 	}
 	// Create a search-box
 	$form = new FormValidator('search_simple','get','','','width=200px',false);
@@ -255,16 +254,16 @@ else
 	$form->addElement('style_submit_button', 'submit', get_lang('SearchCourse'),'class="search"');
 	$form->addElement('static','search_advanced_link',null,'<a href="course_list.php?search=advanced">'.get_lang('AdvancedSearch').'</a>');
 	echo '<div style="float:right;margin-top:5px;margin-right:5px;">
-			  <a href="'.api_get_path(WEB_CODE_PATH).'admin/course_add.php">'.Display::return_icon('course_add.gif',get_lang('AddSession')).get_lang('AddCourse').'</a>									
+			  <a href="'.api_get_path(WEB_CODE_PATH).'admin/course_add.php">'.Display::return_icon('course_add.gif',get_lang('AddSession')).get_lang('AddCourse').'</a>
 		 </div>';
-		 
-	echo '<div class="actions">';		
-		$form->display();				
+
+	echo '<div class="actions">';
+		$form->display();
 	echo '</div>';
 	// Create a sortable table with the course data
 	$table = new SortableTable('courses', 'get_number_of_courses', 'get_course_data',2);
 	$parameters=array();
-	
+
 	if (isset ($_GET['keyword'])) {
 		$parameters = array ('keyword' => Security::remove_XSS($_GET['keyword']));
 	} elseif (isset ($_GET['keyword_code'])) {
@@ -276,7 +275,7 @@ else
 		$parameters['keyword_subscribe'] = Security::remove_XSS($_GET['keyword_subscribe']);
 		$parameters['keyword_unsubscribe'] = Security::remove_XSS($_GET['keyword_unsubscribe']);
 	}
-		
+
 	$table->set_additional_parameters($parameters);
 	$table->set_header(0, '', false);
 	$table->set_header(1, get_lang('Code'));
@@ -287,14 +286,14 @@ else
 	$table->set_header(6, get_lang('UnsubscriptionAllowed'));
 	$table->set_header(7, get_lang('IsVirtualCourse'));
 	$table->set_header(8, get_lang('Teacher'));
-	$table->set_header(9, get_lang('Modify'), false,'width="120px"');	
-	$table->set_column_filter(9,'modify_filter');	
+	$table->set_header(9, get_lang('Modify'), false,'width="120px"');
+	$table->set_column_filter(9,'modify_filter');
 	$table->set_form_actions(array ('delete_courses' => get_lang('DeleteCourse')),'course');
 	$table->display();
 }
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 242 - 263
main/admin/course_user_import.php

@@ -1,263 +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
-==============================================================================
-*/
-/**
- * validate the imported data
- */
-function validate_data($users_courses)
-{
-	$errors = array ();
-	$coursecodes = array ();
-	foreach ($users_courses as $index => $user_course)
-	{
-		$user_course['line'] = $index +1;
-		//1. check if mandatory fields are set
-		$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;
-			}
-		}
-		//2. check if coursecode exists
-		if (isset ($user_course['CourseCode']) && strlen($user_course['CourseCode']) != 0)
-		{
-			//2.1 check if code allready used in this CVS-file
-			if (!isset ($coursecodes[$user_course['CourseCode']]))
-			{
-				//2.1.1 check if code exists in DB
-				$course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
-				$sql = "SELECT * FROM $course_table WHERE code = '".mysql_real_escape_string($user_course['CourseCode'])."'";
-				$res = api_sql_query($sql, __FILE__, __LINE__);
-				if (mysql_num_rows($res) == 0)
-				{
-					$user_course['error'] = get_lang('CodeDoesNotExists');
-					$errors[] = $user_course;
-				}
-				else
-				{
-					$coursecodes[$user_course['CourseCode']] = 1;
-				}
-			}
-		}
-		//3. check if username exists
-		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;
-			}
-		}
-		//4. check if 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;
-}
-
-/**
- * Save the 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;
-		$sql = "SELECT * FROM $user_table u WHERE u.username = '".mysql_real_escape_string($username)."'";
-		$res = api_sql_query($sql,__FILE__,__LINE__);
-		$obj = mysql_fetch_object($res);
-		$user_id = $obj->user_id;
-		$sql = "SELECT * FROM $course_user_table cu WHERE cu.user_id = $user_id";
-		$res = api_sql_query($sql,__FILE__,__LINE__);
-		$db_subscriptions = array();
-		while($obj = Database::fetch_object($res)) {
-			$db_subscriptions[$obj->course_code] = $obj->status;
-		}
-		//echo '<b>User '.$username.'</b><br />';
-		$to_subscribe = array_diff(array_keys($csv_subscriptions),array_keys($db_subscriptions));
-		$to_unsubscribe = array_diff(array_keys($db_subscriptions),array_keys($csv_subscriptions));
-//		echo '<pre>';
-//		echo "CSV SUBSCRIPTION\n";
-//		print_r($csv_subscriptions);
-//		echo "DB SUBSCRIPTION\n";
-//		print_r($db_subscriptions);
-//		echo "TO SUBSCRIBE\n";
-//		print_r($to_subscribe);
-//		echo "TO UNSUBSCRIBE\n";
-//		print_r($to_unsubscribe);
-//		echo '</pre>';
-
-        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]);
-                    $c_info = CourseManager::get_course_information($course_code); 
-                    $inserted_in_course[$course_code] = $c_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) {
-                            //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'];
-                        }
-                    }
-                }
-				//echo get_lang('Subscription').' : '.$course_code.'<br />';
-			}
-		}
-		if($_POST['unsubscribe']) {
-			foreach($to_unsubscribe as $index => $course_code) {
-                if(CourseManager :: course_exists($course_code)) {
-                    CourseManager::unsubscribe_user($user_id,$course_code);
-                    $c_info = CourseManager::get_course_information($course_code); 
-                    $inserted_in_course[$course_code] = $c_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) {
-                            //ignore, this has already been inserted
-                        } else {
-                            CourseManager::unsubscribe_user($user_id,$vcourse['code']);
-                            $inserted_in_course[$vcourse['code']] = $vcourse['title'];
-                        }
-                    }
-                }
-				//echo get_lang('Unsubscription').' : '.$course_code.'<br />';
-			}
-		}
-	}
-}
-/**
- * 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;
-}
-// name of the language file that needs to be included 
-$language_file = array ('admin', 'registration');
-
-$cidReset = true;
-
-// including the global Dokeos file
-include ('../inc/global.inc.php');
-
-// protecting the admin section
-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');
-$formSent = 0;
-$errorMsg = '';
-
-$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);
-        // 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) {
-        	// 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 ();
-	}
-}
-
-// displaying the header
-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) {
-		$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);
-}
-
-// 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; ?>
-
-a.dam;course01;<?php echo STUDENT; ?>
-</pre>
-<?php
-echo COURSEMANAGER.': '.get_lang('Teacher').'<br />';
-echo STUDENT.': '.get_lang('Student').'<br />';
-?>
-</blockquote>
-<?php
-// footer
-Display :: display_footer();
-?>
+<?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 ();
+	foreach ($users_courses as $index => $user_course) {
+		$user_course['line'] = $index +1;
+		// 1. Check whether mandatory fields are set.
+		$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;
+			}
+		}
+		// 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);
+				$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;
+				} else {
+					$coursecodes[$user_course['CourseCode']] = 1;
+				}
+			}
+		}
+		// 3. Check whether username exists.
+		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;
+			}
+		}
+		// 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;
+}
+
+/**
+ * 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;
+		$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";
+		$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;
+        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]);
+                    $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) {
+                            // 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);
+                    $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) {
+                            // Ignore, this has already been inserted.
+                        } 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;
+}
+
+// Language files that should be included,
+$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();
+
+// 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);
+
+// 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);
+        // 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) {
+        	// 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 ();
+	}
+}
+
+// Displaying the header.
+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) {
+		$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);
+}
+
+// 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; ?>
+
+adam;course01;<?php echo STUDENT; ?>
+</pre>
+<?php
+echo COURSEMANAGER.': '.get_lang('Teacher').'<br />';
+echo STUDENT.': '.get_lang('Student').'<br />';
+?>
+</blockquote>
+<?php
+// Footer.
+Display :: display_footer();

+ 1 - 1
main/admin/course_user_list.php

@@ -24,5 +24,5 @@ if (count($list_course)==0) {
     <tr>
         <td><?php echo api_convert_encoding($list_course[$k],'UTF-8',$charset);?></td>
     </tr>
-<?php }?>	
+<?php }?>
 </table>

+ 71 - 71
main/admin/course_virtual.php

@@ -1,47 +1,47 @@
-<?php // $Id: course_virtual.php 20441 2009-05-10 07:39:15Z ivantcholakov $ 
+<?php // $Id: course_virtual.php 20441 2009-05-10 07:39:15Z ivantcholakov $
 /*
-============================================================================== 
+==============================================================================
 	Dokeos - elearning and course management software
-	
+
 	Copyright (c) 2004-2005 Dokeos S.A.
 	Copyright (c) 2003 Ghent University (UGent)
 	Copyright (c) 2001 Universite catholique de Louvain (UCL)
 	Copyright (c) Roan Embrechts (Vrije Universiteit Brussel)
-	
+
 	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
-============================================================================== 
+==============================================================================
 */
 /**
-============================================================================== 
+==============================================================================
 *	@author Roan Embrechts - initial admin interface
 *	@package dokeos.admin
-============================================================================== 
+==============================================================================
 */
 
 /*
-============================================================================== 
+==============================================================================
 		INIT SECTION
-============================================================================== 
-*/ 
+==============================================================================
+*/
 
-// name of the language file that needs to be included 
-$language_file = 'admin'; 
+// name of the language file that needs to be included
+$language_file = 'admin';
 $extra_lang_file = "create_course";
 
-// global settings initialisation 
+// global settings initialisation
 // also provides access to main api (inc/lib/main_api.lib.php)
-include("../inc/global.inc.php"); 
+include("../inc/global.inc.php");
 $this_section=SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
@@ -53,7 +53,7 @@ if (isset($extra_lang_file)) include(api_get_path(INCLUDE_PATH)."../lang/".$lang
 -----------------------------------------------------------
 	Libraries
 -----------------------------------------------------------
-*/ 
+*/
 
 include_once(api_get_path(LIBRARY_PATH) . 'course.lib.php');
 
@@ -61,7 +61,7 @@ include_once(api_get_path(LIBRARY_PATH) . 'course.lib.php');
 -----------------------------------------------------------
 	Constants
 -----------------------------------------------------------
-*/ 
+*/
 
 define ("CREATE_VIRTUAL_COURSE_OPTION", "create_virtual_course");
 define ("DISPLAY_VIRTUAL_COURSE_LIST_OPTION", "display_virtual_course_list");
@@ -80,19 +80,19 @@ define ("COURSE_CATEGORY_FORM_NAME" , "course_category");
 -----------------------------------------------------------
 	Header
 -----------------------------------------------------------
-*/ 
+*/
 
-$tool_name = get_lang('AdminManageVirtualCourses'); // title of the page (should come from the language file) 
+$tool_name = get_lang('AdminManageVirtualCourses'); // title of the page (should come from the language file)
 
 $interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
 
 Display::display_header($tool_name);
 
 /*
-============================================================================== 
+==============================================================================
 		DISPLAY FUNCTIONS
-============================================================================== 
-*/ 
+==============================================================================
+*/
 
 function make_strong($text)
 {
@@ -122,7 +122,7 @@ function get_language_folder_list($dirname)
 }
 
 /**
-* Displays a select element (drop down menu) so the user can select 
+* Displays a select element (drop down menu) so the user can select
 * the course language.
 * @todo function does not belong here, move to (display?) library,
 * @todo language display used apparently no longer existing array, converted to english for now.
@@ -131,25 +131,25 @@ function get_language_folder_list($dirname)
 function display_language_select($element_name)
 {
 	global $platformLanguage;
-	
+
 	//get language list
 	$dirname = api_get_path(SYS_PATH)."main/lang/";
 	$language_list = get_language_folder_list($dirname);
 	sort($language_list);
-	
+
 	//build array with strings to display
 	foreach ($language_list as $this_language)
-	{	
+	{
 		$language_to_display[$this_language] = $this_language;
 	}
-	
+
 	//sort alphabetically
 	//warning: key,value association needs to be maintained --> asort instead of sort
 	asort($language_to_display);
-			 
+
 	$user_selected_language = $_SESSION["user_language_choice"];
 	if (! isset($user_selected_language) ) $user_selected_language = $platformLanguage;
-	
+
 	//display
 	echo "<select name=\"$element_name\">";
 	foreach ($language_to_display as $key => $value)
@@ -171,9 +171,9 @@ function display_language_select($element_name)
 *	We display the course code, but internally store the course id.
 */
 function display_real_course_code_select($element_name)
-{	
+{
 	$real_course_list = CourseManager::get_real_course_list();
-			
+
 	echo "<select name=\"$element_name\" size=\"".SELECT_BOX_SIZE."\" >\n";
 	foreach($real_course_list as $real_course)
 	{
@@ -200,10 +200,10 @@ function display_create_virtual_course_form()
 	<table>
 	<tr valign="top">
 	<td colspan="2">
-	
+
 	</td>
 	</tr>
-	
+
 	<tr valign="top">
 	<td align="right">
 		<?php
@@ -214,20 +214,20 @@ function display_create_virtual_course_form()
 		?>
 	</td>
 	</tr>
-	
+
 	<tr valign="top">
 	<td align="right"><?php echo make_strong(get_lang('CourseFaculty')) . "&nbsp;"; ?> </td>
 	<td>
 		<?php
 			echo "<select name=\"".COURSE_CATEGORY_FORM_NAME."\">";
-			
+
 			$sql_query = "SELECT code, name
 									FROM $category_table
 									WHERE auth_course_child ='TRUE'
 									ORDER BY tree_pos";
-			$category_result = api_sql_query($sql_query, __FILE__, __LINE__);
-		
-			while ($current_category = mysql_fetch_array($category_result))
+			$category_result = Database::query($sql_query, __FILE__, __LINE__);
+
+			while ($current_category = Database::fetch_array($category_result))
 			{
 				echo "<option value=\"", $current_category["code"], "\"";
 				echo ">(", $current_category["code"], ") ", $current_category["name"];
@@ -238,7 +238,7 @@ function display_create_virtual_course_form()
 	<br /><?php echo make_strong(get_lang('TargetFac'))  . "&nbsp;" ?>
 	</td>
 	</tr>
-	
+
 	<tr valign="top">
 	<td align="right"><?php echo make_strong(get_lang('Code'))  . "&nbsp;" ?> </td>
 	<td>
@@ -248,10 +248,10 @@ function display_create_virtual_course_form()
 	?>
 	</td>
 	</tr>
-	
+
 	<tr valign="top">
 	<td align="right">
-	<?php echo make_strong(get_lang('RealCourseCode'))  . "&nbsp;" ?> 
+	<?php echo make_strong(get_lang('RealCourseCode'))  . "&nbsp;" ?>
 	</td>
 	<td>
 		<?php
@@ -260,12 +260,12 @@ function display_create_virtual_course_form()
 		?>
 	</td>
 	</tr>
-	
+
 	<tr valign="top">
 	<td align="right">
-		<?php 
+		<?php
 			echo make_strong(get_lang('CourseLanguage')) . "&nbsp;";
-		?> 
+		?>
 	</td>
 	<td> <?php  display_language_select(LANGUAGE_SELECT_FORM_NAME); ?>
 
@@ -299,19 +299,19 @@ function display_virtual_course_list()
 		echo "<i>".get_lang('ThereAreNoVirtualCourses')."</i>";
 		return;
 	}
-	
-	$column_header[] = array(get_lang('Title'),true);					
-	$column_header[] = array(get_lang('Code'),true);				
-	$column_header[] = array(get_lang('VisualCode'),true);				
-	$column_header[] = array(get_lang('LinkedCourseTitle'),true);	
-	$column_header[] = array(get_lang('LinkedCourseCode'),true);		
+
+	$column_header[] = array(get_lang('Title'),true);
+	$column_header[] = array(get_lang('Code'),true);
+	$column_header[] = array(get_lang('VisualCode'),true);
+	$column_header[] = array(get_lang('LinkedCourseTitle'),true);
+	$column_header[] = array(get_lang('LinkedCourseCode'),true);
 	$table_data = array();
 	for($i = 0; $i < count($course_list); $i++)
 	{
 		$course_list[$i] = Database::generate_abstract_course_field_names($course_list[$i]);
 		$target_course_code = $course_list[$i]["target_course_code"];
 		$real_course_info = Database::get_course_info($target_course_code);
-		
+
 		$row = array();
 		$row[] = $course_list[$i]["title"];
 		$row[] = $course_list[$i]["system_code"];
@@ -325,9 +325,9 @@ function display_virtual_course_list()
 
 
 /*
-============================================================================== 
+==============================================================================
 		TOOL LOGIC FUNCTIONS
-============================================================================== 
+==============================================================================
 */
 
 /**
@@ -336,25 +336,25 @@ function display_virtual_course_list()
 *	Call this function instead of create_virtual_course
 */
 function attempt_create_virtual_course($real_course_code, $course_title, $wanted_course_code, $course_language, $course_category)
-{		
-	//better: create parameter list, check the entire list, when false display errormessage	
+{
+	//better: create parameter list, check the entire list, when false display errormessage
 	CourseManager::check_parameter_or_fail($real_course_code, "Unspecified parameter: real course id.");
 	CourseManager::check_parameter_or_fail($course_title, "Unspecified parameter: course title.");
 	CourseManager::check_parameter_or_fail($wanted_course_code, "Unspecified parameter: wanted course code.");
 	CourseManager::check_parameter_or_fail($course_language, "Unspecified parameter: course language.");
 	CourseManager::check_parameter_or_fail($course_category, "Unspecified parameter: course category.");
-	
+
 	$message = get_lang('AttemptedCreationVirtualCourse') . "<br/>";
 	$message .= get_lang('CourseTitle') . " " . $course_title . "<br/>";
 	$message .= get_lang('WantedCourseCode') . " " . $wanted_course_code . "<br/>";
 	$message .= get_lang('CourseLanguage') . " " . $course_language . "<br/>";
 	$message .= get_lang('CourseFaculty') . " " . $course_category . "<br/>";
 	$message .= get_lang('LinkedToRealCourseCode') . " " . $real_course_code . "<br/>";
-	
+
 	Display::display_normal_message($message);
-	
+
 	$creation_success = CourseManager::create_virtual_course( $real_course_code, $course_title, $wanted_course_code, $course_language, $course_category );
-	
+
 	if ($creation_success == true)
 	{
 		Display::display_normal_message( $course_title . " - " . get_lang('CourseCreationSucceeded') );
@@ -362,12 +362,12 @@ function attempt_create_virtual_course($real_course_code, $course_title, $wanted
 	}
 	return false;
 }
-	
+
 /*
-============================================================================== 
+==============================================================================
 		MAIN CODE
-============================================================================== 
-*/ 
+==============================================================================
+*/
 
 $action = $_GET["action"];
 $attempt_create_virtual_course = $_POST["submit_create_virtual_course"];
@@ -381,18 +381,18 @@ if ( isset($attempt_create_virtual_course) && $attempt_create_virtual_course )
 	$wanted_course_code = $_POST[WANTED_COURSE_CODE_FORM_NAME];
 	$course_language = $_POST[LANGUAGE_SELECT_FORM_NAME];
 	$course_category = $_POST[COURSE_CATEGORY_FORM_NAME];
-	
+
 	$message = get_lang('AttemptedCreationVirtualCourse') . "<br/>";
 	$message .= get_lang('CourseTitle') . " " . $course_title . "<br/>";
 	$message .= get_lang('WantedCourseCode') . " " . $wanted_course_code . "<br/>";
 	$message .= get_lang('CourseLanguage') . " " . $course_language . "<br/>";
 	$message .= get_lang('CourseFaculty') . " " . $course_category . "<br/>";
 	$message .= get_lang('LinkedToRealCourseCode') . " " . $real_course_code . "<br/>";
-	
+
 	Display::display_normal_message($message);
-	
+
 	$creation_success = CourseManager::attempt_create_virtual_course($real_course_code, $course_title, $wanted_course_code, $course_language, $course_category);
-	
+
 	if ($creation_success == true)
 	{
 		Display::display_normal_message( $course_title . " - " . get_lang('CourseCreationSucceeded') );
@@ -419,8 +419,8 @@ switch($action)
 
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
-*/ 
+*/
 Display::display_footer();
 ?>

+ 1 - 1
main/admin/example_session.xml

@@ -32,7 +32,7 @@
     		<CourseCode>08011942</CourseCode>
     		<Coach>Hawking</Coach>
     		<User>jmontoya</User>
-			<User>jmontoya2</User>    		
+			<User>jmontoya2</User>
     	</Course>
     </Session>
 </Sessions>

+ 1 - 1
main/admin/exemple.xml

@@ -11,7 +11,7 @@
         <Status>user</Status>
         <Courses>COURSE1|COURSE2|COURSE3</Courses>
     </Contact>
-    <Contact> 
+    <Contact>
         <LastName>Brown</LastName>
         <FirstName>Emmett</FirstName>
         <UserName>emmett</UserName>

+ 31 - 27
main/admin/index.php

@@ -55,7 +55,7 @@ $tool_name=get_lang('PlatformAdmin');
 Display::display_header($nameTools);
 
 
-if(api_is_platform_admin()) 
+if(api_is_platform_admin())
 {
 	if(is_dir(api_get_path(SYS_CODE_PATH).'install/') && is_readable(api_get_path(SYS_CODE_PATH).'install/index.php'))
 	{
@@ -71,13 +71,13 @@ if(api_is_platform_admin())
 		register_site();
 		Display :: display_confirmation_message(get_lang('VersionCheckEnabled'));
 	}
-	
+
 	/*
 	==============================================================================
 			MAIN SECTION
 	==============================================================================
 	*/
-	$keyword_url = Security::remove_XSS((empty($_GET['keyword'])?'':$_GET['keyword']));	
+	$keyword_url = Security::remove_XSS((empty($_GET['keyword'])?'':$_GET['keyword']));
 }
 
 if (api_is_platform_admin()) {
@@ -85,7 +85,7 @@ if (api_is_platform_admin()) {
 		<div class="admin_section">
 	<h4><?php Display::display_icon('members.gif', get_lang('Users')); ?> <?php echo api_ucfirst(get_lang('Users')); ?></h4>
 	<ul>
-		<li style="list-style-type:none"><form method="get" action="user_list.php">	
+		<li style="list-style-type:none"><form method="get" action="user_list.php">
 			<input type="text" name="keyword" value="<?php echo $keyword_url; ?>"/>
 			<button class="search" type="submit"> <?php echo get_lang('Search');?>
 			</button>
@@ -106,7 +106,7 @@ else
 	?>
 	<div class="admin_section">
 	<h4><?php Display::display_icon('members.gif', get_lang('Users')); ?> <?php echo api_ucfirst(get_lang('Users')); ?></h4>
-	<ul>		
+	<ul>
 		<li><a href="user_list.php">	<?php echo get_lang('UserList') ?></a></li>
 		<li><a href="../mySpace/user_add.php">		<?php echo get_lang('AddUsers') ?></a></li>
 
@@ -120,14 +120,14 @@ if(api_is_platform_admin()) {
 ?>
 	<div class="admin_section">
 <h4><?php Display::display_icon('course.gif', get_lang('Courses')); ?> <?php echo api_ucfirst(get_lang('Courses')); ?></h4>
-		<ul><li style="list-style-type:none"><form method="get" action="course_list.php">	
+		<ul><li style="list-style-type:none"><form method="get" action="course_list.php">
 		<input type="text" name="keyword" value="<?php echo $keyword_url; ?>"/>
 		<button class="search" type="submit"> <?php echo get_lang('Search');?>
 			</button>
 		</form></li>
 		<li>
 		<a href="course_list.php?search=advanced"><?php echo api_ucfirst(get_lang('AdvancedSearch')); ?></a>
-	
+
 	</li>
 	<li><a href="course_list.php"><?php echo get_lang('CourseList') ?></a></li>
 	<li><a href="course_add.php"><?php echo get_lang('AddCourse') ?></a></li>
@@ -141,37 +141,39 @@ if(api_is_platform_admin()) {
 	<?php } ?>
 	</ul>
 	</div>
-	
+
 	<div class="admin_section">
 	 <h4><?php Display::display_icon('settings.gif', get_lang('Platform')); ?> <?php echo api_ucfirst(get_lang('Platform')); ?></h4>
 	 <ul>
 	  <li><a href="settings.php"><?php echo get_lang('DokeosConfigSettings') ?></a></li>
+	  <li><a href="special_exports.php"><?php echo get_lang('SpecialExports') ?></a></li>
 	  <li><a href="system_announcements.php"><?php echo get_lang('SystemAnnouncements') ?></a></li>
 	  <li><a href="languages.php"><?php echo get_lang('Languages'); ?></a></li>
 	  <li><a href="configure_homepage.php"><?php echo get_lang('ConfigureHomePage'); ?></a></li>
+	  <li><a href="configure_inscription.php"><?php echo get_lang('ConfigureInscription'); ?></a></li>
 	  <li><a href="statistics/index.php"><?php echo get_lang('ToolName'); ?> </a></li>
 	  <li><a href="calendar.php"><?php echo get_lang('GlobalAgenda'); ?> </a></li>
 	  <?php if(!empty($phpMyAdminPath)) { ?>
 	  <li><a href="<?php echo $phpMyAdminPath; ?>" target="_blank"><?php echo get_lang("AdminDatabases"); ?></a><br />(<?php echo get_lang("DBManagementOnlyForServerAdmin"); ?>)</li>
 	  <?php } ?>
-	  <?php 
+	  <?php
 	  if(!empty($_configuration['multiple_access_urls']))
 	  {
 	    echo '<li><a href="access_urls.php">'.get_lang('ConfigureMultipleAccessURLs').'</a></li>';
 	  }
-	  
-	  if (get_setting('allow_reservation')=='true') {
+
+	  if (api_get_setting('allow_reservation')=='true') {
 		  	echo '<li><a href="../reservation/m_category.php">'.get_lang('BookingSystem').'</a></li>';
 	  }
-	  
-  	  if (get_setting('allow_terms_conditions')=='true') {
+
+  	  if (api_get_setting('allow_terms_conditions')=='true') {
 		  	echo '<li><a href="legal_add.php">'.get_lang('TermsAndConditions').'</a></li>';
 	  }
-		
+
 	  ?>
 	 </ul>
 	</div>
-	
+
 	<?php
 }
 
@@ -189,9 +191,11 @@ if(api_get_setting('use_session_mode')=='true')
 	</form>
 </li>
   <li><a href="session_list.php"><?php echo get_lang('ListSession') ?></a></li>
+  <li><a href="session_category_list.php"><?php echo get_lang('ListSessionCategory') ?></a></li>
   <li><a href="session_add.php"><?php echo get_lang('AddSession') ?></a></li>
   <li><a href="session_import.php"><?php echo get_lang('ImportSessionListXMLCSV') ?></a></li>
   <li><a href="session_export.php"><?php echo get_lang('ExportSessionListXMLCSV') ?></a></li>
+  <li><a href="../coursecopy/copy_course_session.php"><?php echo get_lang('CopyFromCourseInSessionToAnotherSession') ?></a></li>
   </ul>
 </div>
 
@@ -241,7 +245,7 @@ if(api_is_platform_admin()){
 <?php
 	if(isset($extAuthSource) && isset($extAuthSource['ldap']) && count($extAuthSource['ldap'])>0){
 	?>
-	<!-- dynamic ldap code --> 
+	<!-- dynamic ldap code -->
 	<div class="admin_section">
 	 <h4><?php Display::display_icon('members.gif', 'LDAP'); ?> LDAP</h4>
 	 <ul>
@@ -252,14 +256,14 @@ if(api_is_platform_admin()){
 	 </ul>
 	</div>
 	<!-- dynamic ldap code -->
-	<?php 
+	<?php
 	}
 ?>
 <div class="admin_section">
  <h4><?php Display::display_icon('dokeos.gif', 'Dokeos'); ?> Dokeos.com</h4>
  <ul>
   <li><a href="http://www.dokeos.com/" target="_blank"><?php echo get_lang('DokeosHomepage'); ?></a></li>
-  <li><a href="http://www.dokeos.com/forum/" target="_blank"><?php echo get_lang('DokeosForum'); ?></a></li>  
+  <li><a href="http://www.dokeos.com/forum/" target="_blank"><?php echo get_lang('DokeosForum'); ?></a></li>
   <li><a href="http://www.dokeos.com/extensions/" target="_blank"><?php echo get_lang('DokeosExtensions'); ?></a></li>
   <li>
   <?php
@@ -287,19 +291,19 @@ function version_check()
 {
 	$tbl_settings = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
 	$sql = 'SELECT selected_value FROM  '.$tbl_settings.' WHERE variable="registered" ';
-	$result = api_sql_query($sql,__FILE__,__LINE__);
+	$result = Database::query($sql,__FILE__,__LINE__);
 	$row=Database::fetch_array($result,'ASSOC');
-								
+
 	// The site has not been registered yet
 	//if (api_get_setting('registered')=='false')
-	
+
 	$return = '';
 	if ($row['selected_value']=='false')
-	{	
+	{
 		$return .= '<form action="'.api_get_self().'" id="VersionCheck" name="VersionCheck" method="post">';
 		$return .= get_lang('VersionCheckExplanation');
 		$return .= '<input type="checkbox" name="donotlistcampus" value="1" id="checkbox" />'.get_lang('HideCampusFromPublicDokeosPlatformsList');
-		$return .= '<input type="submit" name="Register" value="'.get_lang('EnableVersionCheck').'" id="register" />';
+		$return .= '<button type="submit" class="save" name="Register" value="'.get_lang('EnableVersionCheck').'" id="register" />'.get_lang('EnableVersionCheck').'</button>';
 		$return .= '</form>';
 	}
 	else
@@ -338,13 +342,13 @@ function register_site()
 
 	// the SQL statment
 	$sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='registered'";
-	$result = api_sql_query($sql,__FILE__,__LINE__);
+	$result = Database::query($sql,__FILE__,__LINE__);
 
 	//
 	if ($_POST['donotlistcampus'])
 	{
 		$sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='donotlistcampus'";
-		$result = api_sql_query($sql,__FILE__,__LINE__);
+		$result = Database::query($sql,__FILE__,__LINE__);
 	}
 
 	// reload the settings
@@ -367,13 +371,13 @@ function check_dokeos_version2()
 	{
 		// the number of courses
 		$sql="SELECT count(code) FROM ".Database::get_main_table(TABLE_MAIN_COURSE);
-		$result=api_sql_query($sql,__FILE__,__LINE__);
+		$result=Database::query($sql,__FILE__,__LINE__);
 		$row = Database::fetch_array($result);
 		$number_of_courses = $row[0];
 
 		// the number of users
 		$sql="SELECT count(user_id) FROM ".Database::get_main_table(TABLE_MAIN_USER);
-		$result=api_sql_query($sql,__FILE__,__LINE__);
+		$result=Database::query($sql,__FILE__,__LINE__);
 		$row = Database::fetch_array($result);
 		$number_of_users = $row[0];
 

+ 57 - 57
main/admin/languages.php

@@ -1,13 +1,13 @@
-<?php // $Id: languages.php 22382 2009-07-27 04:52:23Z iflorespaz $
+<?php
 /* For licensing terms, see /dokeos_license.txt */
 /**
 ==============================================================================
 * This page allows the platform admin to decide which languages should
 * be available in the language selection menu in the login page. This can be
-* useful for countries with more than one official language (like Belgium: 
-* Dutch, French and German) or international organisations that are active in	
-* a limited number of countries. 
-* 
+* useful for countries with more than one official language (like Belgium:
+* Dutch, French and German) or international organisations that are active in
+* a limited number of countries.
+*
 * @author Patrick Cool, main author
 * @author Roan EMbrechts, code cleaning
 * @since Dokeos 1.6
@@ -15,9 +15,9 @@
 ==============================================================================
 */
 /*
-============================================================================== 
+==============================================================================
 	   INIT SECTION
-============================================================================== 
+==============================================================================
 */
 // name of the language file that needs to be included
 $language_file = 'admin';
@@ -37,26 +37,26 @@ if (isset($_POST['sent_http_request'])) {
 	if (isset($_POST['visibility']) && $_POST['visibility']==strval(intval($_POST['visibility'])) && $_POST['visibility']==0) {
 		if (isset($_POST['id'])&& $_POST['id']==strval(intval($_POST['id']))) {
 			SubLanguageManager::make_unavailable_language($_POST['id']);
-			echo 'set_hidden';	
+			echo 'set_hidden';
 		}
-	} 
+	}
 	if (isset($_POST['visibility']) && $_POST['visibility']==strval(intval($_POST['visibility'])) && $_POST['visibility']==1) {
 		if (isset($_POST['id'])&& $_POST['id']==strval(intval($_POST['id']))) {
 			SubLanguageManager::make_available_language($_POST['id']);
-			echo 'set_visible';			
+			echo 'set_visible';
 		}
-	} 	
+	}
 	exit;
 }
 $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
 $htmlHeadXtra[] ='<script type="text/javascript">
  $(document).ready(function() {
 
- 	//$(window).load(function () { 
+ 	//$(window).load(function () {
       $(".make_visible_and_invisible").attr("href","javascript:void(0)");
 	//});
- 		
- 	$("td .make_visible_and_invisible").click(function () { 
+
+ 	$("td .make_visible_and_invisible").click(function () {
 		make_visible="visible.gif";
 		make_invisible="invisible.gif";
 		id_link_tool=$(this).attr("id");
@@ -64,10 +64,10 @@ $htmlHeadXtra[] ='<script type="text/javascript">
 		path_name_of_imglinktool=$("#"+id_img_link_tool).attr("src");
 		link_info_id=id_link_tool.split("linktool_");
 		link_id=link_info_id[1];
-				
+
 		link_tool_info=path_name_of_imglinktool.split("/");
 		my_image_tool=link_tool_info[link_tool_info.length-1];
-    
+
 
 		if (my_image_tool=="visible.gif") {
 			path_name_of_imglinktool=path_name_of_imglinktool.replace(make_visible,make_invisible);
@@ -76,48 +76,48 @@ $htmlHeadXtra[] ='<script type="text/javascript">
 			path_name_of_imglinktool=path_name_of_imglinktool.replace(make_invisible,make_visible);
 			my_visibility=1;
 		}
-		
+
 		$.ajax({
 			contentType: "application/x-www-form-urlencoded",
 			beforeSend: function(objeto) {
 				$("#id_content_message").html("<div class=\"normal-message\"><img src=\'/main/inc/lib/javascript/indicator.gif\' /></div>");
-			
+
 			},
 			type: "POST",
 			url: "../admin/languages.php",
 			data: "id="+link_id+"&visibility="+my_visibility+"&sent_http_request=1",
 			success: function(datos) {
-				
+
 				$("#"+id_img_link_tool).attr("src",path_name_of_imglinktool);
-				
+
 				if (my_image_tool=="visible.gif") {
-					$("#"+id_img_link_tool).attr("alt","'.get_lang('MakeAvailable').'");
-					$("#"+id_img_link_tool).attr("title","'.get_lang('MakeAvailable').'");
+					$("#"+id_img_link_tool).attr("alt","'.get_lang('MakeAvailable', '').'");
+					$("#"+id_img_link_tool).attr("title","'.get_lang('MakeAvailable', '').'");
 				} else {
-					$("#"+id_img_link_tool).attr("alt","'.get_lang('MakeUnavailable').'");
-					$("#"+id_img_link_tool).attr("title","'.get_lang('MakeUnavailable').'");							
+					$("#"+id_img_link_tool).attr("alt","'.get_lang('MakeUnavailable', '').'");
+					$("#"+id_img_link_tool).attr("title","'.get_lang('MakeUnavailable', '').'");
 				}
 
 				if (datos=="set_visible") {
-					$("#id_content_message").html("<div class=\"confirmation-message\">'.get_lang('LanguageIsNowVisible').'</div>");
+					$("#id_content_message").html("<div class=\"confirmation-message\">'.get_lang('LanguageIsNowVisible', '').'</div>");
 				} else {
-					$("#id_content_message").html("<div class=\"confirmation-message\">'.get_lang('LanguageIsNowHidden').'</div>");					
+					$("#id_content_message").html("<div class=\"confirmation-message\">'.get_lang('LanguageIsNowHidden', '').'</div>");
 				}
-				
-		} }); 		
-				
-	}); 	
+
+		} });
+
+	});
 
  });
-</script>';	
+</script>';
 // setting the table that is needed for the styles management (there is a check if it exists later in this code)
 $tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 $tbl_settings_current 	= Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
 
 /*
-============================================================================== 
+==============================================================================
 		STORING THE CHANGES
-============================================================================== 
+==============================================================================
 */
 
 // we change the availability
@@ -136,7 +136,7 @@ if ($_GET['action'] == 'makeavailable') {
 if ($_GET['action'] == 'setplatformlanguage') {
 
 	if (isset($_GET['id']) && $_GET['id']==strval(intval($_GET['id']))) {
-		SubLanguageManager::set_platform_language($_GET['id']);		
+		SubLanguageManager::set_platform_language($_GET['id']);
 	}
 
 }
@@ -146,12 +146,12 @@ if ($_POST['Submit'])
 {
 	// changing the name
 	$sql_update = "UPDATE $tbl_admin_languages SET original_name='{$_POST['txt_name']}' WHERE id='{$_POST['edit_id']}'";
-	$result = api_sql_query($sql_update);
+	$result = Database::query($sql_update);
 	// changing the Platform language
 	if ($_POST['platformlanguage'] && $_POST['platformlanguage'] <> '')
 	{
 		//$sql_update_2 = "UPDATE $tbl_settings_current SET selected_value='{$_POST['platformlanguage']}' WHERE variable='platformLanguage'";
-		//$result_2 = api_sql_query($sql_update_2);
+		//$result_2 = Database::query($sql_update_2);
 		api_set_setting('platformLanguage',$_POST['platformlanguage'],null,null,$_configuration['access_url']);
 	}
 }
@@ -168,7 +168,7 @@ elseif (isset($_POST['action']))
 					$ids[] = Database::escape_string($id);
 				}
 				$sql = "UPDATE $tbl_admin_languages SET available='1' WHERE id IN ('".implode("','", $ids)."')";
-				api_sql_query($sql,__FILE__,__LINE__);
+				Database::query($sql,__FILE__,__LINE__);
 			}
 			break;
 		case 'makeunavailable' :
@@ -180,7 +180,7 @@ elseif (isset($_POST['action']))
 					$ids[] = Database::escape_string($id);
 				}
 				$sql = "UPDATE $tbl_admin_languages SET available='0' WHERE id IN ('".implode("','", $ids)."')";
-				api_sql_query($sql,__FILE__,__LINE__);
+				Database::query($sql,__FILE__,__LINE__);
 			}
 			break;
 	}
@@ -188,9 +188,9 @@ elseif (isset($_POST['action']))
 
 
 /*
-============================================================================== 
+==============================================================================
 		MAIN CODE
-============================================================================== 
+==============================================================================
 */
 // setting the name of the tool
 $tool_name = get_lang('PlatformLanguages');
@@ -201,20 +201,20 @@ $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAd
 // including the header file (which includes the banner itself)
 Display :: display_header($tool_name);
 
-// displaying the naam of the tool 
+// displaying the naam of the tool
 //api_display_tool_title($tool_name);
 
 // displaying the explanation for this tool
 echo '<p>'.get_lang('PlatformLanguagesExplanation').'</p>';
 
-// selecting all the languages	
+// selecting all the languages
 $sql_select = "SELECT * FROM $tbl_admin_languages";
-$result_select = api_sql_query($sql_select);
+$result_select = Database::query($sql_select);
 
 $sql_select_lang = "SELECT * FROM $tbl_settings_current WHERE  category='Languages'";
-$result_select_lang = api_sql_query($sql_select_lang,__FILE__,__LINE__);
+$result_select_lang = Database::query($sql_select_lang,__FILE__,__LINE__);
 $row_lang=Database::fetch_array($result_select_lang);
- 
+
 /*
 --------------------------------------
 		DISPLAY THE TABLE
@@ -224,8 +224,8 @@ $row_lang=Database::fetch_array($result_select_lang);
 // the table data
 $language_data = array ();
 while ($row = Database::fetch_array($result_select)) {
-	
-	$row_td = array ();	
+
+	$row_td = array ();
 	$row_td[] = $row['id'];
 	// the first column is the original name of the language OR a form containing the original name
 	if ($_GET['action'] == 'edit' and $row['id'] == $_GET['id']) {
@@ -242,21 +242,21 @@ while ($row = Database::fetch_array($result_select)) {
 	$row_td[] = $row['english_name'];
 	// the third column
 	$row_td[] = $row['dokeos_folder'];
-	
+
 	if ($row['english_name'] == $row_lang['selected_value']){
 		$setplatformlanguage = Display::return_icon('links.gif', get_lang('CurrentLanguagesPortal'));
-	} else {		
+	} else {
 		$setplatformlanguage = "<a href=\"javascript:if (confirm('".addslashes(get_lang('AreYouSureYouWantToSetThisLanguageAsThePortalDefault'))."')) { location.href='".api_get_self()."?action=setplatformlanguage&id=".$row['id']."'; }\">".Display::return_icon('link_na.gif',get_lang('SetLanguageAsDefault'))."</a>";
-	}	
+	}
 	if (api_get_setting('allow_use_sub_language')=='true') {
 
 		$verified_if_is_sub_language=SubLanguageManager::check_if_language_is_sub_language($row['id']);
 
 		if ($verified_if_is_sub_language===false) {
 			$verified_if_is_father=SubLanguageManager::check_if_language_is_father($row['id']);
-			$allow_use_sub_language = "&nbsp;<a href='new_sub_language.php?action=definenewsublanguage&id=".$row['id']."'>".Display::return_icon('mas.gif', get_lang('CreateSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";		
+			$allow_use_sub_language = "&nbsp;<a href='sub_language_add.php?action=definenewsublanguage&id=".$row['id']."'>".Display::return_icon('mas.gif', get_lang('CreateSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";
 			if ($verified_if_is_father===true) {
-				//$allow_add_term_sub_language = "&nbsp;<a href='register_sub_language.php?action=registersublanguage&id=".$row['id']."'>".Display::return_icon('2rightarrow.gif', get_lang('AddWordForTheSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";						
+				//$allow_add_term_sub_language = "&nbsp;<a href='sub_language.php?action=registersublanguage&id=".$row['id']."'>".Display::return_icon('2rightarrow.gif', get_lang('AddWordForTheSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";
 				$allow_add_term_sub_language='';
 			} else {
 				$allow_add_term_sub_language='';
@@ -264,14 +264,14 @@ while ($row = Database::fetch_array($result_select)) {
 		} else {
 				$allow_use_sub_language='';
 				$all_information_of_sub_language=SubLanguageManager::get_all_information_of_language($row['id']);
-				$allow_add_term_sub_language = "&nbsp;<a href='register_sub_language.php?action=registersublanguage&id=".Security::remove_XSS($all_information_of_sub_language['parent_id'])."&sub_language_id=".Security::remove_XSS($row['id'])."'>".Display::return_icon('2rightarrow.gif', get_lang('AddWordForTheSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";									
-				$allow_delete_sub_language = "&nbsp;<a href='new_sub_language.php?action=deletesublanguage&id=".Security::remove_XSS($all_information_of_sub_language['parent_id'])."&sub_language_id=".Security::remove_XSS($row['id'])."'>".Display::return_icon('delete_data.gif', get_lang('DeleteSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";		
+				$allow_add_term_sub_language = "&nbsp;<a href='sub_language.php?action=registersublanguage&id=".Security::remove_XSS($all_information_of_sub_language['parent_id'])."&sub_language_id=".Security::remove_XSS($row['id'])."'>".Display::return_icon('2rightarrow.gif', get_lang('AddWordForTheSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";
+				$allow_delete_sub_language = "&nbsp;<a href='sub_language_add.php?action=deletesublanguage&id=".Security::remove_XSS($all_information_of_sub_language['parent_id'])."&sub_language_id=".Security::remove_XSS($row['id'])."'>".Display::return_icon('delete_data.gif', get_lang('DeleteSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";
 		}
-		
+
 	} else {
 		$allow_use_sub_language='';
 		$allow_add_term_sub_language='';
-	}	
+	}
 	if ($row['available'] == 1) {
 		$row_td[] = "<a class=\"make_visible_and_invisible\" id=\"linktool_".$row['id']."\" href='".api_get_self()."?action=makeunavailable&id=".$row['id']."'>".Display::return_icon('visible.gif', get_lang('MakeUnavailable'),array('id'=>'imglinktool_'.$row['id']))."</a> <a href='".api_get_self()."?action=edit&id=".$row['id']."#value'>".Display::return_icon('edit.gif', get_lang('Edit'))."</a>&nbsp;".$setplatformlanguage.$allow_use_sub_language.$allow_add_term_sub_language.$allow_delete_sub_language;
 		//$row_td[] = "<a class=\"make_visible_and_invisible\" id=\"linktool_".$row['id']."\" href='javascript:void(0)'>".Display::return_icon('visible.gif', get_lang('MakeUnavailable'),array('id'=>'imglinktool_'.$row['id']))."</a> <a href='".api_get_self()."?action=edit&id=".$row['id']."#value'>".Display::return_icon('edit.gif', get_lang('Edit'))."</a>&nbsp;".$setplatformlanguage.$allow_use_sub_language.$allow_add_term_sub_language;
@@ -298,7 +298,7 @@ $table->display();
 
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 17 - 5
main/admin/ldap_form_add_users_group.php

@@ -40,23 +40,35 @@ elseif(!empty($id_session))
 {
 	echo '<input type="hidden" name="id_session" value="'.Security::remove_XSS($id_session).'">';
 }
+$is_western_name_order = api_is_western_name_order();
 echo '<input type="hidden" name="confirmed" value="yes">';
 echo '<table border="0" cellspacing="0" width="100%">';
 echo '<tr align="center" id="header3">' .
 		'<td width="15%"><input type="button" value="'.get_lang('AllSlashNone').'" onClick="checkAll();"></td>' .
 		'<td width="40%"><b>'.get_lang('Email').'</b></td>' .
-		'<td width="15%"><b>'.get_lang('Name').'</b></td>' .
-		'<td width="15%"><b>'.get_lang('FirstName').'</b></td>' .
+		($is_western_name_order
+			? '<td width="15%"><b>'.get_lang('FirstName').'</b></td>' .
+			'<td width="15%"><b>'.get_lang('Name').'</b></td>'
+			: '<td width="15%"><b>'.get_lang('Name').'</b></td>' .
+			'<td width="15%"><b>'.get_lang('FirstName').'</b></td>') .
 		'<td width="15%"><b>'.get_lang('Login').'</b></td>' .
-	  '</tr>'."\n";																																																					   
+	  '</tr>'."\n";
 while (list ($key, $val) = each($nom_form)) {
 	$nbre=$nbre+1;
 	if($nbre & 1) $ndiv=2; else $ndiv=3;
 	echo '<tr align="center" id="header'.$ndiv.'">';
 	echo '<td><input type="checkbox" name="checkboxes[]" value="'.$key.'" checked="checked"></td>';
 	echo '<td>'.$email_form[$key].'<input type="hidden" name="email_form['.$key.']" size="40" value="'.$email_form[$key].'"></td>';
-	echo '<td>'.$nom_form[$key].'<input type="hidden" name="nom_form['.$key.']" size="20" value="'.$nom_form[$key].'"></td>';
-	echo '<td>'.$prenom_form[$key].'<input type="hidden" name="prenom_form['.$key.']" size="20" value="'.$prenom_form[$key].'"></td>';
+	if ($is_western_name_order)
+	{
+		echo '<td>'.$prenom_form[$key].'<input type="hidden" name="prenom_form['.$key.']" size="20" value="'.$prenom_form[$key].'"></td>';
+		echo '<td>'.$nom_form[$key].'<input type="hidden" name="nom_form['.$key.']" size="20" value="'.$nom_form[$key].'"></td>';
+	}
+	else
+	{
+		echo '<td>'.$nom_form[$key].'<input type="hidden" name="nom_form['.$key.']" size="20" value="'.$nom_form[$key].'"></td>';
+		echo '<td>'.$prenom_form[$key].'<input type="hidden" name="prenom_form['.$key.']" size="20" value="'.$prenom_form[$key].'"></td>';
+	}
 	echo '<td>'.$username_form[$key].'<input type="hidden" name="username_form['.$key.']" size="10" value="'.$username_form[$key].'">';
 	echo '<input type="hidden" name="tutor_form['.$key.']" value="0">';
 	echo '<input type="hidden" name="admin_form['.$key.']" value="1">';

+ 12 - 12
main/admin/ldap_import_students.php

@@ -39,7 +39,7 @@ $tool_name = get_lang('LDAPImport');
 // setting breadcrumbs
 $interbreadcrumb[]=array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
 
-$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">	
+$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">
 var buttoncheck = 1;
 function checkAll() {
 	//var boxes = document.form.elements[\'checkboxes[]\'];
@@ -77,23 +77,23 @@ if (empty($annee) && empty($course))
 		echo get_lang('LDAPSelectFilterOnUsersOU');
 		//echo '<em>'.get_lang('ToDoThisYouMustEnterYearComponentAndComponentStep').'</em><br />';
 		///echo get_lang('FollowEachOfTheseStepsStepByStep').'<br />';
-		
+
 		echo '<form method="get" action="'.api_get_self().'"><br />';
 		echo '<em>'.get_lang('LDAPOUAttributeFilter').' :</em> ';
 		echo '<input  type="text" name="annee" size="4" maxlength="30" value="'.$annee_base.'"><br />';
 		echo '<input type="submit" value="'.get_lang('Submit').'">';
 		echo '</form>';
 		echo '</div>';
-	
+
 }
 /*
-elseif ($annee <> "" && $composante == "" && $etape == "") // form 2 annee != 0; composante= 0 etape = 0 
+elseif ($annee <> "" && $composante == "" && $etape == "") // form 2 annee != 0; composante= 0 etape = 0
 {
 		Display::display_header($tool_name);
 
 	$ds = ldap_connect($ldap_host, $ldap_port) or die(get_lang('LDAPConnectionError'));
 	ldap_set_version($ds);
-	
+
 	if ($ds) {
 		$r = false;
 		$res = ldap_handle_bind($ds, $r);
@@ -109,7 +109,7 @@ elseif ($annee <> "" && $composante == "" && $etape == "") // form 2 annee != 0;
 		for($i = 0; $i < $info['count']; $i ++)
 		{
 			//presupose LDAP server is UTF-8
-			$composante[$info[$i]['ou'][0]] = iconv('utf-8', api_get_setting('platform_charset'), $info[$i]['description'][0]);
+			$composante[$info[$i]['ou'][0]] = api_utf8_decode($info[$i]['description'][0], api_get_setting('platform_charset'));
 		}
 		$oucompotab3=$composante;
 
@@ -139,7 +139,7 @@ elseif ($annee <> "" && $composante == "" && $etape == "") // form 2 annee != 0;
 	echo '<br />';
 	echo '</div>';
 }
-elseif ($annee <> "" && $composante <> "" && $etape == "") // form3 :annee!=0composante=0etape=0 
+elseif ($annee <> "" && $composante <> "" && $etape == "") // form3 :annee!=0composante=0etape=0
 {
 
 		Display::display_header($tool_name);
@@ -189,7 +189,7 @@ elseif ($annee <> "" && $composante <> "" && $etape == "") // form3 :annee!=0com
 			if ($ouetapetab[$key] != $tempcomp) {
 				$etape = $ouetapetab2[$key];
 				$tempcomp = '"'.$ouetapetab[$key].'"';
-				$tempcomp = iconv('utf-8',api_get_setting('platform_charset'),$tempcomp);
+				$tempcomp = api_utf8_decode($tempcomp, api_get_setting('platform_charset'));
 
 				$annee = str_word_count($etape, 1);
 				echo '<option value="'.$etape.'">'.$tempcomp.'</option>';
@@ -255,8 +255,8 @@ elseif (!empty($annee) && !empty($course) && empty($_POST['confirmed']))
 		$info = ldap_get_entries($ds, $sr);
 
 		for ($key = 0; $key < $info["count"]; $key ++) {
-			$nom_form[] = $info[$key]["sn"][0];//iconv("utf-8",api_get_setting('platform_charset'), $info[$key]["sn"][0]);
-			$prenom_form[] = $info[$key]["givenname"][0];//iconv("utf-8",api_get_setting('platform_charset'), $info[$key]["givenname"][0]);
+			$nom_form[] = $info[$key]["sn"][0];//api_utf8_decode($info[$key]["sn"][0], api_get_setting('platform_charset'));
+			$prenom_form[] = $info[$key]["givenname"][0];//api_utf8_decode($info[$key]["givenname"][0], api_get_setting('platform_charset'));
 			$email_form[] = $info[$key]["mail"][0];
 			// Get uid from dn
 			//$dn_array=ldap_explode_dn($info[$key]["dn"],1);
@@ -274,7 +274,7 @@ elseif (!empty($annee) && !empty($course) && empty($_POST['confirmed']))
 		asort($nom_form);
 		reset($nom_form);
 
-		$statut=5;	
+		$statut=5;
 		include ('ldap_form_add_users_group.php');
 	} else {
 		echo '<h4>'.get_lang('UnableToConnectTo').' '.$host.'</h4>';
@@ -331,7 +331,7 @@ elseif (!empty($annee) && !empty($course) && ($_POST['confirmed']=='yes'))
 		Display::display_header($tool_name);
 		$message=get_lang('NoUserAdded');
 		Display :: display_normal_message($message,false);
-	}	
+	}
 	echo '<br /><br />';
     echo '<a href="ldap_import_students.php?annee=&composante=&etape=">'.get_lang('BackToNewSearch').'</a>';
     echo '<br /><br />';

+ 10 - 10
main/admin/ldap_import_students_to_session.php

@@ -39,7 +39,7 @@ $tool_name = get_lang('LDAPImport');
 // setting breadcrumbs
 $interbreadcrumb[]=array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
 
-$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">	
+$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">
 var buttoncheck = 1;
 function checkAll() {
 	//var boxes = document.form.elements[\'checkboxes[]\'];
@@ -78,7 +78,7 @@ if (empty($annee) && empty($id_session))
 		echo '<input type="submit" value="'.get_lang('Submit').'">';
 		echo '</form>';
 		echo '</div>';
-	
+
 }
 elseif(!empty($annee) && empty($id_session))
 {
@@ -92,9 +92,9 @@ elseif(!empty($annee) && empty($id_session))
 	$sql = "SELECT id,name,nbr_courses,date_start,date_end " .
 		" FROM $tbl_session ".
 		" ORDER BY name";
-	$result = api_sql_query($sql,__FILE__,__LINE__);
+	$result = Database::query($sql,__FILE__,__LINE__);
 
-	$sessions=api_store_result($result);
+	$sessions=Database::store_result($result);
 	$nbr_results=count($sessions);
 	foreach($sessions as $row)
 	{
@@ -130,8 +130,8 @@ elseif (!empty($annee) && !empty($id_session) && empty($_POST['confirmed']))
 		$info = ldap_get_entries($ds, $sr);
 
 		for ($key = 0; $key < $info["count"]; $key ++) {
-			$nom_form[] = $info[$key]["sn"][0];//iconv("utf-8",api_get_setting('platform_charset'), $info[$key]["sn"][0]);
-			$prenom_form[] = $info[$key]["givenname"][0];//iconv("utf-8",api_get_setting('platform_charset'), $info[$key]["givenname"][0]);
+			$nom_form[] = $info[$key]["sn"][0];//api_utf8_decode($info[$key]["sn"][0], api_get_setting('platform_charset'));
+			$prenom_form[] = $info[$key]["givenname"][0];//api_utf8_decode($info[$key]["givenname"][0], api_get_setting('platform_charset'));
 			$email_form[] = $info[$key]["mail"][0];
 			// Get uid from dn
 			//$dn_array=ldap_explode_dn($info[$key]["dn"],1);
@@ -149,7 +149,7 @@ elseif (!empty($annee) && !empty($id_session) && empty($_POST['confirmed']))
 		asort($nom_form);
 		reset($nom_form);
 
-		$statut=5;	
+		$statut=5;
 		include ('ldap_form_add_users_group.php');
 	} else {
 		echo '<h4>'.get_lang('UnableToConnectTo').' '.$host.'</h4>';
@@ -184,7 +184,7 @@ elseif (!empty($annee) && !empty($id_session) && ($_POST['confirmed']=='yes'))
 			$sql = 'INSERT INTO '.$tbl_session_user.' SET
 					id_user="'.intval($user_id).'",
 					id_session = "'.intval($id_session).'"';
-			$res_user = api_sql_query($sql,__FILE__,__LINE__);
+			$res_user = Database::query($sql,__FILE__,__LINE__);
 			if($res_user != false)
 			{
 				$num++;
@@ -193,7 +193,7 @@ elseif (!empty($annee) && !empty($id_session) && ($_POST['confirmed']=='yes'))
 		if($num>0)
 		{
 			$sql = 'UPDATE '.$tbl_session.' SET nbr_users = (nbr_users + '.$num.') WHERE id = '.intval($id_session);
-			$res = api_sql_query($sql,__FILE__,__LINE__);			 
+			$res = Database::query($sql,__FILE__,__LINE__);
 		}
 		header('Location: resume_session.php?id_session='.Security::remove_XSS($_POST['id_session']));
 	}
@@ -221,7 +221,7 @@ elseif (!empty($annee) && !empty($id_session) && ($_POST['confirmed']=='yes'))
 		Display::display_header($tool_name);
 		$message=get_lang('NoUserAdded');
 		Display :: display_normal_message($message,false);
-	}	
+	}
 	echo '<br /><br />';
     echo '<a href="ldap_import_students.php?annee=&composante=&etape=">'.get_lang('BackToNewSearch').'</a>';
     echo '<br /><br />';

+ 17 - 17
main/admin/ldap_synchro.php

@@ -60,11 +60,11 @@ $tbl_session_rel_etape 				= "session_rel_etape";
 
 $message="";
 
-$result=api_sql_query("SELECT id, name FROM $tbl_session",__FILE__,__LINE__);
-$Sessions=api_store_result($result);
+$result=Database::query("SELECT id, name FROM $tbl_session",__FILE__,__LINE__);
+$Sessions=Database::store_result($result);
 
-$result=api_sql_query($sql,__FILE__,__LINE__);
-$users=api_store_result($result);
+$result=Database::query($sql,__FILE__,__LINE__);
+$users=Database::store_result($result);
 
 foreach($Sessions as $session){
 	$id_session = $session['id'];
@@ -72,14 +72,14 @@ foreach($Sessions as $session){
 	$UserList=array();
 	$UserUpdate=array();
 	$UserAdd=array();
-	
+
 	// Parse des code etape de la session
 	/*
-	$sql = "SELECT  id_session, code_etape, etape_description, code_ufr, annee 
+	$sql = "SELECT  id_session, code_etape, etape_description, code_ufr, annee
 		FROM $tbl_session_rel_etape
 		WHERE id_session='$id_session'
 		ORDER BY code_ufr, code_etape";
-	$result = api_sql_query($sql);
+	$result = Database::query($sql);
 	*/
 	$ds = ldap_connect($ldap_host, $ldap_port) or die(get_lang('LDAPConnectionError'));
 	ldap_set_version($ds);
@@ -109,8 +109,8 @@ foreach($Sessions as $session){
 					echo "<pre>";
 					print_r($info[$key]);
 					echo "</pre>";
-					$lastname = iconv('utf-8', api_get_setting('platform_charset'), $info[$key]["sn"][0]);
-					$firstname = iconv('utf-8', api_get_setting('platform_charset'), $info[$key]["givenname"][0]);
+					$lastname = api_utf8_decode($info[$key]["sn"][0], api_get_setting('platform_charset'));
+					$firstname = api_utf8_decode($info[$key]["givenname"][0], api_get_setting('platform_charset'));
 					$email = $info[$key]["mail"][0];
 					// Get uid from dn
 					$dn_array=ldap_explode_dn($info[$key]["dn"],1);
@@ -149,9 +149,9 @@ foreach($Sessions as $session){
 		{
 			print "> $name_session: ".count($UserAdd).get_lang('Added').' '.get_lang('And').' '.count($UserUpdate).' '.get_lang('Modified')."\n";
 		}
-		
+
 		// Une fois les utilisateurs importer dans la base des utilisateurs, on peux les affecter a� la session
-		$result=api_sql_query("SELECT course_code FROM $tbl_session_rel_course " .
+		$result=Database::query("SELECT course_code FROM $tbl_session_rel_course " .
 				"WHERE id_session='$id_session'",__FILE__,__LINE__);
 		$CourseList=array();
 		while($row=Database::fetch_array($result))
@@ -163,29 +163,29 @@ foreach($Sessions as $session){
 			// On ajoute la relation entre l'utilisateur et le cours
 			foreach($UserList as $enreg_user)
 			{
-				api_sql_query("INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user) VALUES('$id_session','$enreg_course','$enreg_user')",__FILE__,__LINE__);
+				Database::query("INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user) VALUES('$id_session','$enreg_course','$enreg_user')",__FILE__,__LINE__);
 			}
 			$sql = "SELECT COUNT(id_user) as nbUsers " .
 					"FROM $tbl_session_rel_course_rel_user " .
 					"WHERE id_session='$id_session' AND course_code='$enreg_course'";
-			$rs = api_sql_query($sql, __FILE__, __LINE__);
+			$rs = Database::query($sql, __FILE__, __LINE__);
 			list($nbr_users) = Database::fetch_array($rs);
 			$sql = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'";
-			api_sql_query($sql,__FILE__,__LINE__);
+			Database::query($sql,__FILE__,__LINE__);
 		}
 		// On ajoute la relation entre l'utilisateur et la session
 		foreach($UserList as $enreg_user){
 			$sql = "INSERT IGNORE INTO $tbl_session_rel_user(id_session, id_user) " .
 					"VALUES('$id_session','$enreg_user')";
-			api_sql_query($sql,__FILE__,__LINE__);
+			Database::query($sql,__FILE__,__LINE__);
 		}
 		$sql = "SELECT COUNT(id_user) as nbUsers " .
 				"FROM $tbl_session_rel_user " .
 				"WHERE id_session='$id_session'";
-		$rs = api_sql_query($sql, __FILE__, __LINE__);
+		$rs = Database::query($sql, __FILE__, __LINE__);
 		list($nbr_users) = Database::fetch_array($rs);
 		$sql = "UPDATE $tbl_session SET nbr_users=$nbr_users WHERE id='$id_session'";
-		api_sql_query($sql,__FILE__,__LINE__);
+		Database::query($sql,__FILE__,__LINE__);
 	}
 }
 ?>

+ 27 - 11
main/admin/ldap_users_list.php

@@ -47,7 +47,7 @@ api_protect_admin_script();
 require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
 $action = $_GET["action"];
 $login_as_user_id = $_GET["user_id"];
-	
+
 // Login as ...
 if ($_GET['action'] == "login_as" && isset ($login_as_user_id))
 {
@@ -127,7 +127,7 @@ if (isset ($_GET['action']))
 					Display :: display_normal_message($message,false);
 				}
 				break;
-			default : 
+			default :
 				Display :: display_header($tool_name);
 		}
 		Security::clear_token();
@@ -190,9 +190,9 @@ if (isset ($_POST['action']))
 				else
 				{
 					Display :: display_normal_message(get_lang('NoUserAdded'));
-				}				
+				}
 				break;
-				
+
 		}
 		Security::clear_token();
 	}
@@ -200,9 +200,17 @@ if (isset ($_POST['action']))
 
 $form = new FormValidator('advanced_search','get');
 $form->add_textfield('keyword_username',get_lang('LoginName'),false);
-$form->add_textfield('keyword_lastname',get_lang('LastName'),false);
-$form->add_textfield('keyword_firstname',get_lang('FirstName'),false);
-if (isset($_GET['id_session'])) 
+if (api_is_western_name_order())
+{
+	$form->add_textfield('keyword_firstname', get_lang('FirstName'), false);
+	$form->add_textfield('keyword_lastname', get_lang('LastName'), false);
+}
+else
+{
+	$form->add_textfield('keyword_lastname',get_lang('LastName'),false);
+	$form->add_textfield('keyword_firstname',get_lang('FirstName'),false);
+}
+if (isset($_GET['id_session']))
 	$form->addElement('hidden','id_session',$_GET['id_session']);
 
 $type = array();
@@ -224,17 +232,25 @@ $parameters['keyword_username'] = $_GET['keyword_username'];
 $parameters['keyword_firstname'] = $_GET['keyword_firstname'];
 $parameters['keyword_lastname'] = $_GET['keyword_lastname'];
 $parameters['keyword_email'] = $_GET['keyword_email'];
-if (isset($_GET['id_session'])) 
+if (isset($_GET['id_session']))
 	$parameters['id_session'] = $_GET['id_session'];
 // Create a sortable table with user-data
 
 $parameters['sec_token'] = Security::get_token();
-$table = new SortableTable('users', 'ldap_get_number_of_users', 'ldap_get_user_data',2);
+$table = new SortableTable('users', 'ldap_get_number_of_users', 'ldap_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('LoginName'));
-$table->set_header(2, get_lang('LastName'));
-$table->set_header(3, get_lang('FirstName'));
+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(4, get_lang('Email'));
 $table->set_header(5, get_lang('Actions'));
 //$table->set_column_filter(5, 'email_filter');

+ 1 - 1
main/admin/ldap_users_synchro.php

@@ -86,6 +86,6 @@ if (isset($action) && ($action=="synchro")) {
 	$included=true;
 	require('ldap_synchro.php');
 	Display :: display_normal_message($message,false);
-}	
+}
 Display::display_footer();
 ?>

+ 41 - 41
main/admin/legal_add.php

@@ -10,24 +10,24 @@ api_protect_admin_script();
 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).'legal.lib.php';
-//var_dump($_POST);	
+//var_dump($_POST);
 // Create the form
 $form = new FormValidator('addlegal');
-//var_dump($_POST);// var_dump($_GET); 
+//var_dump($_POST);// var_dump($_GET);
 $defaults=array();
 if( $form->validate()) {
-	$check = Security::check_token('post');			
+	$check = Security::check_token('post');
 		if ($check) {
-			$values  = $form->getSubmitValues();						
+			$values  = $form->getSubmitValues();
 			$lang 	 = $values['language'];
 			//language id
 			$lang = api_get_language_id($lang);
-			 
+
 			$type 	 = $values['type'];
 			$content = $values['content'];
 			$changes = $values['changes'];
 			$navigator_info = api_get_navigator();
-			
+
 			if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
 				if (isset($values['preview'])) {
 					$submit	='preview';
@@ -37,68 +37,68 @@ if( $form->validate()) {
 					$submit	='back';
 				}
 			}else {
-				$submit  = $values['send'];	
-			
-			}		
+				$submit  = $values['send'];
+
+			}
 
 			$default[content]=$content;
 			if (isset($values['language'])){
 				if($submit=='back') {
 					header('Location: legal_add.php');
 					exit;
-				} elseif($submit=='save') {					
-					$insert_result = LegalManager::add($lang,$content,$type,$changes);					
+				} elseif($submit=='save') {
+					$insert_result = LegalManager::add($lang,$content,$type,$changes);
 					if ($insert_result )
 						$message = get_lang('TermAndConditionSaved');
-					else 
-						$message = get_lang('TermAndConditionNotSaved');				
+					else
+						$message = get_lang('TermAndConditionNotSaved');
 					Security::clear_token();
-					$tok = Security::get_token();			
+					$tok = Security::get_token();
 					header('Location: legal_list.php?action=show_message&message='.urlencode($message).'&sec_token='.$tok);
-					exit();		
-				} elseif($submit=='preview') {		
+					exit();
+				} elseif($submit=='preview') {
 					$defaults['type']=$type;
 					$defaults['content']=$content;
 					$defaults['changes']=$changes;
 					$term_preview = $defaults;
-					$term_preview['type'] = intval($_POST['type']);						
-				} else {				
+					$term_preview['type'] = intval($_POST['type']);
+				} else {
 					$my_lang = $_POST['language'];
 					if (isset($_POST['language'])){
-						$all_langs = api_get_languages();						
+						$all_langs = api_get_languages();
 						if (in_array($my_lang, $all_langs['folder'])){
-							$language = api_get_language_id($my_lang);					
+							$language = api_get_language_id($my_lang);
 							$term_preview = LegalManager::get_last_condition($language);
 							$defaults = $term_preview;
 							if ($term_preview==false) {
 								// there are not terms and conditions
 								$term_preview['type']=-1;
 								$defaults['type']=0;
-							}						
+							}
 						}
-					}		
+					}
 				}
 			}
 		}
-} else {	
+} else {
 	/*
 	if (!isset($_POST['language'])) {
 		$language = api_get_setting('platformLanguage');
 		$language = api_get_language_id($language);
-		$term_preview = LegalManager::get_last_condition($language);	
+		$term_preview = LegalManager::get_last_condition($language);
 		$defaults['type']=$term_preview['type'];
 		if ($term_preview==false) {
 			// there are not terms and conditions
 			$term_preview['type']=-1;
 			$defaults['type']=0;
-		}			
+		}
 		$defaults['content']=$term_preview['content'];
 		$defaults['changes']=$term_preview['changes'];
 	}*/
 }
 $form->setDefaults($default);
 //var_dump($term_preview);
-if(isset($_POST['send'])) { 
+if(isset($_POST['send'])) {
 	Security::clear_token();
 }
 $token = Security::get_token();
@@ -118,12 +118,12 @@ $form->addElement('html',$text);
 //$form->addElement('select_language', 'language', get_lang('Language'),null,array('id'=>'language','onchange'=>'sendlang();'));
 
 
-if (isset($_POST['language'])) {	
+if (isset($_POST['language'])) {
 //$form->addElement('html_editor', 'content', null, null, array('ToolbarSet' => 'Basic', 'Width' => '100%', 'Height' => '250'));
 	$form->addElement('static', $_POST['language']);
 	$form->addElement('hidden', 'language',$_POST['language']);
 	$form->add_html_editor('content', get_lang('Content'), true, false, array('ToolbarSet' => 'simple', 'Width' => '100%', 'Height' => '250'));
-	//$form->addElement('textarea', 'content', get_lang('Content'),array('cols'=>'120','rows'=>'10'));	
+	//$form->addElement('textarea', 'content', get_lang('Content'),array('cols'=>'120','rows'=>'10'));
 	$form->addElement('radio', 'type', '', get_lang('HTMLText') ,'0');
 	$form->addElement('radio', 'type', '', get_lang('PageLink') ,'1');
 	$form->addElement('textarea', 'changes', get_lang('ExplainChanges'),array('width'=>'20'));
@@ -135,15 +135,15 @@ if (isset($_POST['language'])) {
 				<div class="formw">
 				'.$preview.'
 				</div>
-				</div>';	
+				</div>';
 		$form->addElement('html',$term_preview);
 	}
 	// Submit & preview button
-	
+
 		$navigator_info = api_get_navigator();
 		//ie6 fix
 	if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
-		
+
 	$buttons = '<div class="row" align="center">
 			<div class="formw">
 			<input type="submit" name="back"  value="'.get_lang('Back').'"/>
@@ -152,7 +152,7 @@ if (isset($_POST['language'])) {
 			</div>
 		</div>';
 		$form->addElement('html',$buttons);
-	} else {				
+	} else {
 	$buttons = '<div class="row" align="center">
 					<div class="formw">
 					<button type="submit" class="back" 	 name="send" value="back">'.get_lang('Back').'</button>
@@ -162,7 +162,7 @@ if (isset($_POST['language'])) {
 				</div>';
 		$form->addElement('html',$buttons);
 	}
-	
+
 /*	$buttons = '<div class="row">
 					<div class="formw">
 					<button type="submit" class="back" 	 name="send" value="back">'.get_lang('Back').'</button>
@@ -170,16 +170,16 @@ if (isset($_POST['language'])) {
 					<button type="submit" class="save" 	 name="send" value="save">'.get_lang('Save').'</button>
 					</div>
 				</div>';	*/
-	
+
 } else {
 	$form->addElement('select_language', 'language', get_lang('Language'),null,array());
 	$buttons = '<div class="row">
-					<div class="formw">					
+					<div class="formw">
 					<button type="submit" class="save" 	 name="send" value="load">'.get_lang('Load').'</button>
 					</div>
-				</div>';	
+				</div>';
 	$form->addElement('html',$buttons);
-	
+
 }
 //var_dump($defaults);
 
@@ -191,7 +191,7 @@ Display :: display_header($tool_name);
 echo '<script>
 function sendlang(){
 	//document.addlegal.send.value=\'load\';
-//	alert(document.addlegal.send.value);	
+//	alert(document.addlegal.send.value);
 	document.addlegal.sec_token.value=\''.$token.'\';
 	document.addlegal.submit();
 }
@@ -201,7 +201,7 @@ function sendlang(){
 echo '<div class="actions" style="height:22px;">';
 echo '<div style="float:right;">
 		<a href="'.api_get_path(WEB_CODE_PATH).'admin/legal_list.php">'.Display::return_icon('search.gif',get_lang('EditTermsAndConditions'),'').get_lang('AllVersions').'</a>&nbsp;&nbsp;
-	  </div><br />';		  
+	  </div><br />';
 echo '</div>';
 
 if (isset ($_GET['action'])) {
@@ -209,9 +209,9 @@ if (isset ($_GET['action'])) {
 		case 'show_message' :
 			Display :: display_normal_message(stripslashes($_GET['message']));
 			break;
-	}	
+	}
 }
-		
+
 
 //var_dump($defaults);
 

+ 6 - 6
main/admin/legal_list.php

@@ -5,7 +5,7 @@ $language_file = 'admin';
 $cidReset = true;
 require ('../inc/global.inc.php');
 $this_section = SECTION_PLATFORM_ADMIN;
-api_protect_admin_script();	
+api_protect_admin_script();
 $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
 $tool_name = get_lang('TermsAndConditions');
 Display :: display_header($tool_name);
@@ -21,7 +21,7 @@ $parameters['sec_token'] = Security::get_token();
 echo '<div class="actions" style="height:22px;">';
 echo '<div style="float:right;">
 		<a href="'.api_get_path(WEB_CODE_PATH).'admin/legal_add.php">'.Display::return_icon('edit.gif',get_lang('EditTermsAndConditions'),'').get_lang('EditTermsAndConditions').'</a>&nbsp;&nbsp;
-	  </div><br />';		  
+	  </div><br />';
 echo '</div>';
 
 // Actions
@@ -31,7 +31,7 @@ if (isset ($_GET['action'])) {
 	Security::clear_token();
 }
 
-$table = new SortableTable('conditions', 'count_mask', 'get_legal_data_mask',2); 
+$table = new SortableTable('conditions', 'count_mask', 'get_legal_data_mask',2);
 $table->set_additional_parameters($parameters);
 $table->set_header(0, get_lang('Version'), false, 'width="15px"');
 $table->set_header(1, get_lang('Language'), false, 'width="30px"');
@@ -39,19 +39,19 @@ $table->set_header(2, get_lang('Content'),false);
 $table->set_header(3, get_lang('Changes'), false, 'width="60px"');
 $table->set_header(4, get_lang('Type'), false, 'width="60px"');
 $table->set_header(5, get_lang('Date'), false, 'width="50px"');
-$table->display(); 
+$table->display();
 
 // this 2 "mask" function are here just because the SortableTable
 function get_legal_data_mask($id, $params=null, $row=null) {
 	return LegalManager::get_legal_data($id, $params, $row);
 }
 function count_mask() {
-	return LegalManager::count();				
+	return LegalManager::count();
 }
 
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 0 - 297
main/admin/register_sub_language.php

@@ -1,297 +0,0 @@
-<?php
-/* For licensing terms, see /dokeos_license.txt */
-/**
-==================================================================================
-	@author Isaac flores paz <florespaz_isaac@hotmail.com> - Added 9 july of 2009
-==================================================================================
-*/
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file = 'admin';
-$cidReset = true;
-require_once '../inc/global.inc.php';
-require_once 'sub_language.class.php';
-$this_section=SECTION_PLATFORM_ADMIN;
-
-api_protect_admin_script();
-$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
-$htmlHeadXtra[] ='<script type="text/javascript">
- $(document).ready(function() {
- 
-	$("#sl_original_file").change(function () { 
-	
-		current_action=$("#Loadlanguage").attr("action");
-		current_action=current_action.split("original_file");
-		current_action=current_action[0];
-		current_action=current_action+"original_file="+$(this).attr("value")
-		$("#Loadlanguage").attr("action",current_action);
-		//
-		current_action=$("#Searchlanguage").attr("action");
-		current_action=current_action.split("original_file");
-		current_action=current_action[0];
-		current_action=current_action+"original_file="+$(this).attr("value")
-		$("#Searchlanguage").attr("action",current_action);	
-	 }); 
-	
-	$(window).load(function () { 
-		/*current_action=$("#Loadlanguage").attr("action");
-		current_action=current_action+"&original_file="+$("#sl_original_file").attr("value")
-		$("#Loadlanguage").attr("action",current_action);*/
-	});
-
- 	$("#sl_original_file option[@value='.Security::remove_XSS($_REQUEST['original_file']).']").attr("selected","selected"); 
-
-	$(".save").click(function() {		
-		button_name=$(this).attr("name");	
-		button_name=button_name.split("_");
-		button_name=button_name[1];
-		is_id=$("#id_hidden_original_file").attr("value");
-		is_sublanguage_id=$("#id_hidden_sublanguage").attr("value");
-		is_variable_language="$"+button_name;
-		is_new_language=$("#txtid_"+button_name).attr("value");
-		if (is_new_language=="undefined") {
-			is_new_language="_";
-		}
-		is_file_language="'.Security::remove_XSS($_REQUEST['original_file']).'";
-		if (is_new_language.length>0 && is_new_language!="_") {
-			$.ajax({
-				contentType: "application/x-www-form-urlencoded",
-				beforeSend: function(objeto) {
-					$("#div_message_information_id").html("<div class=\"normal-message\"><img src=\'../inc/lib/javascript/indicator.gif\' /></div>");
-				
-				},
-				type: "POST",
-				url: "../admin/add_by_ajax_sub_language.inc.php",
-				data: "new_language="+is_new_language+"&variable_language="+is_variable_language+"&file_language="+is_file_language+"&id="+is_id+"&sublanguage_id="+is_sublanguage_id,
-				success: function(datos) {
-					$("#div_message_information_id").html("<div class=\"confirmation-message\">'.get_lang('TheNewWordHasBeenAdded').'</div>");
-				
-			} }); 
-		} else {
-			$("#div_message_information_id").html("<div class=\"error-message\">'.get_lang('FormHasErrorsPleaseComplete').'</div>");
-		}
-				
-
-	});
-
- 		});
-</script>';	
-/*
-============================================================================== 
-		MAIN CODE
-============================================================================== 
-*/
-// setting the name of the tool
-$tool_name = get_lang('CreateSubLanguage');
-
-// setting breadcrumbs  
-$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ('url' => 'languages.php', 'name' => get_lang('PlatformLanguages'));
-
-require_once api_get_path(LIBRARY_PATH).'text.lib.php';
-require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
-
-if (isset($_GET['id']) && $_GET['id']==strval(intval($_GET['id']))) {
-	$language_name=SubLanguageManager::get_name_of_language_by_id ($_GET['id']);
-	$all_data_of_language=SubLanguageManager::get_all_information_of_language($_GET['id']);
-	$my_language=$language_name;
-	if (SubLanguageManager::check_if_exist_language_by_id($_GET['id'])===true) {
-		$parent_id=intval($_GET['id']);
-		$language_id_exist=true;
-	} else {
-		$language_id_exist=false;
-	}
-} else {
-	$language_name='';
-	$language_id_exist=false;	
-}
-
-$language_name=get_lang('RegisterTermsOfSubLanguageForLanguage').' ( '.strtolower($language_name).' )';
-
-// including the header file (which includes the banner itself)
-
-
-$dokeos_path_folder=api_get_path('SYS_LANG_PATH').$all_data_of_language['dokeos_folder'];
-//get file name example : forum.inc.php,gradebook.inc.php
-
-if (!is_dir($dokeos_path_folder) || strlen($all_data_of_language['dokeos_folder'])==0) {
-	api_not_allowed(true);
-}
-
-Display :: display_header($language_name);
-
-$all_file_of_directory=SubLanguageManager::get_all_data_of_dokeos_folder ($dokeos_path_folder);
-$load_array_in_select=array();
-sort($all_file_of_directory);
-foreach ($all_file_of_directory as $value_all_file_of_directory) {
-	$load_array_in_select[$value_all_file_of_directory]=$value_all_file_of_directory;
-}
-
-$request_file='';
-
-if (isset($_POST['original_file']) && $_POST['original_file']!='') {
-	$request_file=Security::remove_XSS($_POST['original_file']);
-} 
-if (isset($_GET['original_file']) && $_GET['original_file']!='') {
-	$request_file=Security::remove_XSS($_GET['original_file']);
-}
-
-/*$form = new FormValidator('Loadlanguage', 'post', 'register_sub_language.php?id='.Security::remove_XSS($_GET['id']).'&original_file='.$request_file);
-$class='plus';
-$form->addElement('hidden','id_hidden_original_file',Security::remove_XSS($_REQUEST['id']),array('id'=>'id_hidden_original_file'));
-$select_level = array (); 	
-$radios_results_enabled[] = FormValidator :: createElement ('select', 'original_file', get_lang('File'),$load_array_in_select,array('id'=>'sl_original_file'));
-$radios_results_enabled[] = FormValidator :: createElement ('style_submit_button', 'SubmitLoadLanguage', get_lang('LoadLanguageFile'), 'class="'.$class.'"');
-$radios_results_enabled[] = FormValidator :: createElement ('text', 'txt_search_word');
-$radios_results_enabled[] = FormValidator :: createElement ('style_submit_button', 'SubmitSearchLanguage', get_lang('Search'), 'class="search"');
-$form->addGroup($radios_results_enabled);*/
-echo '<div class="actions-message" >';
-echo $language_name;
-echo '</div>';
-echo '<br/>';
-/*echo '<div class="actions">';
-$form->display();
-echo '</div>';*/
-
-$html.='<div style="float:left" class="actions" >';
-$html.='<form style="float:left" id="Loadlanguage" name="Loadlanguage" method="post" action="register_sub_language.php?id='.Security::remove_XSS($_GET['id']).'&sub_language_id='.Security::remove_XSS($_GET['sub_language_id']).'&original_file='.$request_file.'" >';
-$html.='<input  type="hidden" name="id_hidden_original_file" id="id_hidden_original_file" value="'.Security::remove_XSS($_REQUEST['id']).'" />';
-$html.='<input  type="hidden" name="id_hidden_sublanguage" id="id_hidden_sublanguage" value="'.Security::remove_XSS($_REQUEST['sub_language_id']).'" />';
-$html.='<select id="sl_original_file" name="original_file">';
-//$html.='<option value="0">'.get_lang('SelectAChoice').'</option>';
-foreach ($load_array_in_select as $index_radios_results_enabled=>$value_radios_results_enabled) {
-$html.='<option value="'.$value_radios_results_enabled.'">'.$value_radios_results_enabled.'</option>';
-}
-$html.='</select>';
-$html.='<button class="plus" name="SubmitLoadLanguage" type="submit">'.get_lang('LoadLanguageFile').'</button>';
-$html.='</form>';
-$html.='</div>';
-
-$html.='<div style="float:left" class="actions">';
-$html.='<form style="float:left"  id="Searchlanguage" name="Searchlanguage" method="post" action="register_sub_language.php?id='.Security::remove_XSS($_GET['id']).'&sub_language_id='.Security::remove_XSS($_GET['sub_language_id']).'&original_file='.$request_file.'" >';
-$html.='&nbsp;'.get_lang('OriginalName').'&nbsp; :&nbsp;';
-$html.='<input name="txt_search_word" type="text" size="30"  id="txt_search_word" value="" />';
-$html.='<button name="SubmitSearchLanguage" class="search" type="submit">'.get_lang('Search').'</button>';
-$html.='</form>';
-$html.='</div>';
-
-echo $html;
-
-echo '<br/>';
-echo '<br/>';
-echo '<br/>';
-//id
-echo '<div id="div_message_information_id">&nbsp;</div>';
-echo '<div class="actions-message"><strong>';
-echo get_lang('AddTermsOfThisSubLanguage');
-echo '</strong></div>';
-echo '<br/>';
-
-//allow see data in sortetable
-if ($_REQUEST['original_file']) {
-
-if (isset($_REQUEST['txt_search_word']) && strlen(trim($_REQUEST['txt_search_word']))==0) {
-	unset($list_info);
-	$search_data=false;
-} else {
-	$search_data=true;	
-}
-if($search_data===true) { 
-	$parent_id=intval($_REQUEST['id']);
-	$sub_language_id=intval($_REQUEST['sub_language_id']);
-	$get_all_info_of_sub_language=SubLanguageManager::get_all_information_of_sub_language ($parent_id,$sub_language_id);
-	$dokeos_path_file=api_get_path('SYS_LANG_PATH').$all_data_of_language['dokeos_folder'].'/'.$request_file;	
-
-	$dokeos_english_path_file=api_get_path('SYS_LANG_PATH').'english/'.$request_file;
-	$dokeos_sub_language_path_file=api_get_path('SYS_LANG_PATH').$get_all_info_of_sub_language['dokeos_folder'].'/'.$request_file;		
-	if (file_exists($dokeos_sub_language_path_file)) {
-		$sub_language_exist=true;
-	} else {
-		$sub_language_exist=false;
-	}
-
-	$all_language_variable=SubLanguageManager::get_all_language_variable_in_file ($dokeos_path_file);
-	$all_english_language_variable=SubLanguageManager::get_all_language_variable_in_file($dokeos_english_path_file);
-	if ($sub_language_exist===true) {
-		$get_all_sub_language_variable=SubLanguageManager::get_all_language_variable_in_file($dokeos_sub_language_path_file);
-	}
-	$i=0;
-	foreach ($all_language_variable as $index_language_variable =>$value_language_variable) {
-		$use_field_name=substr($index_language_variable,1);
-		
-		if ($sub_language_exist===true) {
-			foreach ($get_all_sub_language_variable as $index_get_all_sub_language_variable =>$value_get_all_sub_language_variable) {
-				if ($index_get_all_sub_language_variable==$index_language_variable) {
-					$value_sub_language=$value_get_all_sub_language_variable;
-					break;
-				} else {
-					$value_sub_language='';
-				}
-			}
-		}
-		$value_sub_language=strlen($value_sub_language)>0 ? $value_sub_language : '';
-		
-		$obj_text='<textarea tabindex="1" rows="4" cols="40" name="txt_'.$use_field_name.'" id="txtid_'.$use_field_name.'" >'.substr($value_sub_language,1,(strlen($value_sub_language)-3)).'</textarea>';
-		
-		$obj_button='<button class="save" type="button" name="btn_'.$use_field_name.'" id="btnid_'.$use_field_name.'"  />'.get_lang('Save').'</button>';		
-		
-		$new_element_html=='<input type="hidden" name="code_language_id" id="code_language_id" value="'.Security::remove_XSS($_GET['id']).'" />';
-		
-		if ($i==0) {
-			$obj_button=$obj_button.$new_element_html;
-		} else {
-			$obj_button=$obj_button;
-		}
-		foreach ($all_english_language_variable as $index_english_language_variable =>$value_english_language_variable) {
-			if ($index_english_language_variable==$index_language_variable) {
-				$add_english_language_in_array=$value_english_language_variable;
-				break;
-			}
-		}
-		//FIRST OPTION substr($index_language_variable,1,strlen($index_language_variable)),
-		$list_info[]=array($index_language_variable,substr($add_english_language_in_array,1,(strlen($add_english_language_in_array)-3)),substr($value_language_variable,1,(strlen($value_language_variable)-3)),$obj_text,$obj_button);
-	$i++;
-	}
-}
-if (isset($_REQUEST['txt_search_word']) && strlen(trim($_REQUEST['txt_search_word']))>0) {
-	foreach ($list_info as $index_list_info=>$value_list_info) {
-			$search='/'.Security::remove_XSS(trim($_REQUEST['txt_search_word'])).'/i';
-			if (preg_match($search,$value_list_info[2])===0) {
-				unset($list_info[$index_list_info]);
-			}
-	
-	}
-}
-}
-$parameters=array('id'=>Security::remove_XSS($_GET['id']),'original_file'=>$request_file,'sub_language_id'=>Security::remove_XSS($_GET['sub_language_id']));
-if (isset($_REQUEST['txt_search_word']) && strlen($_REQUEST['txt_search_word'])>0) {
-	$parameters['txt_search_word']=Security::remove_XSS($_REQUEST['txt_search_word']);
-}
-
-$table = new SortableTableFromArrayConfig($list_info, 1,20,'data_info');
-$table->set_additional_parameters($parameters);
-//$table->set_header(0, '');	
-$table->set_header(0, get_lang('LanguageVariable'));
-$table->set_header(1, get_lang('EnglishName'));
-$table->set_header(2, get_lang('OriginalName'));
-$table->set_header(3, get_lang('SubLanguage'),false);
-$table->set_header(4, get_lang('Edit'),false);
-/*$form_actions = array ();
-$form_actions['addsublanguage'] = get_lang('AddSubLanguage');
-$table->set_form_actions($form_actions);*/
-
-$table->display();
-
-/*
-==============================================================================
-		FOOTER 
-==============================================================================
-*/
-		
-Display :: display_footer();
-?>

+ 90 - 38
main/admin/resume_session.php

@@ -2,7 +2,7 @@
 /* For licensing terms, see /dokeos_license.txt */
 /**
 ==============================================================================
-	@author Bart Mollet
+*	@author Bart Mollet
 *	@package dokeos.admin
 ==============================================================================
 */
@@ -35,17 +35,18 @@ $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);
+$tbl_session_category				= Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
 
 $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
+$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, session_category_id, visibility
 		FROM '.$tbl_session.'
 		LEFT JOIN '.$tbl_user.'
 			ON id_coach = user_id
 		WHERE '.$tbl_session.'.id='.$id_session;
 
-$rs = api_sql_query($sql, __FILE__, __LINE__);
-$session = api_store_result($rs);
+$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'])
@@ -53,40 +54,53 @@ if(!api_is_platform_admin() && $session['session_admin_id']!=$_user['user_id'])
 	api_not_allowed(true);
 }
 
+$sql = 'SELECT name FROM  '.$tbl_session_category.' WHERE id = "'.intval($session['session_category_id']).'"';
+$rs = Database::query($sql, __FILE__, __LINE__);
+$session_category = '';
+if(Database::num_rows($rs)>0) {
+	$rows_session_category = Database::store_result($rs);
+	$rows_session_category = $rows_session_category[0];
+	$session_category = $rows_session_category['name'];
+}
 
 if($_GET['action'] == 'delete')
 {
 	$idChecked = $_GET['idChecked'];
-	if(is_array($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)."'";
 
-		api_sql_query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND course_code IN($idChecked)",__FILE__,__LINE__);
+		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();
+		$nbr_affected_rows=Database::affected_rows();
 
-		api_sql_query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code IN($idChecked)",__FILE__,__LINE__);
+		Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code IN($idChecked)",__FILE__,__LINE__);
 
-		api_sql_query("UPDATE $tbl_session SET nbr_courses=nbr_courses-$nbr_affected_rows WHERE id='$id_session'",__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'])){
-		api_sql_query("DELETE FROM $tbl_session_rel_class WHERE session_id='$id_session' AND class_id=".$_GET['class'],__FILE__,__LINE__);
+		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();
+		$nbr_affected_rows=Database::affected_rows();
 
-		api_sql_query("UPDATE $tbl_session SET nbr_classes=nbr_classes-$nbr_affected_rows WHERE id='$id_session'",__FILE__,__LINE__);
+		Database::query("UPDATE $tbl_session SET nbr_classes=nbr_classes-$nbr_affected_rows WHERE id='$id_session'",__FILE__,__LINE__);
 
 	}
 
 	if(!empty($_GET['user'])){
-		api_sql_query("DELETE FROM $tbl_session_rel_user WHERE id_session='$id_session' AND id_user=".$_GET['user'],__FILE__,__LINE__);
-		$nbr_affected_rows=mysql_affected_rows();
-		api_sql_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_user WHERE id_session='$id_session' AND id_user=".intval($_GET['user']),__FILE__,__LINE__);
+		$nbr_affected_rows=Database::affected_rows();
+		Database::query("UPDATE $tbl_session SET nbr_users=nbr_users-$nbr_affected_rows WHERE id='$id_session'",__FILE__,__LINE__);
 
-		api_sql_query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND id_user=".$_GET['user'],__FILE__,__LINE__);
-		$nbr_affected_rows=mysql_affected_rows();
-		api_sql_query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows WHERE id_session='$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=Database::affected_rows();
+		Database::query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows WHERE id_session='$id_session'",__FILE__,__LINE__);
 	}
 }
 
@@ -95,7 +109,7 @@ if($_GET['action'] == 'delete')
 
 Display::display_header($tool_name);
 if (!empty($_GET['warn'])) {
-    Display::display_warning_message(urldecode($_GET['warn']));    
+    Display::display_warning_message(urldecode($_GET['warn']));
 }
 
 api_display_tool_title($tool_name);
@@ -113,10 +127,16 @@ api_display_tool_title($tool_name);
 </tr>
 <tr>
 	<td><?php echo get_lang('GeneralCoach'); ?> :</td>
-	<td><?php echo $session['lastname'].' '.$session['firstname'].' ('.$session['username'].')' ?></td>
+	<td><?php echo api_get_person_name($session['firstname'], $session['lastname']).' ('.$session['username'].')' ?></td>
 </tr>
+<?php if(!empty($session_category)): ?>
 <tr>
-	<td><?php echo ('Dates'); ?> :</td>
+	<td><?php echo get_lang('SessionCategory') ?></td>
+	<td><?php echo $session_category;  ?></td>
+</tr>
+<?php endif; ?>
+<tr>
+	<td><?php echo get_lang('Date'); ?> :</td>
 	<td>
 	<?php
 		if($session['date_start']=='00-00-0000')
@@ -144,6 +164,16 @@ api_display_tool_title($tool_name);
 		<?php echo intval($session['nb_days_access_after_end']) ?>
 	</td>
 </tr>
+
+<tr>
+	<td>
+		<?php echo api_ucfirst(get_lang('SessionVisibility')) ?> :
+	</td>
+	<td>
+		<?php if ($session['visibility']==1) echo get_lang('ReadOnly'); elseif($session['visibility']==2) echo get_lang('Visible');elseif($session['visibility']==3) echo api_ucfirst(get_lang('Invisible'))  ?>
+	</td>
+</tr>
+
 </table>
 
 <br />
@@ -179,20 +209,41 @@ else {
 			WHERE course_code=code
 			AND id_session='$id_session'
 			ORDER BY title";
-	$result=api_sql_query($sql,__FILE__,__LINE__);
-	$courses=api_store_result($result);
+	$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 = api_sql_query($sql, __FILE__, __LINE__);
-		$course['nbr_users'] = mysql_result($rs,0,0);
-		if (empty($course['username'])) {
-			$coach = get_lang('None');		
+
+		$sql = " SELECT count(*) FROM $tbl_session_rel_user sru, $tbl_session_rel_course_rel_user srcru
+				WHERE srcru.id_user = sru.id_user AND srcru.course_code = '".Database::escape_string($course['code'])."'
+				AND srcru.id_session = '".intval($id_session)."'";
+
+		$rs = Database::query($sql, __FILE__, __LINE__);
+		$course['nbr_users'] = Database::result($rs,0,0);
+
+		// Get coachs of the courses in session
+
+		$sql = "SELECT user.lastname,user.firstname,user.username FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
+				WHERE session_rcru.id_user = user.user_id AND session_rcru.id_session = '".intval($id_session)."' AND session_rcru.course_code ='".Database::escape_string($course['code'])."' AND session_rcru.status=2";
+		$rs = Database::query($sql,__FILE__,__LINE__);
+
+		$coachs = array();
+		if (Database::num_rows($rs) > 0) {
+			while($info_coach = Database::fetch_array($rs)) {
+				$coachs[] = api_get_person_name($info_coach['firstname'], $info_coach['lastname']).' ('.$info_coach['username'].')';
+			}
 		} else {
-			$coach = $course['lastname'].' '.$course['firstname'].' ('.$course['username'].')';
+			$coach = get_lang('None');
 		}
 
-		$orig_param = '&origin=resume_session';	
+
+		if (count($coachs) > 0) {
+			$coach = implode('<br />',$coachs);
+		} else {
+			$coach = get_lang('None');
+		}
+
+		$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>
@@ -230,24 +281,25 @@ if($session['nbr_users']==0){
 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 BY lastname, firstname';
+				AND '.$tbl_session_rel_user.'.id_session = '.$id_session.$order_clause;
 
-	$result=api_sql_query($sql,__FILE__,__LINE__);
-	$users=api_store_result($result);
+	$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>'.$user['lastname'].' '.$user['firstname'].' ('.$user['username'].')</b>
+						<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>
+						<a href="../mySpace/myStudents.php?student='.$user['user_id'].''.$orig_param.'">'.Display::return_icon('statistics.gif', get_lang('Reporting')).'</a>&nbsp;
+						<a href="session_course_user.php?id_user='.$user['user_id'].'&id_session='.$id_session.'">'.Display::return_icon('course.gif', get_lang('BlockCoursesForThisUser')).'</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>';
 	}

+ 102 - 80
main/admin/session_add.php

@@ -1,29 +1,11 @@
 <?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2009 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
-==============================================================================
-*/
+/* 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
@@ -36,7 +18,7 @@ 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');
+require_once ('../inc/lib/xajax/xajax.inc.php');
 $xajax = new xajax();
 //$xajax->debugOn();
 $xajax -> registerFunction ('search_coachs');
@@ -59,49 +41,51 @@ $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 BY lastname, firstname, username
-				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);	
+				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){			
-				
+			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 BY lastname, firstname, username
-				LIMIT 10';			
-				
+				AND status=1'.
+				$order_clause.
+				' LIMIT 10';
+
 			}
-		}		
-				
-		$rs = api_sql_query($sql, __FILE__, __LINE__);		
+		}
+
+		$rs = Database::query($sql, __FILE__, __LINE__);
 		while ($user = Database :: fetch_array($rs)) {
-			$return .= '<a href="#" onclick="fill_coach_field(\''.$user['username'].'\')">'.$user['lastname'].' '.$user['firstname'].' ('.$user['username'].')</a><br />';
+			$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));
+	$xajax_response -> addAssign('ajax_list_coachs','innerHTML', api_utf8_encode($return));
 	return $xajax_response;
 }
 $xajax -> processRequests();
@@ -122,17 +106,19 @@ function fill_coach_field (username) {
 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']; 
+	$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);
+	$id_session_category = $_POST['session_category'];
+	$id_visibility = $_POST['session_visibility'];
+	$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, $id_session_category,$id_visibility);
 	if ($return == strval(intval($return))) {
 		// integer => no error on session creation
 		header('Location: add_courses_to_session.php?id_session='.$return.'&add=true&msg=');
@@ -164,41 +150,41 @@ if (!empty($return)) {
 <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="550">
+<table border="0" cellpadding="5" cellspacing="0" width="650">
 <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>
+  <td width="40%"><?php echo get_lang('SessionName') ?>&nbsp;&nbsp;</td>
+  <td width="60%"><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%">
+  <td width="40%"><?php echo get_lang('CoachName') ?>&nbsp;&nbsp;</td>
+  <td width="60%">
 <?php
 
 $sql = 'SELECT COUNT(1) FROM '.$tbl_user.' WHERE status=1';
-$rs = api_sql_query($sql, __FILE__, __LINE__);
+$rs = Database::query($sql, __FILE__, __LINE__);
 $count_users = Database::result($rs, 0, 0);
 
-if (intval($count_users)<50) {	
-	$sql="SELECT user_id,lastname,firstname,username FROM $tbl_user WHERE status='1' ORDER BY lastname,firstname,username";	
-	global $_configuration;	
-	if ($_configuration['multiple_access_urls']==true) {		
-		$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
+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){					
+		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 BY lastname, firstname, username';			
+			WHERE access_url_id = '.$access_url_id.'  AND status=1'.$order_clause;
 		}
-	}	
-	
-	$result=api_sql_query($sql,__FILE__,__LINE__);
-	$Coaches=api_store_result($result);
+	}
+
+	$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 $enreg['firstname'].' '.$enreg['lastname'].' ('.$enreg['username'].')'; ?></option>
+		<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
@@ -209,17 +195,35 @@ if (intval($count_users)<50) {
 }
 ?>
 
-	
+
 </td>
 </tr>
+<?php
+	$id_session_category = '';
+	$tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
+	$sql = 'SELECT id, name FROM '.$tbl_session_category.' ORDER BY name ASC';
+	$result = Database::query($sql,__FILE__,__LINE__);
+	$Categories = Database::store_result($result);
+?>
+<tr>
+  <td width="40%"><?php echo get_lang('SessionCategory') ?></td>
+  <td width="60%">
+  	<select name="session_category" value="true" style="width:250px;">
+		<option value="0"><?php get_lang('None'); ?></option>
+		<?php foreach($Categories as $Rows): ?>
+		<option value="<?php echo $Rows['id']; ?>" <?php if($Rows['id'] == $id_session_category) echo 'selected="selected"'; ?>><?php echo $Rows['name']; ?></option>
+		<?php endforeach; ?>
+	</select>
+  </td>
+</tr>
 <tr>
-  <td width="30%"><?php echo get_lang('NoTimeLimits') ?></td>
-  <td width="70%">
+  <td width="40%"><?php echo get_lang('NoTimeLimits') ?></td>
+  <td width="60%">
   	<input type="checkbox" name="nolimit" onChange="setDisable(this)" />
   </td>
 <tr>
-  <td width="30%"><?php echo get_lang('DateStart') ?>&nbsp;&nbsp;</td>
-  <td width="70%">
+  <td width="40%"><?php echo get_lang('DateStartSession') ?>&nbsp;&nbsp;</td>
+  <td width="60%">
   <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>
@@ -283,8 +287,8 @@ for ($i=$thisYear-5;$i <= ($thisYear+5);$i++) {
   </td>
 </tr>
 <tr>
-  <td width="30%"><?php echo get_lang('DateEnd') ?>&nbsp;&nbsp;</td>
-  <td width="70%">
+  <td width="40%"><?php echo get_lang('DateEndSession') ?>&nbsp;&nbsp;</td>
+  <td width="60%">
   <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>
@@ -359,7 +363,23 @@ for ($i=$thisYear-5;$i <= ($thisYear+5);$i++) {
 			<br>
 		</div>
 	</td>
-</tr>
+</tr>
+
+
+<tr>
+  <td width="40%"><?php echo get_lang('SessionVisibility') ?></td>
+  <td width="60%">
+  	<select name="session_visibility" style="width:250px;">
+		<?php
+		$visibility_list = array(SESSION_VISIBLE_READ_ONLY=>get_lang('ReadOnly'), SESSION_VISIBLE=>get_lang('Visible'), SESSION_INVISIBLE=>api_ucfirst(get_lang('Invisible')));
+		foreach($visibility_list as $key=>$item): ?>
+		<option value="<?php echo $key; ?>" <?php if($item == $visibility_id) echo 'selected="selected"'; ?>><?php echo $item; ?></option>
+		<?php endforeach; ?>
+	</select>
+  </td>
+</tr>
+
+
 <tr>
   <td>&nbsp;</td>
   <td><button class="save" type="submit" value="<?php echo get_lang('NextStep') ?>"><?php echo get_lang('NextStep') ?></button>
@@ -371,7 +391,7 @@ for ($i=$thisYear-5;$i <= ($thisYear+5);$i++) {
 </form>
 <script type="text/javascript">
 
-function setDisable(select) {
+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;
@@ -380,6 +400,8 @@ function setDisable(select) {
 	document.form.month_end.disabled = (select.checked) ? true : false;
 	document.form.year_end.disabled = (select.checked) ? true : false;
 
+	document.form.session_visibility.disabled = (select.checked) ? true : false;
+	document.form.session_visibility.selectedIndex = 0;
 }
 </script>
 <?php

+ 241 - 0
main/admin/session_category_add.php

@@ -0,0 +1,241 @@
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2009 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
+* 	@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 -> 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_category_list.php","name" => get_lang('ListSessionCategory'));
+
+// Database Table Definitions
+$tbl_user		= Database::get_main_table(TABLE_MAIN_USER);
+$tbl_session	= Database::get_main_table(TABLE_MAIN_SESSION);
+
+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'];
+	$return = SessionManager::create_category_session($name,$year_start,$month_start,$day_start,$year_end,$month_end,$day_end);
+	if ($return == strval(intval($return))) {
+		header('Location: session_category_list.php?action=show_message&message='.urlencode(get_lang('SessionCategoryAdded')));
+		exit();
+	}
+}
+$thisYear=date('Y');
+$thisMonth=date('m');
+$thisDay=date('d');
+$tool_name = get_lang('langAddACategory');
+
+//display the header
+Display::display_header($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="550">
+<tr>
+  <td width="30%"><?php echo get_lang('SessionCategoryName') ?>&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('DateStart') ?>&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('DateEnd') ?>&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><button class="save" type="submit" value="<?php echo get_lang('langAddACategory') ?>"><?php echo get_lang('langAddACategory') ?></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();
+?>

+ 238 - 0
main/admin/session_category_edit.php

@@ -0,0 +1,238 @@
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2009 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
+==============================================================================
+*/
+
+// name of the language file that needs to be included
+$language_file ='admin';
+$cidReset=true;
+include('../inc/global.inc.php');
+require_once (api_get_path(LIBRARY_PATH).'sessionmanager.lib.php');
+// setting the section (for the tabs)
+$this_section=SECTION_PLATFORM_ADMIN;
+api_protect_admin_script(true);
+$id=intval($_GET['id']);
+$formSent=0;
+$errorMsg='';
+
+// Database Table Definitions
+$tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
+$tool_name = get_lang('EditSessionCategory');
+$interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[]=array('url' => "session_category_list.php","name" => get_lang('ListSessionCategory'));
+$sql = "SELECT * FROM $tbl_session_category WHERE id='".$id."' ORDER BY name";
+$result=Database::query($sql,__FILE__,__LINE__);
+if (!$infos=Database::fetch_array($result)) {
+	header('Location: session_list.php');
+	exit();
+}
+list($year_start,$month_start,$day_start)=explode('-',$infos['date_start']);
+list($year_end,$month_end,$day_end)=explode('-',$infos['date_end']);
+
+if (!api_is_platform_admin() && $infos['session_admin_id']!=$_user['user_id']) {
+	api_not_allowed(true);
+}
+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'];
+	$return = SessionManager::edit_category_session($id, $name, $year_start, $month_start, $day_start, $year_end, $month_end, $day_end);
+	if ($return == strval(intval($return))) {
+		header('Location: session_category_list.php?action=show_message&message='.urlencode(get_lang('SessionCategoryUpdate')));
+		exit();
+	}
+}
+$thisYear=date('Y');
+$thisMonth=date('m');
+$thisDay=date('d');
+
+// display the header
+Display::display_header($tool_name);
+if (!empty($return)) {
+	Display::display_error_message($return,false);
+}
+?>
+<form method="post" name="form" action="<?php echo api_get_self(); ?>?page=<?php echo $_GET['page'] ?>&id=<?php echo $id; ?>" 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="550">
+<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); else echo api_htmlentities($infos['name'],ENT_QUOTES,$charset); ?>"></td>
+</tr>
+<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($day_start == 2) echo 'selected="selected"'; ?> >02</option>
+	<option value="3" <?php if($day_start == 3) echo 'selected="selected"'; ?> >03</option>
+	<option value="4" <?php if($day_start == 4) echo 'selected="selected"'; ?> >04</option>
+	<option value="5" <?php if($day_start == 5) echo 'selected="selected"'; ?> >05</option>
+	<option value="6" <?php if($day_start == 6) echo 'selected="selected"'; ?> >06</option>
+	<option value="7" <?php if($day_start == 7) echo 'selected="selected"'; ?> >07</option>
+	<option value="8" <?php if($day_start == 8) echo 'selected="selected"'; ?> >08</option>
+	<option value="9" <?php if($day_start == 9) echo 'selected="selected"'; ?> >09</option>
+	<option value="10" <?php if($day_start == 10) echo 'selected="selected"'; ?> >10</option>
+	<option value="11" <?php if($day_start == 11) echo 'selected="selected"'; ?> >11</option>
+	<option value="12" <?php if($day_start == 12) echo 'selected="selected"'; ?> >12</option>
+	<option value="13" <?php if($day_start == 13) echo 'selected="selected"'; ?> >13</option>
+	<option value="14" <?php if($day_start == 14) echo 'selected="selected"'; ?> >14</option>
+	<option value="15" <?php if($day_start == 15) echo 'selected="selected"'; ?> >15</option>
+	<option value="16" <?php if($day_start == 16) echo 'selected="selected"'; ?> >16</option>
+	<option value="17" <?php if($day_start == 17) echo 'selected="selected"'; ?> >17</option>
+	<option value="18" <?php if($day_start == 18) echo 'selected="selected"'; ?> >18</option>
+	<option value="19" <?php if($day_start == 19) echo 'selected="selected"'; ?> >19</option>
+	<option value="20" <?php if($day_start == 20) echo 'selected="selected"'; ?> >20</option>
+	<option value="21" <?php if($day_start == 21) echo 'selected="selected"'; ?> >21</option>
+	<option value="22" <?php if($day_start == 22) echo 'selected="selected"'; ?> >22</option>
+	<option value="23" <?php if($day_start == 23) echo 'selected="selected"'; ?> >23</option>
+	<option value="24" <?php if($day_start == 24) echo 'selected="selected"'; ?> >24</option>
+	<option value="25" <?php if($day_start == 25) echo 'selected="selected"'; ?> >25</option>
+	<option value="26" <?php if($day_start == 26) echo 'selected="selected"'; ?> >26</option>
+	<option value="27" <?php if($day_start == 27) echo 'selected="selected"'; ?> >27</option>
+	<option value="28" <?php if($day_start == 28) echo 'selected="selected"'; ?> >28</option>
+	<option value="29" <?php if($day_start == 29) echo 'selected="selected"'; ?> >29</option>
+	<option value="30" <?php if($day_start == 30) echo 'selected="selected"'; ?> >30</option>
+	<option value="31" <?php if($day_start == 31) echo 'selected="selected"'; ?> >31</option>
+  </select>
+  /
+  <select name="month_start">
+	<option value="1">01</option>
+	<option value="2" <?php if($month_start == 2) echo 'selected="selected"'; ?> >02</option>
+	<option value="3" <?php if($month_start == 3) echo 'selected="selected"'; ?> >03</option>
+	<option value="4" <?php if($month_start == 4) echo 'selected="selected"'; ?> >04</option>
+	<option value="5" <?php if($month_start == 5) echo 'selected="selected"'; ?> >05</option>
+	<option value="6" <?php if($month_start == 6) echo 'selected="selected"'; ?> >06</option>
+	<option value="7" <?php if($month_start == 7) echo 'selected="selected"'; ?> >07</option>
+	<option value="8" <?php if($month_start == 8) echo 'selected="selected"'; ?> >08</option>
+	<option value="9" <?php if($month_start == 9) echo 'selected="selected"'; ?> >09</option>
+	<option value="10" <?php if($month_start == 10) echo 'selected="selected"'; ?> >10</option>
+	<option value="11" <?php if($month_start == 11) echo 'selected="selected"'; ?> >11</option>
+	<option value="12" <?php if($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($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($day_end == 2) echo 'selected="selected"'; ?> >02</option>
+	<option value="3" <?php if($day_end == 3) echo 'selected="selected"'; ?> >03</option>
+	<option value="4" <?php if($day_end == 4) echo 'selected="selected"'; ?> >04</option>
+	<option value="5" <?php if($day_end == 5) echo 'selected="selected"'; ?> >05</option>
+	<option value="6" <?php if($day_end == 6) echo 'selected="selected"'; ?> >06</option>
+	<option value="7" <?php if($day_end == 7) echo 'selected="selected"'; ?> >07</option>
+	<option value="8" <?php if($day_end == 8) echo 'selected="selected"'; ?> >08</option>
+	<option value="9" <?php if($day_end == 9) echo 'selected="selected"'; ?> >09</option>
+	<option value="10" <?php if($day_end == 10) echo 'selected="selected"'; ?> >10</option>
+	<option value="11" <?php if($day_end == 11) echo 'selected="selected"'; ?> >11</option>
+	<option value="12" <?php if($day_end == 12) echo 'selected="selected"'; ?> >12</option>
+	<option value="13" <?php if($day_end == 13) echo 'selected="selected"'; ?> >13</option>
+	<option value="14" <?php if($day_end == 14) echo 'selected="selected"'; ?> >14</option>
+	<option value="15" <?php if($day_end == 15) echo 'selected="selected"'; ?> >15</option>
+	<option value="16" <?php if($day_end == 16) echo 'selected="selected"'; ?> >16</option>
+	<option value="17" <?php if($day_end == 17) echo 'selected="selected"'; ?> >17</option>
+	<option value="18" <?php if($day_end == 18) echo 'selected="selected"'; ?> >18</option>
+	<option value="19" <?php if($day_end == 19) echo 'selected="selected"'; ?> >19</option>
+	<option value="20" <?php if($day_end == 20) echo 'selected="selected"'; ?> >20</option>
+	<option value="21" <?php if($day_end == 21) echo 'selected="selected"'; ?> >21</option>
+	<option value="22" <?php if($day_end == 22) echo 'selected="selected"'; ?> >22</option>
+	<option value="23" <?php if($day_end == 23) echo 'selected="selected"'; ?> >23</option>
+	<option value="24" <?php if($day_end == 24) echo 'selected="selected"'; ?> >24</option>
+	<option value="25" <?php if($day_end == 25) echo 'selected="selected"'; ?> >25</option>
+	<option value="26" <?php if($day_end == 26) echo 'selected="selected"'; ?> >26</option>
+	<option value="27" <?php if($day_end == 27) echo 'selected="selected"'; ?> >27</option>
+	<option value="28" <?php if($day_end == 28) echo 'selected="selected"'; ?> >28</option>
+	<option value="29" <?php if($day_end == 29) echo 'selected="selected"'; ?> >29</option>
+	<option value="30" <?php if($day_end == 30) echo 'selected="selected"'; ?> >30</option>
+	<option value="31" <?php if($day_end == 31) echo 'selected="selected"'; ?> >31</option>
+  </select>
+  /
+  <select name="month_end">
+	<option value="1">01</option>
+	<option value="2" <?php if($month_end == 2) echo 'selected="selected"'; ?> >02</option>
+	<option value="3" <?php if($month_end == 3) echo 'selected="selected"'; ?> >03</option>
+	<option value="4" <?php if($month_end == 4) echo 'selected="selected"'; ?> >04</option>
+	<option value="5" <?php if($month_end == 5) echo 'selected="selected"'; ?> >05</option>
+	<option value="6" <?php if($month_end == 6) echo 'selected="selected"'; ?> >06</option>
+	<option value="7" <?php if($month_end == 7) echo 'selected="selected"'; ?> >07</option>
+	<option value="8" <?php if($month_end == 8) echo 'selected="selected"'; ?> >08</option>
+	<option value="9" <?php if($month_end == 9) echo 'selected="selected"'; ?> >09</option>
+	<option value="10" <?php if($month_end == 10) echo 'selected="selected"'; ?> >10</option>
+	<option value="11" <?php if($month_end == 11) echo 'selected="selected"'; ?> >11</option>
+	<option value="12" <?php if($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($year_end == $i) echo 'selected="selected"'; ?> ><?php echo $i; ?></option>
+<?php
+} ?>
+  </select>
+  </td>
+</tr>
+<tr>
+	<td>
+		&nbsp;
+	</td>
+</tr>
+<tr>
+  <td>&nbsp;</td>
+  <td>
+<button class="save" type="submit" value="<?php echo get_lang('ModifyThisSession') ?>"><?php echo get_lang('ModifyThisSession') ?></button>
+
+  </td>
+</tr>
+
+</table>
+
+</form>
+<script type="text/javascript">
+<?php if($year_start=="0000") echo "setDisable(document.form.nolimit);\r\n"; ?>
+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();
+?>

+ 232 - 0
main/admin/session_category_list.php

@@ -0,0 +1,232 @@
+<?php
+/* For licensing terms, see /dokeos_license.txt */
+
+$language_file='admin';
+$cidReset=true;
+
+include('../inc/global.inc.php');
+require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+require_once (api_get_path(LIBRARY_PATH).'sessionmanager.lib.php');
+
+api_protect_admin_script(true);
+// setting the section (for the tabs)
+$this_section=SECTION_PLATFORM_ADMIN;
+$htmlHeadXtra[] = '<script language="javascript">
+
+				function selectAll(idCheck,numRows,action) {
+
+					for(i=0;i<numRows;i++) {
+						idcheck = document.getElementById(idCheck+"_"+i);
+						if (action == "true"){
+							idcheck.checked = true;
+						} else {
+							idcheck.checked = false;
+						}
+					}
+
+				}
+				</script>';
+
+$tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
+$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
+
+$page=intval($_GET['page']);
+$action= Security::remove_XSS($_REQUEST['action']);
+$sort=in_array($_GET['sort'],array('name','nbr_session','date_start','date_end'))? Security::remove_XSS($_GET['sort']) : 'name';
+$idChecked = Security::remove_XSS($_REQUEST['idChecked']);
+$order = (isset($_REQUEST['order']))? Security::remove_XSS($_REQUEST['order']): 'ASC';
+
+if ($action == 'delete_on_session' || $action == 'delete_off_session') {
+	$delete_session = ($action == 'delete_on_session')? true: false;
+	SessionManager::delete_session_category($idChecked, $delete_session);
+	header('Location: '.api_get_self().'?sort='.$sort.'&action=show_message&message='.urlencode(get_lang('SessionCategoryDelete')));
+	exit();
+}
+
+$interbreadcrumb[]=array("url" => "index.php","name" => get_lang('PlatformAdmin'));
+
+if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
+	$interbreadcrumb[] = array ("url" => 'session_category_list.php', "name" => get_lang('ListSessionCategory'));
+	$tool_name = get_lang('SearchASession');
+	Display :: display_header($tool_name);
+	$form = new FormValidator('advanced_search','get');
+	$form->addElement('header', '', $tool_name);
+	$active_group = array();
+	$active_group[] = $form->createElement('checkbox','active','',get_lang('Active'));
+	$active_group[] = $form->createElement('checkbox','inactive','',get_lang('Inactive'));
+	$form->addGroup($active_group,'',get_lang('ActiveSession'),'<br/>',false);
+
+	$form->addElement('style_submit_button', 'submit',get_lang('SearchUsers'),'class="search"');
+	$defaults['active'] = 1;
+	$defaults['inactive'] = 1;
+	$form->setDefaults($defaults);
+	$form->display();
+} else {
+	$limit = 20;
+	$from = $page * $limit;
+	//if user is crfp admin only list its sessions
+	if(!api_is_platform_admin()) {
+		$where .= (empty($_REQUEST['keyword']) ? " " : " WHERE name LIKE '%".addslashes($_REQUEST['keyword'])."%'");
+	}
+	else {
+		$where .= (empty($_REQUEST['keyword']) ? " " : " WHERE name LIKE '%".addslashes($_REQUEST['keyword'])."%'");
+	}
+
+	$query = "SELECT sc.*, (select count(id) FROM $tbl_session WHERE session_category_id = sc.id) as nbr_session
+	 			FROM $tbl_session_category sc
+	 			$where
+	 			ORDER BY $sort $order
+	 			LIMIT $from,".($limit+1);
+
+	$query_rows = "SELECT count(*) as total_rows
+				FROM $tbl_session_category sc $where ";
+
+	$order = ($order == 'ASC')? 'DESC': 'ASC';
+	$result_rows = Database::query($query_rows,__FILE__,__LINE__);
+	$recorset = Database::fetch_array($result_rows);
+	$num = $recorset['total_rows'];
+	$result = Database::query($query,__FILE__,__LINE__);
+	$Sessions = Database::store_result($result);
+	$nbr_results = sizeof($Sessions);
+	$tool_name = get_lang('ListSessionCategory');
+	Display::display_header($tool_name);
+	api_display_tool_title($tool_name);
+
+    if (!empty($_GET['warn'])) {
+        Display::display_warning_message(urldecode($_GET['warn']),false);
+    }
+    if(isset($_GET['action'])) {
+        Display::display_normal_message(stripslashes($_GET['message']),false);
+    }
+    ?>
+
+	<div class="actions">
+	<?php
+	echo '<div style="float:right;">
+			<a href="'.api_get_path(WEB_CODE_PATH).'admin/session_category_add.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddSession')).get_lang('AddSessionCategory').'</a>
+	 	  </div>';
+	?>
+	<form method="POST" action="session_category_list.php">
+		<input type="text" name="keyword" value="<?php echo Security::remove_XSS($_GET['keyword']); ?>"/>
+		<button class="search" type="submit" name="name" value="<?php echo get_lang('Search') ?>"><?php echo get_lang('Search') ?></button>
+		<!-- <a href="session_list.php?search=advanced"><?php echo get_lang('AdvancedSearch'); ?></a> -->
+		</form>
+	<form method="post" action="<?php echo api_get_self(); ?>?action=delete&sort=<?php echo $sort; ?>" onsubmit="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;">
+	 </div><br />
+	<div align="left">
+	<?php
+	if(count($Sessions)==0 && isset($_POST['keyword'])) {
+		echo get_lang('NoSearchResults');
+		echo '</div>';
+	} else {
+		if ($num > $limit) {
+			if ($page) {
+			?>
+			<a href="<?php echo api_get_self(); ?>?page=<?php echo $page-1; ?>&sort=<?php echo $sort; ?>&order=<?php echo  Security::remove_XSS($_REQUEST['order']); ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Previous'); ?></a>
+			<?php
+			} else {
+				echo get_lang('Previous');
+			}
+			?>
+			|
+			<?php
+			if($nbr_results > $limit) {
+				?>
+				<a href="<?php echo api_get_self(); ?>?page=<?php echo $page+1; ?>&sort=<?php echo $sort; ?>&order=<?php echo  Security::remove_XSS($_REQUEST['order']); ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Next'); ?></a>
+				<?php
+			} else {
+				echo get_lang('Next');
+			}
+		}
+		?>
+	</div>
+		<br />
+		<table class="data_table" width="100%">
+		<tr>
+		  <th>&nbsp;</th>
+		  <th><a href="<?php echo api_get_self(); ?>?sort=name&order=<?php echo ($sort=='name')? $order: 'ASC'; ?>"><?php echo get_lang('SessionCategoryName'); ?></a></th>
+		  <th><a href="<?php echo api_get_self(); ?>?sort=nbr_session&order=<?php echo ($sort=='nbr_session')? $order: 'ASC'; ?>"><?php echo get_lang('NumberOfSession'); ?></a></th>
+		  <th><a href="<?php echo api_get_self(); ?>?sort=date_start&order=<?php echo ($sort=='date_start')? $order: 'ASC'; ?>"><?php echo get_lang('StartDate'); ?></a></th>
+		  <th><a href="<?php echo api_get_self(); ?>?sort=date_end&order=<?php echo ($sort=='date_end')? $order: 'ASC'; ?>"><?php echo get_lang('EndDate'); ?></a></th>
+		  <th><?php echo get_lang('Actions'); ?></th>
+		</tr>
+
+		<?php
+		$i=0;
+		$x=0;
+		foreach ($Sessions as $key=>$enreg) {
+			if($key == $limit) {
+				break;
+			}
+		$sql = 'SELECT COUNT(session_category_id) FROM '.$tbl_session.' WHERE session_category_id = '.intval($enreg['id']);
+		$rs = Database::query($sql, __FILE__, __LINE__);
+		list($nb_courses) = Database::fetch_array($rs);
+		?>
+		<tr class="<?php echo $i?'row_odd':'row_even'; ?>">
+		  <td><input type="checkbox" id="idChecked_<?php echo $x; ?>" name="idChecked[]" value="<?php echo $enreg['id']; ?>"></td>
+		  <td><?php echo api_htmlentities($enreg['name'],ENT_QUOTES,$charset); ?></td>
+		  <td><?php echo "<a href=\"session_list.php?id_category=".$enreg['id']."\">".$nb_courses." Sesion(es) </a>"; ?></td>
+		  <td><?php echo api_htmlentities($enreg['date_start'],ENT_QUOTES,$charset); ?></td>
+		  <td><?php echo api_htmlentities($enreg['date_end'],ENT_QUOTES,$charset); ?></td>
+		  <td>
+			<a href="session_category_edit.php?&id=<?php echo $enreg['id']; ?>"><?php Display::display_icon('edit.gif', get_lang('Edit')); ?></a>
+			<a href="<?php echo api_get_self(); ?>?sort=<?php echo $sort; ?>&action=delete_off_session&idChecked=<?php echo $enreg['id']; ?>" onclick="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;"><?php Display::display_icon('delete.gif', get_lang('Delete')); ?></a>
+		  </td>
+		</tr>
+		<?php
+			$i=$i ? 0 : 1;
+			$x++;
+		}
+		unset($Sessions);
+		?>
+		</table>
+		<br />
+
+		<div align="left">
+
+		<?php
+
+		if ($num > $limit) {
+		if ($page)
+			{
+			?>
+
+			<a href="<?php echo api_get_self(); ?>?page=<?php echo $page-1; ?>&sort=<?php echo $sort; ?>&order=<?php echo  Security::remove_XSS($_REQUEST['order']); ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Previous'); ?></a>
+
+			<?php
+			}
+			else
+			{
+				echo get_lang('Previous');
+			}
+			?>
+
+			|
+
+			<?php
+			if($nbr_results > $limit)
+			{
+			?>
+
+			<a href="<?php echo api_get_self(); ?>?page=<?php echo $page+1; ?>&sort=<?php echo $sort; ?>&order=<?php echo  Security::remove_XSS($_REQUEST['order']); ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Next'); ?></a>
+
+			<?php
+			}
+			else
+			{
+				echo get_lang('Next');
+			}
+		} ?>
+		</div>
+		<br />
+		<a href="#" onclick="selectAll('idChecked',<?php echo $x; ?>,'true');return false;"><?php echo get_lang('SelectAll') ?></a>&nbsp;-&nbsp;
+		<a href="#" onclick="selectAll('idChecked',<?php echo $x; ?>,'false');return false;"><?php echo get_lang('UnSelectAll') ?></a>
+		<select name="action">
+			<option value="delete_off_session" selected="selected"><?php echo get_lang('DeleteSelectedSessionCategory'); ?></option>
+			<option value="delete_on_session"><?php echo get_lang('DeleteSelectedFullSessionCategory'); ?></option>
+		</select>
+		<button class="save" type="submit" name="name" value="<?php echo get_lang('Ok') ?>"><?php echo get_lang('Ok') ?></button>
+		<?php } ?>
+	</table>
+
+<?php } Display::display_footer(); ?>

+ 51 - 22
main/admin/session_course_edit.php

@@ -4,13 +4,13 @@
  * Implements the edition of course-session settings
  * @package dokeos.admin
  */
-// name of the language file that needs to be included 
+// name of the language file that needs to be included
 $language_file='admin';
 
 $cidReset=true;
 
 require '../inc/global.inc.php';
-
+require_once '../inc/lib/sessionmanager.lib.php';
 // setting the section (for the tabs)
 $this_section=SECTION_PLATFORM_ADMIN;
 
@@ -27,6 +27,7 @@ $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);
+$tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 
 $course_info=api_get_course_info($_REQUEST['course_code']);
 $tool_name=$course_info['name'];
@@ -36,46 +37,74 @@ $interbreadcrumb[]=array('url' => "session_list.php","name" => get_lang("Session
 $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=api_sql_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__);
+$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)) {
+if (!list($session_name,$course_title)=Database::fetch_row($result)) {
 	header('Location: session_course_list.php?id_session='.$id_session);
 	exit();
 }
 
+$arr_infos = array();
 if ($_POST['formSent']) {
 	$formSent=1;
 
-	$id_coach=intval($_POST['id_coach']);
+	// get all tutor by course_code in the session
+	$sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user WHERE id_session = '$id_session' AND course_code = '$course_code' AND status = 2";
+	$rs_coachs = Database::query($sql,__FILE__,__LINE__);
 
+	$coachs_course_session = array();
+	if (Database::num_rows($rs_coachs) > 0){
+		while ($row_coachs = Database::fetch_row($rs_coachs)) {
+			$coachs_course_session[] = $row_coachs[0];
+		}
+	}
 
-	api_sql_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();
+	$id_coachs= $_POST['id_coach'];
 
-}else {
-	$result=api_sql_query("SELECT id_coach FROM $tbl_session_course WHERE id_session='$id_session' AND course_code='$course_code'",__FILE__,__LINE__);
+	if (is_array($id_coachs) && count($id_coachs) > 0) {
+
+		foreach ($id_coachs as $id_coach) {
+			$id_coach = intval($id_coach);
+			$rs1 = SessionManager::set_coach_to_course_session($id_coach, $id_session, $course_code);
+		}
+
+		// set status to 0 other tutors from multiple list
+		$array_intersect = array_diff($coachs_course_session,$id_coachs);
+
+		foreach ($array_intersect as $nocoach_user_id) {
+			$rs2 = SessionManager::set_coach_to_course_session($nocoach_user_id, $id_session, $course_code,true);
+		}
 
-	if (!$infos=Database::fetch_array($result)) {
-		//header('Location: '.$_GET['page'].'?id_session='.$id_session);
+		header('Location: '.Security::remove_XSS($_GET['page']).'?id_session='.$id_session);
 		exit();
+
+	}
+
+}else {
+
+	$sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user WHERE id_session = '$id_session' AND course_code = '$course_code' AND status = 2 ";
+	$rs = Database::query($sql,__FILE__,__LINE__);
+
+	if (Database::num_rows($rs) > 0) {
+		while ($infos = Database::fetch_array($rs)) {
+			$arr_infos[] = $infos['id_user'];
+		}
 	}
 }
 
-$sql="SELECT user_id,lastname,firstname,username FROM $tbl_user WHERE status='1' ORDER BY lastname,firstname,username";
+$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=api_sql_query($sql,__FILE__,__LINE__);
+$result=Database::query($sql,__FILE__,__LINE__);
 
-$coaches=api_store_result($result);
+$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 $_GET['page'] ?>" style="margin:0px;">
+<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">
@@ -100,17 +129,17 @@ if(!empty($errorMsg))
 ?>
 
 <tr>
-  <td width="30%"><?php echo get_lang("CoachName") ?>&nbsp;&nbsp;</td>
-  <td width="70%"><select name="id_coach" style="width:250px;">
+  <td width="25%" valign = "top"><?php echo get_lang("CoachName") ?>&nbsp;&nbsp;</td>
+  <td width="70%"><select name="id_coach[]" style="width:300px;" multiple="multiple" size="7">
 	<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>
+	<option value="0" <?php if(count($arr_infos) == 0) 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 $enreg['lastname'].' '.$enreg['firstname'].' ('.$enreg['username'].')'; ?></option>
+	<option value="<?php echo $enreg['user_id']; ?>" <?php if((!$sent && (is_array($arr_infos) && in_array($enreg['user_id'],$arr_infos))) || ($sent && $enreg['user_id'] == $id_coach)) echo 'selected="selected"'; ?>><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
 
 <?php
 }

+ 101 - 111
main/admin/session_course_list.php

@@ -1,111 +1,101 @@
-<?php
-// 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=api_sql_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 = $_POST['idChecked'];
-	if(is_array($idChecked))
-	{
-		$idChecked="'".implode("','",$idChecked)."'";
-
-		api_sql_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();
-
-		api_sql_query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code IN($idChecked)",__FILE__,__LINE__);
-
-		api_sql_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=api_sql_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=api_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);
-?>
-
-<div id="main">
-
-<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>
-	<input type="submit" value="'.get_lang('Ok').'">
-	</form>';
-?>
-
-
-<?php
-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)=Database::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=Database::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();
+?>

+ 310 - 0
main/admin/session_course_user.php

@@ -0,0 +1,310 @@
+<?php //$id: $
+/* For licensing terms, see /dokeos_license.txt */
+/**
+==============================================================================
+*	@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';
+
+// including additonal libraries
+require_once api_get_path(LIBRARY_PATH).'sessionmanager.lib.php';
+
+// 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('EditSessionCoursesByUser');
+$id_session=intval($_GET['id_session']);
+$id_user=intval($_GET['id_user']);
+
+if (empty($id_user) || empty($id_session)) {
+	header('Location: resume_session.php?id_session='.$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 (Database::result($rs,0,0)!=$_user['user_id']) {
+		api_not_allowed(true);
+	}
+}
+
+$formSent=0;
+$errorMsg=$firstLetterCourse=$firstLetterSession='';
+$CourseList=$SessionList=array();
+$courses=$sessions=array();
+$noPHP_SELF=true;
+
+if ($_POST['formSent']) {
+	$formSent			= $_POST['formSent'];
+	$CourseList			= $_POST['SessionCoursesList'];
+
+	if (!is_array($CourseList)) {
+		$CourseList=array();
+	}
+
+	$sql="SELECT distinct code
+			FROM $tbl_course course LEFT JOIN $tbl_session_rel_course session_rel_course
+			ON course.code = session_rel_course.course_code inner join $tbl_session_rel_course_rel_user as srcru
+			ON (srcru.id_session =  session_rel_course.id_session)
+			WHERE id_user = $id_user and session_rel_course.id_session = $id_session";
+
+	$rs = Database::query($sql, __FILE__, __LINE__);
+	$existingCourses = Database::store_result($rs);
+	if (count($CourseList) == count($existingCourses)) {
+		header('Location: session_course_user.php?id_session='.$id_session.'&id_user='.$id_user.'&msg='.get_lang('MaybeYouWantToDeleteThisUserFromSession'));
+		exit;
+	}
+	foreach($CourseList as $enreg_course) {
+		$exists = false;
+		foreach($existingCourses as $existingCourse) {
+			if($enreg_course == $existingCourse['course_code']) {
+				$exists=true;
+			}
+		}
+		if(!$exists) {
+			$enreg_course = Database::escape_string($enreg_course);
+			$sql_delete = "DELETE FROM $tbl_session_rel_course_rel_user
+							WHERE id_user='".$id_user."'  AND course_code='".$enreg_course."' AND id_session=$id_session";
+			Database::query($sql_delete,__FILE__, __LINE__);
+			if(Database::affected_rows()) {
+				//update session rel course table
+				$sql_update  = "UPDATE $tbl_session_rel_course SET nbr_users= nbr_users - 1 WHERE id_session='$id_session' AND course_code='$enreg_course'";
+				Database::query($sql_update,__FILE__, __LINE__);
+			}
+		}
+	}
+	foreach($existingCourses as $existingCourse) {
+		//$sql_insert_rel_course= "INSERT INTO $tbl_session_rel_course(id_session,course_code, id_coach) VALUES('$id_session','$enreg_course','$id_coach')";
+		if(!in_array($existingCourse['code'], $CourseList)){
+			$existingCourse = Database::escape_string($existingCourse['code']);
+			$sql_insert = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user) VALUES('$id_session','$existingCourse','$id_user')";
+			Database::query($sql_insert,__FILE__, __LINE__);
+			if(Database::affected_rows()) {
+				//update session rel course table
+				$sql_update  = "UPDATE $tbl_session_rel_course SET nbr_users= nbr_users + 1 WHERE id_session='$id_session' AND course_code='$existingCourse'";
+				Database::query($sql_update,__FILE__, __LINE__);
+			}
+
+		}
+	}
+	//header('Location: session_course_user.php?id_user='.$id_user.'&id_session='.$id_session);
+	header('Location: session_course_user.php?id_session='.$id_session.'&id_user='.$id_user.'&msg='.get_lang('CoursesUpdated'));
+	exit;
+}
+
+// display the dokeos header
+Display::display_header($tool_name);
+
+if (!empty($_GET['msg'])) {
+    Display::display_normal_message(urldecode($_GET['msg']));
+}
+
+// the form header
+$session_info = SessionManager::fetch($id_session);
+echo '<div class="row"><div class="form_header">'.$tool_name.' ('.$session_info['name'].')</div></div><br />';
+$nosessionCourses = $sessionCourses = array();
+
+/*$sql="SELECT distinct code, title, visual_code, 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 inner join $tbl_session_rel_course_rel_user as srcru
+ON (srcru.id_session =  session_rel_course.id_session)
+WHERE id_user = $id_user and session_rel_course.id_session = $id_session";
+*/
+// actual user
+$sql="SELECT code, title, visual_code, srcru.id_session " .
+			"FROM $tbl_course course inner JOIN $tbl_session_rel_course_rel_user   as srcru  " .
+			"ON course.code = srcru.course_code  where srcru.id_user = $id_user AND id_session = $id_session";
+
+//all
+$sql_all="SELECT code, title, visual_code, src.id_session " .
+			"FROM $tbl_course course inner JOIN $tbl_session_rel_course  as src  " .
+			"ON course.code = src.course_code AND id_session = $id_session";
+
+
+/*
+	echo $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);
+
+$result=Database::query($sql_all,__FILE__,__LINE__);
+$CoursesAll=Database::store_result($result);
+
+$course_temp = array();
+foreach($Courses as $course) {
+	$course_temp[] = $course['code'];
+}
+foreach($CoursesAll as $course) {
+	if (in_array($course['code'], $course_temp)) {
+		$nosessionCourses[$course['code']] = $course ;
+	} else {
+		$sessionCourses[$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_user=<?php echo $id_user; ?>&id_session=<?php echo $id_session; ?>" style="margin:0px;">
+<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('CurrentCourses') ?> :</b></td>
+  <td width="10%">&nbsp;</td>
+  <td align="center" width="45%"><b><?php echo get_lang('CoursesToAvoid') ?> :</b></td>
+</tr>
+</td>
+<tr>
+  <td width="45%" align="center">
+	<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">
+  	<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>
+	<br /><br /><br /><br /><br /><br />
+	<?php
+	echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('EditSessionCourses').'</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();
+?>

+ 171 - 200
main/admin/session_course_user_list.php

@@ -1,200 +1,171 @@
-<?php
-$language_file='admin';
-
-$cidReset=true;
-
-include('../inc/global.inc.php');
-
-api_protect_admin_script();
-
-$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_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']);
-$course_code=trim(stripslashes($_GET['course_code']));
-$page=intval($_GET['page']);
-$action=$_REQUEST['action'];
-$sort=in_array($_GET['sort'],array('lastname','firstname','username'))?$_GET['sort']:'lastname';
-$idChecked = (is_array($_GET['idChecked']) ? $_GET['idChecked'] : (is_array($_POST['idChecked']) ? $_POST['idChecked'] : null));
-
-$result=api_sql_query("SELECT name,title FROM $tbl_session,$tbl_course WHERE id='$id_session' AND 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($action == 'delete')
-{
-	if(is_array($idChecked))
-	{
-		$idChecked=implode(',',$idChecked);
-
-		api_sql_query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='".addslashes($course_code)."' AND id_user IN($idChecked)",__FILE__,__LINE__);
-		
-		$nbr_affected_rows=mysql_affected_rows();
-
-		api_sql_query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows WHERE id_session='$id_session' AND course_code='".addslashes($course_code)."'",__FILE__,__LINE__);
-	}
-
-	header('Location: '.api_get_self().'?id_session='.$id_session.'&course_code='.urlencode($course_code).'&sort='.$sort);
-	exit();
-}
-
-$limit=20;
-$from=$page * $limit;
-
-$result=api_sql_query("SELECT user_id,lastname,firstname,username FROM $tbl_session_rel_course_rel_user,$tbl_user WHERE user_id=id_user AND id_session='$id_session' AND course_code='".addslashes($course_code)."' ORDER BY $sort LIMIT $from,".($limit+1),__FILE__,__LINE__);
-
-$Users=api_store_result($result);
-
-$nbr_results=sizeof($Users);
-
-$tool_name = get_lang('ListOfUsersSubscribedToCourse').' &quot;'.api_htmlentities($course_title,ENT_QUOTES,$charset).'&quot; '.get_lang('ForTheSession').' &quot;'.api_htmlentities($session_name,ENT_QUOTES,$charset).'&quot;';
-
-$interbredcrump[]=array("url" => "index.php","name" => get_lang('AdministrationTools'));
-$interbredcrump[]=array("url" => "session_list.php","name" => get_lang('SessionList'));
-$interbredcrump[]=array("url" => "session_course_list.php?id_session=$id_session","name" => get_lang('ListOfCoursesOfSession')." &quot;".api_htmlentities($session_name,ENT_QUOTES,$charset)."&quot;");
-
-Display::display_header($tool_name);
-
-api_display_tool_title($tool_name);
-?>
-
-<div id="main">
-
-<form method="post" action="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=<?php echo $sort; ?>" onsubmit="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;">
-
-<div align="right">
-
-<?php
-if($page)
-{
-?>
-
-<a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&page=<?php echo $page-1; ?>&sort=<?php echo $sort; ?>"><?php echo get_lang('Previous');?></a>
-
-<?php
-}
-else
-{
-	echo get_lang('Previous');
-}
-?>
-
-|
-
-<?php
-if($nbr_results > $limit)
-{
-?>
-
-<a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&page=<?php echo $page+1; ?>&sort=<?php echo $sort; ?>"><?php echo get_lang('Next');?></a>
-
-<?php
-}
-else
-{
-	echo get_lang('Next');
-}
-?>
-
-</div>
-
-<br>
-
-<table class="data_table" width="100%">
-<tr>
-  <th>&nbsp;</th>
-  <th><a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=lastname">Nom</a></th>
-  <th><a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=firstname">Prénom</a></th>
-  <th><a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=username">Identifiant</a></th>
-  <th>Actions</th>
-</tr>
-
-<?php
-$i=0;
-
-foreach($Users as $key=>$enreg)
-{
-	if($key == $limit)
-	{
-		break;
-	}
-?>
-
-<tr class="<?php echo $i?'row_odd':'row_even'; ?>">
-  <td><input type="checkbox" name="idChecked[]" value="<?php echo $enreg['user_id']; ?>"></td>
-  <td><?php echo api_htmlentities($enreg['lastname'],ENT_QUOTES,$charset); ?></td>
-  <td><?php echo api_htmlentities($enreg['firstname'],ENT_QUOTES,$charset); ?></td>
-  <td><?php echo api_htmlentities($enreg['username'],ENT_QUOTES,$charset); ?></td>
-  <td>
-	<a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=<?php echo $sort; ?>&action=delete&idChecked[]=<?php echo $enreg['user_id']; ?>" onclick="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;"><?php Display::display_icon('delete.gif', get_lang('Delete')); ?></a>
-  </td>
-</tr>
-
-<?php
-	$i=$i ? 0 : 1;
-}
-
-unset($Users);
-?>
-
-</table>
-
-<br>
-
-<div align="left">
-
-<?php
-if($page)
-{
-?>
-
-<a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&page=<?php echo $page-1; ?>&sort=<?php echo $sort; ?>"><?php echo get_lang('Previous'); ?></a>
-
-<?php
-}
-else
-{
-	echo get_lang('Previous');
-}
-?>
-
-|
-
-<?php
-if($nbr_results > $limit)
-{
-?>
-
-<a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&page=<?php echo $page+1; ?>&sort=<?php echo $sort; ?>"><?php echo get_lang('Next'); ?></a>
-
-<?php
-}
-else
-{
-	echo get_lang('Next');
-}
-?>
-
-</div>
-
-<br>
-
-<select name="action">
-<option value="delete"><?php get_lang('UnsubscribeSelectedUsersFromSession');?></option>
-</select>
-<input type="submit" value="<?php echo get_lang('Ok'); ?>">
-
-</table>
-
-</div>
-
-<?php
-Display::display_footer();
-?>
+<?php
+/* For licensing terms, see /dokeos_license.txt */
+/**
+==============================================================================
+*	@package dokeos.admin
+==============================================================================
+*/
+
+$language_file='admin';
+$cidReset=true;
+include('../inc/global.inc.php');
+api_protect_admin_script();
+$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_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']);
+$course_code=trim(stripslashes($_GET['course_code']));
+$page=intval($_GET['page']);
+$action=$_REQUEST['action'];
+$sort=in_array($_GET['sort'],array('lastname','firstname','username'))?$_GET['sort']:api_sort_by_first_name()?'firstname':'lastname';
+$idChecked = (is_array($_GET['idChecked']) ? $_GET['idChecked'] : (is_array($_POST['idChecked']) ? $_POST['idChecked'] : null));
+if (is_array($idChecked)) {
+	$my_temp = array();
+	foreach ($idChecked as $id){
+		$my_temp[]= intval($id);// forcing the intval
+	}
+	$idChecked = $my_temp;
+}
+$result=Database::query("SELECT name,title FROM $tbl_session,$tbl_course WHERE id='$id_session' AND code='".addslashes($course_code)."'",__FILE__,__LINE__);
+
+if(!list($session_name,$course_title)=Database::fetch_row($result))
+{
+	header('Location: session_course_list.php?id_session='.$id_session);
+	exit();
+}
+
+if($action == 'delete') {
+	if(is_array($idChecked) && count($idChecked)>0 ) {
+		$idChecked=implode(',',$idChecked);
+		Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='".addslashes($course_code)."' AND id_user IN($idChecked)",__FILE__,__LINE__);
+		$nbr_affected_rows=Database::affected_rows();
+		Database::query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows WHERE id_session='$id_session' AND course_code='".addslashes($course_code)."'",__FILE__,__LINE__);
+	}
+	header('Location: '.api_get_self().'?id_session='.$id_session.'&course_code='.urlencode($course_code).'&sort='.$sort);
+	exit();
+}
+
+$limit=20;
+$from=$page * $limit;
+$is_western_name_order = api_is_western_name_order();
+
+$result=Database::query("SELECT user_id,".($is_western_name_order ? 'firstname,lastname' : 'lastname,firstname').",username FROM $tbl_session_rel_course_rel_user,$tbl_user WHERE user_id=id_user AND id_session='$id_session' AND course_code='".addslashes($course_code)."' ORDER BY $sort LIMIT $from,".($limit+1),__FILE__,__LINE__);
+$Users=Database::store_result($result);
+
+$nbr_results=sizeof($Users);
+
+$tool_name = get_lang('ListOfUsersSubscribedToCourse').' &quot;'.api_htmlentities($course_title,ENT_QUOTES,$charset).'&quot; '.get_lang('ForTheSession').' &quot;'.api_htmlentities($session_name,ENT_QUOTES,$charset).'&quot;';
+
+$interbreadcrumb[]=array("url" => "index.php","name" => get_lang('AdministrationTools'));
+$interbreadcrumb[]=array("url" => "session_list.php","name" => get_lang('SessionList'));
+$interbreadcrumb[]=array("url" => "session_course_list.php?id_session=$id_session","name" => get_lang('ListOfCoursesOfSession')." &quot;".api_htmlentities($session_name,ENT_QUOTES,$charset)."&quot;");
+
+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; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=<?php echo $sort; ?>" onsubmit="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;">
+<div align="right">
+<?php
+if($page) {
+?>
+<a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&page=<?php echo $page-1; ?>&sort=<?php echo $sort; ?>"><?php echo get_lang('Previous');?></a>
+<?php
+} else {
+	echo get_lang('Previous');
+}
+?>
+|
+<?php
+if($nbr_results > $limit) {
+?>
+<a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&page=<?php echo $page+1; ?>&sort=<?php echo $sort; ?>"><?php echo get_lang('Next');?></a>
+<?php
+} else {
+	echo get_lang('Next');
+}
+?>
+
+</div>
+<br />
+
+<table class="data_table" width="100%">
+<tr>
+  <th>&nbsp;</th>
+  <?php if ($is_western_name_order) { ?>
+  <th><a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=firstname"><?php echo get_lang('FirstName');?></a></th>
+  <th><a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=lastname"><?php echo get_lang('LastName');?></a></th>
+  <?php } else { ?>
+  <th><a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=lastname"><?php echo get_lang('LastName');?></a></th>
+  <th><a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=firstname"><?php echo get_lang('FirstName');?></a></th>
+  <?php } ?>
+  <th><a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=username"><?php echo get_lang('Login');?></a></th>
+  <th><?php echo get_lang('Actions');?></th>
+</tr>
+
+<?php
+$i=0;
+
+foreach($Users as $key=>$enreg) {
+	if($key == $limit) {
+		break;
+	}
+?>
+
+<tr class="<?php echo $i?'row_odd':'row_even'; ?>">
+  <td><input type="checkbox" name="idChecked[]" value="<?php echo $enreg['user_id']; ?>"></td>
+  <?php if ($is_western_name_order) { ?>
+  <td><?php echo api_htmlentities($enreg['firstname'],ENT_QUOTES,$charset); ?></td>
+  <td><?php echo api_htmlentities($enreg['lastname'],ENT_QUOTES,$charset); ?></td>
+  <?php } else { ?>
+  <td><?php echo api_htmlentities($enreg['lastname'],ENT_QUOTES,$charset); ?></td>
+  <td><?php echo api_htmlentities($enreg['firstname'],ENT_QUOTES,$charset); ?></td>
+  <?php } ?>
+  <td><?php echo api_htmlentities($enreg['username'],ENT_QUOTES,$charset); ?></td>
+  <td>
+	<a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=<?php echo $sort; ?>&action=delete&idChecked[]=<?php echo $enreg['user_id']; ?>" onclick="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;"><?php Display::display_icon('delete.gif', get_lang('Delete')); ?></a>
+  </td>
+</tr>
+
+<?php
+	$i=$i ? 0 : 1;
+}
+
+unset($Users);
+?>
+
+</table>
+<br />
+<div align="left">
+<?php
+if($page) {
+?>
+<a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&page=<?php echo $page-1; ?>&sort=<?php echo $sort; ?>"><?php echo get_lang('Previous'); ?></a>
+<?php
+} else {
+	echo get_lang('Previous');
+}
+?>
+|
+<?php
+if($nbr_results > $limit) {
+?>
+<a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&page=<?php echo $page+1; ?>&sort=<?php echo $sort; ?>"><?php echo get_lang('Next'); ?></a>
+<?php
+} else {
+	echo get_lang('Next');
+}
+?>
+</div>
+<br />
+<select name="action">
+<option value="delete"><?php echo get_lang('UnsubscribeSelectedUsersFromSession');?></option>
+</select>
+<button class="save" type="submit"> <?php echo get_lang('Ok'); ?></button>
+</table>
+</form>
+<?php
+Display::display_footer();
+?>

+ 362 - 340
main/admin/session_edit.php

@@ -1,340 +1,362 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2009 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
-==============================================================================
-*/
-
-// name of the language file that needs to be included
-$language_file ='admin';
-$cidReset=true;
-include('../inc/global.inc.php');
-require_once (api_get_path(LIBRARY_PATH).'sessionmanager.lib.php');
-
-// setting the section (for the tabs)
-$this_section=SECTION_PLATFORM_ADMIN;
-
-api_protect_admin_script(true);
-
-$id=intval($_GET['id']);
-
-$formSent=0;
-$errorMsg='';
-
-// Database Table Definitions
-$tbl_user		= Database::get_main_table(TABLE_MAIN_USER);
-$tbl_session	= Database::get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-
-$tool_name = get_lang('EditSession');
-
-$interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[]=array('url' => "session_list.php","name" => get_lang('SessionList'));
-
-$result=api_sql_query("SELECT name,date_start,date_end,id_coach, session_admin_id, nb_days_access_before_beginning, nb_days_access_after_end FROM $tbl_session WHERE id='$id'",__FILE__,__LINE__);
-
-if (!$infos=mysql_fetch_array($result)) {
-	header('Location: session_list.php');
-	exit();
-}
-list($year_start,$month_start,$day_start)=explode('-',$infos['date_start']);
-list($year_end,$month_end,$day_end)=explode('-',$infos['date_end']);
-
-if (!api_is_platform_admin() && $infos['session_admin_id']!=$_user['user_id']) {
-	api_not_allowed(true);
-}
-
-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_access_before']; 
-	$nb_days_acess_after = $_POST['nb_days_access_after']; 
-	$nolimit=$_POST['nolimit'];
-	$id_coach=$_POST['id_coach'];
-	$return = SessionManager::edit_session($id,$name,$year_start,$month_start,$day_start,$year_end,$month_end,$day_end,$nb_days_acess_before,$nb_days_acess_after,$nolimit,$id_coach);
-	if ($return == strval(intval($return))) {
-		header('Location: resume_session.php?id_session='.$return);
-		exit();
-	}
-}
-
-$sql="SELECT user_id,lastname,firstname,username FROM $tbl_user WHERE status='1' ORDER BY lastname,firstname,username";
-
-if ($_configuration['multiple_access_urls']==true){
-	$table_access_url_rel_user= 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 DISTINCT u.user_id,lastname,firstname,username FROM $tbl_user u INNER JOIN $table_access_url_rel_user url_rel_user
-			ON (url_rel_user.user_id = u.user_id)
-			WHERE status='1' AND access_url_id = $access_url_id
-			ORDER BY lastname,firstname,username";
-	}
-}		
-			
-$result=api_sql_query($sql,__FILE__,__LINE__);
-
-$Coaches=api_store_result($result);
-$thisYear=date('Y');
-
-// 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(); ?>?page=<?php echo $_GET['page'] ?>&id=<?php echo $id; ?>" 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="550">
-
-<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); else echo api_htmlentities($infos['name'],ENT_QUOTES,$charset); ?>"></td>
-</tr>
-<tr>
-  <td width="30%"><?php echo get_lang('CoachName') ?>&nbsp;&nbsp;</td>
-  <td width="70%"><select name="id_coach" style="width:250px;">
-	<option value="">----- <?php echo get_lang('Choose') ?> -----</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 $enreg['lastname'].' '.$enreg['firstname'].' ('.$enreg['username'].')'; ?></option>
-
-<?php
-}
-
-unset($Coaches);
-?>
-
-  </select></td>
-</tr>
-<tr>
-  <td width="30%"><?php echo get_lang('NoTimeLimits') ?></td>
-  <td width="70%">
-  	<input type="checkbox" name="nolimit" onChange="setDisable(this)" <?php if($year_start=="0000") echo "checked"; ?>/>
-  </td>
-<tr>
-<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($day_start == 2) echo 'selected="selected"'; ?> >02</option>
-	<option value="3" <?php if($day_start == 3) echo 'selected="selected"'; ?> >03</option>
-	<option value="4" <?php if($day_start == 4) echo 'selected="selected"'; ?> >04</option>
-	<option value="5" <?php if($day_start == 5) echo 'selected="selected"'; ?> >05</option>
-	<option value="6" <?php if($day_start == 6) echo 'selected="selected"'; ?> >06</option>
-	<option value="7" <?php if($day_start == 7) echo 'selected="selected"'; ?> >07</option>
-	<option value="8" <?php if($day_start == 8) echo 'selected="selected"'; ?> >08</option>
-	<option value="9" <?php if($day_start == 9) echo 'selected="selected"'; ?> >09</option>
-	<option value="10" <?php if($day_start == 10) echo 'selected="selected"'; ?> >10</option>
-	<option value="11" <?php if($day_start == 11) echo 'selected="selected"'; ?> >11</option>
-	<option value="12" <?php if($day_start == 12) echo 'selected="selected"'; ?> >12</option>
-	<option value="13" <?php if($day_start == 13) echo 'selected="selected"'; ?> >13</option>
-	<option value="14" <?php if($day_start == 14) echo 'selected="selected"'; ?> >14</option>
-	<option value="15" <?php if($day_start == 15) echo 'selected="selected"'; ?> >15</option>
-	<option value="16" <?php if($day_start == 16) echo 'selected="selected"'; ?> >16</option>
-	<option value="17" <?php if($day_start == 17) echo 'selected="selected"'; ?> >17</option>
-	<option value="18" <?php if($day_start == 18) echo 'selected="selected"'; ?> >18</option>
-	<option value="19" <?php if($day_start == 19) echo 'selected="selected"'; ?> >19</option>
-	<option value="20" <?php if($day_start == 20) echo 'selected="selected"'; ?> >20</option>
-	<option value="21" <?php if($day_start == 21) echo 'selected="selected"'; ?> >21</option>
-	<option value="22" <?php if($day_start == 22) echo 'selected="selected"'; ?> >22</option>
-	<option value="23" <?php if($day_start == 23) echo 'selected="selected"'; ?> >23</option>
-	<option value="24" <?php if($day_start == 24) echo 'selected="selected"'; ?> >24</option>
-	<option value="25" <?php if($day_start == 25) echo 'selected="selected"'; ?> >25</option>
-	<option value="26" <?php if($day_start == 26) echo 'selected="selected"'; ?> >26</option>
-	<option value="27" <?php if($day_start == 27) echo 'selected="selected"'; ?> >27</option>
-	<option value="28" <?php if($day_start == 28) echo 'selected="selected"'; ?> >28</option>
-	<option value="29" <?php if($day_start == 29) echo 'selected="selected"'; ?> >29</option>
-	<option value="30" <?php if($day_start == 30) echo 'selected="selected"'; ?> >30</option>
-	<option value="31" <?php if($day_start == 31) echo 'selected="selected"'; ?> >31</option>
-  </select>
-  /
-  <select name="month_start">
-	<option value="1">01</option>
-	<option value="2" <?php if($month_start == 2) echo 'selected="selected"'; ?> >02</option>
-	<option value="3" <?php if($month_start == 3) echo 'selected="selected"'; ?> >03</option>
-	<option value="4" <?php if($month_start == 4) echo 'selected="selected"'; ?> >04</option>
-	<option value="5" <?php if($month_start == 5) echo 'selected="selected"'; ?> >05</option>
-	<option value="6" <?php if($month_start == 6) echo 'selected="selected"'; ?> >06</option>
-	<option value="7" <?php if($month_start == 7) echo 'selected="selected"'; ?> >07</option>
-	<option value="8" <?php if($month_start == 8) echo 'selected="selected"'; ?> >08</option>
-	<option value="9" <?php if($month_start == 9) echo 'selected="selected"'; ?> >09</option>
-	<option value="10" <?php if($month_start == 10) echo 'selected="selected"'; ?> >10</option>
-	<option value="11" <?php if($month_start == 11) echo 'selected="selected"'; ?> >11</option>
-	<option value="12" <?php if($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($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($day_end == 2) echo 'selected="selected"'; ?> >02</option>
-	<option value="3" <?php if($day_end == 3) echo 'selected="selected"'; ?> >03</option>
-	<option value="4" <?php if($day_end == 4) echo 'selected="selected"'; ?> >04</option>
-	<option value="5" <?php if($day_end == 5) echo 'selected="selected"'; ?> >05</option>
-	<option value="6" <?php if($day_end == 6) echo 'selected="selected"'; ?> >06</option>
-	<option value="7" <?php if($day_end == 7) echo 'selected="selected"'; ?> >07</option>
-	<option value="8" <?php if($day_end == 8) echo 'selected="selected"'; ?> >08</option>
-	<option value="9" <?php if($day_end == 9) echo 'selected="selected"'; ?> >09</option>
-	<option value="10" <?php if($day_end == 10) echo 'selected="selected"'; ?> >10</option>
-	<option value="11" <?php if($day_end == 11) echo 'selected="selected"'; ?> >11</option>
-	<option value="12" <?php if($day_end == 12) echo 'selected="selected"'; ?> >12</option>
-	<option value="13" <?php if($day_end == 13) echo 'selected="selected"'; ?> >13</option>
-	<option value="14" <?php if($day_end == 14) echo 'selected="selected"'; ?> >14</option>
-	<option value="15" <?php if($day_end == 15) echo 'selected="selected"'; ?> >15</option>
-	<option value="16" <?php if($day_end == 16) echo 'selected="selected"'; ?> >16</option>
-	<option value="17" <?php if($day_end == 17) echo 'selected="selected"'; ?> >17</option>
-	<option value="18" <?php if($day_end == 18) echo 'selected="selected"'; ?> >18</option>
-	<option value="19" <?php if($day_end == 19) echo 'selected="selected"'; ?> >19</option>
-	<option value="20" <?php if($day_end == 20) echo 'selected="selected"'; ?> >20</option>
-	<option value="21" <?php if($day_end == 21) echo 'selected="selected"'; ?> >21</option>
-	<option value="22" <?php if($day_end == 22) echo 'selected="selected"'; ?> >22</option>
-	<option value="23" <?php if($day_end == 23) echo 'selected="selected"'; ?> >23</option>
-	<option value="24" <?php if($day_end == 24) echo 'selected="selected"'; ?> >24</option>
-	<option value="25" <?php if($day_end == 25) echo 'selected="selected"'; ?> >25</option>
-	<option value="26" <?php if($day_end == 26) echo 'selected="selected"'; ?> >26</option>
-	<option value="27" <?php if($day_end == 27) echo 'selected="selected"'; ?> >27</option>
-	<option value="28" <?php if($day_end == 28) echo 'selected="selected"'; ?> >28</option>
-	<option value="29" <?php if($day_end == 29) echo 'selected="selected"'; ?> >29</option>
-	<option value="30" <?php if($day_end == 30) echo 'selected="selected"'; ?> >30</option>
-	<option value="31" <?php if($day_end == 31) echo 'selected="selected"'; ?> >31</option>
-  </select>
-  /
-  <select name="month_end">
-	<option value="1">01</option>
-	<option value="2" <?php if($month_end == 2) echo 'selected="selected"'; ?> >02</option>
-	<option value="3" <?php if($month_end == 3) echo 'selected="selected"'; ?> >03</option>
-	<option value="4" <?php if($month_end == 4) echo 'selected="selected"'; ?> >04</option>
-	<option value="5" <?php if($month_end == 5) echo 'selected="selected"'; ?> >05</option>
-	<option value="6" <?php if($month_end == 6) echo 'selected="selected"'; ?> >06</option>
-	<option value="7" <?php if($month_end == 7) echo 'selected="selected"'; ?> >07</option>
-	<option value="8" <?php if($month_end == 8) echo 'selected="selected"'; ?> >08</option>
-	<option value="9" <?php if($month_end == 9) echo 'selected="selected"'; ?> >09</option>
-	<option value="10" <?php if($month_end == 10) echo 'selected="selected"'; ?> >10</option>
-	<option value="11" <?php if($month_end == 11) echo 'selected="selected"'; ?> >11</option>
-	<option value="12" <?php if($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($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){
-					if($nb_days_access_before!=0 || $nb_days_access_after!=0) 
-						echo 'block'; 
-					else echo 'none';
-				}
-				else{
-					if($infos['nb_days_access_before_beginning']!=0 || $infos['nb_days_access_after_end']!=0)
-						echo 'block'; 
-					else
-						echo 'none';
-				}
-			?>
-				;" id="options">
-			<br>
-			<input type="text" name="nb_days_access_before" value="<?php if($formSent) echo api_htmlentities($nb_days_access_before,ENT_QUOTES,$charset); else echo api_htmlentities($infos['nb_days_access_before_beginning'],ENT_QUOTES,$charset); ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysBefore') ?><br>
-			<input type="text" name="nb_days_access_after" value="<?php if($formSent) echo api_htmlentities($nb_days_access_after,ENT_QUOTES,$charset); else echo api_htmlentities($infos['nb_days_access_after_end'],ENT_QUOTES,$charset); ?>" 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('ModifyThisSession') ?>"><?php echo get_lang('ModifyThisSession') ?></button>
-  
-  </td>
-</tr>
-
-</table>
-
-</form>
-<script type="text/javascript">
-
-<?php if($year_start=="0000") echo "setDisable(document.form.nolimit);\r\n"; ?>
-
-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 */
+
+// name of the language file that needs to be included
+$language_file ='admin';
+$cidReset=true;
+include('../inc/global.inc.php');
+require_once (api_get_path(LIBRARY_PATH).'sessionmanager.lib.php');
+
+// setting the section (for the tabs)
+$this_section=SECTION_PLATFORM_ADMIN;
+
+api_protect_admin_script(true);
+
+$id=intval($_GET['id']);
+
+$formSent=0;
+$errorMsg='';
+
+// Database Table Definitions
+$tbl_user		= Database::get_main_table(TABLE_MAIN_USER);
+$tbl_session	= Database::get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+
+$tool_name = get_lang('EditSession');
+
+$interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[]=array('url' => "session_list.php","name" => get_lang('SessionList'));
+
+$result=Database::query("SELECT name,date_start,date_end,id_coach, session_admin_id, nb_days_access_before_beginning, nb_days_access_after_end, session_category_id, visibility FROM $tbl_session WHERE id='$id'",__FILE__,__LINE__);
+
+if (!$infos=Database::fetch_array($result)) {
+	header('Location: session_list.php');
+	exit();
+}
+list($year_start,$month_start,$day_start)=explode('-',$infos['date_start']);
+list($year_end,$month_end,$day_end)=explode('-',$infos['date_end']);
+
+if (!api_is_platform_admin() && $infos['session_admin_id']!=$_user['user_id']) {
+	api_not_allowed(true);
+}
+
+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_access_before'];
+	$nb_days_acess_after = $_POST['nb_days_access_after'];
+	$nolimit=$_POST['nolimit'];
+	$id_coach=$_POST['id_coach'];
+	$id_session_category = $_POST['session_category'];
+	$id_visibility = $_POST['session_visibility'];
+
+	$return = SessionManager::edit_session($id,$name,$year_start,$month_start,$day_start,$year_end,$month_end,$day_end,$nb_days_acess_before,$nb_days_acess_after,$nolimit, $id_coach, $id_session_category,$id_visibility);
+	if ($return == strval(intval($return))) {
+		header('Location: resume_session.php?id_session='.$return);
+		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;
+
+if ($_configuration['multiple_access_urls']==true){
+	$table_access_url_rel_user= 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 DISTINCT u.user_id,lastname,firstname,username FROM $tbl_user u INNER JOIN $table_access_url_rel_user url_rel_user
+			ON (url_rel_user.user_id = u.user_id)
+			WHERE status='1' AND access_url_id = '$access_url_id' $order_clause";
+	}
+}
+
+$result=Database::query($sql,__FILE__,__LINE__);
+
+$Coaches=Database::store_result($result);
+$thisYear=date('Y');
+
+// 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(); ?>?page=<?php echo Security::remove_XSS($_GET['page']) ?>&id=<?php echo $id; ?>" 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="650">
+
+<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); else echo api_htmlentities($infos['name'],ENT_QUOTES,$charset); ?>"></td>
+</tr>
+<tr>
+  <td width="30%"><?php echo get_lang('CoachName') ?>&nbsp;&nbsp;</td>
+  <td width="70%"><select name="id_coach" style="width:250px;">
+	<option value="">----- <?php echo get_lang('Choose') ?> -----</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['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
+
+<?php
+}
+
+unset($Coaches);
+?>
+
+  </select></td>
+</tr>
+<?php
+	$tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
+	//$access_url_id = api_get_current_access_url_id();
+	$sql = 'SELECT id, name FROM '.$tbl_session_category.' ORDER BY name ASC';
+	$result = Database::query($sql,__FILE__,__LINE__);
+	$Categories = Database::store_result($result);
+?>
+<tr>
+  <td width="30%"><?php echo get_lang('SessionCategory') ?></td>
+  <td width="70%">
+  	<select name="session_category" value="true" style="width:250px;">
+		<option value="0"><?php get_lang('None'); ?></option>
+		<?php foreach($Categories as $Rows): ?>
+		<option value="<?php echo $Rows['id']; ?>" <?php if($Rows['id'] == $infos['session_category_id']) echo 'selected="selected"'; ?>><?php echo $Rows['name']; ?></option>
+		<?php endforeach; ?>
+	</select>
+  </td>
+</tr>
+
+<tr>
+  <td width="30%"><?php echo get_lang('NoTimeLimits') ?></td>
+  <td width="70%">
+  	<input type="checkbox" name="nolimit" onChange="setDisable(this)" <?php if($year_start=="0000") echo "checked"; ?>/>
+  </td>
+<tr>
+<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($day_start == 2) echo 'selected="selected"'; ?> >02</option>
+	<option value="3" <?php if($day_start == 3) echo 'selected="selected"'; ?> >03</option>
+	<option value="4" <?php if($day_start == 4) echo 'selected="selected"'; ?> >04</option>
+	<option value="5" <?php if($day_start == 5) echo 'selected="selected"'; ?> >05</option>
+	<option value="6" <?php if($day_start == 6) echo 'selected="selected"'; ?> >06</option>
+	<option value="7" <?php if($day_start == 7) echo 'selected="selected"'; ?> >07</option>
+	<option value="8" <?php if($day_start == 8) echo 'selected="selected"'; ?> >08</option>
+	<option value="9" <?php if($day_start == 9) echo 'selected="selected"'; ?> >09</option>
+	<option value="10" <?php if($day_start == 10) echo 'selected="selected"'; ?> >10</option>
+	<option value="11" <?php if($day_start == 11) echo 'selected="selected"'; ?> >11</option>
+	<option value="12" <?php if($day_start == 12) echo 'selected="selected"'; ?> >12</option>
+	<option value="13" <?php if($day_start == 13) echo 'selected="selected"'; ?> >13</option>
+	<option value="14" <?php if($day_start == 14) echo 'selected="selected"'; ?> >14</option>
+	<option value="15" <?php if($day_start == 15) echo 'selected="selected"'; ?> >15</option>
+	<option value="16" <?php if($day_start == 16) echo 'selected="selected"'; ?> >16</option>
+	<option value="17" <?php if($day_start == 17) echo 'selected="selected"'; ?> >17</option>
+	<option value="18" <?php if($day_start == 18) echo 'selected="selected"'; ?> >18</option>
+	<option value="19" <?php if($day_start == 19) echo 'selected="selected"'; ?> >19</option>
+	<option value="20" <?php if($day_start == 20) echo 'selected="selected"'; ?> >20</option>
+	<option value="21" <?php if($day_start == 21) echo 'selected="selected"'; ?> >21</option>
+	<option value="22" <?php if($day_start == 22) echo 'selected="selected"'; ?> >22</option>
+	<option value="23" <?php if($day_start == 23) echo 'selected="selected"'; ?> >23</option>
+	<option value="24" <?php if($day_start == 24) echo 'selected="selected"'; ?> >24</option>
+	<option value="25" <?php if($day_start == 25) echo 'selected="selected"'; ?> >25</option>
+	<option value="26" <?php if($day_start == 26) echo 'selected="selected"'; ?> >26</option>
+	<option value="27" <?php if($day_start == 27) echo 'selected="selected"'; ?> >27</option>
+	<option value="28" <?php if($day_start == 28) echo 'selected="selected"'; ?> >28</option>
+	<option value="29" <?php if($day_start == 29) echo 'selected="selected"'; ?> >29</option>
+	<option value="30" <?php if($day_start == 30) echo 'selected="selected"'; ?> >30</option>
+	<option value="31" <?php if($day_start == 31) echo 'selected="selected"'; ?> >31</option>
+  </select>
+  /
+  <select name="month_start">
+	<option value="1">01</option>
+	<option value="2" <?php if($month_start == 2) echo 'selected="selected"'; ?> >02</option>
+	<option value="3" <?php if($month_start == 3) echo 'selected="selected"'; ?> >03</option>
+	<option value="4" <?php if($month_start == 4) echo 'selected="selected"'; ?> >04</option>
+	<option value="5" <?php if($month_start == 5) echo 'selected="selected"'; ?> >05</option>
+	<option value="6" <?php if($month_start == 6) echo 'selected="selected"'; ?> >06</option>
+	<option value="7" <?php if($month_start == 7) echo 'selected="selected"'; ?> >07</option>
+	<option value="8" <?php if($month_start == 8) echo 'selected="selected"'; ?> >08</option>
+	<option value="9" <?php if($month_start == 9) echo 'selected="selected"'; ?> >09</option>
+	<option value="10" <?php if($month_start == 10) echo 'selected="selected"'; ?> >10</option>
+	<option value="11" <?php if($month_start == 11) echo 'selected="selected"'; ?> >11</option>
+	<option value="12" <?php if($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($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($day_end == 2) echo 'selected="selected"'; ?> >02</option>
+	<option value="3" <?php if($day_end == 3) echo 'selected="selected"'; ?> >03</option>
+	<option value="4" <?php if($day_end == 4) echo 'selected="selected"'; ?> >04</option>
+	<option value="5" <?php if($day_end == 5) echo 'selected="selected"'; ?> >05</option>
+	<option value="6" <?php if($day_end == 6) echo 'selected="selected"'; ?> >06</option>
+	<option value="7" <?php if($day_end == 7) echo 'selected="selected"'; ?> >07</option>
+	<option value="8" <?php if($day_end == 8) echo 'selected="selected"'; ?> >08</option>
+	<option value="9" <?php if($day_end == 9) echo 'selected="selected"'; ?> >09</option>
+	<option value="10" <?php if($day_end == 10) echo 'selected="selected"'; ?> >10</option>
+	<option value="11" <?php if($day_end == 11) echo 'selected="selected"'; ?> >11</option>
+	<option value="12" <?php if($day_end == 12) echo 'selected="selected"'; ?> >12</option>
+	<option value="13" <?php if($day_end == 13) echo 'selected="selected"'; ?> >13</option>
+	<option value="14" <?php if($day_end == 14) echo 'selected="selected"'; ?> >14</option>
+	<option value="15" <?php if($day_end == 15) echo 'selected="selected"'; ?> >15</option>
+	<option value="16" <?php if($day_end == 16) echo 'selected="selected"'; ?> >16</option>
+	<option value="17" <?php if($day_end == 17) echo 'selected="selected"'; ?> >17</option>
+	<option value="18" <?php if($day_end == 18) echo 'selected="selected"'; ?> >18</option>
+	<option value="19" <?php if($day_end == 19) echo 'selected="selected"'; ?> >19</option>
+	<option value="20" <?php if($day_end == 20) echo 'selected="selected"'; ?> >20</option>
+	<option value="21" <?php if($day_end == 21) echo 'selected="selected"'; ?> >21</option>
+	<option value="22" <?php if($day_end == 22) echo 'selected="selected"'; ?> >22</option>
+	<option value="23" <?php if($day_end == 23) echo 'selected="selected"'; ?> >23</option>
+	<option value="24" <?php if($day_end == 24) echo 'selected="selected"'; ?> >24</option>
+	<option value="25" <?php if($day_end == 25) echo 'selected="selected"'; ?> >25</option>
+	<option value="26" <?php if($day_end == 26) echo 'selected="selected"'; ?> >26</option>
+	<option value="27" <?php if($day_end == 27) echo 'selected="selected"'; ?> >27</option>
+	<option value="28" <?php if($day_end == 28) echo 'selected="selected"'; ?> >28</option>
+	<option value="29" <?php if($day_end == 29) echo 'selected="selected"'; ?> >29</option>
+	<option value="30" <?php if($day_end == 30) echo 'selected="selected"'; ?> >30</option>
+	<option value="31" <?php if($day_end == 31) echo 'selected="selected"'; ?> >31</option>
+  </select>
+  /
+  <select name="month_end">
+	<option value="1">01</option>
+	<option value="2" <?php if($month_end == 2) echo 'selected="selected"'; ?> >02</option>
+	<option value="3" <?php if($month_end == 3) echo 'selected="selected"'; ?> >03</option>
+	<option value="4" <?php if($month_end == 4) echo 'selected="selected"'; ?> >04</option>
+	<option value="5" <?php if($month_end == 5) echo 'selected="selected"'; ?> >05</option>
+	<option value="6" <?php if($month_end == 6) echo 'selected="selected"'; ?> >06</option>
+	<option value="7" <?php if($month_end == 7) echo 'selected="selected"'; ?> >07</option>
+	<option value="8" <?php if($month_end == 8) echo 'selected="selected"'; ?> >08</option>
+	<option value="9" <?php if($month_end == 9) echo 'selected="selected"'; ?> >09</option>
+	<option value="10" <?php if($month_end == 10) echo 'selected="selected"'; ?> >10</option>
+	<option value="11" <?php if($month_end == 11) echo 'selected="selected"'; ?> >11</option>
+	<option value="12" <?php if($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($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){
+					if($nb_days_access_before!=0 || $nb_days_access_after!=0)
+						echo 'block';
+					else echo 'none';
+				}
+				else{
+					if($infos['nb_days_access_before_beginning']!=0 || $infos['nb_days_access_after_end']!=0)
+						echo 'block';
+					else
+						echo 'none';
+				}
+			?>
+				;" id="options">
+			<br>
+			<input type="text" name="nb_days_access_before" value="<?php if($formSent) echo api_htmlentities($nb_days_access_before,ENT_QUOTES,$charset); else echo api_htmlentities($infos['nb_days_access_before_beginning'],ENT_QUOTES,$charset); ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysBefore') ?><br>
+			<input type="text" name="nb_days_access_after" value="<?php if($formSent) echo api_htmlentities($nb_days_access_after,ENT_QUOTES,$charset); else echo api_htmlentities($infos['nb_days_access_after_end'],ENT_QUOTES,$charset); ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysAfter') ?>
+			<br>
+		</div>
+	</td>
+</tr>
+
+<tr>
+  <td width="30%"><?php echo get_lang('SessionVisibility') ?></td>
+  <td width="70%">
+  	<select name="session_visibility" style="width:250px;">
+		<?php
+		$visibility_list = array(SESSION_VISIBLE_READ_ONLY=>get_lang('ReadOnly'), SESSION_VISIBLE=>get_lang('Visible'), SESSION_INVISIBLE=>api_ucfirst(get_lang('Invisible')));
+		foreach($visibility_list as $key=>$item): ?>
+		<option value="<?php echo $key; ?>" <?php if($key == $infos['visibility']) echo 'selected="selected"'; ?>><?php echo $item; ?></option>
+		<?php endforeach; ?>
+	</select>
+  </td>
+</tr>
+
+
+<tr>
+  <td>&nbsp;</td>
+  <td>
+<button class="save" type="submit" value="<?php echo get_lang('ModifyThisSession') ?>"><?php echo get_lang('ModifyThisSession') ?></button>
+
+  </td>
+</tr>
+
+</table>
+
+</form>
+<script type="text/javascript">
+
+<?php if($year_start=="0000") echo "setDisable(document.form.nolimit);\r\n"; ?>
+
+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;
+
+	document.form.session_visibility.disabled = (select.checked) ? true : false;
+
+	document.form.session_visibility.selectedIndex = 0;
+
+}
+</script>
+<?php
+Display::display_footer();
+?>

+ 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=api_sql_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 = api_sql_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 = api_sql_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 = api_sql_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 = api_sql_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=api_sql_query($sql,__FILE__,__LINE__);
-
-$Sessions=api_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();
+?>

+ 912 - 898
main/admin/session_import.php

@@ -1,898 +1,912 @@
-<?php // $Id: session_import.php 20699 2009-05-15 16:32:03Z ivantcholakov $
-/* For licensing terms, see /dokeos_license.txt */
-/**
-==============================================================================
-*	@package dokeos.admin
-==============================================================================
-*/
-$language_file = array('admin','registration');
-$cidReset=true;
-require('../inc/global.inc.php');
-if (empty($charset)) {
-	$charset = 'ISO-8859-15';
-}
-api_protect_admin_script(true);
-
-require_once(api_get_path(LIBRARY_PATH).'fileManage.lib.php');
-require_once(api_get_path(LIBRARY_PATH).'usermanager.lib.php');
-require(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).'sessionmanager.lib.php');
-require_once(api_get_path(INCLUDE_PATH).'lib/mail.lib.inc.php');
-require_once(api_get_path(INCLUDE_PATH).'lib/course.lib.php');
-$formSent=0;
-$errorMsg='';
-
-$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);
-
-$tool_name=get_lang('ImportSessionListXMLCSV');
-
-$interbreadcrumb[]=array('url' => 'index.php','name' => get_lang('AdministrationTools'));
-
-set_time_limit(0);
-$inserted_in_course = array();
-
-if ($_POST['formSent']) {
-	if (isset($_FILES['import_file']['tmp_name'])) {
-		$formSent=$_POST['formSent'];
-		$file_type=$_POST['file_type'];
-		$sendMail=$_POST['sendMail']?1:0;		
-		//$updatesession=$_POST['updatesession']?1:0;
-		$updatesession = 0;
-		$sessions=array();
-
-		///////////////////////
-		//XML/////////////////
-		/////////////////////
-		
-		$countSessions = 0;
-		
-		if ($file_type == 'xml') {
-			$racine = @simplexml_load_file($_FILES['import_file']['tmp_name']);	
-			if (is_object($racine)) {																				
-				if (count($racine->Users->User) > 0) {
-					
-					//Creating - updating users
-					// from the <Sessions> <User> racine 		
-					foreach($racine->Users->User as $userNode) {
-						$username = api_convert_encoding($userNode->Username,$charset,'utf-8');
-						$isCut = 0; // if the username given is too long
-						if(api_strlen($username)>20) {
-							$user_name_dist = $username;
-							$username = api_substr($username,0,20);
-							$isCut = 1;
-						}						
-						$user_exist = UserManager::is_username_available($username);												
-						if ($user_exist == true) {
-							if ($isCut) {
-								$errorMsg .= get_lang('UsernameTooLongWasCut').' '.get_lang('From').' '.$user_name_dist.' '.get_lang('To').' '.$username.' <br />';
-							}	
-							$lastname = api_convert_encoding($userNode->Lastname,$charset,'utf-8');
-							$firstname = api_convert_encoding($userNode->Firstname,$charset,'utf-8');
-							$password = api_convert_encoding($userNode->Password,$charset,'utf-8');
-							if(empty($password)) {
-								$password = base64_encode(rand(1000,10000));
-	                        }
-							$email = api_convert_encoding($userNode->Email,$charset,'utf-8');
-							$official_code = api_convert_encoding($userNode->OfficialCode,$charset,'utf-8');
-							$phone = api_convert_encoding($userNode->Phone,$charset,'utf-8');
-							$status = api_convert_encoding($userNode->Status,$charset,'utf-8');
-							switch ($status) {
-								case 'student' : $status = 5; break;
-								case 'teacher' : $status = 1; break;
-								default : $status = 5; 
-								$errorMsg = get_lang('StudentStatusWasGivenTo').' : '.$username.'<br />';
-							}
-							
-							//adding user to the platform 
-							$sql = "INSERT INTO $tbl_user SET
-									username = '".Database::escape_string($username)."',
-									lastname = '".Database::escape_string($lastname)."',
-									firstname = '".Database::escape_string($firstname)."',
-									password = '".(api_get_encrypted_password($password))."',
-									email = '".Database::escape_string($email)."',
-									official_code = '".Database::escape_string($official_code)."',
-									phone = '".Database::escape_string($phone)."',
-									status = '".Database::escape_string($status)."'";
-							
-							//if available adding also the access_url rel user relationship
-							api_sql_query($sql, __FILE__, __LINE__);
-							$return=Database::get_last_insert_id();						
-							global $_configuration;
-							require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
-							if ($_configuration['multiple_access_urls']==true) {										
-								if (api_get_current_access_url_id()!=-1)
-									UrlManager::add_user_to_url($return, api_get_current_access_url_id());
-								else
-									UrlManager::add_user_to_url($return, 1);
-							} else {
-								//we are adding by default the access_url_user table with access_url_id = 1
-								UrlManager::add_user_to_url($return, 1);				
-							}
-							// send an email to users
-							if($sendMail) {														
-								$recipient_name = $firstname.' '.$lastname;
-								$emailsubject = '['.get_setting('siteName').'] '.get_lang('YourReg').' '.get_setting('siteName');			
-								$emailbody="[NOTE:] ".get_lang('ThisIsAutomaticEmailNoReply').".\n\n".get_lang('langDear')." $firstname $lastname,\n\n".get_lang('langYouAreReg')." ". 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 = get_setting('administratorName').' '.get_setting('administratorSurname');
-							    $email_admin = get_setting('emailAdministrator');							
-								@api_mail($recipient_name, $email, $emailsubject, $emailbody, $sender_name,$email_admin);
-							}
-						} else {
-							$lastname = api_convert_encoding($userNode->Lastname,$charset,'utf-8');
-							$firstname = api_convert_encoding($userNode->Firstname,$charset,'utf-8');
-							$password = api_convert_encoding($userNode->Password,$charset,'utf-8');
-							$email = api_convert_encoding($userNode->Email,$charset,'utf-8');
-							$official_code = api_convert_encoding($userNode->OfficialCode,$charset,'utf-8');
-							$phone = api_convert_encoding($userNode->Phone,$charset,'utf-8');
-							$status = api_convert_encoding($userNode->Status,$charset,'utf-8');
-							switch($status) {
-								case 'student' : $status = 5; break;
-								case 'teacher' : $status = 1; break;
-								default : $status = 5; $errorMsg = get_lang('StudentStatusWasGivenTo').' : '.$username.'<br />';
-							}
-							
-							$sql = "UPDATE $tbl_user SET
-										lastname = '".Database::escape_string($lastname)."',
-										firstname = '".Database::escape_string($firstname)."',
-										".(empty($password) ? "" : "password = '".(api_get_encrypted_password($password))."',")."
-										email = '".Database::escape_string($email)."',
-										official_code = '".Database::escape_string($official_code)."',
-										phone = '".Database::escape_string($phone)."',
-										status = '".Database::escape_string($status)."'
-									WHERE username = '".Database::escape_string($username)."'";
-	
-							api_sql_query($sql, __FILE__, __LINE__);						
-						}
-					}
-				}
-				
-				// Creating - editing courses
-				// from the <Sessions> <Courses> racine
-				if (count($racine->Courses->Course) > 0) {			
-					foreach($racine->Courses->Course as $courseNode) {
-						$course_code = api_convert_encoding($courseNode->CourseCode,$charset,'utf-8');
-						$title = api_convert_encoding($courseNode->CourseTitle,$charset,'utf-8');
-						$description = api_convert_encoding($courseNode->CourseDescription,$charset,'utf-8');
-						$language = api_convert_encoding($courseNode->CourseLanguage,$charset,'utf-8');
-						$username = api_convert_encoding($courseNode->CourseTeacher,$charset,'utf-8');
-						
-						//looking for the teacher
-						$sql = "SELECT user_id, lastname, firstname FROM $tbl_user WHERE username='$username'";
-						$rs = api_sql_query($sql, __FILE__, __LINE__);	
-						list($user_id, $lastname, $firstname) = Database::fetch_array($rs);						
-						global $_configuration;
-						$keys = define_course_keys($course_code, "", $_configuration['db_prefix']);		
-											
-						if (sizeof($keys)) {	
-							$currentCourseCode = $keys['visual_code'];
-							$currentCourseId = $keys['currentCourseId'];
-							if(empty($currentCourseCode))
-								$currentCourseCode = $currentCourseId;
-							$currentCourseDbName = $keys['currentCourseDbName'];
-							$currentCourseRepository = $keys['currentCourseRepository'];
-							//creating a course
-							
-							if($currentCourseId == api_strtoupper($course_code)) {
-								if (empty ($title)) {
-									$title = $keys['currentCourseCode'];
-								}																									
-								prepare_course_repository($currentCourseRepository, $currentCourseId);
-								update_Db_course($currentCourseDbName);								
-								$pictures_array=fill_course_repository($currentCourseRepository); 
-								fill_Db_course($currentCourseDbName, $currentCourseRepository, 'english',$pictures_array);								
-								register_course($currentCourseId, $currentCourseCode, $currentCourseRepository, $currentCourseDbName, "$lastname $firstname", $course['unit_code'], addslashes($course['FR']['title']), $language, $user_id);
-								$sql = "INSERT INTO ".$tbl_course." SET
-											code = '".$currentCourseId."',
-											db_name = '".$currentCourseDbName."',
-											directory = '".$currentCourseRepository."',
-											course_language = '".$language."',
-											title = '".$title."',
-											description = '".lang2db($description)."',
-											category_code = '',
-											visibility = '".$defaultVisibilityForANewCourse."',
-											show_score = '',
-											disk_quota = NULL,
-											creation_date = now(),
-											expiration_date = NULL,
-											last_edit = now(),
-											last_visit = NULL,
-											tutor_name = '".$lastname." ".$firstname."',
-											visual_code = '".$currentCourseCode."'";
-	
-								api_sql_query($sql, __FILE__, __LINE__);
-	
-								$sql = "INSERT INTO ".$tbl_course_user." SET
-											course_code = '".$currentCourseId."',
-											user_id = '".$user_id."',
-											status = '1',
-											role = '".lang2db('Professor')."',
-											tutor_id='1',
-											sort='". ($sort +1)."',
-											user_course_cat='0'";
-	
-								api_sql_query($sql, __FILE__, __LINE__);
-							}
-	
-						}
-					}                    
-				}
-				
-				// Creating sessions
-				// from the <Sessions><Session> racine
-				if (count($racine->Session) > 0) {
-					foreach ($racine->Session as $sessionNode) {						 
-						// foreach session						
-						$countCourses = 0;
-						$countUsers = 0;
-	
-						$SessionName = api_convert_encoding($sessionNode->SessionName,$charset,'utf-8');
-						$Coach = api_convert_encoding($sessionNode->Coach,$charset,'utf-8');
-	
-						if (!empty($Coach)) {													
-							$coach_id = UserManager::get_user_id_from_username($Coach);
-							if($coach_id === false) {
-								$errorMsg .= get_lang('UserDoesNotExist').' : '.$Coach.'<br />';
-								//forcing the coach id if user does not exist
-								$coach_id = api_get_user_id();
-							}
-						} else {
-							//forcing the coach id 
-							$coach_id = api_get_user_id();
-						}
-						
-						$DateStart = $sessionNode->DateStart;
-						
-						if(!empty($DateStart)) {
-							list($YearStart,$MonthStart, $DayStart) = explode('-',$DateStart);
-							if(empty($YearStart) || empty($MonthStart) || empty($DayStart)) {
-								$errorMsg .= get_lang('WrongDate').' : '.$DateStart.'<br />';
-								break;
-							} else {
-								$timeStart = mktime(0,0,0,$MonthStart,$DayStart,$YearStart);
-							}
-	
-							$DateEnd = $sessionNode->DateEnd;
-							if(!empty($DateStart)) {
-								list($YearEnd,$MonthEnd, $DayEnd) = explode('-',$DateEnd);
-								if(empty($YearEnd) || empty($MonthEnd) || empty($DayEnd)) {
-									$errorMsg .= get_lang('WrongDate').' : '.$DateEnd.'<br />';
-									break;
-								} else {
-									$timeEnd = mktime(0,0,0,$MonthEnd,$DayEnd,$YearEnd);
-								}
-							}
-							if($timeEnd - $timeStart < 0) {
-								$errorMsg .= get_lang('StartDateShouldBeBeforeEndDate').' : '.$DateEnd.'<br />';
-							}
-						}
-						
-						//						
-						if (!$updatesession) {
-							// Always create a session
-							$uniqueName = false; // this MUST be initializead
-							$i = 0;
-							//change session name												
-							// verify that session doesn't exist
-							while(!$uniqueName) {
-								if($i>1)
-									$suffix = ' - '.$i;
-								$sql = 'SELECT 1 FROM '.$tbl_session.' WHERE name="'.Database::escape_string($SessionName.$suffix).'"';
-								$rs = api_sql_query($sql, __FILE__, __LINE__);		
-								if(Database::result($rs,0,0)) {
-									$i++;
-								} else {
-									$uniqueName = true;
-									$SessionName .= $suffix;
-								}
-							}							
-							// Creating the session	
-							$sqlSession = "INSERT IGNORE INTO $tbl_session SET
-											name = '".Database::escape_string($SessionName)."',
-											id_coach = '$coach_id',
-											date_start = '$DateStart',
-											date_end = '$DateEnd',
-											session_admin_id=".intval($_user['user_id']);					
-							$rsSession = api_sql_query($sqlSession, __FILE__, __LINE__);					
-							$session_id = Database::get_last_insert_id();					
-							$countSessions++;					
-								
-						} else {
-							// update the session if needed it						
-							$my_session_result = SessionManager::get_session_by_name($SessionName);
-							if ($my_session_result == false) {							
-								// Creating the session	
-									$sqlSession = "INSERT IGNORE INTO $tbl_session SET
-													name = '".Database::escape_string($SessionName)."',
-													id_coach = '$coach_id',
-													date_start = '$DateStart',
-													date_end = '$DateEnd',
-													session_admin_id=".intval($_user['user_id']);					
-									$rsSession = api_sql_query($sqlSession, __FILE__, __LINE__);					
-									$session_id = Database::get_last_insert_id();					
-									$countSessions++;					
-							} else {
-								//if already exists we update the session						
-								$sqlSession = "UPDATE $tbl_session SET
-												id_coach = '$coach_id',
-												date_start = '$DateStart',
-												date_end = '$DateEnd'
-												WHERE name = '$SessionName'";
-								$rsSession = api_sql_query($sqlSession, __FILE__, __LINE__);
-								$session_id = api_sql_query("SELECT id FROM $tbl_session WHERE name='$SessionName'",__FILE__,__LINE__);
-								list($session_id) = Database::fetch_array($session_id);
-								api_sql_query("DELETE FROM $tbl_session_user WHERE id_session='$session_id'",__FILE__,__LINE__);
-								api_sql_query("DELETE FROM $tbl_session_course WHERE id_session='$session_id'",__FILE__,__LINE__);
-								api_sql_query("DELETE FROM $tbl_session_course_user WHERE id_session='$session_id'",__FILE__,__LINE__);
-							}
-						}												
-					
-						//adding the session to an access_url 
-						global $_configuration;	
-	                    require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
-						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();			
-							UrlManager::add_session_to_url($session_id,$access_url_id);			
-						} else {
-							// we are filling by default the access_url_rel_session table 
-							UrlManager::add_session_to_url($session_id,1);
-						}
-						
-						// Adding users to the new session 
-						foreach ($sessionNode->User as $userNode){		
-							$username = api_convert_encoding(api_substr($userNode,0,20),$charset,'utf-8');
-							$user_id = UserManager::get_user_id_from_username($username);					
-							if($user_id!==false){						
-								$sql = "INSERT IGNORE INTO $tbl_session_user SET
-										id_user='$user_id',
-										id_session = '$session_id'";								
-								$rsUser = api_sql_query($sql,__FILE__,__LINE__);							
-								$countUsers++;							
-							}
-						}
-						// Adding courses to a session
-						//var_dump($sessionNode->Course);
-						
-						foreach ($sessionNode->Course as $courseNode) {	
-							$CourseCode = Database::escape_string($courseNode->CourseCode);	
-							// Verify that the course pointed by the course code node exists
-	                        if (CourseManager::course_exists($CourseCode)) {
-							    // If the course exists we continue
-	                            $c_info = CourseManager::get_course_information($CourseCode);
-							$Coach = api_substr($courseNode->Coach,0,20);
-								// finding the user coach
-								if(!empty($Coach)){
-									$coach_id = UserManager::get_user_id_from_username($Coach);													
-									if($coach_id===false) {
-										$errorMsg .= get_lang('UserDoesNotExist').' : '.$Coach.'<br />';
-										$coach_id = '';
-									}
-								} else {
-									$coach_id = '';
-								}
-								$session_course_relation = SessionManager::relation_session_course_exist($session_id, $CourseCode);								
-								if ($session_course_relation==false) {
-									$sqlCourse = "INSERT INTO $tbl_session_course SET
-												  course_code = '$CourseCode',
-												  id_coach='$coach_id',
-												  id_session='$session_id'";
-									$rsCourse = api_sql_query($sqlCourse,__FILE__,__LINE__);
-								}
-								if (Database::affected_rows()) {
-									$countCourses++;
-									$countUsersCourses = 0;								
-									foreach ($courseNode->User as $userNode) {
-										$username = api_substr($userNode,0,20);
-										$user_id = UserManager::get_user_id_from_username($username);																		
-										if ($user_id!==false) {
-											// adding to session_rel_user table
-											$sql = "INSERT IGNORE INTO $tbl_session_user SET
-												id_user='$user_id',
-												id_session = '$session_id'";										                                    
-											$rsUser = api_sql_query($sql,__FILE__,__LINE__);
-											$countUsers++;
-											// adding to session_rel_user_rel_course table			
-											$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
-													id_user='$user_id',
-													course_code='$CourseCode',
-													id_session = '$session_id'";
-											$rsUsers = api_sql_query($sql,__FILE__,__LINE__);										
-											$countUsersCourses++;                                       
-										} else {
-											$errorMsg .= get_lang('UserDoesNotExist').' : '.$username.'<br />';
-										}
-									}
-									$update_session_course = "UPDATE $tbl_session_course SET nbr_users='$countUsersCourses' WHERE course_code='$CourseCode'";
-									api_sql_query($update_session_course,__FILE__,__LINE__);
-	                                $inserted_in_course[$CourseCode] = $c_info['title'];
-								}
-							}
-							
-	                        if (CourseManager::course_exists($CourseCode,true)) {
-	                            // if the course exists we continue
-	                            // also subscribe to virtual courses through check on visual code
-	                            $list = CourseManager :: get_courses_info_from_visual_code($CourseCode);
-	                            foreach ($list as $vcourse) {
-	                                if ($vcourse['code'] == $CourseCode) {
-	                                    //ignore, this has already been inserted
-	                                } else {
-	                                    $Coach = substr($courseNode->Coach,0,20);
-	                                    if(!empty($Coach)){
-	                                    	$CoachId = UserManager::get_user_id_from_username($Coach);																		
-											if ($user_id===false) {
-												$errorMsg .= get_lang('UserDoesNotExist').' : '.$Coach.'<br />';
-												$CoachId = '';
-											}	                                     
-	                                    } else {
-	                                        $CoachId = '';
-	                                    }
-	                                    	        
-	                                    $sqlCourse = "INSERT INTO $tbl_session_course SET
-	                                                  course_code = '".$vcourse['code']."',
-	                                                  id_coach='$CoachId',
-	                                                  id_session='$session_id'";
-	                                    $rsCourse = api_sql_query($sqlCourse,__FILE__,__LINE__);
-	                                    if (Database::affected_rows()) {
-	                                        $countCourses++;	        
-	                                        $countUsersCourses = 0;
-	                                        foreach ($courseNode->User as $userNode) {
-	                                            $username = substr($userNode,0,20);	                                            
-	                                            $user_id = UserManager::get_user_id_from_username($username);
-	                                            if ($user_id !==false) {	                                           
-	                                                $sql = "INSERT IGNORE INTO $tbl_session_user SET
-	                                                    id_user='$user_id',
-	                                                    id_session = '$session_id'";
-	                                                $rsUser = api_sql_query($sql,__FILE__,__LINE__);
-	                                                if (Database::affected_rows()) {
-	                                                    $countUsers++;
-	                                                }	                                                
-	                                                $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
-	                                                        id_user='$user_id',
-	                                                        course_code='".$vcourse['code']."',
-	                                                        id_session = '$session_id'";
-	                                                $rsUsers = api_sql_query($sql,__FILE__,__LINE__);
-	                                                if(Database::affected_rows())
-	                                                    $countUsersCourses++;
-	                                            } else {
-	                                                $errorMsg .= get_lang('UserDoesNotExist').' : '.$username.'<br />';
-	                                            }
-	                                        }
-	                                        api_sql_query("UPDATE $tbl_session_course SET nbr_users='$countUsersCourses' WHERE course_code='$CourseCode'",__FILE__,__LINE__);
-	                                    }
-	                                }
-	                                $inserted_in_course[$vcourse['code']] = $vcourse['title'];
-	                            }                         
-	                        } else { // if the course does not exists
-								$errorMsg .= get_lang('CourseDoesNotExist').' : '.$CourseCode.'<br />';
-							}
-						}
-						api_sql_query("UPDATE $tbl_session SET nbr_users='$countUsers', nbr_courses='$countCourses' WHERE id='$session_id'",__FILE__,__LINE__);
-				}
-
-				}
-				if(empty($racine->Users->User) && empty($racine->Courses->Course) && empty($racine->Session)) {
-					$errorMsg=get_lang('NoNeededData');
-				}
-			} else {
-				$errorMsg .= get_lang('XMLNotValid');
-			}
-		} else {
-			/////////////////////
-			// CSV /////////////
-			///////////////////
-						
-			$content=file($_FILES['import_file']['tmp_name']);
-			if(!api_strstr($content[0],';')) {
-				$errorMsg=get_lang('NotCSV');
-			} else {
-				$tag_names=array();
-
-				foreach ($content as $key=>$enreg) {
-					$enreg=explode(';',trim($enreg));
-					if ($key) {
-						foreach($tag_names as $tag_key=>$tag_name) {
-							$sessions[$key-1][$tag_name]=$enreg[$tag_key];
-						}
-					} else {
-						foreach($enreg as $tag_name) {
-							$tag_names[]=api_eregi_replace('[^a-z0-9_-]','',$tag_name);
-						}
-						if(!in_array('SessionName',$tag_names) || !in_array('DateStart',$tag_names) || !in_array('DateEnd',$tag_names)) {
-							$errorMsg=get_lang('NoNeededData');
-							break;
-						}
-					}
-				}
-				// looping the sessions
-				foreach($sessions as $enreg) {			
-					$countUsers = 0;
-					$countCourses = 0;
-					
-					$SessionName = $enreg['SessionName'];
-					$DateStart = $enreg['DateStart'];
-					$DateEnd = $enreg['DateEnd'];
-					
-					// searching a coach	
-					if (!empty($enreg['Coach'])) {
-						$coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
-	                    if ($coach_id === false) {	                                            	
-							// if the user does not exist I'm the coach
-							$coach_id = api_get_user_id();	
-						}
-					} else {
-						$coach_id = api_get_user_id();
-					}
-										
-					if (!$updatesession) {
-						// Always create a session
-						$uniqueName = false; // this MUST be initializead
-						$i = 0;
-						//change session name												
-						// verify that session doesn't exist
-						while(!$uniqueName) {
-							if($i>1)
-								$suffix = ' - '.$i;
-							$sql = 'SELECT 1 FROM '.$tbl_session.' WHERE name="'.Database::escape_string($SessionName.$suffix).'"';
-							$rs = api_sql_query($sql, __FILE__, __LINE__);
-	
-							if(Database::result($rs,0,0)) {
-								$i++;
-							} else {
-								$uniqueName = true;
-								$SessionName .= $suffix;
-							}
-						}
-						
-						// Creating the session	
-						$sqlSession = "INSERT IGNORE INTO $tbl_session SET
-										name = '".Database::escape_string($SessionName)."',
-										id_coach = '$coach_id',
-										date_start = '$DateStart',
-										date_end = '$DateEnd',
-										session_admin_id=".intval($_user['user_id']);					
-						$rsSession = api_sql_query($sqlSession, __FILE__, __LINE__);					
-						$session_id = Database::get_last_insert_id();					
-						$countSessions++;								
-					} else {										
-						$my_session_result = SessionManager::get_session_by_name($SessionName);
-						if ($my_session_result == false) {
-							
-							// creating a session
-							$sqlSession = "INSERT IGNORE INTO $tbl_session SET
-									name = '$SessionName',
-									id_coach = '$coach_id',
-									date_start = '$DateStart',
-									date_end = '$DateEnd'";
-							$rsSession = api_sql_query($sqlSession, __FILE__, __LINE__);
-							// we get the last insert id
-							$my_session_result = SessionManager::get_session_by_name($SessionName);
-							$session_id = $my_session_result['id'];
-							//echo '<br>';				
-						} else {
-							//if already exists we update the session						
-							$sqlSession = "UPDATE $tbl_session SET
-											id_coach = '$coach_id',
-											date_start = '$DateStart',
-											date_end = '$DateEnd'
-											WHERE name = '$SessionName'";
-							$rsSession = api_sql_query($sqlSession, __FILE__, __LINE__);
-							$session_id = api_sql_query("SELECT id FROM $tbl_session WHERE name='$SessionName'",__FILE__,__LINE__);
-							list($session_id) = Database::fetch_array($session_id);
-							api_sql_query("DELETE FROM $tbl_session_user WHERE id_session='$session_id'",__FILE__,__LINE__);
-							api_sql_query("DELETE FROM $tbl_session_course WHERE id_session='$session_id'",__FILE__,__LINE__);
-							api_sql_query("DELETE FROM $tbl_session_course_user WHERE id_session='$session_id'",__FILE__,__LINE__);
-						} 		
-						$countSessions++;					
-					}				
-					
-					$users = explode('|',$enreg['Users']);
-					//var_dump($users );
-					//Adding the relationship  Session - User
-					if (is_array($users)) {
-						foreach ($users as $user) {									
-							$user_id = UserManager::get_user_id_from_username($user);							
-							if ($user_id!==false) {					
-							// insert new users							
-								$sql = "INSERT IGNORE INTO $tbl_session_user SET
-									id_user='$user_id',
-									id_session = '$session_id'";
-								$rsUser = api_sql_query($sql,__FILE__,__LINE__);
-								$countUsers++;
-							}
-						}
-					}
-					
-					$courses = explode('|',$enreg['Courses']);
-					//var_dump($courses);
-					
-					foreach ($courses as $course) {			
-                        $CourseCode = api_strtoupper(api_substr($course,0,api_strpos($course,'[')));
-                        if (CourseManager::course_exists($CourseCode)) {
-                        	       	
-                            // If the course exists we continue
-                            $c_info = CourseManager::get_course_information($CourseCode);
-							
-    						$Coach = api_strstr($course,'[');
-    						$Coach = api_substr($Coach,1,api_strpos($Coach,']')-1);
-    
-    						if(!empty($Coach)) {
-    								$coach_id = UserManager::get_user_id_from_username($Coach);
-	                    		if ($coach_id === false) {	
-	                    			$coach_id = '';
-	                    		}    							
-    						} else {
-    							$Coach = '';
-    						}
-    						// Adding the course to a session		
-    						$sqlCourse = "INSERT IGNORE INTO $tbl_session_course SET
-    									  course_code = '$CourseCode',
-    									  id_coach='$coach_id',
-    									  id_session='$session_id'";    						
-    						$rsCourse = api_sql_query($sqlCourse,__FILE__,__LINE__);    						
-    						$countCourses++;
-    						
-    						$users = api_substr($course , api_strpos($course,'[',1)+1 , api_strpos($course,']',1));
-    						$users = explode('|',$enreg['Users']);
-    						$countUsersCourses = 0;    						
-    						
-    						//Adding the relationship  Session - Course - User 
-    						foreach ($users as $user) {    								
-    							$user_id = UserManager::get_user_id_from_username($user);    											
-								if ($user_id!==false) {	    									    								
-	    							$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
-	    									id_user='$user_id',
-	    									course_code='$CourseCode',
-	    									id_session = '$session_id'";
-	    							$rsUsers = api_sql_query($sql,__FILE__,__LINE__);
-	    							$countUsersCourses++;
-    							} else {
-    								$errorMsg .= get_lang('UserDoesNotExist').' : '.$user.'<br />';
-    							}
-    						}
-    						api_sql_query("UPDATE $tbl_session_course SET nbr_users='$countUsersCourses' WHERE course_code='$CourseCode'",__FILE__,__LINE__);
-    					
-                            $c_info = CourseManager::get_course_information($CourseCode);
-                            $inserted_in_course[$CourseCode] = $c_info['title'];                        
-                     	} else {
-                     		//we should create the course as in the XML import                     		
-                     	}
-                        
-	                    if (CourseManager::course_exists($CourseCode,true)) {
-	                        $list = CourseManager :: get_courses_info_from_visual_code($CourseCode);
-	                        foreach ($list as $vcourse) {
-	                            if ($vcourse['code'] == $CourseCode) {
-	                                //ignore, this has already been inserted
-	                            } else {
-                                    $Coach = api_strstr($course,'[');
-                                    $Coach = api_substr($Coach,1,api_strpos($Coach,']')-1);
-	        
-	                                if(!empty($Coach)){
-	                                    $sqlCoach = "SELECT user_id FROM $tbl_user WHERE username='$Coach'";
-	                                    $rsCoach = api_sql_query($sqlCoach,__FILE__,__LINE__);
-	                                    list($Coach) = (Database::fetch_array($rsCoach));
-	                                } else {
-	                                    $Coach = '';
-	                                }
-            						//Adding the relationship  Session - Course
-	                                $sqlCourse = "INSERT IGNORE INTO $tbl_session_course SET
-	                                              course_code = '".$vcourse['code']."',
-	                                              id_coach='$Coach',
-	                                              id_session='$session_id'";
-	        
-	                                $rsCourse = api_sql_query($sqlCourse,__FILE__,__LINE__);
-	                                if(Database::affected_rows()){
-	                                    $countCourses++;
-                                        $users = api_substr($course , api_strpos($course,'[',1)+1 , api_strpos($course,']',1));
-	                                    $users = explode('|',$enreg['Users']);
-	                                    $countUsersCourses = 0;
-	                                    foreach ($users as $user){
-	                                        $sqlUser = "SELECT user_id FROM $tbl_user WHERE username='".$user."'";
-	                                        $rsUser = api_sql_query($sqlUser);
-	                                        list($user_id) = (Database::fetch_array($rsUser));
-	                                        $sql = "INSERT INTO $tbl_session_course_user SET
-	                                                id_user='$user_id',
-	                                                course_code='".$vcourse['code']."',
-	                                                id_session = '$session_id'";
-	                                        $rsUsers = api_sql_query($sql,__FILE__,__LINE__);
-	                                        if(Database::affected_rows())
-	                                            $countUsersCourses++;
-	                                    }
-	                                    api_sql_query("UPDATE $tbl_session_course SET nbr_users='$countUsersCourses' WHERE course_code='".$vcourse['code']."'",__FILE__,__LINE__);
-	                                }
-	                            }
-	                        }
-                        	$inserted_in_course[$vcourse['code']] = $vcourse['title'];                        
-                   		}
-					}
-					
-					$sql_update_users = "UPDATE $tbl_session SET nbr_users='$countUsers', nbr_courses='$countCourses' WHERE id='$session_id'";
-					api_sql_query($sql_update_users,__FILE__,__LINE__);
-				}
-			}
-		}
-		if(!empty($errorMsg)) {
-			$errorMsg = get_lang('ButProblemsOccured').' :<br />'.$errorMsg;
-		}
-
-        if (count($inserted_in_course)>1) {
-        	$warn = get_lang('SeveralCoursesSubscribedToSessionBecauseOfSameVisualCode').': ';
-            foreach ($inserted_in_course as $code => $title) {
-            	$warn .= ' '.$title.' ('.$code.'),';
-            }
-            $warn = substr($warn,0,-1);
-        }
-		if($countSessions == 1) {
-			header('Location: resume_session.php?id_session='.$session_id.'&warn='.urlencode($warn));
-			exit;
-		} else {
-			header('Location: session_list.php?action=show_message&message='.urlencode(get_lang('FileImported').' '.$errorMsg).'&warn='.urlencode($warn));
-			exit;
-		}
-	} else {
-		$errorMsg = get_lang('NoInputFile');
-	}
-}
-
-// display the header
-Display::display_header($tool_name);
-
-// display the tool title
-// api_display_tool_title($tool_name);
-
-if (count($inserted_in_course) > 1) {
-	$msg = get_lang('SeveralCoursesSubscribedToSessionBecauseOfSameVisualCode').': ';
-    foreach ($inserted_in_course as $code => $title) {
-    	$msg .= ' '.$title.' ('.$title.'),';
-    }
-    $msg = substr($msg,0,-1);
-    Display::display_warning_message($msg);
-}
-
-/*
- 
- update session by default is true
- <tr>
-  <td nowrap="nowrap" valign="top"><?php echo get_lang('UpdateSession'); ?> :</td>
-  <td>
-	<input class="checkbox" type="checkbox" name="updatesession" id="updatesession" value="true" />
-  </td>
-</tr>
-
- 
-  */
-?>
-
-<form method="post" action="<?php echo api_get_self(); ?>" enctype="multipart/form-data" 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">
-
-<?php
-if(!empty($errorMsg)) {
-?>
-<tr>
-  <td colspan="2">
-<?php
-	Display::display_normal_message($errorMsg,false); //main API
-?>
-  </td>
-</tr>
-<?php
-}
-?>
-<tr>
-  <td nowrap="nowrap"><?php echo get_lang('ImportFileLocation'); ?> :</td>
-  <td><input type="file" name="import_file" size="30"></td>
-</tr>
-<tr>
-  <td nowrap="nowrap" valign="top"><?php echo get_lang('FileType'); ?> :</td>
-  <td>
-	<input class="checkbox" type="radio" name="file_type" id="file_type_xml" value="xml" checked="checked" /> <label for="file_type_xml">XML</label> (<a href="example_session.xml" target="_blank"><?php echo get_lang('ExampleXMLFile'); ?></a>)<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> (<a href="example_session.csv" target="_blank"><?php echo get_lang('ExampleCSVFile'); ?></a>)<br>
-  </td>
-</tr>
-<tr>
-  <td nowrap="nowrap" valign="top"><?php echo get_lang('SendMailToUsers'); ?> :</td>
-  <td>
-	<input class="checkbox" type="checkbox" name="sendMail" id="sendMail" value="true" />
-  </td>
-</tr>
-
-
-
-
-<tr>
-  <td>&nbsp;</td>
-  <td>
-  <button class="save" type="submit" name="name" value="<?php echo get_lang('ImportSession') ?>"><?php echo get_lang('ImportSession') ?></button>
-  </td>
-</tr>
-</table>
-</form>
-
-<font color="gray">
-<p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
-
-<blockquote>
-<pre>
-<b>SessionName</b>;Coach;<b>DateStart</b>;<b>DateEnd</b>;Users;Courses
-<b>xxx1</b>;xxx;<b>xxx;xxx</b>;username1|username2;course1[coach1][username1,username2,...]|course2[coach1][username1,username2,...]
-<b>xxx2</b>;xxx;<b>xxx;xxx</b>;username1|username2;course1[coach1][username1,username2,...]|course2[coach1][username1,username2,...]
-</pre>
-</blockquote>
-
-<p><?php echo get_lang('XMLMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
-
-<blockquote>
-<pre>
-&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
-&lt;Sessions&gt;
-    &lt;Users&gt;
-        &lt;User&gt;
-            &lt;Username&gt;<b>username1</b>&lt;/Username&gt;
-            &lt;Lastname&gt;xxx&lt;/Lastname&gt;
-            &lt;Firstname&gt;xxx&lt;/Firstname&gt;
-            &lt;Password&gt;xxx&lt;/Password&gt;
-            &lt;Email&gt;xxx@xx.xx&lt;/Email&gt;
-            &lt;OfficialCode&gt;xxx&lt;/OfficialCode&gt;
-            &lt;Phone&gt;xxx&lt;/Phone&gt;
-            &lt;Status&gt;student|teacher&lt;/Status&gt;
-        &lt;/User&gt;
-    &lt;/Users&gt;
-    &lt;Courses&gt;
-        &lt;Course&gt;
-            &lt;CourseCode&gt;<b>xxx</b>&lt;/CourseCode&gt;
-            &lt;CourseTeacher&gt;xxx&lt;/CourseTeacher&gt;
-            &lt;CourseLanguage&gt;xxx&lt;/CourseLanguage&gt;
-            &lt;CourseTitle&gt;xxx&lt;/CourseTitle&gt;
-            &lt;CourseDescription&gt;xxx&lt;/CourseDescription&gt;
-        &lt;/Course&gt;
-    &lt;/Courses&gt;
-    &lt;Session&gt;
-        <b>&lt;SessionName&gt;xxx&lt;/SessionName&gt;</b>
-        &lt;Coach&gt;xxx&lt;/Coach&gt;
-        <b>&lt;DateStart&gt;xxx&lt;/DateStart&gt;</b>
-        <b>&lt;DateEnd&gt;xxx&lt;/DateEnd&gt;</b>
-        &lt;User&gt;xxx&lt;/User&gt;
-        &lt;User&gt;xxx&lt;/User&gt;
-    	&lt;Course&gt;
-    		&lt;CourseCode&gt;coursecode1&lt;/CourseCode&gt;
-    		&lt;Coach&gt;coach1&lt;/Coach&gt;
-		&lt;User&gt;username1&lt;/User&gt;
-		&lt;User&gt;username2&lt;/User&gt;
-    	&lt;/Course&gt;
-    &lt;/Session&gt;
-    
-    &lt;Session&gt;
-        <b>&lt;SessionName&gt;xxx&lt;/SessionName&gt;</b>
-        &lt;Coach&gt;xxx&lt;/Coach&gt;
-        <b>&lt;DateStart&gt;xxx&lt;/DateStart&gt;</b>
-        <b>&lt;DateEnd&gt;xxx&lt;/DateEnd&gt;</b>
-        &lt;User&gt;xxx&lt;/User&gt;
-        &lt;User&gt;xxx&lt;/User&gt;
-    	&lt;Course&gt;
-    		&lt;CourseCode&gt;coursecode1&lt;/CourseCode&gt;
-    		&lt;Coach&gt;coach1&lt;/Coach&gt;
-		&lt;User&gt;username1&lt;/User&gt;
-		&lt;User&gt;username2&lt;/User&gt;
-    	&lt;/Course&gt;
-    &lt;/Session&gt;
-&lt;/Sessions&gt;
-</pre>
-</blockquote>
-</font>
-<?php
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display::display_footer();
-?>
+<?php // $Id: session_import.php 20699 2009-05-15 16:32:03Z ivantcholakov $
+/* For licensing terms, see /dokeos_license.txt */
+/**
+==============================================================================
+*	@package dokeos.admin
+==============================================================================
+*/
+
+$language_file = array('admin', 'registration');
+$cidReset = true;
+
+require '../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).'usermanager.lib.php';
+require 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).'sessionmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'course.lib.php';
+
+$form_sent = 0;
+$error_message = ''; // Avoid conflict with the global variable $error_msg (array type) in add_course.conf.php.
+
+$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);
+
+$tool_name = get_lang('ImportSessionListXMLCSV');
+
+$interbreadcrumb[] = array('url' => 'index.php','name' => get_lang('AdministrationTools'));
+
+set_time_limit(0);
+
+// Set this option to true to enforce strict purification for usenames.
+$purification_option_for_usernames = false;
+
+$inserted_in_course = array();
+
+if ($_POST['formSent']) {
+	if (isset($_FILES['import_file']['tmp_name'])) {
+		$form_sent = $_POST['formSent'];
+		$file_type = $_POST['file_type'];
+		$send_mail = $_POST['sendMail'] ? 1 : 0;
+		//$updatesession = $_POST['updatesession'] ? 1 : 0;
+		$updatesession = 0;
+		$sessions = array();
+
+		$session_counter = 0;
+
+		if ($file_type == 'xml') {
+
+			///////////////////////
+			//XML/////////////////
+			/////////////////////
+
+			// SimpleXML for PHP5 deals with various encodings, but how many they are, what are version issues, do we need to waste time with configuration options?
+			// For avoiding complications we go some sort of "PHP4 way" - we convert the input xml-file into UTF-8 before passing it to the parser.
+			// Instead of:
+			// $root = @simplexml_load_file($_FILES['import_file']['tmp_name']);
+			// we may use the following construct:
+			// $root = @simplexml_load_string(api_utf8_encode_xml(file_get_contents($_FILES['import_file']['tmp_name'])));
+			// To ease debugging let us use:
+			$content = file_get_contents($_FILES['import_file']['tmp_name']);
+			$content = api_utf8_encode_xml($content);
+			$root = @simplexml_load_string($content);
+			unset($content);
+
+			if (is_object($root)) {
+				if (count($root->Users->User) > 0) {
+
+					// Creating/updating users from <Sessions> <Users> base node.
+					foreach ($root->Users->User as $node_user) {
+						$username = $username_old = trim(api_utf8_decode($node_user->Username));
+							$username = UserManager::purify_username($username, $purification_option_for_usernames);
+						if (UserManager::is_username_available($username)) {
+							if (UserManager::is_username_too_long($username_old)) {
+								$error_message .= get_lang('UsernameTooLongWasCut').' '.get_lang('From').' '.$username_old.' '.get_lang('To').' '.$username.' <br />';
+							}
+							$lastname = trim(api_utf8_decode($node_user->Lastname));
+							$firstname = trim(api_utf8_decode($node_user->Firstname));
+							$password = api_utf8_decode($node_user->Password);
+							if (empty($password)) {
+								$password = api_generate_password();
+							}
+							$email = trim(api_utf8_decode($node_user->Email));
+							$official_code = trim(api_utf8_decode($node_user->OfficialCode));
+							$phone = trim(api_utf8_decode($node_user->Phone));
+							$status = trim(api_utf8_decode($node_user->Status));
+							switch ($status) {
+								case 'student' : $status = 5; break;
+								case 'teacher' : $status = 1; break;
+								default : $status = 5; $error_message .= get_lang('StudentStatusWasGivenTo').' : '.$username.'<br />';
+							}
+
+							// Adding the current user to the platform.
+							$sql = "INSERT INTO $tbl_user SET
+									username = '".Database::escape_string($username)."',
+									lastname = '".Database::escape_string($lastname)."',
+									firstname = '".Database::escape_string($firstname)."',
+									password = '".(api_get_encrypted_password($password))."',
+									email = '".Database::escape_string($email)."',
+									official_code = '".Database::escape_string($official_code)."',
+									phone = '".Database::escape_string($phone)."',
+									status = '".Database::escape_string($status)."'";
+
+							// When it is applicable, adding the access_url rel user relationship too.
+							Database::query($sql, __FILE__, __LINE__);
+							$return = Database::insert_id();
+							global $_configuration;
+							require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
+							if ($_configuration['multiple_access_urls']) {
+								if (api_get_current_access_url_id() != -1) {
+									UrlManager::add_user_to_url($return, api_get_current_access_url_id());
+								} else {
+									UrlManager::add_user_to_url($return, 1);
+								}
+							} else {
+								// We add by default in the access_url_user table with access_url_id = 1.
+								UrlManager::add_user_to_url($return, 1);
+							}
+							// 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');
+								@api_mail($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
+							}
+						} else {
+							$lastname = trim(api_utf8_decode($node_user->Lastname));
+							$firstname = trim(api_utf8_decode($node_user->Firstname));
+							$password = api_utf8_decode($node_user->Password);
+							$email = trim(api_utf8_decode($node_user->Email));
+							$official_code = trim(api_utf8_decode($node_user->OfficialCode));
+							$phone = trim(api_utf8_decode($node_user->Phone));
+							$status = trim(api_utf8_decode($node_user->Status));
+							switch ($status) {
+								case 'student' : $status = 5; break;
+								case 'teacher' : $status = 1; break;
+								default : $status = 5; $error_message .= get_lang('StudentStatusWasGivenTo').' : '.$username.'<br />';
+							}
+
+							$sql = "UPDATE $tbl_user SET
+									lastname = '".Database::escape_string($lastname)."',
+									firstname = '".Database::escape_string($firstname)."',
+									".(empty($password) ? "" : "password = '".(api_get_encrypted_password($password))."',")."
+									email = '".Database::escape_string($email)."',
+									official_code = '".Database::escape_string($official_code)."',
+									phone = '".Database::escape_string($phone)."',
+									status = '".Database::escape_string($status)."'
+								WHERE username = '".Database::escape_string($username)."'";
+
+							Database::query($sql, __FILE__, __LINE__);
+						}
+					}
+				}
+
+				// Creating  courses from <Sessions> <Courses> base node.
+				if (count($root->Courses->Course) > 0) {
+					foreach ($root->Courses->Course as $courseNode) {
+						$course_code = trim(api_utf8_decode($courseNode->CourseCode));
+						$title = trim(api_utf8_decode($courseNode->CourseTitle));
+						$description = trim(api_utf8_decode($courseNode->CourseDescription));
+						$language = api_get_valid_language(api_utf8_decode($courseNode->CourseLanguage));
+						$username = trim(api_utf8_decode($courseNode->CourseTeacher));
+
+						// Looking up for the teacher.
+						$sql = "SELECT user_id, lastname, firstname FROM $tbl_user WHERE username='$username'";
+						$rs = Database::query($sql, __FILE__, __LINE__);
+						list($user_id, $lastname, $firstname) = Database::fetch_array($rs);
+						global $_configuration;
+						$keys = define_course_keys($course_code, '', $_configuration['db_prefix']);
+
+						if (sizeof($keys)) {
+							$current_course_code = $keys['visual_code'];
+							$current_course_id = $keys['currentCourseId'];
+							if (empty($current_course_code)) {
+								$current_course_code = $current_course_id;
+							}
+							$current_course_db_name = $keys['currentCourseDbName'];
+							$current_course_repository = $keys['currentCourseRepository'];
+
+							// Course creation.
+							if ($current_course_id == api_strtoupper($course_code)) {
+								if (empty ($title)) {
+									$title = $keys['currentCourseCode'];
+								}
+
+								prepare_course_repository($current_course_repository, $current_course_id);
+								update_Db_course($current_course_db_name);
+								$pictures_array = fill_course_repository($current_course_repository);
+
+								//fill_Db_course($current_course_db_name, $current_course_repository, 'english', $pictures_array);
+								//register_course($current_course_id, $current_course_code, $current_course_repository, $current_course_db_name, "$lastname $firstname", $course['unit_code'], addslashes($course['FR']['title']), $language, $user_id);
+								fill_Db_course($current_course_db_name, $current_course_repository, $language, $pictures_array);
+								register_course($current_course_id, $current_course_code, $current_course_repository, $current_course_db_name, api_get_person_name($firstname, $lastname, null, null, $language), null, addslashes($title), $language, $user_id);
+
+								$sql = "INSERT INTO ".$tbl_course." SET
+										code = '".$current_course_id."',
+										db_name = '".$current_course_db_name."',
+										directory = '".$current_course_repository."',
+										course_language = '".$language."',
+										title = '".$title."',
+										description = '".lang2db($description)."',
+										category_code = '',
+										visibility = '".$defaultVisibilityForANewCourse."',
+										show_score = '',
+										disk_quota = NULL,
+										creation_date = now(),
+										expiration_date = NULL,
+										last_edit = now(),
+										last_visit = NULL,
+										tutor_name = '".api_get_person_name($firstname, $lastname, null, null, $language)."',
+										visual_code = '".$current_course_code."'";
+
+								Database::query($sql, __FILE__, __LINE__);
+
+								$sql = "INSERT INTO ".$tbl_course_user." SET
+										course_code = '".$current_course_id."',
+										user_id = '".$user_id."',
+										status = '1',
+										role = '".lang2db('Professor')."',
+										tutor_id='1',
+										sort='". ($sort + 1)."',
+										user_course_cat='0'";
+
+								Database::query($sql, __FILE__, __LINE__);
+							}
+						}
+					}
+				}
+
+				// Creating sessions from <Sessions> base node.
+				if (count($root->Session) > 0) {
+					foreach ($root->Session as $node_session) {
+
+						$course_counter = 0;
+						$user_counter = 0;
+
+						$session_name = trim(api_utf8_decode($node_session->SessionName));
+						$coach = UserManager::purify_username(api_utf8_decode($node_session->Coach), $purification_option_for_usernames);
+
+						if (!empty($coach)) {
+							$coach_id = UserManager::get_user_id_from_username($coach);
+							if ($coach_id === false) {
+								$error_message .= get_lang('UserDoesNotExist').' : '.$coach.'<br />';
+								// Forcing the coach id if user does not exist.
+								$coach_id = api_get_user_id();
+							}
+						} else {
+							// Forcing the coach id.
+							$coach_id = api_get_user_id();
+						}
+
+						$date_start = trim(api_utf8_decode($node_session->DateStart)); // Just in case - encoding conversion.
+
+						if (!empty($date_start)) {
+							list($year_start, $month_start, $day_start) = explode('-', $date_start);
+							if(empty($year_start) || empty($month_start) || empty($day_start)) {
+								$error_message .= get_lang('WrongDate').' : '.$date_start.'<br />';
+								break;
+							} else {
+								$time_start = mktime(0, 0, 0, $month_start, $day_start, $year_start);
+							}
+
+							$date_end = trim(api_utf8_decode($node_session->DateEnd));
+							if (!empty($date_start)) {
+								list($year_end, $month_end, $day_end) = explode('-', $date_end);
+								if (empty($year_end) || empty($month_end) || empty($day_end)) {
+									$error_message .= get_lang('WrongDate').' : '.$date_end.'<br />';
+									break;
+								} else {
+									$time_end = mktime(0, 0, 0, $month_end, $day_end, $year_end);
+								}
+							}
+							if ($time_end - $time_start < 0) {
+								$error_message .= get_lang('StartDateShouldBeBeforeEndDate').' : '.$date_end.'<br />';
+							}
+						}
+
+						if (!$updatesession) {
+							// Always create a session.
+							$unique_name = false; // This MUST be initializead.
+							$i = 0;
+							// Change session name, verify that session doesn't exist.
+							while (!$unique_name) {
+								if ($i > 1) {
+									$suffix = ' - '.$i;
+								}
+								$sql = 'SELECT 1 FROM '.$tbl_session.' WHERE name="'.Database::escape_string($session_name.$suffix).'"';
+								$rs = Database::query($sql, __FILE__, __LINE__);
+								if (Database::result($rs, 0, 0)) {
+									$i++;
+								} else {
+									$unique_name = true;
+									$session_name .= $suffix;
+								}
+							}
+							// Creating the session.
+							$sql_session = "INSERT IGNORE INTO $tbl_session SET
+									name = '".Database::escape_string($session_name)."',
+									id_coach = '$coach_id',
+									date_start = '$date_start',
+									date_end = '$date_end',
+									session_admin_id=".intval($_user['user_id']);
+							$rs_session = Database::query($sql_session, __FILE__, __LINE__);
+							$session_id = Database::insert_id();
+							$session_counter++;
+
+						} else {
+							// Update the session if it is needed.
+							$my_session_result = SessionManager::get_session_by_name($session_name);
+							if ($my_session_result === false) {
+								// Creating the session.
+								$sql_session = "INSERT IGNORE INTO $tbl_session SET
+										name = '".Database::escape_string($session_name)."',
+										id_coach = '$coach_id',
+										date_start = '$date_start',
+										date_end = '$date_end',
+										session_admin_id=".intval($_user['user_id']);
+								$rs_session = Database::query($sql_session, __FILE__, __LINE__);
+								$session_id = Database::insert_id();
+								$session_counter++;
+							} else {
+								// if the session already exists - update it.
+								$sql_session = "UPDATE $tbl_session SET
+										id_coach = '$coach_id',
+										date_start = '$date_start',
+										date_end = '$date_end'
+									WHERE name = '$session_name'";
+								$rs_session = Database::query($sql_session, __FILE__, __LINE__);
+								$session_id = Database::query("SELECT id FROM $tbl_session WHERE name='$session_name'", __FILE__, __LINE__);
+								list($session_id) = Database::fetch_array($session_id);
+								Database::query("DELETE FROM $tbl_session_user WHERE id_session='$session_id'", __FILE__, __LINE__);
+								Database::query("DELETE FROM $tbl_session_course WHERE id_session='$session_id'", __FILE__, __LINE__);
+								Database::query("DELETE FROM $tbl_session_course_user WHERE id_session='$session_id'", __FILE__, __LINE__);
+							}
+						}
+
+						// Associate the session with access_url.
+						global $_configuration;
+						require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
+						if ($_configuration['multiple_access_urls']) {
+							$tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+							$access_url_id = api_get_current_access_url_id();
+							UrlManager::add_session_to_url($session_id, $access_url_id);
+						} else {
+							// We fill by default the access_url_rel_session table.
+							UrlManager::add_session_to_url($session_id, 1);
+						}
+
+						// Adding users to the new session.
+						foreach ($node_session->User as $node_user) {
+							$username = UserManager::purify_username(api_utf8_decode($node_user), $purification_option_for_usernames);
+							$user_id = UserManager::get_user_id_from_username($username);
+							if ($user_id !== false) {
+								$sql = "INSERT IGNORE INTO $tbl_session_user SET
+										id_user='$user_id',
+										id_session = '$session_id'";
+								$rs_user = Database::query($sql, __FILE__, __LINE__);
+								$user_counter++;
+							}
+						}
+
+						// Adding courses to a session.
+						foreach ($node_session->Course as $node_course) {
+							$course_code = Database::escape_string(trim(api_utf8_decode($node_course->CourseCode)));
+							// Verify that the course pointed by the course code node exists.
+							if (CourseManager::course_exists($course_code)) {
+								// If the course exists we continue.
+								$course_info = CourseManager::get_course_information($course_code);
+								// Searching the coach.
+								$coach = UserManager::purify_username(api_utf8_decode($node_course->Coach), $purification_option_for_usernames);
+								if (!empty($coach)) {
+									$coach_id = UserManager::get_user_id_from_username($coach);
+									if ($coach_id === false) {
+										$error_message .= get_lang('UserDoesNotExist').' : '.$coach.'<br />';
+										$coach_id = '';
+									}
+								} else {
+									$coach_id = '';
+								}
+								$session_course_relation = SessionManager::relation_session_course_exist($session_id, $course_code);
+								if (!$session_course_relation) {
+									$sql_course = "INSERT INTO $tbl_session_course SET
+											course_code = '$course_code',
+											id_coach='$coach_id',
+											id_session='$session_id'";
+									$rs_course = Database::query($sql_course, __FILE__, __LINE__);
+								}
+								if (Database::affected_rows()) {
+									$course_counter++;
+									$users_in_course_counter = 0;
+									foreach ($node_course->User as $node_user) {
+										$username = UserManager::purify_username(api_utf8_decode($node_user), $purification_option_for_usernames);
+										$user_id = UserManager::get_user_id_from_username($username);
+										if ($user_id !== false) {
+											// Adding to session_rel_user table.
+											$sql = "INSERT IGNORE INTO $tbl_session_user SET
+													id_user='$user_id',
+													id_session = '$session_id'";
+											$rs_user = Database::query($sql, __FILE__, __LINE__);
+											$user_counter++;
+											// Adding to session_rel_user_rel_course table.
+											$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
+													id_user='$user_id',
+													course_code='$course_code',
+													id_session = '$session_id'";
+											$rs_users = Database::query($sql, __FILE__, __LINE__);
+											$users_in_course_counter++;
+										} else {
+											$error_message .= get_lang('UserDoesNotExist').' : '.$username.'<br />';
+										}
+									}
+									$update_session_course = "UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='$course_code'";
+									Database::query($update_session_course, __FILE__, __LINE__);
+									$inserted_in_course[$course_code] = $course_info['title'];
+								}
+							}
+
+							if (CourseManager::course_exists($course_code, true)) {
+								// If the course exists we continue.
+								// 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 {
+										$coach = UserManager::purify_username(api_utf8_decode($node_course->Coach), $purification_option_for_usernames);
+										if (!empty($coach)) {
+											$coach_id = UserManager::get_user_id_from_username($coach);
+											if ($user_id === false) {
+												$error_message .= get_lang('UserDoesNotExist').' : '.$coach.'<br />';
+												$coach_id = '';
+											}
+										} else {
+											$coach_id = '';
+										}
+
+										$sql_course = "INSERT INTO $tbl_session_course SET
+												course_code = '".$vcourse['code']."',
+												id_coach='$coach_id',
+												id_session='$session_id'";
+										$rs_course = Database::query($sql_course, __FILE__, __LINE__);
+										if (Database::affected_rows()) {
+											$course_counter++;
+											$users_in_course_counter = 0;
+											foreach ($node_course->User as $node_user) {
+												$username = UserManager::purify_username(api_utf8_decode($node_user), $purification_option_for_usernames);
+												$user_id = UserManager::get_user_id_from_username($username);
+												if ($user_id !== false) {
+													$sql = "INSERT IGNORE INTO $tbl_session_user SET
+															id_user='$user_id',
+															id_session = '$session_id'";
+													$rs_user = Database::query($sql, __FILE__, __LINE__);
+													if (Database::affected_rows()) {
+														$user_counter++;
+													}
+													$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
+															id_user='$user_id',
+															course_code='".$vcourse['code']."',
+															id_session = '$session_id'";
+													$rs_users = Database::query($sql, __FILE__, __LINE__);
+													if (Database::affected_rows()) {
+														$users_in_course_counter++;
+													}
+												} else {
+													$error_message .= get_lang('UserDoesNotExist').' : '.$username.'<br />';
+												}
+											}
+											Database::query("UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='$course_code'",__FILE__,__LINE__);
+										}
+									}
+									$inserted_in_course[$vcourse['code']] = $vcourse['title'];
+								}
+							} else {
+								// Tthe course does not exist.
+								$error_message .= get_lang('CourseDoesNotExist').' : '.$course_code.'<br />';
+							}
+						}
+						Database::query("UPDATE $tbl_session SET nbr_users='$user_counter', nbr_courses='$course_counter' WHERE id='$session_id'", __FILE__, __LINE__);
+					}
+
+				}
+				if (empty($root->Users->User) && empty($root->Courses->Course) && empty($root->Session)) {
+					$error_message = get_lang('NoNeededData');
+				}
+			} else {
+				$error_message .= get_lang('XMLNotValid');
+			}
+		} else {
+
+			/////////////////////
+			// CSV /////////////
+			///////////////////
+
+			$content = file($_FILES['import_file']['tmp_name']);
+			if (!api_strstr($content[0], ';')) {
+				$error_message = get_lang('NotCSV');
+			} else {
+				$tag_names = array();
+
+				foreach ($content as $key => $enreg) {
+					$enreg = explode(';', trim($enreg));
+					if ($key) {
+						foreach ($tag_names as $tag_key => $tag_name) {
+							$sessions[$key - 1][$tag_name] = $enreg[$tag_key];
+						}
+					} else {
+						foreach ($enreg as $tag_name) {
+							$tag_names[] = api_eregi_replace('[^a-z0-9_-]', '', $tag_name);
+						}
+						if (!in_array('SessionName', $tag_names) || !in_array('DateStart', $tag_names) || !in_array('DateEnd', $tag_names)) {
+							$error_message = get_lang('NoNeededData');
+							break;
+						}
+					}
+				}
+				// looping the sessions
+				foreach ($sessions as $enreg) {
+					$user_counter = 0;
+					$course_counter = 0;
+
+					$session_name = $enreg['SessionName'];
+					$date_start = $enreg['DateStart'];
+					$date_end = $enreg['DateEnd'];
+
+					// searching a coach
+					if (!empty($enreg['Coach'])) {
+						$coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
+						if ($coach_id === false) {
+							// If the coach-user does not exist - I'm the coach.
+							$coach_id = api_get_user_id();
+						}
+					} else {
+						$coach_id = api_get_user_id();
+					}
+
+					if (!$updatesession) {
+						// Always create a session.
+						$unique_name = false; // This MUST be initializead.
+						$i = 0;
+						// Change session name, verify that session doesn't exist
+						while (!$unique_name) {
+							if ($i > 1) {
+								$suffix = ' - '.$i;
+							}
+							$sql = 'SELECT 1 FROM '.$tbl_session.' WHERE name="'.Database::escape_string($session_name.$suffix).'"';
+							$rs = Database::query($sql, __FILE__, __LINE__);
+
+							if (Database::result($rs, 0, 0)) {
+								$i++;
+							} else {
+								$unique_name = true;
+								$session_name .= $suffix;
+							}
+						}
+
+						// Creating the session.
+						$sql_session = "INSERT IGNORE INTO $tbl_session SET
+								name = '".Database::escape_string($session_name)."',
+								id_coach = '$coach_id',
+								date_start = '$date_start',
+								date_end = '$date_end',
+								session_admin_id=".intval($_user['user_id']);
+						$rs_session = Database::query($sql_session, __FILE__, __LINE__);
+						$session_id = Database::insert_id();
+						$session_counter++;
+					} else {
+						$my_session_result = SessionManager::get_session_by_name($session_name);
+						if ($my_session_result === false) {
+
+							// Creating a session.
+							$sql_session = "INSERT IGNORE INTO $tbl_session SET
+									name = '$session_name',
+									id_coach = '$coach_id',
+									date_start = '$date_start',
+									date_end = '$date_end'";
+							$rs_session = Database::query($sql_session, __FILE__, __LINE__);
+							// We get the last insert id.
+							$my_session_result = SessionManager::get_session_by_name($session_name);
+							$session_id = $my_session_result['id'];
+							//echo '<br>';
+						} else {
+							// The session already exists, update it then.
+							$sql_session = "UPDATE $tbl_session SET
+									id_coach = '$coach_id',
+									date_start = '$date_start',
+									date_end = '$date_end'
+								WHERE name = '$session_name'";
+							$rs_session = Database::query($sql_session, __FILE__, __LINE__);
+							$session_id = Database::query("SELECT id FROM $tbl_session WHERE name='$session_name'", __FILE__, __LINE__);
+							list($session_id) = Database::fetch_array($session_id);
+							Database::query("DELETE FROM $tbl_session_user WHERE id_session='$session_id'", __FILE__, __LINE__);
+							Database::query("DELETE FROM $tbl_session_course WHERE id_session='$session_id'", __FILE__, __LINE__);
+							Database::query("DELETE FROM $tbl_session_course_user WHERE id_session='$session_id'", __FILE__, __LINE__);
+						}
+						$session_counter++;
+					}
+
+					$users = explode('|', $enreg['Users']);
+
+					// Adding the relationship "Session - User".
+					if (is_array($users)) {
+						foreach ($users as $user) {
+							$user_id = UserManager::get_user_id_from_username($user);
+							if ($user_id !== false) {
+								// Insert new users.
+								$sql = "INSERT IGNORE INTO $tbl_session_user SET
+										id_user='$user_id',
+										id_session = '$session_id'";
+								$rs_user = Database::query($sql, __FILE__, __LINE__);
+								$user_counter++;
+							}
+						}
+					}
+
+					$courses = explode('|', $enreg['Courses']);
+
+					foreach ($courses as $course) {
+						$course_code = api_strtoupper(api_substr($course, 0, api_strpos($course, '[')));
+						if (CourseManager::course_exists($course_code)) {
+
+							// If the course exists we continue
+							$course_info = CourseManager::get_course_information($course_code);
+
+							$coach = api_strstr($course, '[');
+							$coach = api_substr($coach, 1, api_strpos($coach,']') - 1);
+
+							if (!empty($coach)) {
+								$coach_id = UserManager::get_user_id_from_username($coach);
+								if ($coach_id === false) {
+									$coach_id = '';
+								}
+							} else {
+								$coach = '';
+							}
+							// Adding the course to a session
+							$sql_course = "INSERT IGNORE INTO $tbl_session_course SET
+									course_code = '$course_code',
+									id_coach='$coach_id',
+									id_session='$session_id'";
+							$rs_course = Database::query($sql_course, __FILE__, __LINE__);
+							$course_counter++;
+
+							$users = api_substr($course, api_strpos($course, '[', 1) + 1 , api_strpos($course, ']', 1));
+							$users = explode('|', $enreg['Users']);
+							$users_in_course_counter = 0;
+
+							// Adding the relationship "Session - Course - User".
+							foreach ($users as $user) {
+								$user_id = UserManager::get_user_id_from_username($user);
+								if ($user_id !== false) {
+									$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
+											id_user='$user_id',
+											course_code='$course_code',
+											id_session = '$session_id'";
+									$rs_users = Database::query($sql, __FILE__, __LINE__);
+									$users_in_course_counter++;
+								} else {
+									$error_message .= get_lang('UserDoesNotExist').' : '.$user.'<br />';
+								}
+							}
+							Database::query("UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='$course_code'", __FILE__, __LINE__);
+
+							$course_info = CourseManager::get_course_information($course_code);
+							$inserted_in_course[$course_code] = $course_info['title'];
+						} else {
+							// TODO: We should create the course as in the XML import.
+						}
+
+						if (CourseManager::course_exists($course_code, true)) {
+							$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 {
+									$coach = api_strstr($course, '[');
+									$coach = api_substr($coach, 1, api_strpos($coach,']') - 1);
+
+									if (!empty($coach)) {
+										$sql_coach = "SELECT user_id FROM $tbl_user WHERE username='$coach'";
+										$rs_coach = Database::query($sql_coach,__FILE__,__LINE__);
+										list($coach) = (Database::fetch_array($rs_coach));
+									} else {
+										$coach = '';
+									}
+									// Adding the relationship "Session - Course".
+									$sql_course = "INSERT IGNORE INTO $tbl_session_course SET
+											course_code = '".$vcourse['code']."',
+											id_coach='$coach',
+											id_session='$session_id'";
+
+									$rs_course = Database::query($sql_course, __FILE__, __LINE__);
+									if (Database::affected_rows()) {
+										$course_counter++;
+										$users = api_substr($course , api_strpos($course,'[', 1) + 1, api_strpos($course,']', 1));
+										$users = explode('|', $enreg['Users']);
+										$users_in_course_counter = 0;
+										foreach ($users as $user) {
+											$sqlUser = "SELECT user_id FROM $tbl_user WHERE username='".$user."'";
+											$rs_user = Database::query($sqlUser);
+											list($user_id) = (Database::fetch_array($rs_user));
+											$sql = "INSERT INTO $tbl_session_course_user SET
+													id_user='$user_id',
+													course_code='".$vcourse['code']."',
+													id_session = '$session_id'";
+											$rs_users = Database::query($sql, __FILE__, __LINE__);
+											if (Database::affected_rows()) {
+												$users_in_course_counter++;
+											}
+										}
+										Database::query("UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='".$vcourse['code']."'", __FILE__, __LINE__);
+									}
+								}
+							}
+							$inserted_in_course[$vcourse['code']] = $vcourse['title'];
+						}
+					}
+
+					$sql_update_users = "UPDATE $tbl_session SET nbr_users='$user_counter', nbr_courses='$course_counter' WHERE id='$session_id'";
+					Database::query($sql_update_users, __FILE__, __LINE__);
+				}
+			}
+		}
+		if (!empty($error_message)) {
+			$error_message = get_lang('ButProblemsOccured').' :<br />'.$error_message;
+		}
+
+		if (count($inserted_in_course) > 1) {
+			$warn = get_lang('SeveralCoursesSubscribedToSessionBecauseOfSameVisualCode').': ';
+			foreach ($inserted_in_course as $code => $title) {
+				$warn .= ' '.$title.' ('.$code.'),';
+			}
+			$warn = substr($warn, 0, -1);
+		}
+		if ($session_counter == 1) {
+			header('Location: resume_session.php?id_session='.$session_id.'&warn='.urlencode($warn));
+			exit;
+		} else {
+			header('Location: session_list.php?action=show_message&message='.urlencode(get_lang('FileImported').' '.$error_message).'&warn='.urlencode($warn));
+			exit;
+		}
+	} else {
+		$error_message = get_lang('NoInputFile');
+	}
+}
+
+// display the header
+Display::display_header($tool_name);
+
+// display the tool title
+// api_display_tool_title($tool_name);
+
+if (count($inserted_in_course) > 1) {
+	$msg = get_lang('SeveralCoursesSubscribedToSessionBecauseOfSameVisualCode').': ';
+	foreach ($inserted_in_course as $code => $title) {
+		$msg .= ' '.$title.' ('.$title.'),';
+	}
+	$msg = substr($msg, 0, -1);
+	Display::display_warning_message($msg);
+}
+
+/*
+
+ update session by default is true
+ <tr>
+  <td nowrap="nowrap" valign="top"><?php echo get_lang('UpdateSession'); ?> :</td>
+  <td>
+	<input class="checkbox" type="checkbox" name="updatesession" id="updatesession" value="true" />
+  </td>
+</tr>
+
+
+  */
+?>
+
+<form method="post" action="<?php echo api_get_self(); ?>" enctype="multipart/form-data" 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">
+
+<?php
+if (!empty($error_message)) {
+?>
+<tr>
+  <td colspan="2">
+<?php
+	Display::display_normal_message($error_message, false);
+?>
+  </td>
+</tr>
+<?php
+}
+?>
+<tr>
+  <td nowrap="nowrap"><?php echo get_lang('ImportFileLocation'); ?> :</td>
+  <td><input type="file" name="import_file" size="30"></td>
+</tr>
+<tr>
+  <td nowrap="nowrap" valign="top"><?php echo get_lang('FileType'); ?> :</td>
+  <td>
+	<input class="checkbox" type="radio" name="file_type" id="file_type_xml" value="xml" checked="checked" /> <label for="file_type_xml">XML</label> (<a href="example_session.xml" target="_blank"><?php echo get_lang('ExampleXMLFile'); ?></a>)<br>
+	<input class="checkbox" type="radio" name="file_type" id="file_type_csv"  value="csv" <?php if ($form_sent && $file_type == 'csv') echo 'checked="checked"'; ?>> <label for="file_type_csv">CSV</label> (<a href="example_session.csv" target="_blank"><?php echo get_lang('ExampleCSVFile'); ?></a>)<br>
+  </td>
+</tr>
+<tr>
+  <td nowrap="nowrap" valign="top"><?php echo get_lang('SendMailToUsers'); ?> :</td>
+  <td>
+	<input class="checkbox" type="checkbox" name="sendMail" id="sendMail" value="true" />
+  </td>
+</tr>
+
+
+
+
+<tr>
+  <td>&nbsp;</td>
+  <td>
+  <button class="save" type="submit" name="name" value="<?php echo get_lang('ImportSession'); ?>"><?php echo get_lang('ImportSession'); ?></button>
+  </td>
+</tr>
+</table>
+</form>
+
+<font color="gray">
+<p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
+
+<blockquote>
+<pre>
+<b>SessionName</b>;Coach;<b>DateStart</b>;<b>DateEnd</b>;Users;Courses
+<b>xxx1</b>;xxx;<b>xxx;xxx</b>;username1|username2;course1[coach1][username1,username2,...]|course2[coach1][username1,username2,...]
+<b>xxx2</b>;xxx;<b>xxx;xxx</b>;username1|username2;course1[coach1][username1,username2,...]|course2[coach1][username1,username2,...]
+</pre>
+</blockquote>
+
+<p><?php echo get_lang('XMLMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
+
+<blockquote>
+<pre>
+&lt;?xml version=&quot;1.0&quot; encoding=&quot;<?php echo api_refine_encoding_id(api_get_system_encoding()); ?>&quot;?&gt;
+&lt;Sessions&gt;
+    &lt;Users&gt;
+        &lt;User&gt;
+            &lt;Username&gt;<b>username1</b>&lt;/Username&gt;
+            &lt;Lastname&gt;xxx&lt;/Lastname&gt;
+            &lt;Firstname&gt;xxx&lt;/Firstname&gt;
+            &lt;Password&gt;xxx&lt;/Password&gt;
+            &lt;Email&gt;xxx@xx.xx&lt;/Email&gt;
+            &lt;OfficialCode&gt;xxx&lt;/OfficialCode&gt;
+            &lt;Phone&gt;xxx&lt;/Phone&gt;
+            &lt;Status&gt;student|teacher&lt;/Status&gt;
+        &lt;/User&gt;
+    &lt;/Users&gt;
+    &lt;Courses&gt;
+        &lt;Course&gt;
+            &lt;CourseCode&gt;<b>xxx</b>&lt;/CourseCode&gt;
+            &lt;CourseTeacher&gt;xxx&lt;/CourseTeacher&gt;
+            &lt;CourseLanguage&gt;xxx&lt;/CourseLanguage&gt;
+            &lt;CourseTitle&gt;xxx&lt;/CourseTitle&gt;
+            &lt;CourseDescription&gt;xxx&lt;/CourseDescription&gt;
+        &lt;/Course&gt;
+    &lt;/Courses&gt;
+    &lt;Session&gt;
+        <b>&lt;SessionName&gt;xxx&lt;/SessionName&gt;</b>
+        &lt;Coach&gt;xxx&lt;/Coach&gt;
+        <b>&lt;DateStart&gt;xxx&lt;/DateStart&gt;</b>
+        <b>&lt;DateEnd&gt;xxx&lt;/DateEnd&gt;</b>
+        &lt;User&gt;xxx&lt;/User&gt;
+        &lt;User&gt;xxx&lt;/User&gt;
+    	&lt;Course&gt;
+    		&lt;CourseCode&gt;coursecode1&lt;/CourseCode&gt;
+    		&lt;Coach&gt;coach1&lt;/Coach&gt;
+		&lt;User&gt;username1&lt;/User&gt;
+		&lt;User&gt;username2&lt;/User&gt;
+    	&lt;/Course&gt;
+    &lt;/Session&gt;
+
+    &lt;Session&gt;
+        <b>&lt;SessionName&gt;xxx&lt;/SessionName&gt;</b>
+        &lt;Coach&gt;xxx&lt;/Coach&gt;
+        <b>&lt;DateStart&gt;xxx&lt;/DateStart&gt;</b>
+        <b>&lt;DateEnd&gt;xxx&lt;/DateEnd&gt;</b>
+        &lt;User&gt;xxx&lt;/User&gt;
+        &lt;User&gt;xxx&lt;/User&gt;
+    	&lt;Course&gt;
+    		&lt;CourseCode&gt;coursecode1&lt;/CourseCode&gt;
+    		&lt;Coach&gt;coach1&lt;/Coach&gt;
+		&lt;User&gt;username1&lt;/User&gt;
+		&lt;User&gt;username2&lt;/User&gt;
+    	&lt;/Course&gt;
+    &lt;/Session&gt;
+&lt;/Sessions&gt;
+</pre>
+</blockquote>
+</font>
+<?php
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display::display_footer();

+ 332 - 324
main/admin/session_list.php

@@ -1,324 +1,332 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2009 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
-==============================================================================
-*/
-
-$language_file='admin';
-$cidReset=true;
-
-include('../inc/global.inc.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-require_once (api_get_path(LIBRARY_PATH).'sessionmanager.lib.php');
-
-api_protect_admin_script(true);
-
-$htmlHeadXtra[] = '<script language="javascript">
-		
-				function selectAll(idCheck,numRows,action) {
-					
-					for(i=0;i<numRows;i++) {
-						idcheck = document.getElementById(idCheck+"_"+i);
-						if (action == "true"){
-							idcheck.checked = true;
-						} else {
-							idcheck.checked = false;
-						}		
-					}		
-							
-				}
-				
-				</script>
-		';
-
-$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);
-$tbl_session_rel_user=Database::get_main_table(TABLE_MAIN_SESSION_USER);
-$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
-
-$page=intval($_GET['page']);
-$action=$_REQUEST['action'];
-$sort=in_array($_GET['sort'],array('name','nbr_courses','date_start','date_end'))?$_GET['sort']:'name';
-$idChecked = $_REQUEST['idChecked'];
-
-if ($action == 'delete') {
-	SessionManager::delete_session($idChecked);
-	header('Location: '.api_get_self().'?sort='.$sort);
-	exit();
-}
-
-$interbreadcrumb[]=array("url" => "index.php","name" => get_lang('PlatformAdmin'));
-
-if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
-	
-	$interbreadcrumb[] = array ("url" => 'session_list.php', "name" => get_lang('SessionList'));
-	$tool_name = get_lang('SearchASession');
-	Display :: display_header($tool_name);
-	
-	$form = new FormValidator('advanced_search','get');
-	$form->addElement('header', '', $tool_name);
-	$active_group = array();
-	$active_group[] = $form->createElement('checkbox','active','',get_lang('Active'));
-	$active_group[] = $form->createElement('checkbox','inactive','',get_lang('Inactive'));
-	$form->addGroup($active_group,'',get_lang('ActiveSession'),'<br/>',false);
-	
-	$form->addElement('style_submit_button', 'submit',get_lang('SearchUsers'),'class="search"');
-	$defaults['active'] = 1;
-	$defaults['inactive'] = 1;
-	$form->setDefaults($defaults);
-	$form->display();
-	
-} else {
-	
-	$limit = 20;
-	$from = $page * $limit;
-	
-	//if user is crfp admin only list its sessions
-	if(!api_is_platform_admin()) {
-		$where = 'WHERE session_admin_id='.intval($_user['user_id']);
-		$where .= (empty($_REQUEST['keyword']) ? " " : " AND name LIKE '%".addslashes($_REQUEST['keyword'])."%'");
-	}
-	else {
-		$where .= (empty($_REQUEST['keyword']) ? " " : " WHERE name LIKE '%".addslashes($_REQUEST['keyword'])."%'");
-	}
-	
-	if(trim($where) == ''){
-		$and=" WHERE id_coach=user_id";
-	} else {
-		$and=" AND id_coach=user_id";
-	}
-	
-	if (isset($_REQUEST['active']) && !isset($_REQUEST['inactive']) ){
-		$and .= ' AND ( (session.date_start <= CURDATE() AND session.date_end >= CURDATE()) OR session.date_start="0000-00-00" ) ';
-		$cond_url = '&amp;active='.Security::remove_XSS($_REQUEST['active']);
-	}
-	if (!isset($_REQUEST['active']) && isset($_REQUEST['inactive']) ){
-		$and .= ' AND ( (session.date_start > CURDATE() OR session.date_end < CURDATE()) AND session.date_start<>"0000-00-00" ) ';
-		$cond_url = '&amp;inactive='.Security::remove_XSS($_REQUEST['inactive']);
-	}
-	
-	$query= "SELECT id,name,nbr_courses,date_start,date_end, firstname, lastname
-			FROM $tbl_session, $tbl_user
-			$where
-			$and
-			ORDER BY $sort
-			LIMIT $from,".($limit+1);
-			
-	//query which allows me to get a record without taking into account the page
-	$query_rows= "SELECT count(*) as total_rows
-				FROM $tbl_session, $tbl_user
-				$where
-				$and
-				ORDER BY $sort";
-				
-	
-	//filtering the session list by access_url
-	if ($_configuration['multiple_access_urls']==true){
-		$table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);	
-		$access_url_id = api_get_current_access_url_id();
-		if ($access_url_id != -1) {
-			$and.= " AND access_url_id = $access_url_id AND $table_access_url_rel_session.session_id = $tbl_session.id";
-			$query= "SELECT id,name,nbr_courses,date_start,date_end, firstname, lastname 
-				FROM $tbl_session, $tbl_user, $table_access_url_rel_session
-				$where
-				$and
-				ORDER BY $sort 
-				LIMIT $from,".($limit+1);
-				
-			$query_rows= "SELECT count(*) as total_rows
-				FROM $tbl_session, $tbl_user,$table_access_url_rel_session
-				$where
-				$and
-				ORDER BY $sort";
-		}
-	}
-	
-
-
-	$result_rows = api_sql_query($query_rows,__FILE__,__LINE__);
-	$recorset = Database::fetch_array($result_rows);
-	$num = $recorset['total_rows'];
-	
-	$result = api_sql_query($query,__FILE__,__LINE__);
-	$Sessions = api_store_result($result);
-	$nbr_results = sizeof($Sessions);
-	$tool_name = get_lang('SessionList');	
-	Display::display_header($tool_name);	
-	//api_display_tool_title($tool_name);
-    
-    if (!empty($_GET['warn'])) {
-        Display::display_warning_message(urldecode($_GET['warn']),false);
-    }
-    if(isset($_GET['action'])) {
-        Display::display_normal_message(stripslashes($_GET['message']),false);
-    }
-    ?>	
-	<div id="main">
-	<div class="actions">		
-	<?php
-		
-	echo '<div style="float:right;">
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/session_add.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddSession')).get_lang('AddSession').'</a>									
-	 </div>';	  
-	?>  
-	<form method="POST" action="session_list.php">
-		<input type="text" name="keyword" value="<?php echo Security::remove_XSS($_GET['keyword']); ?>"/>
-		<button class="search" type="submit" name="name" value="<?php echo get_lang('Search') ?>"><?php echo get_lang('Search') ?></button>
-		<a href="session_list.php?search=advanced"><?php echo get_lang('AdvancedSearch'); ?></a>
-		</form>
-	<form method="post" action="<?php echo api_get_self(); ?>?action=delete&sort=<?php echo $sort; ?>" onsubmit="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;">
-	 </div><br />
-	
-	<div align="left">	
-	<?php
-	if(count($Sessions)==0 && isset($_POST['keyword'])) {
-		echo get_lang('NoSearchResults');
-	} else {
-		if ($num > $limit) {
-			if ($page) {
-			?>
-			<a href="<?php echo api_get_self(); ?>?page=<?php echo $page-1; ?>&sort=<?php echo $sort; ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Previous'); ?></a>	
-			<?php
-			} else {
-				echo get_lang('Previous');
-			}
-			?>	
-			|
-			<?php
-			if($nbr_results > $limit) {
-				?>	
-				<a href="<?php echo api_get_self(); ?>?page=<?php echo $page+1; ?>&sort=<?php echo $sort; ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Next'); ?></a>	
-				<?php
-			} else {
-				echo get_lang('Next');
-			}
-		}
-		?>	
-	</div>
-		<br />
-		<table class="data_table" width="100%">
-		<tr>
-		  <th>&nbsp;</th>
-		  <th><a href="<?php echo api_get_self(); ?>?sort=name"><?php echo get_lang('NameOfTheSession'); ?></a></th>
-		  <th><a href="<?php echo api_get_self(); ?>?sort=nbr_courses"><?php echo get_lang('NumberOfCourses'); ?></a></th>
-		  <th><a href="<?php echo api_get_self(); ?>?sort=date_start"><?php echo get_lang('StartDate'); ?></a></th>
-		  <th><a href="<?php echo api_get_self(); ?>?sort=date_end"><?php echo get_lang('EndDate'); ?></a></th>
-		  <th><a href="<?php echo api_get_self(); ?>?sort=coach_name"><?php echo get_lang('Coach'); ?></a></th>
-		  <th><?php echo get_lang('Actions'); ?></th>
-		</tr>
-	
-		<?php
-		$i=0;
-		$x=0;
-		foreach ($Sessions as $key=>$enreg) {
-			if($key == $limit) {
-				break;
-			}
-			$sql = 'SELECT COUNT(course_code) FROM '.$tbl_session_rel_course.' WHERE id_session='.intval($enreg['id']);
-	
-		  	$rs = api_sql_query($sql, __FILE__, __LINE__);
-		  	list($nb_courses) = Database::fetch_array($rs);
-	
-		?>
-	
-		<tr class="<?php echo $i?'row_odd':'row_even'; ?>">
-		  <td><input type="checkbox" id="idChecked_<?php echo $x; ?>" name="idChecked[]" value="<?php echo $enreg['id']; ?>"></td>		  
-		  <td><a href="resume_session.php?id_session=<?php echo $enreg['id']; ?>"><?php echo api_htmlentities($enreg['name'],ENT_QUOTES,$charset); ?></a></td>
-		  <td><a href="session_course_list.php?id_session=<?php echo $enreg['id']; ?>"><?php echo $nb_courses; ?> cours</a></td>
-		  <td><?php echo api_htmlentities($enreg['date_start'],ENT_QUOTES,$charset); ?></td>
-		  <td><?php echo api_htmlentities($enreg['date_end'],ENT_QUOTES,$charset); ?></td>
-		  <td><?php echo api_htmlentities($enreg['firstname'],ENT_QUOTES,$charset).' '.api_htmlentities($enreg['lastname'],ENT_QUOTES,$charset); ?></td>
-		  <td>
-			<a href="add_users_to_session.php?page=session_list.php&id_session=<?php echo $enreg['id']; ?>"><?php Display::display_icon('add_user_big.gif', get_lang('SubscribeUsersToSession')); ?></a>
-			<a href="add_courses_to_session.php?page=session_list.php&id_session=<?php echo $enreg['id']; ?>"><?php Display::display_icon('synthese_view.gif', get_lang('SubscribeCoursesToSession')); ?></a>
-			<a href="session_edit.php?page=session_list.php&id=<?php echo $enreg['id']; ?>"><?php Display::display_icon('edit.gif', get_lang('Edit')); ?></a>
-			<a href="<?php echo api_get_self(); ?>?sort=<?php echo $sort; ?>&action=delete&idChecked=<?php echo $enreg['id']; ?>" onclick="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;"><?php Display::display_icon('delete.gif', get_lang('Delete')); ?></a>
-		  </td>
-		</tr>
-	
-		<?php
-			$i=$i ? 0 : 1;
-			$x++;
-		}
-	
-		unset($Sessions);
-	
-		?>
-	
-		</table>
-	
-		<br />
-	
-		<div align="left">
-	
-		<?php
-		
-		if ($num > $limit) {
-		if ($page)
-			{
-			?>
-		
-			<a href="<?php echo api_get_self(); ?>?page=<?php echo $page-1; ?>&sort=<?php echo $sort; ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Previous'); ?></a>
-		
-			<?php
-			}
-			else
-			{
-				echo get_lang('Previous');
-			}
-			?>
-		
-			|
-		
-			<?php
-			if($nbr_results > $limit)
-			{
-			?>
-		
-			<a href="<?php echo api_get_self(); ?>?page=<?php echo $page+1; ?>&sort=<?php echo $sort; ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Next'); ?></a>
-		
-			<?php
-			}
-			else
-			{
-				echo get_lang('Next');
-			}
-		}
-		?>
-	
-		</div>
-	
-		<br />
-		<a href="#" onclick="selectAll('idChecked',<?php echo $x; ?>,'true');return false;"><?php echo get_lang('SelectAll') ?></a>&nbsp;-&nbsp;
-		<a href="#" onclick="selectAll('idChecked',<?php echo $x; ?>,'false');return false;"><?php echo get_lang('UnSelectAll') ?></a>
-		<select name="action">
-		<option value="delete"><?php echo get_lang('DeleteSelectedSessions'); ?></option>
-		</select>
-		<button class="save" type="submit" name="name" value="<?php echo get_lang('Ok') ?>"><?php echo get_lang('Ok') ?></button>
-		<?php } ?>
-	</table>
-	
-	</div>
-
-<?php
-
-}
-
-Display::display_footer();
-?>
+<?php
+/* For licensing terms, see /dokeos_license.txt */
+$language_file='admin';
+$cidReset=true;
+
+include('../inc/global.inc.php');
+require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+require_once (api_get_path(LIBRARY_PATH).'sessionmanager.lib.php');
+
+$this_section = SECTION_PLATFORM_ADMIN;
+api_protect_admin_script(true);
+
+$htmlHeadXtra[] = '<script language="javascript">
+
+				function selectAll(idCheck,numRows,action) {
+
+					for(i=0;i<numRows;i++) {
+						idcheck = document.getElementById(idCheck+"_"+i);
+						if (action == "true"){
+							idcheck.checked = true;
+						} else {
+							idcheck.checked = false;
+						}
+					}
+
+				}
+
+				</script>
+		';
+
+$tbl_session=Database::get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_category=Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
+$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);
+$tbl_session_rel_user=Database::get_main_table(TABLE_MAIN_SESSION_USER);
+$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
+
+$page=intval($_GET['page']);
+$action=$_REQUEST['action'];
+$sort=in_array($_GET['sort'],array('name', 'nbr_courses', 'name_category', 'date_start', 'date_end','visibility'))?$_GET['sort']:'name';
+$idChecked = $_REQUEST['idChecked'];
+$id_category = intval($_REQUEST['id_category']);
+$cond_url = '';
+if ($action == 'delete') {
+	SessionManager::delete_session($idChecked);
+	header('Location: '.api_get_self().'?sort='.$sort);
+	exit();
+}
+
+$interbreadcrumb[]=array("url" => "index.php","name" => get_lang('PlatformAdmin'));
+
+if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
+
+	$interbreadcrumb[] = array ("url" => 'session_list.php', "name" => get_lang('SessionList'));
+	$tool_name = get_lang('SearchASession');
+	Display :: display_header($tool_name);
+
+	$form = new FormValidator('advanced_search','get');
+	$form->addElement('header', '', $tool_name);
+	$active_group = array();
+	$active_group[] = $form->createElement('checkbox','active','',get_lang('Active'));
+	$active_group[] = $form->createElement('checkbox','inactive','',get_lang('Inactive'));
+	$form->addGroup($active_group,'',get_lang('ActiveSession'),'<br/>',false);
+
+	$form->addElement('style_submit_button', 'submit',get_lang('Search'),'class="search"');
+	$defaults['active'] = 1;
+	$defaults['inactive'] = 1;
+	$form->setDefaults($defaults);
+	$form->display();
+
+} else {
+
+	$limit=20;
+	$from=$page * $limit;
+	$where = '';
+	//if user is crfp admin only list its sessions
+	if(!api_is_platform_admin()) {
+		$where = 'WHERE session_admin_id='.intval($_user['user_id']);
+		$where .= (empty($_REQUEST['keyword']) ? "" : " AND s.name LIKE '%".addslashes($_REQUEST['keyword'])."%'");
+	} else {
+		$where .= (empty($_REQUEST['keyword']) ? "" : " WHERE s.name LIKE '%".addslashes($_REQUEST['keyword'])."%'");
+	}
+	if (isset($_REQUEST['active']) && isset($_REQUEST['inactive'] )) {
+		// if both are set we search all sessions
+		$cond_url = '&amp;active='.Security::remove_XSS($_REQUEST['active']);
+		$cond_url .= '&amp;inactive='.Security::remove_XSS($_REQUEST['inactive']);
+	} else {
+		if (isset($_REQUEST['active'])) {
+			if (empty($where)) {
+				$where .= ' WHERE ( (s.date_start <= CURDATE() AND s.date_end >= CURDATE()) OR s.date_start="0000-00-00" ) ';	
+			} else {
+				$where .= ' AND ( (s.date_start <= CURDATE() AND s.date_end >= CURDATE()) OR s.date_start="0000-00-00" ) ';
+			}
+			$cond_url = '&amp;active='.Security::remove_XSS($_REQUEST['active']);
+		}
+		if (isset($_REQUEST['inactive'])) {
+			if (empty($where)) {
+				$where .= ' WHERE ( (s.date_start > CURDATE() OR s.date_end < CURDATE()) AND s.date_start<>"0000-00-00" ) ';
+			} else {
+				$where .= ' AND ( (s.date_start > CURDATE() OR s.date_end < CURDATE()) AND s.date_start<>"0000-00-00" ) ';
+			}	
+			$cond_url = '&amp;inactive='.Security::remove_XSS($_REQUEST['inactive']);
+		}
+	}
+	if(isset($_GET['id_category'])){
+		$where.= (empty($where))? ' AND ' : ' WHERE ';
+		$id_category = Security::remove_XSS($id_category); 
+		$where.= ' session_category_id = "'.$id_category.'" ';
+		$cond_url.= '&amp;id_category='.$id_category;	
+	}
+	$sort = ($sort != "name_category")?  's.'.$sort : 'category_name';
+	$query = "SELECT s.id, s.name, s.nbr_courses, s.date_start, s.date_end, u.firstname, u.lastname , sc.name as category_name, s.visibility
+			 FROM $tbl_session s 
+			 	LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id 
+			 	INNER JOIN $tbl_user u ON s.id_coach = u.user_id 
+			 $where 
+			 ORDER BY $sort ";
+	//query which allows me to get a record without taking into account the page
+	$query_rows = "SELECT count(*) as total_rows 
+			 FROM $tbl_session s 
+			 	LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
+			 	INNER JOIN $tbl_user u ON s.id_coach = u.user_id 
+			 $where ";
+
+//filtering the session list by access_url
+	if ($_configuration['multiple_access_urls'] == true){
+		$table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);	
+		$access_url_id = api_get_current_access_url_id();
+		if ($access_url_id != -1) {
+			$where.= " AND ar.access_url_id = $access_url_id ";
+			$query = "SELECT s.id, s.name, s.nbr_courses, s.date_start, s.date_end, u.firstname, u.lastname , sc.name as category_name , s.visibility
+			 FROM $tbl_session s 
+			 	LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
+			 	INNER JOIN $tbl_user u ON s.id_coach = u.user_id 
+				INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
+			 $where 
+			 ORDER BY $sort LIMIT $from,".($limit+1);
+
+			$query_rows = "SELECT count(*) as total_rows 
+			 FROM $tbl_session s 
+			 	LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id  
+			 	INNER JOIN $tbl_user u ON s.id_coach = u.user_id 
+			 	INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id 
+			 $where ";
+		}
+	}
+
+	$result_rows = Database::query($query_rows,__FILE__,__LINE__);
+	$recorset = Database::fetch_array($result_rows);
+	$num = $recorset['total_rows'];
+	$result=Database::query($query,__FILE__,__LINE__);
+	$Sessions=Database::store_result($result);
+	$nbr_results=sizeof($Sessions);
+	$tool_name = get_lang('SessionList');
+	Display::display_header($tool_name);
+	//api_display_tool_title($tool_name);
+
+    if (!empty($_GET['warn'])) {
+        Display::display_warning_message(urldecode($_GET['warn']),false);
+    }
+    if(isset($_GET['action'])) {
+        Display::display_normal_message(stripslashes($_GET['message']),false);
+    }
+	?>
+	<div class="actions">
+	<?php
+
+	echo '<div style="float:right;">
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/add_many_session_to_category.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddSessionsInCategories')).get_lang('AddSessionsInCategories').'</a>
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/session_add.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddSession')).get_lang('AddSession').'</a>									
+	  </div>';
+	?>
+	<form method="POST" action="session_list.php">
+		<input type="text" name="keyword" value="<?php echo Security::remove_XSS($_GET['keyword']); ?>"/>
+		<button class="search" type="submit" name="name" value="<?php echo get_lang('Search') ?>"><?php echo get_lang('Search') ?></button>
+		<a href="session_list.php?search=advanced"><?php echo get_lang('AdvancedSearch'); ?></a>
+		</form>
+	<form method="post" action="<?php echo api_get_self(); ?>?action=delete&sort=<?php echo $sort; ?>" onsubmit="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;">
+	 </div><br />
+
+	<div align="left">
+	<?php
+	if(count($Sessions)==0 && isset($_POST['keyword'])) {
+		echo get_lang('NoSearchResults');
+		echo '	</div>';
+	} else {
+		if($num>$limit){
+			if($page) {
+			?>
+			<a href="<?php echo api_get_self(); ?>?page=<?php echo $page-1; ?>&sort=<?php echo $sort; ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Previous'); ?></a>
+			<?php
+			} else {
+				echo get_lang('Previous');
+			}
+			?>
+			|
+			<?php
+			if($nbr_results > $limit) {
+				?>
+				<a href="<?php echo api_get_self(); ?>?page=<?php echo $page+1; ?>&sort=<?php echo $sort; ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Next'); ?></a>
+				<?php
+			} else {
+				echo get_lang('Next');
+			}
+		}
+		?>
+	</div>
+		<br />
+		<table class="data_table" width="100%">
+		<tr>
+		  <th>&nbsp;</th>
+		  <th><a href="<?php echo api_get_self(); ?>?sort=name"><?php echo get_lang('NameOfTheSession'); ?></a></th>
+		  <th><a href="<?php echo api_get_self(); ?>?sort=nbr_courses"><?php echo get_lang('NumberOfCourses'); ?></a></th>
+		  <th><a href="<?php echo api_get_self(); ?>?sort=name_category<?php echo $cond_url; ?>"><?php echo get_lang('SessionCategoryName'); ?></a></th>
+		  <th><a href="<?php echo api_get_self(); ?>?sort=date_start"><?php echo get_lang('StartDate'); ?></a></th>
+		  <th><a href="<?php echo api_get_self(); ?>?sort=date_end"><?php echo get_lang('EndDate'); ?></a></th>
+		  <th><a href="<?php echo api_get_self(); ?>?sort=coach_name"><?php echo get_lang('Coach'); ?></a></th>
+		  <th><a href="<?php echo api_get_self(); ?>?sort=visibility<?php echo $cond_url; ?>"><?php echo get_lang('Visibility'); ?></a></th>
+		  <th><?php echo get_lang('Actions'); ?></th>
+		</tr>
+
+		<?php
+		$i=0;
+		$x=0;
+		foreach ($Sessions as $key=>$enreg) {
+			if($key == $limit) {
+				break;
+			}
+			$sql = 'SELECT COUNT(course_code) FROM '.$tbl_session_rel_course.' WHERE id_session='.intval($enreg['id']);
+
+		  	$rs = Database::query($sql, __FILE__, __LINE__);
+		  	list($nb_courses) = Database::fetch_array($rs);
+
+		?>
+
+		<tr class="<?php echo $i?'row_odd':'row_even'; ?>">
+		  <td><input type="checkbox" id="idChecked_<?php echo $x; ?>" name="idChecked[]" value="<?php echo $enreg['id']; ?>"></td>
+	      <td><a href="resume_session.php?id_session=<?php echo $enreg['id']; ?>"><?php echo api_htmlentities($enreg['name'],ENT_QUOTES,$charset); ?></a></td>
+	      <td><a href="session_course_list.php?id_session=<?php echo $enreg['id']; ?>"><?php echo $nb_courses; ?> cours</a></td>
+	      <td><?php echo api_htmlentities($enreg['category_name'],ENT_QUOTES,$charset); ?></td>
+	      <td><?php echo api_htmlentities($enreg['date_start'],ENT_QUOTES,$charset); ?></td>
+	      <td><?php echo api_htmlentities($enreg['date_end'],ENT_QUOTES,$charset); ?></td>
+	      <td><?php echo api_htmlentities(api_get_person_name($enreg['firstname'], $enreg['lastname']),ENT_QUOTES,$charset); ?></td>
+		  <td><?php
+		  
+		  switch (intval($enreg['visibility'])) {
+				case SESSION_VISIBLE_READ_ONLY: //1
+					echo get_lang('ReadOnly');
+				break;
+				case SESSION_VISIBLE:			//2
+					echo get_lang('Visible');
+				break;
+				case SESSION_INVISIBLE:			//3
+					echo api_ucfirst(get_lang('Invisible'));
+				break;				 
+		  }
+		   
+		  
+		  ?></td>
+		  <td>
+			<a href="add_users_to_session.php?page=session_list.php&id_session=<?php echo $enreg['id']; ?>"><?php Display::display_icon('add_user_big.gif', get_lang('SubscribeUsersToSession')); ?></a>
+			<a href="add_courses_to_session.php?page=session_list.php&id_session=<?php echo $enreg['id']; ?>"><?php Display::display_icon('synthese_view.gif', get_lang('SubscribeCoursesToSession')); ?></a>
+			<a href="session_edit.php?page=session_list.php&id=<?php echo $enreg['id']; ?>"><?php Display::display_icon('edit.gif', get_lang('Edit')); ?></a>
+			<a href="<?php echo api_get_self(); ?>?sort=<?php echo $sort; ?>&action=delete&idChecked=<?php echo $enreg['id']; ?>" onclick="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;"><?php Display::display_icon('delete.gif', get_lang('Delete')); ?></a>
+		  </td>
+		</tr>
+
+		<?php
+			$i=$i ? 0 : 1;
+			$x++;
+		}
+
+		unset($Sessions);
+
+		?>
+
+		</table>
+
+		<br />
+
+		<div align="left">
+
+		<?php
+
+		if($num>$limit) {
+		if($page)
+			{
+			?>
+
+			<a href="<?php echo api_get_self(); ?>?page=<?php echo $page-1; ?>&sort=<?php echo $sort; ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Previous'); ?></a>
+
+			<?php
+			}
+			else
+			{
+				echo get_lang('Previous');
+			}
+			?>
+
+			|
+
+			<?php
+			if($nbr_results > $limit)
+			{
+			?>
+
+			<a href="<?php echo api_get_self(); ?>?page=<?php echo $page+1; ?>&sort=<?php echo $sort; ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Next'); ?></a>
+
+			<?php
+			}
+			else
+			{
+				echo get_lang('Next');
+			}
+		}
+		?>
+
+		</div>
+
+		<br />
+		<a href="javascript: void(0);" onclick="javascript: selectAll('idChecked',<?php echo $x; ?>,'true');return false;"><?php echo get_lang('SelectAll') ?></a>&nbsp;-&nbsp;
+		<a href="javascript: void(0);" onclick="javascript: selectAll('idChecked',<?php echo $x; ?>,'false');return false;"><?php echo get_lang('UnSelectAll') ?></a>
+		<select name="action">
+		<option value="delete"><?php echo get_lang('DeleteSelectedSessions'); ?></option>
+		</select>
+		<button class="save" type="submit" name="name" value="<?php echo get_lang('Ok') ?>"><?php echo get_lang('Ok') ?></button>
+		<?php } ?>
+	</table>
+<?php
+}
+Display::display_footer();
+?>

+ 295 - 253
main/admin/settings.php

@@ -42,7 +42,11 @@
 ==============================================================================
 */
 // name of the language file that needs to be included
-$language_file = 'admin';
+if ($_GET['category']=='Templates') {
+	$language_file = array('admin','document');
+} else {
+	$language_file = array('admin');
+}
 // resetting the course id
 $cidReset=true;
 // including some necessary dokeos files
@@ -76,18 +80,18 @@ $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAd
 $tool_name = get_lang('DokeosConfigSettings');
 
 // Build the form
-if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins', 'stylesheets', 'Search')))
+if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', 'stylesheets', 'Search')))
 {
 	$form = new FormValidator('settings', 'post', 'settings.php?category='.$_GET['category']);
 	$renderer = & $form->defaultRenderer();
 	$renderer->setHeaderTemplate('<div class="sectiontitle">{header}</div>'."\n");
 	$renderer->setElementTemplate('<div class="sectioncomment">{label}</div>'."\n".'<div class="sectionvalue">{element}</div>'."\n");
-	$my_category = mysql_real_escape_string($_GET['category']);
-	
+	$my_category = Database::escape_string($_GET['category']);
+
 	$sqlcountsettings = "SELECT COUNT(*) FROM $table_settings_current WHERE category='".$my_category."' AND type<>'checkbox'";
-	$resultcountsettings = api_sql_query($sqlcountsettings, __FILE__, __LINE__);
-	$countsetting = mysql_fetch_array($resultcountsettings);
-	 
+	$resultcountsettings = Database::query($sqlcountsettings, __FILE__, __LINE__);
+	$countsetting = Database::fetch_array($resultcountsettings);
+
 	if ($_configuration['access_url']==1)
 	{
 		$settings = api_get_settings($my_category,'group',$_configuration['access_url']);
@@ -98,9 +102,9 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 		if ($url_info['active']==1)
 		{
 			//the default settings of Dokeos
-			$settings = api_get_settings($my_category,'group',1,0);		
-			//the settings that are changeable from a particular site 
-			$settings_by_access = api_get_settings($my_category,'group',$_configuration['access_url'],1);			
+			$settings = api_get_settings($my_category,'group',1,0);
+			//the settings that are changeable from a particular site
+			$settings_by_access = api_get_settings($my_category,'group',$_configuration['access_url'],1);
 			//echo '<pre>';
 			//print_r($settings_by_access);
 			$settings_by_access_list=array();
@@ -117,36 +121,36 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 					$settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ]	[ $row['category'] ]  = $row;
 				else
 					$settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ]	[ $row['category'] ]  = array();
-			}	
+			}
 		}
 	}
 
 	//print_r($settings_by_access_list);echo '</pre>';
 	//$sqlsettings = "SELECT DISTINCT * FROM $table_settings_current WHERE category='$my_category' GROUP BY variable ORDER BY id ASC";
-	//$resultsettings = api_sql_query($sqlsettings, __FILE__, __LINE__);
-	//while ($row = mysql_fetch_array($resultsettings))
+	//$resultsettings = Database::query($sqlsettings, __FILE__, __LINE__);
+	//while ($row = Database::fetch_array($resultsettings))
 	$default_values = array();
-	foreach($settings as $row) {			
-
+	foreach($settings as $row) {
+		if ($row['variable'] == 'search_enabled') { continue; }
 		$anchor_name = $row['variable'].(!empty($row['subkey']) ? '_'.$row['subkey'] : '');
 		$form->addElement('html',"\n<a name=\"$anchor_name\"></a>\n");
 
-		($countsetting['0']%10) < 5 ?$b=$countsetting['0']-10:$b=$countsetting['0'];		
+		($countsetting['0']%10) < 5 ?$b=$countsetting['0']-10:$b=$countsetting['0'];
 		if ($i % 10 == 0 and $i<$b){
 			if ($_GET['category'] <> "Languages"){
 				$form->addElement('html','<div align="right">');
 				$form->addElement('style_submit_button', null,get_lang('SaveSettings'), 'class="save"');
 				$form->addElement('html','</div>');
-			}		
+			}
 		}
 		$i++;
 
 		$form->addElement('header', null, get_lang($row['title']));
-		
+
 		if ($row['access_url_changeable']=='1' && $_configuration['multiple_access_urls']==true) {
-			$form->addElement('html', '<div style="float:right;">'.Display::return_icon('shared_setting.png',get_lang('SharedSettingIconComment')).'</div>');						
-		}	
-		
+			$form->addElement('html', '<div style="float:right;">'.Display::return_icon('shared_setting.png',get_lang('SharedSettingIconComment')).'</div>');
+		}
+
 		$hideme=array();
 		$hide_element=false;
 		if ($_configuration['access_url']!=1)
@@ -159,35 +163,60 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 			}
 			elseif($url_info['active']==1)
 			{
-				// we show the elements 
+				// we show the elements
 				if (empty($row['variable']))
 					$row['variable']=0;
 				if (empty($row['subkey']))
 					$row['subkey']=0;
 				if (empty($row['category']))
 					$row['category']=0;
-					
+
 				if (is_array ($settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ]	[ $row['category'] ]))
 				{
-					// we are sure that the other site have a selected value 
-					if ($settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ]	[ $row['category'] ]['selected_value']!='')											
+					// we are sure that the other site have a selected value
+					if ($settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ]	[ $row['category'] ]['selected_value']!='')
 						$row['selected_value']	=$settings_by_access_list[$row['variable']] [$row['subkey']]	[ $row['category'] ]['selected_value'];
 				}
 				// there is no else because we load the default $row['selected_value'] of the main Dokeos site
-			}	
-		}	
-				
+			}
+		}
+
 		switch ($row['type']) {
-			case 'textfield' :	
+			case 'textfield' :
 				if ($row['variable']=='account_valid_duration') {
 					$form->addElement('text', $row['variable'], get_lang($row['comment']),array('maxlength'=>'5'));
-					$form->applyFilter($row['variable'],'html_filter');					
-					$default_values[$row['variable']] = $row['selected_value'];	
+					$form->applyFilter($row['variable'],'html_filter');
+					$default_values[$row['variable']] = $row['selected_value'];
+
+				// For platform character set selection: Conversion of the textfield to a select box with valid values.
+				} elseif ($row['variable'] == 'platform_charset') {
+					$current_system_encoding = api_refine_encoding_id(trim($row['selected_value']));
+					$valid_encodings = array_flip(api_get_valid_encodings());
+					if (!isset($valid_encodings[$current_system_encoding])) {
+						$is_alias_encoding = false;
+						foreach ($valid_encodings as $encoding) {
+							if (api_equal_encodings($encoding, $current_system_encoding)) {
+								$is_alias_encoding = true;
+								$current_system_encoding = $encoding;
+								break;
+							}
+						}
+						if (!$is_alias_encoding) {
+							$valid_encodings[$current_system_encoding] = $current_system_encoding;
+						}
+					}
+					foreach ($valid_encodings as $key => &$encoding) {
+						$encoding = api_is_encoding_supported($key) ? $key : $key.' (n.a.)';
+					}
+					$form->addElement('select', $row['variable'], get_lang($row['comment']), $valid_encodings);
+					$default_values[$row['variable']] = $current_system_encoding;
+				//
+
 				} else {
 					$form->addElement('text', $row['variable'], get_lang($row['comment']),$hideme);
 					$form->applyFilter($row['variable'],'html_filter');
-					$default_values[$row['variable']] = $row['selected_value'];		
-				}					
+					$default_values[$row['variable']] = $row['selected_value'];
+				}
 
 				break;
 			case 'textarea' :
@@ -203,7 +232,7 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 						if ($hide_element) {
 							$element->freeze();
 						}
-						$group[] = $element; 
+						$group[] = $element;
 					}
 				}
 				$form->addGroup($group, $row['variable'], get_lang($row['comment']), '<br />', false);
@@ -212,26 +241,27 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 			case 'checkbox';
 				//1. we collect all the options of this variable
 				$sql = "SELECT * FROM settings_current WHERE variable='".$row['variable']."' AND access_url =  1";
-				
-				$result = api_sql_query($sql, __FILE__, __LINE__);
-				$group = array ();	
+
+				$result = Database::query($sql, __FILE__, __LINE__);
+				$group = array ();
 				while ($rowkeys = Database::fetch_array($result)) {
+ 					if ($rowkeys['variable'] == 'course_create_active_tools' && $rowkeys['subkey'] == 'enable_search') {continue;}
 					$element = & $form->createElement('checkbox', $rowkeys['subkey'], '', get_lang($rowkeys['subkeytext']));
-					if ($row['access_url_changeable']==1) {						
+					if ($row['access_url_changeable']==1) {
 						//2. we look into the DB if there is a setting for a specific access_url
 						$access_url = $_configuration['access_url'];
 						if(empty($access_url )) $access_url =1;
-						$sql = "SELECT selected_value FROM settings_current WHERE variable='".$rowkeys['variable']."' AND subkey='".$rowkeys['subkey']."'  AND  subkeytext='".$rowkeys['subkeytext']."' AND access_url =  $access_url";						
-						$result_access = api_sql_query($sql, __FILE__, __LINE__);
+						$sql = "SELECT selected_value FROM settings_current WHERE variable='".$rowkeys['variable']."' AND subkey='".$rowkeys['subkey']."'  AND  subkeytext='".$rowkeys['subkeytext']."' AND access_url =  $access_url";
+						$result_access = Database::query($sql, __FILE__, __LINE__);
 						$row_access = Database::fetch_array($result_access);
 						if ($row_access['selected_value'] == 'true' && ! $form->isSubmitted()) {
-							$element->setChecked(true); 
+							$element->setChecked(true);
 						}
-					} else {											
+					} else {
 						if ($rowkeys['selected_value'] == 'true' && ! $form->isSubmitted()) {
-							$element->setChecked(true); 
+							$element->setChecked(true);
 						}
-					}					
+					}
 					if ($hide_element) {
 						$element->freeze();
 					}
@@ -259,41 +289,41 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 		// will be set to false.
 		$r = api_set_settings_category($my_category,'false',$_configuration['access_url']);
 		//$sql = "UPDATE $table_settings_current SET selected_value='false' WHERE category='$my_category' AND type='checkbox'";
-		//$result = api_sql_query($sql, __FILE__, __LINE__);
+		//$result = Database::query($sql, __FILE__, __LINE__);
 		// Save the settings
 		$keys = array();
 		foreach ($values as $key => $value)
 		{
 			if (!is_array($value))
 			{
-				//$sql = "UPDATE $table_settings_current SET selected_value='".mysql_real_escape_string($value)."' WHERE variable='$key'";
-				//$result = api_sql_query($sql, __FILE__, __LINE__);
-				
-				if (api_get_setting($key) != $value) $keys[] = $key;	
-																
-				$result = api_set_setting($key,$value,null,null,$_configuration['access_url']);												
+				//$sql = "UPDATE $table_settings_current SET selected_value='".Database::escape_string($value)."' WHERE variable='$key'";
+				//$result = Database::query($sql, __FILE__, __LINE__);
+
+				if (api_get_setting($key) != $value) $keys[] = $key;
+
+				$result = api_set_setting($key,$value,null,null,$_configuration['access_url']);
 
 			}
 			else
 			{
-				
+
 				$sql = "SELECT subkey FROM $table_settings_current WHERE variable = '$key'";
-				$res = api_sql_query($sql,__FILE__,__LINE__);
+				$res = Database::query($sql,__FILE__,__LINE__);
 				$subkeys = array();
 				while ($row_subkeys = Database::fetch_array($res)) {
-					// if subkey is changed					
+					// if subkey is changed
 					if ( (isset($value[$row_subkeys['subkey']]) && api_get_setting($key,$row_subkeys['subkey']) == 'false') ||
 						 (!isset($value[$row_subkeys['subkey']]) && api_get_setting($key,$row_subkeys['subkey']) == 'true')) {
 						$keys[] = $key;
-						break;	
-					} 																		
+						break;
+					}
 				}
 
 				foreach ($value as $subkey => $subvalue)
 				{
 
 					//$sql = "UPDATE $table_settings_current SET selected_value='true' WHERE variable='$key' AND subkey = '$subkey'";
-					//$result = api_sql_query($sql, __FILE__, __LINE__);
+					//$result = Database::query($sql, __FILE__, __LINE__);
 
 					$result = api_set_setting($key,'true',$subkey,null,$_configuration['access_url']);
 
@@ -301,19 +331,19 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 			}
 		}
 
-		// add event configuration settings category to system log		
+		// add event configuration settings category to system log
 		$time = time();
-		$user_id = api_get_user_id();		
-		$category = $_GET['category']; 		
+		$user_id = api_get_user_id();
+		$category = $_GET['category'];
 		event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, $time, $user_id);
-		
 
-		// add event configuration settings variable to system log				
-		if (is_array($keys) && count($keys) > 0) {			
-			foreach($keys as $variable) {																	
-					event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_VARIABLE, $variable, $time, $user_id);				
+
+		// add event configuration settings variable to system log
+		if (is_array($keys) && count($keys) > 0) {
+			foreach($keys as $variable) {
+					event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_VARIABLE, $variable, $time, $user_id);
 			}
-		}			
+		}
 
 		header('Location: settings.php?action=stored&category='.Security::remove_XSS($_GET['category']));
 		exit;
@@ -348,10 +378,10 @@ $action_images['search']        = 'search.gif';
 
 // grabbing the categories
 //$selectcategories = "SELECT DISTINCT category FROM ".$table_settings_current." WHERE category NOT IN ('stylesheets','Plugins')";
-//$resultcategories = api_sql_query($selectcategories, __FILE__, __LINE__);
+//$resultcategories = Database::query($selectcategories, __FILE__, __LINE__);
 $resultcategories = api_get_settings_categories(array('stylesheets','Plugins', 'Templates', 'Search'));
 echo "\n<div class=\"actions\">";
-//while ($row = mysql_fetch_array($resultcategories))
+//while ($row = Database::fetch_array($resultcategories))
 foreach($resultcategories as $row)
 {
 	echo "\n\t<a href=\"".api_get_self()."?category=".$row['category']."\">".Display::return_icon($action_images[strtolower($row['category'])], api_ucfirst(get_lang($row['category']))).api_ucfirst(get_lang($row['category']))."</a>";
@@ -362,7 +392,7 @@ echo "\n\t<a href=\"".api_get_self()."?category=Templates\">".Display::return_ic
 echo "\n\t<a href=\"".api_get_self()."?category=Search\">".Display::return_icon($action_images['search'], api_ucfirst(get_lang('Search'))).api_ucfirst(get_lang('Search'))."</a>";
 echo "\n</div>";
 
-if (isset ($_GET['category']))
+if (!empty($_GET['category']))
 {
 	switch ($_GET['category'])
 	{
@@ -380,7 +410,7 @@ if (isset ($_GET['category']))
             break;
 		case 'Templates' :
 			handle_templates();
-			break;            
+			break;
 		default :
 			$form->display();
 	}
@@ -408,7 +438,7 @@ function get_settings_options($var)
 {
 	$table_settings_options = Database :: get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
 	$sql = "SELECT * FROM $table_settings_options WHERE variable='$var'";
-	$result = api_sql_query($sql, __FILE__, __LINE__);
+	$result = Database::query($sql, __FILE__, __LINE__);
 	while ($row = Database::fetch_array($result))
 	{
 		$temp_array = array ('value' => $row['value'], 'display_text' => $row['display_text']);
@@ -430,11 +460,11 @@ function handle_plugins()
 
 	if (isset($_POST['submit_plugins']))
 	{
-		store_plugins();		
-		// add event to system log		
+		store_plugins();
+		// add event to system log
 		$time = time();
-		$user_id = api_get_user_id();		
-		$category = $_GET['category']; 		
+		$user_id = api_get_user_id();
+		$category = $_GET['category'];
 		event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, $time, $user_id);
 
 		Display :: display_normal_message(get_lang('SettingsStored'));
@@ -498,9 +528,9 @@ function handle_plugins()
 
 	/* We retrieve all the active plugins. */
 	//$sql = "SELECT * FROM $table_settings_current WHERE category='Plugins'";
-	//$result = api_sql_query($sql);
+	//$result = Database::query($sql);
 	$result = api_get_settings('Plugins');
-	//while ($row = mysql_fetch_array($result))
+	//while ($row = Database::fetch_array($result))
 	foreach($result as $row)
 	{
 		$usedplugins[$row['variable']][] = $row['selected_value'];
@@ -561,7 +591,7 @@ function display_plugin_cell($location, $plugin_info, $current_plugin, $active_p
 	echo "\t\t<td align=\"center\">\n";
 	if (in_array($location, $plugin_info['location']))
 	{
-		if (isset($active_plugins[$location]) && is_array($active_plugins[$location]) 
+		if (isset($active_plugins[$location]) && is_array($active_plugins[$location])
 			&& in_array($current_plugin, $active_plugins[$location]))
 		{
 			$checked = "checked";
@@ -585,32 +615,32 @@ function handle_stylesheets()
 	// Current style
 	$currentstyle = api_get_setting('stylesheets');
 	$is_style_changeable=false;
-	
-	
+
+
 	if ($_configuration['access_url']!=1)
 	{
 		$style_info = api_get_settings('stylesheets','',1,0);
-		$url_info = api_get_access_url($_configuration['access_url']);	 
+		$url_info = api_get_access_url($_configuration['access_url']);
 		if ($style_info[0]['access_url_changeable']==1 && $url_info['active']==1)
 		{
-			$is_style_changeable=true;	
-			echo '<div class="actions" id="stylesheetuploadlink">';	
-			Display::display_icon('theme_add.gif');	
+			$is_style_changeable=true;
+			echo '<div class="actions" id="stylesheetuploadlink">';
+			Display::display_icon('theme_add.gif');
 			echo '<a href="" onclick="document.getElementById(\'newstylesheetform\').style.display = \'block\'; document.getElementById(\'stylesheetuploadlink\').style.display = \'none\';return false; ">'.get_lang('UploadNewStylesheet').'</a>';
 			echo '</div>';
-		} 
+		}
 	}
 	else
 	{
 		$is_style_changeable=true;
-		echo '<div class="actions" id="stylesheetuploadlink">';	
+		echo '<div class="actions" id="stylesheetuploadlink">';
 		Display::display_icon('theme_add.gif');
 		echo '<a href="" onclick="document.getElementById(\'newstylesheetform\').style.display = \'block\'; document.getElementById(\'stylesheetuploadlink\').style.display = \'none\';return false; ">'.get_lang('UploadNewStylesheet').'</a>';
 		echo '</div>';
-	}	
-		
+	}
+
 	$form = new FormValidator('stylesheet_upload','post','settings.php?category=stylesheets&showuploadform=true');
-	$form->addElement('text','name_stylesheet',get_lang('NameStylesheet'),array('size' => '40', 'maxlength' => '40'));	
+	$form->addElement('text','name_stylesheet',get_lang('NameStylesheet'),array('size' => '40', 'maxlength' => '40'));
 	$form->addRule('name_stylesheet', get_lang('ThisFieldIsRequired'), 'required');
 	$form->addElement('file', 'new_stylesheet', get_lang('UploadNewStylesheet'));
 	$allowed_file_types = array ('css');
@@ -623,41 +653,41 @@ function handle_stylesheets()
 		$picture_element = & $form->getElement('new_stylesheet');
 		$picture = $picture_element->getValue();
 		upload_stylesheet($values, $picture);
-		
-		// add event to system log		
+
+		// add event to system log
 		$time = time();
-		$user_id = api_get_user_id();		
-		$category = $_GET['category']; 		
+		$user_id = api_get_user_id();
+		$category = $_GET['category'];
 		event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, $time, $user_id);
-		
+
 		Display::display_confirmation_message(get_lang('StylesheetAdded'));
 	}
-	else 
+	else
 	{
 		if (!is_writable(api_get_path(SYS_CODE_PATH).'css/'))
 		{
 			Display::display_error_message(api_get_path(SYS_CODE_PATH).'css/'.get_lang('IsNotWritable'));
 		}
-		else 
+		else
 		{
 			if ($_GET['showuploadform'] == 'true')
 			{
 				echo '<div id="newstylesheetform">';
 			}
-			else 
+			else
 			{
 				echo '<div id="newstylesheetform" style="display: none;">';
 			}
 				// uploading a new stylesheet
 			if ($_configuration['access_url']==1)
 			{
-				$form->display();	
+				$form->display();
 			}
 			else
 			{
 				if ($is_style_changeable)
 				{
-					$form->display();				
+					$form->display();
 				}
 			}
 			echo '</div>';
@@ -691,9 +721,9 @@ function handle_stylesheets()
 						$selected = '';
 					}
 					$show_name=get_lang(str_replace(' ','', ucwords(str_replace('_',' ', $style_dir))), '');
-					
+
 					if ($is_style_changeable)
-					{					
+					{
 						echo "<input type=\"radio\" name=\"style\" value=\"".$style_dir."\" ".$selected." onClick=\"parent.preview.location='style_preview.php?style=".$style_dir."';\"/>";
 						echo '<a href="style_preview.php?style='.$style_dir.'" target="preview">'.$show_name.'</a>';
 					}
@@ -710,7 +740,7 @@ function handle_stylesheets()
 		@closedir($handle);
 	}
 	if ($is_style_changeable)
-	{	
+	{
 		echo '<button class="save" type="submit" name="submit_stylesheets"> '.get_lang('SaveSettings').' </button></form>';
 	}
 }
@@ -720,7 +750,7 @@ function handle_stylesheets()
  *
  * @param array $values the values of the form
  * @param array $picture the values of the uploaded file
- * 
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version May 2008
  * @since Dokeos 1.8.5
@@ -729,7 +759,7 @@ function upload_stylesheet($values,$picture)
 {
 	// valid name for the stylesheet folder
 	$style_name = api_ereg_replace("[^A-Za-z0-9]", "", $values['name_stylesheet'] );
-	
+
 	// create the folder if needed
 	if(!is_dir(api_get_path(SYS_CODE_PATH).'css/'.$style_name.'/'))
 	{
@@ -738,9 +768,9 @@ function upload_stylesheet($values,$picture)
 			$perm = api_get_setting('permissions_for_new_directories');
 			$perm = octdec(!empty($perm)?$perm:'0770');
 			chmod(api_get_path(SYS_CODE_PATH).'css/'.$style_name.'/', $perm);
-		}		
+		}
 	}
-	
+
 	// move the file in the folder
 	move_uploaded_file($picture['tmp_name'], api_get_path(SYS_CODE_PATH).'css/'.$style_name.'/'.$picture['name']);
 }
@@ -757,7 +787,7 @@ function store_plugins()
 
 	// Step 1 : we remove all the plugins
 	//$sql = "DELETE FROM $table_settings_current WHERE category='Plugins'";
-	//api_sql_query($sql, __LINE__, __FILE__);
+	//Database::query($sql, __LINE__, __FILE__);
 	$r = api_delete_category_settings('Plugins',$_configuration['access_url']);
 
 	// step 2: looping through all the post values we only store these which are really a valid plugin location.
@@ -767,8 +797,8 @@ function store_plugins()
 		if (is_valid_plugin_location($form_name_elements[1]))
 		{
 			//$sql = "INSERT into $table_settings_current (variable,category,selected_value) VALUES ('".$form_name_elements['1']."','Plugins','".$form_name_elements['0']."')";
-			//api_sql_query($sql, __LINE__, __FILE__);
-			api_add_setting($form_name_elements['0'],$form_name_elements['1'],$form_name_elements['0'],null,'Plugins',$form_name_elements['0'],null,null,null,$_configuration['access_url'],1);			
+			//Database::query($sql, __LINE__, __FILE__);
+			api_add_setting($form_name_elements['0'],$form_name_elements['1'],$form_name_elements['0'],null,'Plugins',$form_name_elements['0'],null,null,null,$_configuration['access_url'],1);
 		}
 	}
 }
@@ -811,9 +841,9 @@ function store_stylesheets()
 				WHERE variable = "stylesheets"
 				AND category = "stylesheets"';
 
-		api_sql_query($sql, __LINE__, __FILE__);
+		Database::query($sql, __LINE__, __FILE__);
 		*/
-		
+
 		api_set_setting('stylesheets',$style,null,'stylesheets',$_configuration['access_url']);
 	}
 
@@ -908,7 +938,7 @@ function handle_search() {
 
 /**
  * wrapper for the templates
- * 
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version August 2008
  * @since Dokeos 1.8.6
@@ -923,21 +953,21 @@ function handle_templates()
 
 	if ($_GET['action'] == 'add' OR ( $_GET['action'] == 'edit' AND is_numeric($_GET['id']))) {
 		add_edit_template();
-		
-		// add event to system log		
+
+		// add event to system log
 		$time = time();
-		$user_id = api_get_user_id();		
-		$category = $_GET['category']; 		
+		$user_id = api_get_user_id();
+		$category = $_GET['category'];
 		event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, $time, $user_id);
-		
+
 	} else {
 		if ($_GET['action'] == 'delete' and is_numeric($_GET['id'])) {
 			delete_template($_GET['id']);
-			
-			// add event to system log		
+
+			// add event to system log
 			$time = time();
-			$user_id = api_get_user_id();		
-			$category = $_GET['category']; 		
+			$user_id = api_get_user_id();
+			$category = $_GET['category'];
 			event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, $time, $user_id);
 		}
 		display_templates();
@@ -954,20 +984,20 @@ function handle_templates()
 function display_templates()
 {
 	$table = new SortableTable('templates', 'get_number_of_templates', 'get_template_data',1);
-	$table->set_additional_parameters(array('category'=>$_GET['category']));
+	$table->set_additional_parameters(array('category'=>Security::remove_XSS($_GET['category'])));
 	$table->set_header(0, get_lang('Image'), true, array ('style' => 'width:101px;'));
 	$table->set_header(1, get_lang('Title'));
-	$table->set_header(2, get_lang('Actions'), false, array ('style' => 'width:30px;'));	
+	$table->set_header(2, get_lang('Actions'), false, array ('style' => 'width:50px;'));
 	$table->set_column_filter(2,'actions_filter');
 	$table->set_column_filter(0,'image_filter');
-	$table->display();	
+	$table->display();
 }
 
 /**
- * Get the number of templates that are defined by the platform admin. 
+ * Get the number of templates that are defined by the platform admin.
+ *
+ * @return integer
  *
- * @return integer 
- * 
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version August 2008
  * @since Dokeos 1.8.6
@@ -976,12 +1006,12 @@ function get_number_of_templates()
 {
 	// Database table definition
 	$table_system_template = Database :: get_main_table('system_template');
-	
+
 	// The sql statement
 	$sql = "SELECT COUNT(id) AS total FROM $table_system_template";
-	$result = api_sql_query($sql, __FILE__, __LINE__);
+	$result = Database::query($sql, __FILE__, __LINE__);
 	$row = Database::fetch_array($result);
-	
+
 	// returning the number of templates
 	return $row['total'];
 }
@@ -991,10 +1021,10 @@ function get_number_of_templates()
  *
  * @param integer $from the start of the limit statement
  * @param integer $number_of_items the number of elements that have to be retrieved from the database
- * @param integer $column the column that is 
+ * @param integer $column the column that is
  * @param string $direction the sorting direction (ASC or DESC�
- * @return array 
- * 
+ * @return array
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version August 2008
  * @since Dokeos 1.8.6
@@ -1003,17 +1033,16 @@ function get_template_data($from, $number_of_items, $column, $direction)
 {
 	// Database table definition
 	$table_system_template = Database :: get_main_table('system_template');
-	
+
 	// the sql statement
 	$sql = "SELECT image as col0, title as col1, id as col2 FROM $table_system_template";
 	$sql .= " ORDER BY col$column $direction ";
-	$sql .= " LIMIT $from,$number_of_items";	
-	$result = api_sql_query($sql, __FILE__, __LINE__);
-	while ($row = Database::fetch_array($result))
-	{
+	$sql .= " LIMIT $from,$number_of_items";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	while ($row = Database::fetch_array($result)) {
+		$row['1'] = get_lang($row['1']);
 		$return[]=$row;
 	}
-	
 	// returning all the information for the sortable table
 	return $return;
 }
@@ -1023,7 +1052,7 @@ function get_template_data($from, $number_of_items, $column, $direction)
  *
  * @param integer $id the id of the template
  * @return html code for the link to edit and delete the template
- * 
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version August 2008
  * @since Dokeos 1.8.6
@@ -1040,7 +1069,7 @@ function actions_filter($id)
  *
  * @param string $image the image
  * @return html code for the image
- * 
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version August 2008
  * @since Dokeos 1.8.6
@@ -1068,153 +1097,166 @@ function add_edit_template()
 {
 	// initiate the object
 	$form = new FormValidator('template', 'post', 'settings.php?category=Templates&action='.$_GET['action'].'&id='.$_GET['id']);
-	
+
 	// settting the form elements: the header
-	if ($_GET['action'] == 'add')
-	{
+	if ($_GET['action'] == 'add') {
 		$title = get_lang('AddTemplate');
 	}
-	else 
+	else
 	{
 		$title = get_lang('EditTemplate');
 	}
 	$form->addElement('header', '', $title);
-	
+
 	// settting the form elements: the title of the template
 	$form->add_textfield('title', get_lang('Title'), false);
-	
+
 	// settting the form elements: the content of the template (wysiwyg editor)
-	$form->addElement('html_editor', 'template_text', get_lang('Text'), null, array('ToolbarSet' => 'AdminTemplates', 'Width' => '100%', 'Height' => '400', 'FullPage' => true));
-	
+	$form->addElement('html_editor', 'template_text', get_lang('Text'), null, array('ToolbarSet' => 'AdminTemplates', 'Width' => '100%', 'Height' => '400'));
+
 	// settting the form elements: the form to upload an image to be used with the template
 	$form->addElement('file','template_image',get_lang('Image'),'');
-	
+
 	// settting the form elements: a little bit information about the template image
 	$form->addElement('static', 'file_comment', '', get_lang('TemplateImageComment100x70'));
-	
-	// getting all the information of the template when editing a template 
-	if ($_GET['action'] == 'edit')
-	{
-		// Database table definition		
+
+	// getting all the information of the template when editing a template
+	if ($_GET['action'] == 'edit') {
+		// Database table definition
 		$table_system_template = Database :: get_main_table('system_template');
 		$sql = "SELECT * FROM $table_system_template WHERE id = '".Database::escape_string($_GET['id'])."'";
-		$result = api_sql_query($sql, __FILE__, __LINE__);
+		$result = Database::query($sql, __FILE__, __LINE__);
 		$row = Database::fetch_array($result);
-		
-		$defaults['template_id'] 	= $_GET['id'];
+
+		$defaults['template_id'] 	= intval($_GET['id']);
 		$defaults['template_text'] 	= $row['content'];
-		$defaults['title'] 			= $row['title'];
-		
+		//forcing a get_lang
+		$defaults['title'] 			= get_lang($row['title']);
+
 		// adding an extra field: a hidden field with the id of the template we are editing
 		$form->addElement('hidden','template_id');
-		
+
 		// adding an extra field: a preview of the image that is currently used
 		if (!empty($row['image']))
-		{		
+		{
 			$form->addElement('static','template_image_preview', '', '<img src="'.api_get_path(WEB_PATH).'home/default_platform_document/template_thumb/'.$row['image'].'" alt="'.get_lang('TemplatePreview').'"/>');
 		}
 		else
 		{
 			$form->addElement('static','template_image_preview', '', '<img src="'.api_get_path(WEB_PATH).'home/default_platform_document/template_thumb/noimage.gif" alt="'.get_lang('NoTemplatePreview').'"/>');
 		}
-		
-		// setting the information of the template that we are editing 
+
+		// setting the information of the template that we are editing
 		$form->setDefaults($defaults);
-	}	
+	}
 		// settting the form elements: the submit button
 	$form->addElement('style_submit_button' , 'submit', get_lang('Ok') ,'class="save"');
-	
+
 	// setting the rules: the required fields
-	$form->addRule('title', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');	
-	$form->addRule('template_text', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');	
-	
+	$form->addRule('title', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
+	$form->addRule('template_text', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
+
 	// if the form validates (complies to all rules) we save the information, else we display the form again (with error message if needed)
 	if( $form->validate() )
 	{
-		// exporting the values
-		$values = $form->exportValues();
-		
-		// upload the file
-		if (!empty($_FILES['template_image']['name']))
-		{
-			include_once (api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
-			$upload_ok = process_uploaded_file($_FILES['template_image']);
-			
-			if ($upload_ok)
+
+		$check = Security::check_token('post');
+		if ($check) {
+			// exporting the values
+			$values = $form->exportValues();
+
+			// upload the file
+			if (!empty($_FILES['template_image']['name']))
 			{
-				// Try to add an extension to the file if it hasn't one
-				$new_file_name = add_ext_on_mime(stripslashes($_FILES['template_image']['name']), $_FILES['template_image']['type']);	
-				
-				// upload dir
-				$upload_dir = api_get_path(SYS_PATH).'home/default_platform_document/template_thumb/';
-				
-				// create dir if not exists
-                if (!is_dir($upload_dir)) {
-                    $perm = api_get_setting('permissions_for_new_directories');
-                    $perm = octdec(!empty($perm)?$perm:'0770');
-                	$res = @mkdir($upload_dir,$perm);
-                }
-				
-				// resize image to max default and upload
-				require_once (api_get_path(LIBRARY_PATH).'image.lib.php');
-				$temp = new image($_FILES['template_image']['tmp_name']);	
-				$picture_infos=@getimagesize($_FILES['template_image']['tmp_name']);
-				
-				$max_width_for_picture = 100;
-				
-				if ($picture_infos[0]>$max_width_for_picture)
-				{		
-					$thumbwidth = $max_width_for_picture;
-					if (empty($thumbwidth) or $thumbwidth==0) {
-					  $thumbwidth=$max_width_for_picture;
-					}
-					$new_height = round(($thumbwidth/$picture_infos[0])*$picture_infos[1]);
-					
-					$temp->resize($thumbwidth,$new_height,0);
-				}
-				
-				$type=$picture_infos[2];
-						  
-				switch (!empty($type))
+				include_once (api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
+				$upload_ok = process_uploaded_file($_FILES['template_image']);
+
+				if ($upload_ok)
 				{
-					case 2 : $temp->send_image('JPG',$upload_dir.$new_file_name);							 
-							 break;
-					case 3 : $temp->send_image('PNG',$upload_dir.$new_file_name);							
-							 break;
-					case 1 : $temp->send_image('GIF',$upload_dir.$new_file_name);							 
-							 break;
+					// Try to add an extension to the file if it hasn't one
+					$new_file_name = add_ext_on_mime(stripslashes($_FILES['template_image']['name']), $_FILES['template_image']['type']);
+
+					// upload dir
+					$upload_dir = api_get_path(SYS_PATH).'home/default_platform_document/template_thumb/';
+
+					// create dir if not exists
+	                if (!is_dir($upload_dir)) {
+	                    $perm = api_get_setting('permissions_for_new_directories');
+	                    $perm = octdec(!empty($perm)?$perm:'0770');
+	                	$res = @mkdir($upload_dir,$perm);
+	                }
+
+					// resize image to max default and upload
+					require_once (api_get_path(LIBRARY_PATH).'image.lib.php');
+					$temp = new image($_FILES['template_image']['tmp_name']);
+					$picture_infos=@getimagesize($_FILES['template_image']['tmp_name']);
+
+					$max_width_for_picture = 100;
+
+					if ($picture_infos[0]>$max_width_for_picture)
+					{
+						$thumbwidth = $max_width_for_picture;
+						if (empty($thumbwidth) or $thumbwidth==0) {
+						  $thumbwidth=$max_width_for_picture;
+						}
+						$new_height = round(($thumbwidth/$picture_infos[0])*$picture_infos[1]);
+
+						$temp->resize($thumbwidth,$new_height,0);
+					}
+
+					$type=$picture_infos[2];
+
+					switch (!empty($type))
+					{
+						case 2 : $temp->send_image('JPG',$upload_dir.$new_file_name);
+								 break;
+						case 3 : $temp->send_image('PNG',$upload_dir.$new_file_name);
+								 break;
+						case 1 : $temp->send_image('GIF',$upload_dir.$new_file_name);
+								 break;
+					}
 				}
-			}
-	   }
-	   
-	   // store the information in the database (as insert or as update)
-	   $table_system_template = Database :: get_main_table('system_template');
-	   if ($_GET['action'] == 'add') {
-		   	$sql = "INSERT INTO $table_system_template (title, content, image) VALUES ('".Database::escape_string($values['title'])."','".Database::escape_string($values['template_text'])."','".Database::escape_string($new_file_name)."')";
-		   	$result = api_sql_query($sql, __FILE__, __LINE__);
-		   	
-		   	// display a feedback message
-		   	Display::display_confirmation_message('TemplateAdded');
-		   	echo '<a href="settings.php?category=Templates&amp;action=add">'.Display::return_icon('template_add.gif', get_lang('AddTemplate')).get_lang('AddTemplate').'</a>';
-	   } else {
-		   	$sql = "UPDATE $table_system_template set title = '".Database::escape_string($values['title'])."',
-											   		  content = '".Database::escape_string($values['template_text'])."'";
-		   	if (!empty($new_file_name))
-		   	{
-		   		$sql .= ", image = '".Database::escape_string($new_file_name)."'";
-		   	}
-		   	$sql .= " WHERE id='".Database::escape_string($_GET['id'])."'";
-		   	$result = api_sql_query($sql, __FILE__, __LINE__);
-		   	
-		   	// display a feedback message
-		   	Display::display_confirmation_message('TemplateEdited');		   	
-	   }
+		   }
+
+		   // store the information in the database (as insert or as update)
+		   $table_system_template = Database :: get_main_table('system_template');
+		   if ($_GET['action'] == 'add') {
+		   		$content_template = '<head>{CSS}<style type="text/css">.text{font-weight: normal;}</style></head><body>'.Database::escape_string($values['template_text']).'</body>';
+			   	$sql = "INSERT INTO $table_system_template (title, content, image) VALUES ('".Database::escape_string($values['title'])."','".$content_template."','".Database::escape_string($new_file_name)."')";
+			   	$result = Database::query($sql, __FILE__, __LINE__);
+
+			   	// display a feedback message
+			   	Display::display_confirmation_message(get_lang('TemplateAdded'));
+			   	echo '<a href="settings.php?category=Templates&amp;action=add">'.Display::return_icon('template_add.gif', get_lang('AddTemplate')).get_lang('AddTemplate').'</a>';
+		   } else {
+		   		$content_template = '<head>{CSS}<style type="text/css">.text{font-weight: normal;}</style></head><body>'.Database::escape_string($values['template_text']).'</body>';
+			   	$sql = "UPDATE $table_system_template set title = '".Database::escape_string($values['title'])."',
+												   		  content = '".$content_template."'";
+			   	if (!empty($new_file_name))
+			   	{
+			   		$sql .= ", image = '".Database::escape_string($new_file_name)."'";
+			   	}
+			   	$sql .= " WHERE id='".Database::escape_string($_GET['id'])."'";
+			   	$result = Database::query($sql, __FILE__, __LINE__);
+
+			   	// display a feedback message
+			   	Display::display_confirmation_message(get_lang('TemplateEdited'));
+		   }
+
+		}
+	   Security::clear_token();
 	   display_templates();
+
+
+
 	}
-	else 
+	else
 	{
+		$token = Security::get_token();
+		$form->addElement('hidden','sec_token');
+		$form->setConstants(array('sec_token' => $token));
 		// display the form
-		$form->display();		
+		$form->display();
 	}
 }
 
@@ -1222,7 +1264,7 @@ function add_edit_template()
  * Delete a template
  *
  * @param integer $id the id of the template that has to be deleted
- * 
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version August 2008
  * @since Dokeos 1.8.6
@@ -1232,18 +1274,18 @@ function delete_template($id)
 	// first we remove the image
 	$table_system_template = Database :: get_main_table('system_template');
 	$sql = "SELECT * FROM $table_system_template WHERE id = '".Database::escape_string($id)."'";
-	$result = api_sql_query($sql, __FILE__, __LINE__);
-	$row = Database::fetch_array($result);	
+	$result = Database::query($sql, __FILE__, __LINE__);
+	$row = Database::fetch_array($result);
 	if (!empty($row['image']))
 	{
 		unlink(api_get_path(SYS_PATH).'home/default_platform_document/template_thumb/'.$row['image']);
 	}
-	
+
 	// now we remove it from the database
 	$sql = "DELETE FROM $table_system_template WHERE id = '".Database::escape_string($id)."'";
-	$result = api_sql_query($sql, __FILE__, __LINE__);
-	
+	$result = Database::query($sql, __FILE__, __LINE__);
+
 	// display a feedback message
-	Display::display_confirmation_message('TemplateDeleted');
+	Display::display_confirmation_message(get_lang('TemplateDeleted'));
 }
 ?>

+ 286 - 0
main/admin/special_exports.php

@@ -0,0 +1,286 @@
+<?php
+/* For licensing terms, see /dokeos_license.txt */
+/**
+ * ==============================================================================
+ * Special exports
+ *
+ * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>
+ * @package special.export
+ * ==============================================================================
+ */
+
+// name of the language file that needs to be included
+$language_file = array ('admin');
+// including the global file
+$cidReset = true;
+include ('../inc/global.inc.php');
+// setting the section (for the tabs)
+$this_section = SECTION_PLATFORM_ADMIN;
+// setting breadcrumbs
+$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+// Access restrictions
+api_protect_admin_script(true);
+$nameTools = get_lang('SpecialExports');
+
+// include additional libraries
+require_once '../document/document.inc.php';
+// include additional libraries
+include_once(api_get_path(LIBRARY_PATH) . 'fileManage.lib.php');
+require_once ('../coursecopy/classes/CourseBuilder.class.php');
+require_once ('../coursecopy/classes/CourseArchiver.class.php');
+require_once ('../coursecopy/classes/CourseRestorer.class.php');
+require_once ('../coursecopy/classes/CourseSelectForm.class.php');
+
+if(function_exists('ini_set')) {
+	ini_set('memory_limit','256M');
+	ini_set('max_execution_time',0);
+}
+
+// Displaying the header
+Display::display_header($nameTools);
+// Display the tool title
+api_display_tool_title($nameTools);
+$error =0;
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
+*/
+
+$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+
+if ((isset ($_POST['action']) && $_POST['action'] == 'course_select_form') || (isset ($_POST['backup_option']) && $_POST['backup_option'] == 'full_backup')) {
+	require_once api_get_path(LIBRARY_PATH).'document.lib.php';
+	require_once api_get_path(LIBRARY_PATH).'pclzip/pclzip.lib.php';
+	$export = false;
+	if (isset ($_POST['action']) && $_POST['action'] == 'course_select_form') {
+		$FileZip = create_zip();
+		$to_group_id = 0;
+		$code_course = '';
+		$sql_session = "SELECT id, name FROM $tbl_session ";
+		$query_session = Database::query($sql_session, __FILE__, __LINE__);
+		$ListSession = array();
+		while($rows_session = mysql_fetch_assoc($query_session)) {
+			$ListSession[$rows_session['id']] = $rows_session['name'];
+		}
+		$zip_folder=new PclZip($FileZip['TEMP_FILE_ZIP']);
+		if(!isset($_POST['resource']) || count($_POST['resource']) == 0 ) {
+			Display::display_error_message(get_lang('ErrorMsgSpecialExport'));
+		} else {
+			$Resource = $_POST['resource'];
+			foreach($Resource as $Code_course => $Sessions) {
+				$_course = Database::get_course_info(Security::remove_XSS($Code_course));
+				$tbl_document = Database::get_course_table(TABLE_DOCUMENT, $_course['db_name']);
+				$tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['db_name']);
+				//Add tem to the zip file course
+				$sql = "SELECT path FROM $tbl_document AS docs, $tbl_property AS props
+					WHERE `props`.`tool`='".TOOL_DOCUMENT."'
+						AND `docs`.`id`=`props`.`ref`
+						AND `docs`.`path` LIKE '".$querypath."/%'
+						AND `docs`.`filetype`='file'
+						AND `docs`.`session_id` = '0'
+						AND `props`.`visibility`<>'2'
+						AND `props`.`to_group_id`=".$to_group_id."";
+				$query = Database::query($sql ,__FILE__,__LINE__);
+				while($rows_course_file = mysql_fetch_assoc($query)) {
+					$zip_folder->add($FileZip['PATH_COURSE'].$_course['directory']."/document".$rows_course_file['path'],
+									 PCLZIP_OPT_ADD_PATH, $_course['directory'],
+									 PCLZIP_OPT_REMOVE_PATH, $FileZip['PATH_COURSE'].$_course['directory']."/document".$FileZip['PATH_REMOVE']
+									);
+				}
+				foreach($Sessions as $IdSession => $value){
+					$session_id = Security::remove_XSS($IdSession);
+					//Add tem to the zip file session course
+					$sql_session_doc = "SELECT path FROM $tbl_document AS docs,$tbl_property AS props
+						WHERE `props`.`tool`='".TOOL_DOCUMENT."'
+							AND `docs`.`id`=`props`.`ref`
+							AND `docs`.`path` LIKE '".$querypath."/%'
+							AND `docs`.`filetype`='file'
+							AND `docs`.`session_id` = '$session_id'
+							AND `props`.`visibility`<>'2'
+							AND `props`.`to_group_id`=".$to_group_id."";
+					$query_session_doc = Database::query($sql_session_doc, __FILE__, __LINE__);
+					while($rows_course_session_file = mysql_fetch_assoc($query_session_doc)) {
+						$zip_folder->add($FileZip['PATH_COURSE'].$_course['directory'].'/document'.$rows_course_session_file['path'],
+										 PCLZIP_OPT_ADD_PATH, $_course['directory']."/".$ListSession[$session_id],
+										 PCLZIP_OPT_REMOVE_PATH, $FileZip['PATH_COURSE'].$_course['directory'].'/document'.$FileZip['PATH_REMOVE']
+										);
+					}
+				}
+			}
+			$name = rename_zip($FileZip);
+			$export = true;
+		}
+	} else {
+		$name = fullexportspecial();
+	}
+?>
+<!-- Manual download <script language="JavaScript">
+ // setTimeout(\'download_backup()\',2000);
+ function download_backup()
+ {
+	window.location="../course_info/download.php?archive=<?php echo $name; ?>&session=true";
+ }
+</script> //-->
+<?php
+}
+
+function create_zip(){
+	$path = '';
+	if(empty($path)) { $path='/'; }
+	$remove_dir = ($path!='/') ? substr($path,0,strlen($path) - strlen(basename($path))) : '/';
+	$to_group_id = $_SESSION['_gid'];
+	$sys_archive_path = api_get_path(SYS_ARCHIVE_PATH);
+	$sys_course_path = api_get_path(SYS_COURSE_PATH);
+	$temp_zip_dir = $sys_archive_path."temp";
+	if(!is_dir($temp_zip_dir)) {
+		mkdir($temp_zip_dir);
+	} else {
+		$handle=opendir($temp_zip_dir);
+		while (false!==($file = readdir($handle))) {
+			if ($file != "." && $file != "..") {
+				$Diff = (time() - filemtime("$temp_zip_dir/$file"))/60/60;	//the "age" of the file in hours
+				if ($Diff > 4) unlink("$temp_zip_dir/$file"); 	//delete files older than 4 hours
+			}
+		}
+		closedir($handle);
+	}
+	$temp_zip_file = $temp_zip_dir."/".md5(time()).".zip"; 	//create zipfile of given directory
+
+
+
+	return array('PATH' => $path,
+				 'PATH_TEMP_ARCHIVE' => $temp_zip_dir,
+				 'PATH_COURSE' => $sys_course_path,
+				 'TEMP_FILE_ZIP' => $temp_zip_file,
+				 'PATH_REMOVE' => $remove_dir);
+}
+
+function rename_zip($FileZip) {
+	event_download(($FileZip['PATH'] == '/')?'full_export_'.date('Ymd').'.zip (folder)': basename($FileZip['PATH']).'.zip (folder)');
+	$name = ($FileZip['PATH']=='/')? 'full_export_'.date('Ymd').'.zip':basename($FileZip['PATH']).'.zip';
+	if(file_exists($FileZip['PATH_TEMP_ARCHIVE'].'/'.$name)){ unlink($FileZip['PATH_TEMP_ARCHIVE'].'/'.$name); }
+	if(file_exists($FileZip['TEMP_FILE_ZIP'])) {
+		rename($FileZip['TEMP_FILE_ZIP'], $FileZip['PATH_TEMP_ARCHIVE'].'/'.$name);
+		return $name;
+	} else { return false; }
+
+}
+
+function fullexportspecial(){
+	global $tbl_session, $tbl_session_course, $export;
+	$FileZip = create_zip();
+	$to_group_id = 0;
+	$code_course = '';
+	$list_course = array();
+	$zip_folder = new PclZip($FileZip['TEMP_FILE_ZIP']);
+	$list_course = Database::get_course_list();
+	if(count($list_course) >0 ) {
+		foreach($list_course as $_course) {
+			if($FileZip['PATH'] == '/') {
+				$querypath=''; // to prevent ...path LIKE '//%'... in query
+			} else {
+				$querypath = $FileZip['PATH'];
+			}
+			$tbl_document = Database::get_course_table(TABLE_DOCUMENT, $_course['db_name']);
+			$tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['db_name']);
+			//Add tem to the zip file course
+			$sql = "SELECT path FROM $tbl_document AS docs, $tbl_property AS props
+				WHERE `props`.`tool`='".TOOL_DOCUMENT."'
+					AND `docs`.`id`=`props`.`ref`
+					AND `docs`.`path` LIKE '".$querypath."/%'
+					AND `docs`.`filetype`='file'
+					AND `docs`.`session_id` = '0'
+					AND `props`.`visibility`<>'2'
+					AND `props`.`to_group_id`=".$to_group_id."";
+			$query = Database::query($sql ,__FILE__,__LINE__);
+			while($rows_course_file = mysql_fetch_assoc($query)) {
+				$rows_course_file['path'];
+				$zip_folder->add($FileZip['PATH_COURSE'].$_course['directory']."/document".$rows_course_file['path'],
+								 PCLZIP_OPT_ADD_PATH, $_course['directory'],
+								 PCLZIP_OPT_REMOVE_PATH, $FileZip['PATH_COURSE'].$_course['directory']."/document".$FileZip['PATH_REMOVE']
+								);
+			}
+			//Add tem to the zip file session course
+			$code_course = $_course['code'];
+			$sql_session = "SELECT id, name, course_code  FROM $tbl_session_course
+				INNER JOIN  $tbl_session ON id_session = id
+				WHERE course_code = '$code_course' ";
+			$query_session = Database::query($sql_session, __FILE__, __LINE__);
+			while($rows_session = mysql_fetch_assoc($query_session)) {
+				$session_id = $rows_session['id'];
+				$sql_session_doc = "SELECT path FROM $tbl_document AS docs,$tbl_property AS props
+					WHERE `props`.`tool`='".TOOL_DOCUMENT."'
+						AND `docs`.`id`=`props`.`ref`
+						AND `docs`.`path` LIKE '".$querypath."/%'
+						AND `docs`.`filetype`='file'
+						AND `docs`.`session_id` = '$session_id'
+						AND `props`.`visibility`<>'2'
+						AND `props`.`to_group_id`=".$to_group_id."";
+				$query_session_doc = Database::query($sql_session_doc, __FILE__, __LINE__);
+				while($rows_course_session_file = mysql_fetch_assoc($query_session_doc)) {
+					$zip_folder->add($FileZip['PATH_COURSE'].$_course['directory'].'/document'.$rows_course_session_file['path'],
+									 PCLZIP_OPT_ADD_PATH, $_course['directory']."/".$rows_session['name'],
+									 PCLZIP_OPT_REMOVE_PATH, $FileZip['PATH_COURSE'].$_course['directory'].'/document'.$FileZip['PATH_REMOVE']
+									);
+				}
+			}
+		}
+		$name = rename_zip($FileZip);
+		if($name === false){
+			$export = false;
+			return false;
+		}else{
+			$export = true;
+			return $name;
+		}
+	}else{
+		Display::display_error_message(get_lang('ErrorMsgSpecialExport')); //main API
+		$export = false;
+		return false;
+	}
+}
+
+if($export == true && $name != false) {
+	Display::display_confirmation_message(get_lang('BackupCreated').'<br /><br /><a class="bottom-link" href="'.api_get_path(WEB_CODE_PATH).'course_info/download.php?archive='.urlencode($name).'&session=true">'.$name.'</a>', false);
+	echo '<p><a class="bottom-link"  href="'.api_get_path(WEB_CODE_PATH).'admin/index.php">&nbsp;'.get_lang('MainMenu').'</a></p>';
+} else{
+	// Display forms especial export
+	if (isset ($_POST['backup_option']) && $_POST['backup_option'] == 'select_items') {
+		$cb = new CourseBuilder();
+		$course = $cb->build_session_course();
+		if($course === false){
+			Display::display_error_message(get_lang('ErrorMsgSpecialExport'));
+			form_special_export();
+		} else {
+			Display::display_normal_message(get_lang('ToExportSpecialSelect'));
+			CourseSelectForm :: display_form_session_export($course);
+		}
+	} else {
+		form_special_export();
+	}
+}
+
+function form_special_export(){
+	$htlm = get_lang('SelectOptionExport');
+	include_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+	$form = new FormValidator('special_exports','post');
+	$renderer = $form->defaultRenderer();
+	$renderer->setElementTemplate('<div>{element}</div> ');
+	$form->addElement('radio', 'backup_option', '',  get_lang('SpecialCreateFullBackup'), 'full_backup');
+	$form->addElement('radio', 'backup_option', '',  get_lang('SpecialLetMeSelectItems'), 'select_items');
+	$form->addElement('html','<br />');
+	$form->addElement('style_submit_button', null, get_lang('CreateBackup'), 'class="save"');
+	$form->add_progress_bar();
+	$values['backup_option'] = 'full_backup';
+	$form->setDefaults($values);
+	$form->display();
+}
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display::display_footer();
+?>

+ 3 - 3
main/admin/statistics.php

@@ -52,12 +52,12 @@ Display::display_header($tool_name);
 ==============================================================================
 		MAIN CODE
 ==============================================================================
-*/ 
+*/
 
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
-*/ 
+*/
 Display::display_footer();
 ?>

+ 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 - 440
main/admin/statistics/statistics.lib.php

@@ -1,440 +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 = api_sql_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 = api_sql_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 = api_sql_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 = api_sql_query($sql, __FILE__, __LINE__);
-		$activities = array ();
-		while ($row = Database::fetch_row($res)) {
-			$row[4] = api_ucfirst(format_locale_date($dateTimeFormatLong,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 = api_sql_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':
-				$period = get_lang('PeriodMonth');
-				$sql = "SELECT DATE_FORMAT( login_date, '%Y %b' ) 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':
-				$period = get_lang('PeriodDay');
-				$sql = "SELECT DATE_FORMAT( login_date, '%a' ) 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 = api_sql_query($sql,__FILE__,__LINE__);
-		$result = array();
-		while($obj = Database::fetch_object($res))
-		{
-			$result[$obj->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 = api_sql_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','bb_forum');
-		$sql = "SELECT access_tool, count( access_id ) AS number_of_logins FROM $table WHERE access_tool IN ('".implode("','",$tools)."') GROUP BY access_tool ";
-		$res = api_sql_query($sql,__FILE__,__LINE__);
-		$result = array();
-		while($obj = Database::fetch_object($res))
-		{
-			$result[$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 = api_sql_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 = api_sql_query($sql,__FILE__,__LINE__);
-		$count1 = Database::fetch_object($res);
-		$sql = "SELECT COUNT(*) AS n FROM $user_table WHERE LENGTH(picture_uri) > 0";
-		$res = api_sql_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 = api_sql_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 = api_sql_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"></br>
+      <label>Username</label></br>
+      <input type="text" name="login" id="login" size="15" value="" /></br>
+      <label>Password</label></br>
+      <input type="password" name="password" id="password" size="15" /></br>
+  	  <button class="login" type="submit" name="submitAuth"disabled="disabled" >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();
 ?>

+ 53 - 46
main/admin/sub_language.class.php

@@ -18,23 +18,30 @@ class SubLanguageManager {
     /**
      * Get all data of dokeos folder (forum.inc.php,gradebook.inc.php,notebook.inc.php)
      * @param String The dokeos path folder  (/var/www/my_dokeos/main/lang/spanish)
+     * @param bool true if we only want the "subname" trad4all instead of  trad4all.inc.php
      * @return Array All file of dokeos folder
+     *
      */
-    public static function get_all_data_of_dokeos_folder ($dokeos_path_folder) {
+    public static function get_all_data_of_dokeos_folder ($dokeos_path_folder,$only_main_name=false) {
 	   $content_dir=array();
 	    if (is_dir($dokeos_path_folder)) {
 		    if ($dh = opendir($dokeos_path_folder)) {
 		        while (($file = readdir($dh)) !== false) {
 		           if ($file[0]<>'.' && substr($file,-4,strlen($file))=='.php') {
-		           	  $content_dir[]=$file;
+		           		if ($only_main_name) {
+		           			if ($file!='' && strpos($file, '.inc.php'))
+		           				$content_dir[]=substr($file, 0, strpos($file, '.inc.php'));
+		           		} else {
+		           	  		$content_dir[]=$file;
+		           		}
 		           }
-		           
+
 		        }
-		       
+
 		    }
  			closedir($dh);
-		    return $content_dir; 
-		}	
+		    return $content_dir;
+		}
     }
     /**
      * Get all information of sub-language
@@ -43,74 +50,74 @@ class SubLanguageManager {
      * @return Array All information about sub-language
      */
 	public static function get_all_information_of_sub_language ($parent_id,$sub_language_id) {
-		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);	
-		$sql='SELECT * FROM '.$tbl_admin_languages.' WHERE parent_id="'.Database::escape_string($parent_id).'" AND id="'.Database::escape_string($sub_language_id).'"';
+		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
+	 	$sql='SELECT * FROM '.$tbl_admin_languages.' WHERE parent_id="'.Database::escape_string($parent_id).'" AND id="'.Database::escape_string($sub_language_id).'"';
 		$rs=Database::query($sql,__FILE__,__LINE__);
 		$all_information=array();
 		while ($row=Database::fetch_array($rs,'ASSOC')) {
 			$all_information=$row;
 		}
 		return $all_information;
-	} 
+	}
     /**
      * Get all information of language
      * @param Integer The parent id(Language father id)
      * @return Array All information about language
-     */	
+     */
    public static function get_all_information_of_language ($parent_id) {
- 		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);	
+ 		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 		$sql='SELECT * FROM '.$tbl_admin_languages.' WHERE id="'.Database::escape_string($parent_id).'"';
 		$rs=Database::query($sql,__FILE__,__LINE__);
 		$all_information=array();
 		while ($row=Database::fetch_array($rs,'ASSOC')) {
 			$all_information=$row;
 		}
-		return $all_information;  	
+		return $all_information;
    }
      /**
-     * Get all information of dokeos file 
+     * Get all information of dokeos file
      * @param String The dokeos path file (/var/www/my_dokeos/main/lang/spanish/gradebook.inc.php)
      * @return Array Contains all information of dokeos file
-     */	  
+     */
    public static function get_all_language_variable_in_file ($dokeos_path_file) {
-   	$info_file=file($dokeos_path_file);
-   	foreach ($info_file as $line) {
-        if (substr($line,0,1)!='$') { continue; }
-    	list($var,$val) = split('=',$line,2);
-        $var = trim($var); $val = trim($val);
-        $res_list[$var] = $val;
-    }
-		return $res_list;
+	   	$info_file=file($dokeos_path_file);
+	   	foreach ($info_file as $line) {
+	        if (substr($line,0,1)!='$') { continue; }
+	    	list($var,$val) = split('=',$line,2);
+	        $var = trim($var); $val = trim($val);
+	        $res_list[$var] = $val;
+	    }
+			return $res_list;
    }
-   
+
      /**
-     * Add file in sub-language directory and add header(tag php) 
+     * Add file in sub-language directory and add header(tag php)
      * @param String The dokeos path file (/var/www/my_dokeos/main/lang/spanish/gradebook.inc.php)
      * @return void()
-     */	   
+     */
    public static function add_file_in_language_directory ($dokeos_path_file) {
    		file_put_contents($dokeos_path_file,'<?php'.PHP_EOL);
    }
      /**
-     * Write in file of sub-language 
+     * Write in file of sub-language
      * @param String The path file (/var/www/my_dokeos/main/lang/spanish/gradebook.inc.php)
      * @param String The new sub-language
      * @param String The language variable
      * @return void()
-     */	    
+     */
    public static function write_data_in_file ($path_file,$new_sub_language,$variable_sub_language) {
    		$new_data=$variable_sub_language.'='.$new_sub_language;
    		$g_open_file = fopen($path_file, "a");
    		if (fwrite($g_open_file, $new_data.PHP_EOL) === false) {
    			//not allow to write
-   		} 
+   		}
    		fclose($g_open_file);
    }
      /**
-     * Add directory for sub-language 
+     * Add directory for sub-language
      * @param String The sub-language path directory ( /var/www/my_dokeos/main/lang/spanish_corporate )
      * @return boolean
-     */	      
+     */
    public static function add_directory_of_sub_language($path_sub_language) {
    		$rs=@mkdir($path_sub_language,0777);
 		if ($rs) {
@@ -123,9 +130,9 @@ class SubLanguageManager {
 	 * Delete sub-language
 	 * @param Integer The parent id
 	 * @return void()
-	 */   
+	 */
    public static function removed_sub_language ($parent_id,$sub_language_id) {
-   		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);		
+   		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 		$sql='DELETE FROM '.$tbl_admin_languages.' WHERE parent_id="'.Database::escape_string($parent_id).'" AND id="'.Database::escape_string($sub_language_id).'" ';
     	$rs=Database::query($sql,__FILE__,__LINE__);
    }
@@ -135,7 +142,7 @@ class SubLanguageManager {
 	 * @return Boolean
 	 */
 	public static function check_if_exist_language_by_id ($language_id) {
-		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);	
+		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 		$sql='SELECT count(*) as count FROM '.$tbl_admin_languages.' WHERE id="'.Database::escape_string($language_id).'"';
 		$rs=Database::query($sql,__FILE__,__LINE__);
 		if (Database::num_rows($rs)>0) {
@@ -146,32 +153,32 @@ class SubLanguageManager {
 			}
 		} else {
 			return false;;
-		}	
+		}
 	}
 
 	/**
 	 * Get name of language by id
 	 * @param Integer The language id
 	 * @return String The original name of language
-	 */	
+	 */
 	public static function get_name_of_language_by_id ($language_id) {
-		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);	
+		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 		$sql='SELECT original_name FROM '.$tbl_admin_languages.' WHERE id="'.Database::escape_string($language_id).'"';
 		$rs=Database::query($sql,__FILE__,__LINE__);
 		if (Database::num_rows($rs)>0) {
-			return Database::result($rs,0,'original_name');	
+			return Database::result($rs,0,'original_name');
 		} else {
 			return '';
 		}
-	
+
 	}
 	/**
 	 * Verified if language is sub-language
 	 * @param Integer The language id
-	 * @return Boolean 
+	 * @return Boolean
 	 */
 	public static function check_if_language_is_sub_language ($language_id) {
-	$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);	
+	$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 	$sql='SELECT count(*) AS count FROM '.$tbl_admin_languages.' WHERE id="'.Database::escape_string($language_id).'" AND NOT ISNULL(parent_id)';
     $rs=Database::query($sql,__FILE__,__LINE__);
 
@@ -187,10 +194,10 @@ class SubLanguageManager {
 	 * @return Boolean
 	 */
 	public static function check_if_language_is_father ($language_id) {
-		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);	
+		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 		$sql='SELECT count(*) AS count FROM '.$tbl_admin_languages.' WHERE parent_id="'.Database::escape_string($language_id).'" AND NOT ISNULL(parent_id);';
 	    $rs=Database::query($sql,__FILE__,__LINE__);
-	
+
 	    if (Database::num_rows($rs)>0 && Database::result($rs,'0','count')==1) {
 	    	return true;
 	    } else {
@@ -203,9 +210,9 @@ class SubLanguageManager {
 	 * @return void()
 	 */
 	public static function make_unavailable_language ($language_id) {
-		$tbl_admin_languages= Database :: get_main_table(TABLE_MAIN_LANGUAGE);		
+		$tbl_admin_languages= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 		$sql_make_unavailable = "UPDATE $tbl_admin_languages SET available='0' WHERE id='".Database::escape_string($language_id)."'";
-		$result = Database::query($sql_make_unavailable,__FILE__,__LINE__);		
+		$result = Database::query($sql_make_unavailable,__FILE__,__LINE__);
 	}
 	/**
 	 * Make available the language
@@ -224,12 +231,12 @@ class SubLanguageManager {
 	  */
 	  public static function set_platform_language ($language_id) {
 		$tbl_admin_languages= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
-		$tbl_settings_current 	= Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);	
+		$tbl_settings_current 	= Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
 		$sql_update = "SELECT english_name FROM ". $tbl_admin_languages." WHERE id='".Database::escape_string($language_id)."'";
 		$result = Database::query($sql_update,__FILE__,__LINE__);
 		$lang=Database::fetch_array($result);
 		$sql_update_2 = "UPDATE ".$tbl_settings_current." SET selected_value='".$lang['english_name']."' WHERE variable='platformLanguage'";
-		$result_2 = Database::query($sql_update_2);	  	
+		$result_2 = Database::query($sql_update_2);
 	  }
 }
 ?>

+ 291 - 0
main/admin/sub_language.php

@@ -0,0 +1,291 @@
+<?php
+/* For licensing terms, see /dokeos_license.txt */
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
+*/
+// name of the language file that needs to be included
+$language_file = 'admin';
+$cidReset = true;
+require_once '../inc/global.inc.php';
+require_once 'sub_language.class.php';
+require_once api_get_path(LIBRARY_PATH).'array.lib.php';
+$this_section=SECTION_PLATFORM_ADMIN;
+
+api_protect_admin_script();
+$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
+$htmlHeadXtra[] ='<script type="text/javascript">
+ $(document).ready(function() {
+
+	$(".save").click(function() {
+		button_name=$(this).attr("name");
+		button_array=button_name.split("|");
+		button_name=button_array[1];
+		file_id=button_array[2];
+		is_variable_language="$"+button_name;
+
+		is_new_language=$("#txtid_"+button_name).attr("value");
+   		if (is_new_language=="undefined") {
+     			is_new_language="_";
+    	}
+
+		if (is_new_language.length>0 && is_new_language!="_" && file_id!="" && button_name!="") {
+			$.ajax({
+				contentType: "application/x-www-form-urlencoded",
+				beforeSend: function(objeto) {
+					$("#div_message_information_id").html("<div class=\"normal-message\"><img src=\'../inc/lib/javascript/indicator.gif\' /></div>");
+
+				},
+				type: "POST",
+				url: "../admin/sub_language_ajax.inc.php",
+				data: "new_language="+is_new_language+"&variable_language="+is_variable_language+"&file_id="+file_id+"&id="+'.intval($_REQUEST['id']).'+"&sub="+'.intval($_REQUEST['sub_language_id']).',
+				success: function(datos) {
+					$("#div_message_information_id").html("<div class=\"confirmation-message\">'.get_lang('TheNewWordHasBeenAdded').'</div>");
+
+			} });
+		} else {
+			$("#div_message_information_id").html("<div class=\"error-message\">'.get_lang('FormHasErrorsPleaseComplete').'</div>");
+		}
+	});
+ 		});
+</script>';
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
+*/
+// setting the name of the tool
+$tool_name = get_lang('CreateSubLanguage');
+// setting breadcrumbs
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'languages.php', 'name' => get_lang('PlatformLanguages'));
+
+require_once api_get_path(LIBRARY_PATH).'text.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+
+if (isset($_GET['id']) && $_GET['id']==strval(intval($_GET['id']))) {
+	$language_name=SubLanguageManager::get_name_of_language_by_id ($_GET['id']);
+	$all_data_of_language=SubLanguageManager::get_all_information_of_language($_GET['id']);
+	$my_language=$language_name;
+	if (SubLanguageManager::check_if_exist_language_by_id($_GET['id'])===true) {
+		$parent_id=intval($_GET['id']);
+		$language_id_exist=true;
+	} else {
+		$language_id_exist=false;
+	}
+} else {
+	$language_name='';
+	$language_id_exist=false;
+}
+
+$language_name=get_lang('RegisterTermsOfSubLanguageForLanguage').' ( '.strtolower($language_name).' )';
+$dokeos_path_folder=api_get_path('SYS_LANG_PATH').$all_data_of_language['dokeos_folder'];
+//
+if (!is_dir($dokeos_path_folder) || strlen($all_data_of_language['dokeos_folder'])==0) {
+	api_not_allowed(true);
+}
+
+Display :: display_header($language_name);
+
+echo '<div class="actions-message" >';
+echo $language_name;
+echo '</div>';
+echo '<br />';
+
+$txt_search_word = Security::remove_XSS($_REQUEST['txt_search_word']);
+$html.='<div style="float:left" class="actions">';
+$html.='<form style="float:left"  id="Searchlanguage" name="Searchlanguage" method="GET" action="sub_language.php">';
+$html.='&nbsp;'.get_lang('OriginalName').'&nbsp; :&nbsp;';
+
+$html.='<input name="id" type="hidden"  id="id" value="'.Security::remove_XSS($_REQUEST['id']).'" />';
+$html.='<input name="sub_language_id" type="hidden"  id="id" value="'.Security::remove_XSS($_REQUEST['sub_language_id']).'" />';
+
+$html.='<input name="txt_search_word" type="text" size="50"  id="txt_search_word" value="'.Security::remove_XSS($_REQUEST['txt_search_word']).'" />';
+$html.="&nbsp;".'<button name="SubmitSearchLanguage" class="search" type="submit">'.get_lang('Search').'</button>';
+$html.='</form>';
+$html.='</div>';
+echo $html;
+echo '<br /><br /><br /><br />';
+echo '<div id="div_message_information_id">&nbsp;</div>';
+
+/**
+ * Search a term in the language
+ * @param string the term to search
+ * @param bool the search will include the variable definition of the term
+ * @param bool the search will include the english language variables
+ * @param bool the search will include the parent language variables of the sub language
+ * @param bool the search will include the sub language variables
+ * @author Julio Montoya
+ *
+ */
+function search_language_term($term, $search_in_variable = true , $search_in_english = true, $search_in_parent = true, $search_in_sub_language= true) {
+	//These the $_REQUEST['id'] and the $_REQUEST['sub_language_id'] variables are process in global.inc.php (LOAD LANGUAGE FILES SECTION)
+	/*
+		These 4 arrays are set in global.inc.php with the condition that will be load from sub_language.php or sub_language_ajax.inc.php
+		$english_language_array
+		$parent_language_array
+		$sub_language_array
+		$language_files_to_load
+	*/
+	//echo '<pre>';
+	// array with the list of files to load i.e trad4fall, notification, etc set in global.inc.php
+
+	global $language_files_to_load, $sub_language_array, $english_language_array, $parent_language_array;
+	$language_files_to_load_keys = array_flip($language_files_to_load);
+	$array_to_search = $parent_language_array;
+	$list_info = array();
+	//echo '<pre>';
+	//print_r($language_files_to_load);
+	$term='/'.Security::remove_XSS(trim($_REQUEST['txt_search_word'])).'/i';
+	//@todo optimize this foreach
+	foreach ($language_files_to_load as $lang_file) {
+		//searching in parent language of the sub language
+		if ($search_in_parent) {
+			$variables = $parent_language_array[$lang_file];
+			foreach ($variables as $parent_name_variable =>$parent_variable_value) {
+				//arrays are avoided
+				if (is_array($parent_variable_value)) {
+					continue;
+				}
+				$founded = false;
+				// searching the item in the parent tool
+				if (preg_match($term,$parent_variable_value)!==0) {
+					$founded = true;
+				}
+				if ($founded) {
+					//loading variable from the english array
+					$sub_language_name_variable = $sub_language_array[$lang_file][$parent_name_variable];
+					//loading variable from the english array
+					$english_name_variable = $english_language_array[$lang_file][$parent_name_variable];
+
+					//config buttons
+					/*if (strlen($english_name_variable)>1500) {
+						$size =20;
+					} else {
+						$size =4;
+					}*/
+
+					$obj_text='<textarea rows="10" cols="40" name="txt|'.$parent_name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="txtid_'.$parent_name_variable.'" >'.$sub_language_name_variable.'</textarea>';
+					$obj_button='<button class="save" type="button" name="btn|'.$parent_name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="btnid_'.$parent_name_variable.'"  />'.get_lang('Save').'</button>';
+
+					$list_info[]=array($lang_file.'.inc.php',
+									   $parent_name_variable,
+									   $english_name_variable,
+									   $parent_variable_value,$obj_text,$obj_button);
+				}
+			}
+		}
+
+		//search in english
+		if ($search_in_english || $search_in_variable) {
+			$variables = $english_language_array[$lang_file];
+			foreach ($variables as $name_variable =>$variable_value) {
+				if (is_array($variable_value)) {
+					continue;
+				}
+				if (is_array($variable_value))
+					echo $lang_file;
+				$founded = false;
+				if ($search_in_english && $search_in_variable) {
+					// searching the item in the parent tool
+					if (preg_match($term,$variable_value)!==0 || preg_match($term,$name_variable)!==0 ) {
+						$founded = true;
+					}
+				} else {
+					if ($search_in_english) {
+						if (preg_match($term,$variable_value)!==0) {
+							$founded = true;
+						}
+					} else {
+						if (preg_match($term,$name_variable)!==0) {
+							$founded = true;
+						}
+					}
+				}
+
+				if ($founded) {
+					//loading variable from the english array
+					$sub_language_name_variable = $sub_language_array[$lang_file][$name_variable];
+					$parent_variable_value 		= $parent_language_array[$lang_file][$name_variable];
+					//config buttons
+					$obj_text='<textarea rows="10" cols="40" name="txt|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="txtid_'.$name_variable.'" >'.$sub_language_name_variable.'</textarea>';
+					$obj_button='<button class="save" type="button" name="btn|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="btnid_'.$name_variable.'"  />'.get_lang('Save').'</button>';
+
+					//loading variable from the english array
+					$english_name_variable = $english_language_array[$lang_file][$name_variable];
+
+					$list_info[]=array($lang_file.'.inc.php',
+									   $name_variable,
+									   $english_name_variable,
+									   $parent_variable_value,$obj_text,$obj_button);
+				}
+			}
+		}
+
+
+		//search in sub language
+		if ($search_in_sub_language) {
+			$variables = $sub_language_array[$lang_file];
+			foreach ($variables as $name_variable =>$variable_value) {
+				if (is_array($parent_variable_value)) {
+					continue;
+				}
+
+				$founded = false;
+				// searching the item in the parent tool
+				if (preg_match($term,$variable_value)!==0) {
+					$founded = true;
+				}
+				if ($founded) {
+					//loading variable from the english array
+					$sub_language_name_variable = $sub_language_array[$lang_file][$name_variable];
+					$parent_variable_value 		= $parent_language_array[$lang_file][$name_variable];
+					//config buttons
+					$obj_text='<textarea rows="10" cols="40" name="txt|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="txtid_'.$name_variable.'" >'.$sub_language_name_variable.'</textarea>';
+					$obj_button='<button class="save" type="button" name="btn|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="btnid_'.$name_variable.'"  />'.get_lang('Save').'</button>';
+
+					//loading variable from the english array
+					$english_name_variable = $english_language_array[$lang_file][$name_variable];
+					$list_info[]=array($lang_file.'.inc.php',
+									   $name_variable,
+									   $english_name_variable,
+									   $parent_variable_value,$obj_text,$obj_button);
+				}
+			}
+		}
+	}
+
+	$list_info = array_unique_dimensional($list_info);
+	return $list_info;
+}
+
+//allow see data in sortetable
+if (isset($_REQUEST['txt_search_word'])) {
+	//@todo fix to accept a char with 1 char
+	if (strlen(trim($_REQUEST['txt_search_word']))>2) {
+		$list_info = search_language_term($_REQUEST['txt_search_word'],true, true, true,true);
+	}
+}
+
+$parameters=array('id'=>intval($_GET['id']),'sub_language_id'=>intval($_GET['sub_language_id']),'txt_search_word'=> $txt_search_word);
+$table = new SortableTableFromArrayConfig($list_info, 1,20,'data_info');
+$table->set_additional_parameters($parameters);
+//$table->set_header(0, '');
+$table->set_header(0, get_lang('LanguageFile'));
+$table->set_header(1, get_lang('LanguageVariable'));
+$table->set_header(2, get_lang('EnglishName'));
+$table->set_header(3, get_lang('OriginalName'));
+$table->set_header(4, get_lang('SubLanguage'),false);
+$table->set_header(5, get_lang('Edit'),false);
+
+$table->display();
+
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+
+Display :: display_footer();
+?>

+ 44 - 49
main/admin/new_sub_language.php → main/admin/sub_language_add.php

@@ -1,10 +1,5 @@
 <?php
 /* For licensing terms, see /dokeos_license.txt */
-/**
-==============================================================================
-	@author Isaac flores - Added 9 july of 2009
-==============================================================================
-*/
 /*
 ==============================================================================
 		INIT SECTION
@@ -20,14 +15,14 @@ $this_section=SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
 
 /*
-============================================================================== 
+==============================================================================
 		MAIN CODE
-============================================================================== 
+==============================================================================
 */
 // setting the name of the tool
 $tool_name = get_lang('CreateSubLanguage');
 
-// setting breadcrumbs  
+// setting breadcrumbs
 $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array ('url' => 'languages.php', 'name' => get_lang('PlatformLanguages'));
 
@@ -63,18 +58,18 @@ function check_if_language_exist ($original_name,$english_name,$isocode,$sublang
 	if ($count_original_name==1) {
 		$has_error=true;
 		$message_information['original_name']=true;
-	} 
+	}
 	if ($count_english_name==1) {
 		$has_error=true;
 		$message_information['english_name']=true;
-	} 
+	}
 	if ($count_isocode==1) {
 		$has_error=true;
 		$message_information['isocode']=true;
-	} 
+	}
 	if ($has_error===true) {
 		$message_information['execute_add']=false;
-	} 
+	}
 	if ($has_error===false) {
 		$message_information['execute_add']=true;
 	}
@@ -92,7 +87,7 @@ function get_name_of_language_by_id ($language_id) {
  * check if language exist by id
  */
 function check_if_exist_language_by_id ($language_id) {
-	return SubLanguageManager::check_if_exist_language_by_id($language_id); 
+	return SubLanguageManager::check_if_exist_language_by_id($language_id);
 }
 /**
  * check if is parent of sub-language
@@ -101,20 +96,20 @@ function ckeck_if_is_parent_of_sub_language ($parent_id) {
 	$sql='SELECT count(*) AS count FROM language WHERE parent_id="'.Database::escape_string($parent_id).'"';
 	$rs=Database::query($sql,__FILE__,__LINE__);
 	if (Database::num_rows($rs)>0 && Database::result($rs,0,'count')==1) {
-		return true;	
+		return true;
 	} else {
 		return false;
-	}	
+	}
 }
 /**
  * Get all information of sub-language
  */
 function allow_get_all_information_of_sub_language ($parent_id,$sub_language_id) {
-	return SubLanguageManager::get_all_information_of_sub_language($parent_id,$sub_language_id); 
+	return SubLanguageManager::get_all_information_of_sub_language($parent_id,$sub_language_id);
 }
 
 /**
- * Add directory for sub-language 
+ * Add directory for sub-language
  */
 function add_directory_of_sub_language ($path_sub_language) {
 	return SubLanguageManager::add_directory_of_sub_language($path_sub_language);
@@ -144,7 +139,7 @@ function remove_directory_of_sub_language ($path) {
 			return false;
 		}
 	}
-		
+
 }
 /*end declare functions*/
 
@@ -158,7 +153,7 @@ if (isset($_GET['sub_language_id']) && $_GET['sub_language_id']==strval(intval($
 		} else {
 			$sub_language_id_exist=false;
 		}
-		
+
 }
 
 if (isset($_GET['id']) && $_GET['id']==strval(intval($_GET['id']))) {
@@ -169,10 +164,10 @@ if (isset($_GET['id']) && $_GET['id']==strval(intval($_GET['id']))) {
 		} else {
 			$language_id_exist=false;
 		}
-		
+
 } else {
 	$language_name='';
-	$language_id_exist=false;	
+	$language_id_exist=false;
 }
 
 //removed and register
@@ -183,8 +178,8 @@ if ((isset($_GET['id']) && $_GET['id']==strval(intval($_GET['id']))) && (isset($
 		$original_name=$get_all_information['original_name'];
 		$english_name=$get_all_information['english_name'];
 		$isocode=$get_all_information['isocode'];
-		
-	} 
+
+	}
 }
 
 $language_name=get_lang('CreateSubLanguageForLanguage').' ( '.strtolower($language_name).' )';
@@ -201,9 +196,9 @@ if (isset($_POST['SubmitAddNewLanguage'])) {
 	$isocode=$_POST['isocode'];
 	$english_name=str_replace(' ','_',$english_name);
 	$isocode=str_replace(' ','_',$isocode);
-			
+
 	$sublanguage_available=$_POST['sub_language_is_visible'];
-	$check_information=array();	
+	$check_information=array();
 	$check_information=check_if_language_exist($original_name,$english_name,$isocode,$sublanguage_available);
 	foreach ($check_information as $index_information => $value_information) {
 		$allow_insert_info=false;
@@ -211,38 +206,38 @@ if (isset($_POST['SubmitAddNewLanguage'])) {
 			Display::display_error_message(get_lang('AlreadyExists').' "'.get_lang('OriginalName').'" '.'('.$original_name.')');
 		}
 		if ($index_information=='english_name') {
-			Display::display_error_message(get_lang('AlreadyExists').' "'.get_lang('EnglishName').'" '.'('.$english_name.')');			
+			Display::display_error_message(get_lang('AlreadyExists').' "'.get_lang('EnglishName').'" '.'('.$english_name.')');
 		}
 		if ($index_information=='isocode') {
-			Display::display_error_message(get_lang('AlreadyExists').' "'.get_lang('PlatformCharsetTitle').'" '.'('.$isocode.')');			
-		}	
+			Display::display_error_message(get_lang('AlreadyExists').' "'.get_lang('PlatformCharsetTitle').'" '.'('.$isocode.')');
+		}
 		if ($index_information=='execute_add' && $value_information===true) {
 			$allow_insert_info=true;
 		}
 
 	}
-	
+
 	if (strlen($original_name)>0 && strlen($english_name)>0 && strlen($isocode)>0) {
 		if ($allow_insert_info===true && $language_id_exist===true) {
 			$english_name=str_replace(' ','_',$english_name);
-			$isocode=str_replace(' ','_',$isocode);			
+			$isocode=str_replace(' ','_',$isocode);
 			$str_info='<br/>'.get_lang('OriginalName').' : '.$original_name.'<br/>'.get_lang('EnglishName').' : '.$english_name.'<br/>'.get_lang('PlatformCharsetTitle').' : '.$isocode;
 			$path=api_get_path('SYS_LANG_PATH').$english_name;
-			
+
 			$mkdir_result=add_directory_of_sub_language($path);
 			if ($mkdir_result===true) {
 			  	add_sub_language($original_name,$english_name,$isocode,$sublanguage_available,$parent_id);
-			  	Display::display_confirmation_message(get_lang('TheNewSubLanguageHasBeenAdd').$str_info);
+			  	Display::display_confirmation_message(get_lang('TheNewSubLanguageHasBeenAdd').$str_info,false);
 			} else {
-				  Display::display_error_message(get_lang('LanguageDirectoryNotWriteableContactAdmin'));			
+				  Display::display_error_message(get_lang('LanguageDirectoryNotWriteableContactAdmin'));
 			}
 		} else {
 			if ($language_id_exist===false) {
-				Display::display_error_message(get_lang('LanguageParentNotExist'));	
-			}	
+				Display::display_error_message(get_lang('LanguageParentNotExist'));
+			}
 		}
 	} else {
-			Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'));		
+			Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'));
 	}
 }
 if (isset($_POST['SubmitAddDeleteLanguage'])) {
@@ -253,46 +248,46 @@ if (isset($_POST['SubmitAddDeleteLanguage'])) {
 			SubLanguageManager::removed_sub_language($parent_id,$sub_language_id);
 			Display::display_confirmation_message(get_lang('TheSubLanguageHasBeenRemoved'));
 		}
-		
+
 	}
 }
      // ckeck_if_is_parent_of_sub_language($parent_id)===false
 	//
 	if (isset($_GET['action']) && $_GET['action']=='definenewsublanguage') {
 		$text=$language_name;
-		$form = new FormValidator('addsublanguage', 'post', 'new_sub_language.php?id='.Security::remove_XSS($_GET['id']).'&action=definenewsublanguage');
+		$form = new FormValidator('addsublanguage', 'post', 'sub_language_add.php?id='.Security::remove_XSS($_GET['id']).'&action=definenewsublanguage');
 		$class='add';
-		$form->addElement('header', '', $text);			
+		$form->addElement('header', '', $text);
 		$form->addElement('text', 'original_name', get_lang('OriginalName'),'class="input_titles"');
-		$form->addRule('original_name', get_lang('ThisFieldIsRequired'), 'required');	
+		$form->addRule('original_name', get_lang('ThisFieldIsRequired'), 'required');
 		$form->addElement('text', 'english_name', get_lang('EnglishName'),'class="input_titles"');
-		$form->addRule('english_name', get_lang('ThisFieldIsRequired'), 'required');	
+		$form->addRule('english_name', get_lang('ThisFieldIsRequired'), 'required');
 		$form->addElement('text', 'isocode', get_lang('PlatformCharsetTitle'),'class="input_titles"');
-		$form->addRule('isocode', get_lang('ThisFieldIsRequired'), 'required');	
-		$form->addElement('checkbox', 'sub_language_is_visible', '', get_lang('Visibility'));	
+		$form->addRule('isocode', get_lang('ThisFieldIsRequired'), 'required');
+		$form->addElement('checkbox', 'sub_language_is_visible', '', get_lang('Visibility'));
 		$form->addElement('style_submit_button', 'SubmitAddNewLanguage', get_lang('CreateSubLanguage'), 'class="'.$class.'"');
 		$form->display();
 	} else {
 		if (isset($_GET['action']) && $_GET['action']=='deletesublanguage') {
 			$text=$language_name;
-			$form = new FormValidator('deletesublanguage', 'post', 'new_sub_language.php?id='.Security::remove_XSS($_GET['id']).'&sub_language_id='.Security::remove_XSS($_GET['sub_language_id']));
+			$form = new FormValidator('deletesublanguage', 'post', 'sub_language_add.php?id='.Security::remove_XSS($_GET['id']).'&sub_language_id='.Security::remove_XSS($_GET['sub_language_id']));
 			$class='minus';
 			$form->addElement('header', '', $text);
 			$form->addElement('static', '', get_lang('OriginalName'),$original_name);
 			$form->addElement('static', '', get_lang('EnglishName'),$english_name);
-			$form->addElement('static', '', get_lang('PlatformCharsetTitle'),$isocode);				
+			$form->addElement('static', '', get_lang('PlatformCharsetTitle'),$isocode);
 			$form->addElement('style_submit_button', 'SubmitAddDeleteLanguage', get_lang('DeleteSubLanguage'), 'class="'.$class.'"');
-			$form->display();		
+			$form->display();
 		}
 		if (isset($_GET['action']) && $_GET['action']=='definenewsublanguage') {
 			Display::display_normal_message(get_lang('TheSubLanguageForThisLanguageHasBeenAdd'));
 		}
 	}
-	
+
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
-*/	
+*/
 Display :: display_footer();
 ?>

+ 30 - 0
main/admin/sub_language_ajax.inc.php

@@ -0,0 +1,30 @@
+<?php
+/* For licensing terms, see /dokeos_license.txt */
+// including the global dokeos file
+require_once '../inc/global.inc.php';
+require_once 'sub_language.class.php';
+/*
+ * search a term and return description from a glossary
+ */
+global $charset;
+
+$new_language		= Security::remove_XSS($_REQUEST['new_language']);
+$language_variable	= Security::remove_XSS($_REQUEST['variable_language']);
+$file_id			= Security::remove_XSS($_REQUEST['file_id']);
+
+if (isset($new_language) && isset($language_variable) && isset($file_id)) {
+	$file_language = $language_files_to_load[$file_id].'.inc.php';
+	$id_language = intval($_REQUEST['id']);
+	$sub_language_id = intval($_REQUEST['sub']);
+	$all_data_of_language=SubLanguageManager::get_all_information_of_sub_language($id_language,$sub_language_id);
+	$dokeos_path_folder=api_get_path('SYS_LANG_PATH').$all_data_of_language['dokeos_folder'].'/'.$file_language;
+	$all_file_of_directory=SubLanguageManager::get_all_language_variable_in_file($dokeos_path_folder);
+	SubLanguageManager::add_file_in_language_directory ($dokeos_path_folder);
+
+	//update variable language
+	$all_file_of_directory[$language_variable]="\"".mb_convert_encoding($new_language,$charset,'UTF-8')."\";";
+
+	foreach ($all_file_of_directory as $key_value=>$value_info) {
+		SubLanguageManager::write_data_in_file ($dokeos_path_folder,$value_info,$key_value);
+	}
+}

+ 11 - 11
main/admin/subscribe_class2course.php

@@ -24,9 +24,9 @@
 ==============================================================================
 */
 /**
-============================================================================== 
+==============================================================================
 *	@package dokeos.admin
-============================================================================== 
+==============================================================================
 */
 // name of the language file that needs to be included
 $language_file = 'admin';
@@ -73,7 +73,7 @@ if ($_POST['formSent'])
 		{
 			Display::display_error_message(get_lang('AtLeastOneClassAndOneCourse'));
 		}
-		elseif (api_substr($_POST['formSubmit'], -2) == '>>') // add classes to courses 
+		elseif (api_substr($_POST['formSubmit'], -2) == '>>') // add classes to courses
 		{
 			foreach ($courses as $course_code)
 			{
@@ -99,14 +99,14 @@ if ($_POST['formSent'])
 }
 
 $sql = "SELECT id,name FROM $tbl_class WHERE name LIKE '".$first_letter_class."%' ORDER BY ". (count($classes) > 0 ? "(id IN('".implode("','", $classes)."')) DESC," : "")." name";
-$result = api_sql_query($sql, __FILE__, __LINE__);
-$db_classes = api_store_result($result);
+$result = Database::query($sql, __FILE__, __LINE__);
+$db_classes = Database::store_result($result);
 $sql = "SELECT code,visual_code,title FROM $tbl_course WHERE visual_code LIKE '".$first_letter_course."%' ORDER BY ". (count($courses) > 0 ? "(code IN('".implode("','", $courses)."')) DESC," : "")." visual_code";
-$result = api_sql_query($sql, __FILE__, __LINE__);
-$db_courses = api_store_result($result);
+$result = Database::query($sql, __FILE__, __LINE__);
+$db_courses = Database::store_result($result);
 if (!empty ($error_message))
 {
-	Display :: display_normal_message($error_message); 
+	Display :: display_normal_message($error_message);
 }
 ?>
 <form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;">
@@ -116,7 +116,7 @@ if (!empty ($error_message))
    <td width="40%" align="center">
     <b><?php echo get_lang('ClassList'); ?></b>
     <br/><br/>
-    <?php echo get_lang('FirstLetterClass'); ?> : 
+    <?php echo get_lang('FirstLetterClass'); ?> :
     <select name="firstLetterClass" onchange="javascript:document.formulaire.formSent.value='2'; document.formulaire.submit();">
      <option value="">--</option>
      <?php
@@ -128,7 +128,7 @@ if (!empty ($error_message))
    <td width="40%" align="center">
     <b><?php echo get_lang('CourseList'); ?> :</b>
     <br/><br/>
-    <?php echo get_lang('FirstLetterCourse'); ?> : 
+    <?php echo get_lang('FirstLetterCourse'); ?> :
     <select name="firstLetterCourse" onchange="javascript:document.formulaire.formSent.value='2'; document.formulaire.submit();">
      <option value="">--</option>
      <?php
@@ -173,7 +173,7 @@ foreach ($db_courses as $course)
 <?php
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 21 - 17
main/admin/subscribe_user2class.php

@@ -23,9 +23,9 @@
 ==============================================================================
 */
 /**
-============================================================================== 
+==============================================================================
 *	@package dokeos.admin
-============================================================================== 
+==============================================================================
 */
 // name of the language file that needs to be included
 $language_file = 'admin';
@@ -34,7 +34,10 @@ $cidReset = true;
 
 require ('../inc/global.inc.php');
 require_once (api_get_path(LIBRARY_PATH).'classmanager.lib.php');
+
+$this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
+
 $course = $_GET['course'];
 $class_id = intval($_GET['idclass']);
 $form_sent = 0;
@@ -50,9 +53,9 @@ $tbl_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
 $tbl_user 		= Database :: get_main_table(TABLE_MAIN_USER);
 
 $sql = "SELECT name FROM $tbl_class WHERE id='$class_id'";
-$result = api_sql_query($sql, __FILE__, __LINE__);
+$result = Database::query($sql, __FILE__, __LINE__);
 
-if (!list ($class_name) = mysql_fetch_row($result))
+if (!list ($class_name) = Database::fetch_row($result))
 {
 	header('Location: class_list.php?filtreCours='.urlencode($course));
 	exit ();
@@ -110,15 +113,16 @@ if ($_POST['formSent'])
 }
 Display :: display_header($tool_name);
 //api_display_tool_title($tool_name);
-$sql = "SELECT u.user_id,lastname,firstname,username FROM $tbl_user u LEFT JOIN $tbl_class_user cu ON u.user_id=cu.user_id AND class_id='$class_id' WHERE lastname LIKE '".$first_letter_left."%' AND class_id IS NULL ORDER BY ". (count($left_user_list) > 0 ? "(user_id IN(".implode(',', $left_user_list).")) DESC," : "")." lastname";
-$result = api_sql_query($sql, __FILE__, __LINE__);
-$left_users = api_store_result($result);
-$sql = "SELECT u.user_id,lastname,firstname,username FROM $tbl_user u,$tbl_class_user cu WHERE cu.user_id=u.user_id AND class_id='$class_id' AND lastname LIKE '".$first_letter_right."%' ORDER BY ". (count($right_user_list) > 0 ? "(user_id IN(".implode(',', $right_user_list).")) DESC," : "")." lastname";
-$result = api_sql_query($sql, __FILE__, __LINE__);
-$right_users = api_store_result($result);
+$target_name = api_sort_by_first_name() ? 'firstname' : 'lastname';
+$sql = "SELECT u.user_id,lastname,firstname,username FROM $tbl_user u LEFT JOIN $tbl_class_user cu ON u.user_id=cu.user_id AND class_id='$class_id' WHERE ".$target_name." LIKE '".$first_letter_left."%' AND class_id IS NULL ORDER BY ". (count($left_user_list) > 0 ? "(user_id IN(".implode(',', $left_user_list).")) DESC," : "")." ".$target_name;
+$result = Database::query($sql, __FILE__, __LINE__);
+$left_users = Database::store_result($result);
+$sql = "SELECT u.user_id,lastname,firstname,username FROM $tbl_user u,$tbl_class_user cu WHERE cu.user_id=u.user_id AND class_id='$class_id' AND ".$target_name." LIKE '".$first_letter_right."%' ORDER BY ". (count($right_user_list) > 0 ? "(user_id IN(".implode(',', $right_user_list).")) DESC," : "")." ".$target_name;
+$result = Database::query($sql, __FILE__, __LINE__);
+$right_users = Database::store_result($result);
 if (!empty ($error_message))
 {
-	Display :: display_normal_message($error_message); 
+	Display :: display_normal_message($error_message);
 }
 ?>
 <form name="formulaire" method="post" action="<?php echo api_get_self(); ?>?course=<?php echo urlencode($course); ?>&amp;idclass=<?php echo $class_id; ?>" style="margin:0px;">
@@ -128,19 +132,19 @@ if (!empty ($error_message))
    <td width="40%" align="center">
     <b><?php echo get_lang('UsersOutsideClass'); ?> :</b>
     <br/><br/>
-    <?php echo get_lang('FirstLetterUser'); ?> : 
+    <?php echo get_lang('FirstLetterUser'); ?> :
     <select name="firstLetterLeft" onchange="javascript:document.formulaire.formSent.value='2'; document.formulaire.submit();">
      <option value="">--</option>
       <?php
       echo Display :: get_alphabet_options($first_letter_left);
-      ?>  
+      ?>
     </select>
    </td>
    <td width="20%">&nbsp;</td>
    <td width="40%" align="center">
     <b><?php echo get_lang('UsersInsideClass'); ?> :</b>
     <br/><br/>
-    <?php echo get_lang('FirstLetterUser'); ?> : 
+    <?php echo get_lang('FirstLetterUser'); ?> :
     <select name="firstLetterRight" onchange="javascript:document.formulaire.formSent.value='2'; document.formulaire.submit();">
      <option value="">--</option>
 <?php
@@ -156,7 +160,7 @@ echo Display :: get_alphabet_options($first_letter_right);
 foreach ($left_users as $user)
 {
 ?>
-     <option value="<?php echo $user['user_id']; ?>" <?php if(in_array($user['user_id'],$left_user_list)) echo 'selected="selected"'; ?>><?php echo $user['lastname'].' '.$user['firstname'].' ('.$user['username'].')'; ?></option>
+     <option value="<?php echo $user['user_id']; ?>" <?php if (in_array($user['user_id'],$left_user_list)) echo 'selected="selected"'; ?>><?php echo api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')'; ?></option>
 <?php
 }
 ?>
@@ -173,7 +177,7 @@ foreach ($left_users as $user)
 foreach ($right_users as $user)
 {
 ?>
-     <option value="<?php echo $user['user_id']; ?>" <?php if(in_array($user['user_id'],$right_user_list)) echo 'selected="selected"'; ?>><?php echo $user['lastname'].' '.$user['firstname'].' ('.$user['username'].')'; ?></option>
+     <option value="<?php echo $user['user_id']; ?>" <?php if (in_array($user['user_id'],$right_user_list)) echo 'selected="selected"'; ?>><?php echo api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')'; ?></option>
 <?php
 }
 ?>
@@ -185,7 +189,7 @@ foreach ($right_users as $user)
 <?php
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 85 - 83
main/admin/subscribe_user2course.php

@@ -3,28 +3,28 @@
 /*
 ==============================================================================
 	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) 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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 /**
-============================================================================== 
+==============================================================================
 *	This script allows platform admins to add users to courses.
 *	It displays a list of users and a list of courses;
 *	you can select multiple users and courses and then click on
@@ -32,7 +32,7 @@
 *
 *	@package dokeos.admin
 * 	@todo use formvalidator for the form
-============================================================================== 
+==============================================================================
 */
 
 /*
@@ -53,8 +53,9 @@ require_once(api_get_path(LIBRARY_PATH).'course.lib.php');
 require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
 include_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
 
-// security
+$this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
+
 /*
 -----------------------------------------------------------
 	Global constants and variables
@@ -84,14 +85,14 @@ $htmlHeadXtra[] = '
 <script type="text/javascript">
 
 function validate_filter() {
-	
-		document.formulaire.form_sent.value=0;				
+
+		document.formulaire.form_sent.value=0;
 		document.formulaire.submit();
-		
+
 }
-			
 
-	
+
+
 </script>';
 
 // displaying the header
@@ -121,7 +122,7 @@ if (is_array($extra_field_list)) {
 			$new_field_list[] = array('name'=> $extra_field[3], 'variable'=>$extra_field[1], 'data'=> $extra_field[9]);
 		}
 	}
-}	
+}
 
 
 /*
@@ -137,7 +138,7 @@ if ($_POST['form_sent']) {
 	$first_letter_course = $_POST['firstLetterCourse'];
 
 	foreach ($users as $key => $value) {
-		$users[$key] = intval($value);	
+		$users[$key] = intval($value);
 	}
 
 	if ($form_sent == 1) {
@@ -161,9 +162,9 @@ if ($_POST['form_sent']) {
 */
 if(empty($first_letter_user)) {
 	$sql = "SELECT count(*) as nb_users FROM $tbl_user";
-	$result = api_sql_query($sql, __FILE__, __LINE__);
+	$result = Database::query($sql, __FILE__, __LINE__);
 	$num_row = Database::fetch_array($result);
-	if($num_row['nb_users']>1000) 
+	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';
@@ -172,108 +173,109 @@ if(empty($first_letter_user)) {
 }
 
 //Filter by Extra Fields
-$use_extra_fields = false;		
+$use_extra_fields = false;
 if (is_array($extra_field_list)) {
-	if (is_array($new_field_list) && count($new_field_list)>0 ) {			
+	if (is_array($new_field_list) && count($new_field_list)>0 ) {
 		$result_list=array();
 		foreach ($new_field_list as $new_field) {
-			$varname = 'field_'.$new_field['variable'];				
+			$varname = 'field_'.$new_field['variable'];
 			if (Usermanager::is_extra_field_available($new_field['variable'])) {
-				if (isset($_POST[$varname]) && $_POST[$varname]!='0') {		
-					$use_extra_fields = true;																	
+				if (isset($_POST[$varname]) && $_POST[$varname]!='0') {
+					$use_extra_fields = true;
 					$extra_field_result[]= Usermanager::get_extra_user_data_by_value($new_field['variable'], $_POST[$varname]);
-				}								
+				}
 			}
-		}									
+		}
 	}
-}	
+}
 
 if ($use_extra_fields) {
 	$final_result = array();
 	if (count($extra_field_result)>1) {
 		for($i=0;$i<count($extra_field_result)-1;$i++) {
 			if (is_array($extra_field_result[$i+1])) {
-				$final_result  = array_intersect($extra_field_result[$i],$extra_field_result[$i+1]);				
+				$final_result  = array_intersect($extra_field_result[$i],$extra_field_result[$i+1]);
 			}
 		}
-	} else {				
+	} else {
 		$final_result = $extra_field_result[0];
 	}
-			
+
 	$where_filter ='';
 	if ($_configuration['multiple_access_urls']==true) {
 		if (is_array($final_result) && count($final_result)>0) {
 			$where_filter = " AND u.user_id IN  ('".implode("','",$final_result)."') ";
 		} else {
 			//no results
-			$where_filter = " AND u.user_id  = -1"; 
+			$where_filter = " AND u.user_id  = -1";
 		}
-	} else {			
+	} else {
 		if (is_array($final_result) && count($final_result)>0) {
 			$where_filter = " AND user_id IN  ('".implode("','",$final_result)."') ";
 		} else {
 			//no results
-			$where_filter = " AND user_id  = -1"; 
+			$where_filter = " AND user_id  = -1";
 		}
-	}		
+	}
 }
 
+$target_name = api_sort_by_first_name() ? 'firstname' : 'lastname';
 $sql = "SELECT user_id,lastname,firstname,username
 		FROM $tbl_user
-		WHERE user_id<>2 AND lastname LIKE '".$first_letter_user."%' $where_filter
-		ORDER BY ". (count($users) > 0 ? "(user_id IN(".implode(',', $users).")) DESC," : "")." lastname";
+		WHERE user_id<>2 AND ".$target_name." LIKE '".$first_letter_user."%' $where_filter
+		ORDER BY ". (count($users) > 0 ? "(user_id IN(".implode(',', $users).")) DESC," : "")." ".$target_name;
 
-global $_configuration;	
-if ($_configuration['multiple_access_urls']==true) {	
-	$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
+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 u.user_id,lastname,firstname,username  FROM ".$tbl_user ." u 			
-		INNER JOIN $tbl_user_rel_access_url user_rel_url 
-		ON (user_rel_url.user_id = u.user_id)						
-		WHERE u.user_id<>2 AND access_url_id =  $access_url_id AND (lastname LIKE '".$first_letter_user."%' )  $where_filter
-		ORDER BY ". (count($users) > 0 ? "(u.user_id IN(".implode(',', $users).")) DESC," : "")." lastname";			
+	if ($access_url_id != -1){
+		$sql = "SELECT u.user_id,lastname,firstname,username  FROM ".$tbl_user ." u
+		INNER JOIN $tbl_user_rel_access_url user_rel_url
+		ON (user_rel_url.user_id = u.user_id)
+		WHERE u.user_id<>2 AND access_url_id =  $access_url_id AND (".$target_name." LIKE '".$first_letter_user."%' ) $where_filter
+		ORDER BY ". (count($users) > 0 ? "(u.user_id IN(".implode(',', $users).")) DESC," : "")." ".$target_name;
 	}
 }
 
-$result = api_sql_query($sql, __FILE__, __LINE__);
-$db_users = api_store_result($result);
+$result = Database::query($sql, __FILE__, __LINE__);
+$db_users = Database::store_result($result);
 unset($result);
 
 $sql = "SELECT code,visual_code,title FROM $tbl_course WHERE visual_code LIKE '".$first_letter_course."%' ORDER BY ". (count($courses) > 0 ? "(code IN('".implode("','", $courses)."')) DESC," : "")." visual_code";
 
-if ($_configuration['multiple_access_urls']==true) {	
-	$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);	
+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, visual_code, title 
-				FROM $tbl_course as course			
+	if ($access_url_id != -1){
+		$sql = "SELECT code, visual_code, title
+				FROM $tbl_course as course
 		  		INNER JOIN $tbl_course_rel_access_url course_rel_url
-				ON (course_rel_url.course_code= course.code)	  	
-		  		WHERE access_url_id =  $access_url_id  AND (visual_code LIKE '".$first_letter_course."%' ) ORDER BY ". (count($courses) > 0 ? "(code IN('".implode("','", $courses)."')) DESC," : "")." visual_code";		  				  			
+				ON (course_rel_url.course_code= course.code)
+		  		WHERE access_url_id =  $access_url_id  AND (visual_code LIKE '".$first_letter_course."%' ) ORDER BY ". (count($courses) > 0 ? "(code IN('".implode("','", $courses)."')) DESC," : "")." visual_code";
 	}
 }
-	
-$result = api_sql_query($sql, __FILE__, __LINE__);
-$db_courses = api_store_result($result);
+
+$result = Database::query($sql, __FILE__, __LINE__);
+$db_courses = Database::store_result($result);
 unset($result);
 
-if ($_configuration['multiple_access_urls']==true) {	
-	$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);	
+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 ($access_url_id != -1){
 		$sqlNbCours = "	SELECT course_rel_user.course_code, course.title
 			FROM $tbl_course_user as course_rel_user
 			INNER JOIN $tbl_course as course
 			ON course.code = course_rel_user.course_code
 		  	INNER JOIN $tbl_course_rel_access_url course_rel_url
-			ON (course_rel_url.course_code= course.code)	  	
+			ON (course_rel_url.course_code= course.code)
 		  	WHERE access_url_id =  $access_url_id  AND course_rel_user.user_id='".$_user['user_id']."' AND course_rel_user.status='1'
-		  	ORDER BY course.title";		  			
+		  	ORDER BY course.title";
 	}
 }
 
-	
+
 ?>
 
 <form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;">
@@ -284,24 +286,24 @@ if (is_array($extra_field_list)) {
 		echo '<h3>'.get_lang('FilterUsers').'</h3>';
 		foreach ($new_field_list as $new_field) {
 			echo $new_field['name'];
-			$varname = 'field_'.$new_field['variable'];						
+			$varname = 'field_'.$new_field['variable'];
 			echo '&nbsp;<select name="'.$varname.'">';
-			echo '<option value="0">--'.get_lang('Select').'--</option>';	
+			echo '<option value="0">--'.get_lang('Select').'--</option>';
 			foreach	($new_field['data'] as $option) {
 				$checked='';
 				if (isset($_POST[$varname])) {
 					if ($_POST[$varname]==$option[1]) {
-						$checked = 'selected="true"'; 
+						$checked = 'selected="true"';
 					}
-				}							
-				echo '<option value="'.$option[1].'" '.$checked.'>'.$option[1].'</option>';		
+				}
+				echo '<option value="'.$option[1].'" '.$checked.'>'.$option[1].'</option>';
 			}
-			echo '</select>';	
+			echo '</select>';
 			echo '&nbsp;&nbsp;';
 		}
 		echo '<input type="button" value="'.get_lang('Filter').'" onclick="validate_filter()" />';
 		echo '<br /><br />';
-	}	
+	}
 }
 
 ?>
@@ -313,7 +315,7 @@ if (is_array($extra_field_list)) {
     <td width="40%" align="center">
      <b><?php echo get_lang('UserList'); ?></b>
      <br/><br/>
-     <?php echo get_lang('FirstLetterUser'); ?> : 
+     <?php echo get_lang('FirstLetterUser'); ?> :
      <select name="firstLetterUser" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
       <option value="">--</option>
       <?php
@@ -325,25 +327,25 @@ if (is_array($extra_field_list)) {
     <td width="40%" align="center">
      <b><?php echo get_lang('CourseList'); ?> :</b>
      <br/><br/>
-     <?php echo get_lang('FirstLetterCourse'); ?> : 
+     <?php echo get_lang('FirstLetterCourse'); ?> :
      <select name="firstLetterCourse" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
       <option value="">--</option>
       <?php
       echo Display :: get_alphabet_options($first_letter_course);
-      ?> 
+      ?>
      </select>
     </td>
    </tr>
    <tr>
     <td width="40%" align="center">
      <select name="UserList[]" multiple="multiple" size="20" style="width:230px;">
-		<?php
+<?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 $user['lastname'].' '.$user['firstname'].' ('.$user['username'].')'; ?></option>
-		<?php
-		}
-		?>
+?>
+	  <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">
@@ -351,12 +353,12 @@ if (is_array($extra_field_list)) {
    </td>
    <td width="40%" align="center">
     <select name="CourseList[]" multiple="multiple" size="20" style="width:230px;">
-		<?php
+<?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['visual_code'].') '.$course['title']; ?></option>
-		<?php
-		}
+?>
+	 <option value="<?php echo $course['code']; ?>" <?php if(in_array($course['code'],$courses)) echo 'selected="selected"'; ?>><?php echo '('.$course['visual_code'].') '.$course['title']; ?></option>
+<?php
+}
 ?>
     </select>
    </td>
@@ -366,7 +368,7 @@ if (is_array($extra_field_list)) {
 <?php
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 6 - 6
main/admin/system_announcements.php

@@ -168,7 +168,7 @@ if ($action_todo)
 	} elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit') {
 		$form_title = get_lang('EditNews');
 	}
-	
+
 	$form = new FormValidator('system_announcement');
 	$form->addElement('header', '', $form_title);
 	$form->add_textfield('title', get_lang('Title'));
@@ -188,21 +188,21 @@ if ($action_todo)
 	$form->add_timewindow('start','end',get_lang('StartTimeWindow'),get_lang('EndTimeWindow'));
 	$form->addElement('checkbox', 'visible_teacher', get_lang('Visible'), get_lang('Teacher'));
 	$form->addElement('checkbox', 'visible_student', null, get_lang('Student'));
-	$form->addElement('checkbox', 'visible_guest', null, get_lang('Guest'));	
+	$form->addElement('checkbox', 'visible_guest', null, get_lang('Guest'));
 	$form->addElement('hidden', 'id');
 	$form->addElement('checkbox', 'send_mail', get_lang('SendMail'));
-	
+
 	if (isset($_REQUEST['action']) && $_REQUEST['action']=='add') {
 		$text=get_lang('AddNews');
 		$class='add';
 		$form->addElement('hidden', 'action','add');
-		
+
 	} elseif (isset($_REQUEST['action']) && $_REQUEST['action']=='edit') {
 		$text=get_lang('EditNews');
 		$class='save';
 		$form->addElement('hidden', 'action','edit');
 	}
-	
+
 	$form->addElement('style_submit_button', 'submit', $text,'class="'.$class.'"');
 	if (api_get_setting('wcag_anysurfer_public_pages')=='true')
 	{
@@ -239,7 +239,7 @@ if ($action_todo)
 				{
 					Display :: display_normal_message(get_lang('AnnouncementAdded'));
 				}
-				else 
+				else
 				{
 					$show_announcement_list = false;
 					$form->display();

+ 219 - 297
main/admin/user_add.php

@@ -1,50 +1,30 @@
-<?php // $Id: user_add.php 22233 2009-07-20 09:54:05Z ivantcholakov $
-/*
-==============================================================================
-	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
-	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, rue du Corbeau, 108, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
+<?php
+/* For licensing terms, see /dokeos_license.txt */
 /**
 ==============================================================================
 *	@package dokeos.admin
 ==============================================================================
 */
-// name of the language file that needs to be included
-$language_file = array('admin','registration');
+
+// Language files that should be included
+$language_file = array('admin', 'registration');
+
 $cidReset = true;
 
-// including necessary libraries
+// Including necessary libraries.
 require '../inc/global.inc.php';
 $libpath = api_get_path(LIBRARY_PATH);
 require_once $libpath.'fileManage.lib.php';
 require_once $libpath.'fileUpload.lib.php';
 require_once $libpath.'usermanager.lib.php';
 require_once $libpath.'formvalidator/FormValidator.class.php';
-require_once api_get_path(LIBRARY_PATH).'image.lib.php';
-require_once api_get_path(INCLUDE_PATH).'lib/mail.lib.inc.php';
+require_once $libpath.'image.lib.php';
+require_once $libpath.'mail.lib.inc.php';
 
-// section for the tabs
-$this_section=SECTION_PLATFORM_ADMIN;
+// Section for the tabs
+$this_section = SECTION_PLATFORM_ADMIN;
 
-// user permissions
+// User permissions
 api_protect_admin_script();
 
 // Database table definitions
@@ -53,18 +33,18 @@ $table_user 	= Database :: get_main_table(TABLE_MAIN_USER);
 $database 		= Database::get_main_database();
 
 $htmlHeadXtra[] = '
-<script language="JavaScript" type="text/JavaScript">
+<script type="text/javascript">
 <!--
 function enable_expiration_date() { //v2.0
 	document.user_add.radio_expiration_date[0].checked=false;
 	document.user_add.radio_expiration_date[1].checked=true;
 }
 
-function password_switch_radio_button(form, input){
-	var NodeList = document.getElementsByTagName("input");
-	for(var i=0; i< NodeList.length; i++){
-		if(NodeList.item(i).name=="password[password_auto]" && NodeList.item(i).value=="0"){
-			NodeList.item(i).checked=true;
+function password_switch_radio_button() {
+	var input_elements = document.getElementsByTagName("input");
+	for (var i = 0; i < input_elements.length; i++) {
+		if (input_elements.item(i).name == "password[password_auto]" && input_elements.item(i).value == "0") {
+			input_elements.item(i).checked = true;
 		}
 	}
 }
@@ -76,7 +56,7 @@ function display_drh_list(){
 		document.getElementById("id_platform_admin").style.display="none";
 	}
 	else
-	{ 
+	{
 		document.getElementById("drh_list").style.display="none";
 		document.getElementById("id_platform_admin").style.display="block";
 		document.getElementById("drh_select").options[0].selected="selected";
@@ -86,258 +66,256 @@ function display_drh_list(){
 //-->
 </script>';
 
-if(!empty($_GET['message'])){
+if (!empty($_GET['message'])) {
 	$message = urldecode($_GET['message']);
-}	
+}
 
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 $tool_name = get_lang('AddUsers');
+
 // Create the form
 $form = new FormValidator('user_add');
 $form->addElement('header', '', $tool_name);
-// Lastname
-$form->addElement('text','lastname',get_lang('LastName'));
-$form->applyFilter('lastname','html_filter');
-$form->applyFilter('lastname','trim');
-$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
-// Firstname
-$form->addElement('text','firstname',get_lang('FirstName'));
-$form->applyFilter('firstname','html_filter');
-$form->applyFilter('firstname','trim');
-$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
+if (api_is_western_name_order()) {
+	// Firstname
+	$form->addElement('text', 'firstname', get_lang('FirstName'));
+	$form->applyFilter('firstname', 'html_filter');
+	$form->applyFilter('firstname', 'trim');
+	$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
+	// Lastname
+	$form->addElement('text', 'lastname', get_lang('LastName'));
+	$form->applyFilter('lastname', 'html_filter');
+	$form->applyFilter('lastname', 'trim');
+	$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
+} else {
+	// Lastname
+	$form->addElement('text', 'lastname', get_lang('LastName'));
+	$form->applyFilter('lastname', 'html_filter');
+	$form->applyFilter('lastname', 'trim');
+	$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
+	// Firstname
+	$form->addElement('text', 'firstname', get_lang('FirstName'));
+	$form->applyFilter('firstname', 'html_filter');
+	$form->applyFilter('firstname', 'trim');
+	$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
+}
 // Official code
-$form->addElement('text', 'official_code', get_lang('OfficialCode'),array('size' => '40'));
-$form->applyFilter('official_code','html_filter');
-$form->applyFilter('official_code','trim');
+$form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => '40'));
+$form->applyFilter('official_code', 'html_filter');
+$form->applyFilter('official_code', 'trim');
 // Email
-$form->addElement('text', 'email', get_lang('Email'),array('size' => '40'));
+$form->addElement('text', 'email', get_lang('Email'), array('size' => '40'));
 $form->addRule('email', get_lang('EmailWrong'), 'email');
 $form->addRule('email', get_lang('EmailWrong'), 'required');
 // Phone
-$form->addElement('text','phone',get_lang('PhoneNumber'));
+$form->addElement('text', 'phone', get_lang('PhoneNumber'));
 // Picture
 $form->addElement('file', 'picture', get_lang('AddPicture'));
 $allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
+
 $form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
 // Username
-$form->addElement('text', 'username', get_lang('LoginName'),array('maxlength'=>20));
+$form->addElement('text', 'username', get_lang('LoginName'), array('maxlength' => USERNAME_MAX_LENGTH));
 $form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule('username', sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH), 'maxlength', USERNAME_MAX_LENGTH);
 $form->addRule('username', get_lang('OnlyLettersAndNumbersAllowed'), 'username');
-$form->addRule('username', '', 'maxlength',20);
 $form->addRule('username', get_lang('UserTaken'), 'username_available', $user_data['username']);
 // Password
 $group = array();
 $auth_sources = 0; //make available wider as we need it in case of form reset (see below)
-if(count($extAuthSource) > 0)
-{
-	$group[] =& HTML_QuickForm::createElement('radio','password_auto',null,get_lang('ExternalAuthentication').' ',2);
+if (count($extAuthSource) > 0) {
+	$group[] =& HTML_QuickForm::createElement('radio', 'password_auto', null, get_lang('ExternalAuthentication').' ', 2);
 	$auth_sources = array();
-	foreach($extAuthSource as $key => $info)
-	{
+	foreach($extAuthSource as $key => $info) {
 		$auth_sources[$key] = $key;
 	}
-	$group[] =& HTML_QuickForm::createElement('select','auth_source',null,$auth_sources);
-	$group[] =& HTML_QuickForm::createElement('static','','','<br />');
+	$group[] =& HTML_QuickForm::createElement('select', 'auth_source', null, $auth_sources);
+	$group[] =& HTML_QuickForm::createElement('static', '', '', '<br />');
 }
-$group[] =& HTML_QuickForm::createElement('radio','password_auto',get_lang('Password'),get_lang('AutoGeneratePassword').'<br />',1);
-$group[] =& HTML_QuickForm::createElement('radio', 'password_auto','id="radio_user_password"',null,0);
-$group[] =& HTML_QuickForm::createElement('password', 'password',null,'onkeydown=password_switch_radio_button(document.user_add,"password[password_auto]")');
+$group[] =& HTML_QuickForm::createElement('radio', 'password_auto', get_lang('Password'), get_lang('AutoGeneratePassword').'<br />', 1);
+$group[] =& HTML_QuickForm::createElement('radio', 'password_auto', 'id="radio_user_password"', null, 0);
+$group[] =& HTML_QuickForm::createElement('password', 'password', null, array('onkeydown' => 'javascript: password_switch_radio_button();'));
 $form->addGroup($group, 'password', get_lang('Password'), '');
 
 // Status
 $status = array();
-$status[COURSEMANAGER]  = get_lang('Teacher');
+$status[COURSEMANAGER] = get_lang('Teacher');
 $status[STUDENT] = get_lang('Learner');
 $status[DRH] = get_lang('Drh');
 $status[SESSIONADMIN] = get_lang('SessionsAdmin');
 
-$form->addElement('select','status',get_lang('Status'),$status,'id="status_select" onchange="display_drh_list()"');
+$form->addElement('select', 'status', get_lang('Status'), $status, array('id' => 'status_select', 'onchange' => 'javascript: display_drh_list();'));
 $form->addElement('select_language', 'language', get_lang('Language'));
 //drh list (display only if student)
 $display = ($_POST['status'] == STUDENT || !isset($_POST['status'])) ? 'block' : 'none';
-$form->addElement('html','<div id="drh_list" style="display:'.$display.';">');
-$drh_select = $form->addElement('select','hr_dept_id',get_lang('Drh'),array(),'id="drh_select"');
-$drh_list = UserManager :: get_user_list(array('status'=>DRH),array('lastname','firstname'));
+$form->addElement('html', '<div id="drh_list" style="display:'.$display.';">');
+$drh_select = $form->addElement('select', 'hr_dept_id', get_lang('Drh'), array(), 'id="drh_select"');
+$drh_list = UserManager :: get_user_list(array('status' => DRH), api_sort_by_first_name() ? array('firstname', 'lastname') : array('lastname', 'firstname'));
 if (count($drh_list) == 0) {
-	$drh_select->addOption('- '.get_lang('ThereIsNotStillAResponsible').' -',0);	
+	$drh_select->addOption('- '.get_lang('ThereIsNotStillAResponsible', '').' -', 0);
 } else {
-	$drh_select->addOption('- '.get_lang('SelectAResponsible').' -',0);
+	$drh_select->addOption('- '.get_lang('SelectAResponsible').' -', 0);
 }
 
-if(is_array($drh_list))
-{
-	foreach($drh_list as $drh)
-	{
-		$drh_select->addOption($drh['lastname'].' '.$drh['firstname'],$drh['user_id']);
+if (is_array($drh_list)) {
+	foreach ($drh_list as $drh) {
+		$drh_select->addOption(api_get_person_name($drh['firstname'], $drh['lastname']), $drh['user_id']);
 	}
 }
 $form->addElement('html', '</div>');
 
 // Platform admin
 $group = array();
-$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin','id="id_platform_admin"',get_lang('Yes'),1);
-$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin','id="id_platform_admin"',get_lang('No'),0);
+$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin', 'id="id_platform_admin"', get_lang('Yes'), 1);
+$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin', 'id="id_platform_admin"', get_lang('No'), 0);
 $display = ($_POST['status'] == STUDENT || !isset($_POST['status'])) ? 'none' : 'block';
-$form->addElement('html','<div id="id_platform_admin" style="display:'.$display.';">');
+$form->addElement('html', '<div id="id_platform_admin" style="display:'.$display.';">');
 $form->addGroup($group, 'admin', get_lang('PlatformAdmin'), '&nbsp;');
 $form->addElement('html', '</div>');
 // Send email
 $group = array();
-$group[] =& HTML_QuickForm::createElement('radio', 'send_mail',null,get_lang('Yes'),1);
-$group[] =& HTML_QuickForm::createElement('radio', 'send_mail',null,get_lang('No'),0);
+$group[] =& HTML_QuickForm::createElement('radio', 'send_mail', null, get_lang('Yes'), 1);
+$group[] =& HTML_QuickForm::createElement('radio', 'send_mail', null, get_lang('No'), 0);
 $form->addGroup($group, 'mail', get_lang('SendMailToNewUser'), '&nbsp;');
 // Expiration Date
 $form->addElement('radio', 'radio_expiration_date', get_lang('ExpirationDate'), get_lang('NeverExpires'), 0);
 $group = array ();
 $group[] = & $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
-$group[] = & $form->createElement('datepicker','expiration_date', null, array ('form_name' => $form->getAttribute('name'), 'onChange'=>'enable_expiration_date()'));
+$group[] = & $form->createElement('datepicker', 'expiration_date', null, array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();'));
 $form->addGroup($group, 'max_member_group', null, '', false);
 // Active account or inactive account
-$form->addElement('radio','active',get_lang('ActiveAccount'),get_lang('Active'),1);
-$form->addElement('radio','active','',get_lang('Inactive'),0);
+$form->addElement('radio', 'active', get_lang('ActiveAccount'), get_lang('Active'), 1);
+$form->addElement('radio', 'active', '', get_lang('Inactive'), 0);
 
 // EXTRA FIELDS
-$extra = UserManager::get_extra_fields(0,50,5,'ASC');
-$extra_data = UserManager::get_extra_user_data(0,true);
-foreach($extra as $id => $field_details)
-{
-	switch($field_details[2])
-	{
-		case USER_FIELD_TYPE_TEXT:
-			$form->addElement('text', 'extra_'.$field_details[1], $field_details[3], array('size' => 40));
-			$form->applyFilter('extra_'.$field_details[1], 'stripslashes');
-			$form->applyFilter('extra_'.$field_details[1], 'trim');
-			break;
-		case USER_FIELD_TYPE_TEXTAREA:
-			$form->add_html_editor('extra_'.$field_details[1], $field_details[3], false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130'));
-			//$form->addElement('textarea', 'extra_'.$field_details[1], $field_details[3], array('size' => 80));
-			$form->applyFilter('extra_'.$field_details[1], 'stripslashes');
-			$form->applyFilter('extra_'.$field_details[1], 'trim');
-			break;
-		case USER_FIELD_TYPE_RADIO:
-			$group = array();
-			foreach($field_details[9] as $option_id => $option_details)
-			{
-				$options[$option_details[1]] = $option_details[2];
-				$group[] =& HTML_QuickForm::createElement('radio', 'extra_'.$field_details[1], $option_details[1],$option_details[2].'<br />',$option_details[1]);
-			}
-			$form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '');
-			break;
-		case USER_FIELD_TYPE_SELECT:
-			$options = array();
-			foreach($field_details[9] as $option_id => $option_details)
-			{
-				$options[$option_details[1]] = $option_details[2];
-			}
-			$form->addElement('select','extra_'.$field_details[1],$field_details[3],$options,'');			
-			break;
-		case USER_FIELD_TYPE_SELECT_MULTIPLE:
-			$options = array();
-			foreach($field_details[9] as $option_id => $option_details)
-			{
-				$options[$option_details[1]] = $option_details[2];
-			}
-			$form->addElement('select','extra_'.$field_details[1],$field_details[3],$options,array('multiple' => 'multiple'));
-			break;
-		case USER_FIELD_TYPE_DATE:
-			$form->addElement('datepickerdate', 'extra_'.$field_details[1], $field_details[3],array('form_name'=>'user_add'));
-			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear',1900);
-			$defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
-			$form -> setDefaults($defaults);
-			$form->applyFilter('theme', 'trim');
-			break;
-		case USER_FIELD_TYPE_DATETIME:
-			$form->addElement('datepicker', 'extra_'.$field_details[1], $field_details[3],array('form_name'=>'user_add'));
-			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear',1900);
-			$defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
-			$form -> setDefaults($defaults);
-			$form->applyFilter('theme', 'trim');
-			break;
-		case USER_FIELD_TYPE_DOUBLE_SELECT:
-			foreach ($field_details[9] as $key=>$element)
-			{
-				if ($element[2][0] == '*')
-				{
-					$values['*'][$element[0]] = str_replace('*','',$element[2]);
+$extra = UserManager::get_extra_fields(0, 50, 5, 'ASC');
+$extra_data = UserManager::get_extra_user_data(0, true);
+
+foreach($extra as $id => $field_details) {
+	if ($field_details[6] == 1) { // only show extra fields that are visible
+		switch ($field_details[2]) {
+			case USER_FIELD_TYPE_TEXT:
+				$form->addElement('text', 'extra_'.$field_details[1], $field_details[3], array('size' => 40));
+				$form->applyFilter('extra_'.$field_details[1], 'stripslashes');
+				$form->applyFilter('extra_'.$field_details[1], 'trim');
+				break;
+			case USER_FIELD_TYPE_TEXTAREA:
+				$form->add_html_editor('extra_'.$field_details[1], $field_details[3], false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130'));
+				//$form->addElement('textarea', 'extra_'.$field_details[1], $field_details[3], array('size' => 80));
+				$form->applyFilter('extra_'.$field_details[1], 'stripslashes');
+				$form->applyFilter('extra_'.$field_details[1], 'trim');
+				break;
+			case USER_FIELD_TYPE_RADIO:
+				$group = array();
+				foreach ($field_details[9] as $option_id => $option_details) {
+					$options[$option_details[1]] = $option_details[2];
+					$group[] =& HTML_QuickForm::createElement('radio', 'extra_'.$field_details[1], $option_details[1], $option_details[2].'<br />', $option_details[1]);
 				}
-				else 
-				{
-					$values[0][$element[0]] = $element[2];
+				$form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '');
+				break;
+			case USER_FIELD_TYPE_SELECT:
+				$options = array();
+				foreach($field_details[9] as $option_id => $option_details) {
+					$options[$option_details[1]] = $option_details[2];
 				}
-			}
-			
-			$group='';
-			$group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1],'',$values[0],'');
-			$group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1].'*','',$values['*'],'');
-			$form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '&nbsp;');
-			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
-
-			// recoding the selected values for double : if the user has selected certain values, we have to assign them to the correct select form
-			if (key_exists('extra_'.$field_details[1], $extra_data))
-			{
-				// exploding all the selected values (of both select forms)
-				$selected_values = explode(';',$extra_data['extra_'.$field_details[1]]);
-				$extra_data['extra_'.$field_details[1]]  =array();
-				
-				// looping through the selected values and assigning the selected values to either the first or second select form
-				foreach ($selected_values as $key=>$selected_value)
-				{
-					if (key_exists($selected_value,$values[0]))
-					{
-						$extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1]] = $selected_value;
+				$form->addElement('select','extra_'.$field_details[1],$field_details[3],$options,'');
+				break;
+			case USER_FIELD_TYPE_SELECT_MULTIPLE:
+				$options = array();
+				foreach($field_details[9] as $option_id => $option_details) {
+					$options[$option_details[1]] = $option_details[2];
+				}
+				$form->addElement('select', 'extra_'.$field_details[1], $field_details[3], $options, array('multiple' => 'multiple'));
+				break;
+			case USER_FIELD_TYPE_DATE:
+				$form->addElement('datepickerdate', 'extra_'.$field_details[1], $field_details[3], array('form_name' => 'user_add'));
+				$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
+				$defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
+				$form -> setDefaults($defaults);
+				$form->applyFilter('theme', 'trim');
+				break;
+			case USER_FIELD_TYPE_DATETIME:
+				$form->addElement('datepicker', 'extra_'.$field_details[1], $field_details[3], array('form_name' => 'user_add'));
+				$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
+				$defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
+				$form -> setDefaults($defaults);
+				$form->applyFilter('theme', 'trim');
+				break;
+			case USER_FIELD_TYPE_DOUBLE_SELECT:
+				foreach ($field_details[9] as $key => $element) {
+					if ($element[2][0] == '*') {
+						$values['*'][$element[0]] = str_replace('*','',$element[2]);
+					} else {
+						$values[0][$element[0]] = $element[2];
 					}
-					else 
-					{
-						$extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1].'*'] = $selected_value;
+				}
+
+				$group = '';
+				$group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1], '', $values[0], '');
+				$group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1].'*', '', $values['*'], '');
+				$form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '&nbsp;');
+				if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+
+				// recoding the selected values for double : if the user has selected certain values, we have to assign them to the correct select form
+				if (key_exists('extra_'.$field_details[1], $extra_data)) {
+					// exploding all the selected values (of both select forms)
+					$selected_values = explode(';', $extra_data['extra_'.$field_details[1]]);
+					$extra_data['extra_'.$field_details[1]] = array();
+
+					// looping through the selected values and assigning the selected values to either the first or second select form
+					foreach ($selected_values as $key => $selected_value) {
+						if (key_exists($selected_value, $values[0])) {
+							$extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1]] = $selected_value;
+						} else {
+							$extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1].'*'] = $selected_value;
+						}
 					}
 				}
-			}
-			break;
-		case USER_FIELD_TYPE_DIVIDER:
-			$form->addElement('static',$field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
-			break;
+				break;
+			case USER_FIELD_TYPE_DIVIDER:
+				$form->addElement('static', $field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
+				break;
+		}
 	}
 }
 
-
 // Set default values
 $defaults['admin']['platform_admin'] = 0;
 $defaults['mail']['send_mail'] = 1;
 $defaults['password']['password_auto'] = 1;
 $defaults['active'] = 1;
-$defaults['expiration_date']=array();
+$defaults['expiration_date'] = array();
 $days = api_get_setting('account_valid_duration');
 $time = strtotime('+'.$days.' day');
-$defaults['expiration_date']['d']=date('d',$time);
-$defaults['expiration_date']['F']=date('m',$time);
-$defaults['expiration_date']['Y']=date('Y',$time);
+$defaults['expiration_date']['d'] = date('d', $time);
+$defaults['expiration_date']['F'] = date('m', $time);
+$defaults['expiration_date']['Y'] = date('Y', $time);
 $defaults['radio_expiration_date'] = 0;
 $defaults['status'] = STUDENT;
-$defaults = array_merge($defaults,$extra_data);
+$defaults = array_merge($defaults, $extra_data);
 $form->setDefaults($defaults);
+
 // Submit button
 /*
-$form->addElement('style_submit_button', 'submit', get_lang('Add'), 'class="add"') ;
+$form->addElement('style_submit_button', 'submit', get_lang('Add'), 'class="add"');
 $form->addElement('style_submit_button', 'submit_plus', get_lang('Add').'+', 'class="add"');
 */
-$select_level = array (); 	
+$select_level = array ();
 $html_results_enabled[] = FormValidator :: createElement ('style_submit_button', 'submit_plus', get_lang('Add').'+', 'class="add"');
 $html_results_enabled[] = FormValidator :: createElement ('style_submit_button', 'submit', get_lang('Add'), 'class="add"');
 $form->addGroup($html_results_enabled);
 
 // Validate form
-if( $form->validate())
-{
+if( $form->validate()) {
 	$check = Security::check_token('post');
-	if($check)
-	{
+	if ($check) {
 		$user = $form->exportValues();
+
 		$picture_element = & $form->getElement('picture');
 		$picture = $picture_element->getValue();
+
 		$picture_uri = '';
-		if (strlen($picture['name']) > 0 ) {
-		$picture_uri = uniqid('').'_'.replace_dangerous_char($picture['name']);
-		}
+
 		$lastname = $user['lastname'];
 		$firstname = $user['firstname'];
 		$official_code = $user['official_code'];
@@ -350,130 +328,78 @@ if( $form->validate())
 		$platform_admin = intval($user['admin']['platform_admin']);
 		$send_mail = intval($user['mail']['send_mail']);
 		$hr_dept_id = intval($user['hr_dept_id']);
-		if(count($extAuthSource) > 0 && $user['password']['password_auto'] == '2')
-		{
+		if (count($extAuthSource) > 0 && $user['password']['password_auto'] == '2') {
 			$auth_source = $user['password']['auth_source'];
 			$password = 'PLACEHOLDER';
-		}
-		else
-		{
+		} else {
 			$auth_source = PLATFORM_AUTH_SOURCE;
 			$password = $user['password']['password_auto'] == '1' ? api_generate_password() : $user['password']['password'];
 		}
-		if ($user['radio_expiration_date']=='1' )
-		{
-			$expiration_date=$user['expiration_date'];
-		}
-		else
-		{
-			$expiration_date='0000-00-00 00:00:00';
+		if ($user['radio_expiration_date'] == '1') {
+			$expiration_date = $user['expiration_date'];
+		} else {
+			$expiration_date = '0000-00-00 00:00:00';
 		}
 		$active = intval($user['active']);
-	
-		$user_id = UserManager::create_user($firstname,$lastname,$status,$email,$username,$password,$official_code,$language,$phone,$picture_uri,$auth_source,$expiration_date,$active, $hr_dept_id);
-
-		// picture path
-		$picture_path = api_get_path(SYS_CODE_PATH).'upload/users/'.$user_id.'/';		
-
-		if (strlen($picture['name']) > 0 ) {			
-			if (!is_dir($picture_path)) {
-				if (mkdir($picture_path)) {
-					$perm = api_get_setting('permissions_for_new_directories');
-					$perm = octdec(!empty($perm)?$perm:'0770');					
-					chmod($picture_path,$perm);
-				}
-			}
-			$picture_infos=getimagesize($_FILES['picture']['tmp_name']);
-			$type=$picture_infos[2];
-			$small_temp = UserManager::resize_picture($_FILES['picture']['tmp_name'], 22); //small picture
-			$medium_temp = UserManager::resize_picture($_FILES['picture']['tmp_name'], 85); //medium picture
-			$temp = UserManager::resize_picture($_FILES['picture']['tmp_name'], 200); // normal picture
-			$big_temp = new image($_FILES['picture']['tmp_name']); // original picture
-			
-		    switch (!empty($type)) {
-			    case 2 :
-			    	$small_temp->send_image('JPG',$picture_path.'small_'.$picture_uri); 
-			    	$medium_temp->send_image('JPG',$picture_path.'medium_'.$picture_uri);
-			    	$temp->send_image('JPG',$picture_path.$picture_uri);
-			    	$big_temp->send_image('JPG',$picture_path.'big_'.$picture_uri);	    		 
-			    	break;
-			    case 3 :
-			    	$small_temp->send_image('PNG',$picture_path.'small_'.$picture_uri);
-			    	$medium_temp->send_image('PNG',$picture_path.'medium_'.$picture_uri);
-			    	$temp->send_image('PNG',$picture_path.$picture_uri);
-			    	$big_temp->send_image('PNG',$picture_path.'big_'.$picture_uri);
-			    	break;
-			    case 1 :
-			    	$small_temp->send_image('GIF',$picture_path.'small_'.$picture_uri);
-			    	$medium_temp->send_image('GIF',$picture_path.'medium_'.$picture_uri);
-			    	$temp->send_image('GIF',$picture_path.$picture_uri);
-			    	$big_temp->send_image('GIF',$picture_path.'big_'.$picture_uri);	    		 
-			    	break;
-		    }
+
+		$user_id = UserManager::create_user($firstname, $lastname, $status, $email, $username, $password, $official_code, $language, $phone, $picture_uri, $auth_source, $expiration_date, $active, $hr_dept_id);
+
+		if (!empty($picture['name'])) {
+			$picture_uri = UserManager::update_user_picture($user_id, $_FILES['picture']['name'], $_FILES['picture']['tmp_name']);
+			UserManager::update_user($user_id, $firstname, $lastname, $username, $password, $auth_source, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active, null, $hr_dept_id, null, $language);
 		}
-		
+
 		$extras = array();
-		foreach($user as $key => $value)
-		{
-			if(substr($key,0,6)=='extra_') //an extra field
-			{
-				$myres = UserManager::update_extra_field_value($user_id,substr($key,6),$value);
+		foreach($user as $key => $value) {
+			if (substr($key, 0, 6) == 'extra_') { //an extra field
+				$myres = UserManager::update_extra_field_value($user_id, substr($key, 6), $value);
 			}
 		}
-		
-		if ($platform_admin)
-		{
+
+		if ($platform_admin) {
 			$sql = "INSERT INTO $table_admin SET user_id = '".$user_id."'";
-			api_sql_query($sql,__FILE__,__LINE__);
+			Database::query($sql,__FILE__,__LINE__);
 		}
-		if (!empty ($email) && $send_mail)
-		{
-			$recipient_name = $firstname.' '.$lastname;
-			$emailsubject = '['.get_setting('siteName').'] '.get_lang('YourReg').' '.get_setting('siteName');			
-									
-			$sender_name = get_setting('administratorName').' '.get_setting('administratorSurname');
-		    $email_admin = get_setting('emailAdministrator');
-		    
-		    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);					
-					$emailbody=get_lang('Dear')." ".stripslashes("$firstname $lastname").",\n\n".get_lang('YouAreReg')." ". get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". get_setting('siteName') ." ". get_lang('Is') ." : ". $url['url'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".get_setting('administratorName')." ".get_setting('administratorSurname')."\n". get_lang('Manager'). " ".get_setting('siteName')."\nT. ".get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".get_setting('emailAdministrator');
-				}		
+		if (!empty($email) && $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');
+
+			$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');
+
+			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);
+					$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $url['url'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
+				}
 			}
 			else {
-				$emailbody=get_lang('Dear')." ".stripslashes("$firstname $lastname").",\n\n".get_lang('YouAreReg')." ". get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". get_setting('siteName') ." ". get_lang('Is') ." : ". $_configuration['root_web'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".get_setting('administratorName')." ".get_setting('administratorSurname')."\n". get_lang('Manager'). " ".get_setting('siteName')."\nT. ".get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".get_setting('emailAdministrator');
+				$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $_configuration['root_web'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
 			}
-					
-		    	
-			@api_mail($recipient_name, $email, $emailsubject, $emailbody, $sender_name,$email_admin);
+			@api_mail($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
 		}
 		Security::clear_token();
-		if(isset($user['submit_plus']))
-		{
+		if (isset($user['submit_plus'])) {
 			//we want to add more. Prepare report message and redirect to the same page (to clean the form)
 			$tok = Security::get_token();
 			header('Location: user_add.php?message='.urlencode(get_lang('UserAdded')).'&sec_token='.$tok);
 			exit ();
-		}
-		else
-		{
-			$tok = Security::get_token();		
+		} else {
+			$tok = Security::get_token();
 			header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('UserAdded')).'&sec_token='.$tok);
 			exit ();
 		}
 	}
-}
-else
-{
-	if(isset($_POST['submit']))
-	{
+} else {
+	if (isset($_POST['submit'])) {
 		Security::clear_token();
 	}
 	$token = Security::get_token();
-	$form->addElement('hidden','sec_token');
+	$form->addElement('hidden', 'sec_token');
 	$form->setConstants(array('sec_token' => $token));
 }
+
 // Display form
 Display::display_header($tool_name);
 //api_display_tool_title($tool_name);
@@ -481,10 +407,6 @@ if(!empty($message)){
 	Display::display_normal_message(stripslashes($message));
 }
 $form->display();
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
+
+// Footer
 Display::display_footer();
-?>

+ 206 - 284
main/admin/user_edit.php

@@ -1,46 +1,37 @@
 <?php // $Id: user_edit.php 22233 2009-07-20 09:54:05Z ivantcholakov $
-/*
-==============================================================================
-	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
-	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, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
+/* For licensing terms, see /dokeos_license.txt */
 /**
 ==============================================================================
 *	@package dokeos.admin
 ==============================================================================
 */
-// name of the language file that needs to be included
-$language_file=array('admin','registration');
-$cidReset=true;
-include('../inc/global.inc.php');
-$this_section=SECTION_PLATFORM_ADMIN;
+
+// Language files that should be included
+$language_file = array('admin', 'registration');
+
+$cidReset = true;
+
+include '../inc/global.inc.php';
+
+$this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
 
 $htmlHeadXtra[] = '
-<script language="JavaScript" type="text/JavaScript">
+<script type="text/javascript">
 <!--
 function enable_expiration_date() { //v2.0
-	document.user_add.radio_expiration_date[0].checked=false;
-	document.user_add.radio_expiration_date[1].checked=true;
+	document.user_edit.radio_expiration_date[0].checked=false;
+	document.user_edit.radio_expiration_date[1].checked=true;
+}
+
+function password_switch_radio_button(){
+	var input_elements = document.getElementsByTagName("input");
+	for (var i = 0; i < input_elements.length; i++) {
+		if(input_elements.item(i).name == "reset_password" && input_elements.item(i).value == "2") {
+			input_elements.item(i).checked = true;
+		}
+	}
 }
 
 function display_drh_list(){
@@ -49,194 +40,197 @@ function display_drh_list(){
 		document.getElementById("drh_list").style.display="block";
 	}
 	else
-	{ 
+	{
 		document.getElementById("drh_list").style.display="none";
 		document.getElementById("drh_select").options[0].selected="selected";
 	}
 }
-		
+
 function show_image(image,width,height) {
 	width = parseInt(width) + 20;
-	height = parseInt(height) + 20;			
-	window_x = window.open(image,\'windowX\',\'width=\'+ width + \', height=\'+ height + \' , resizable=0\');		
-}		
+	height = parseInt(height) + 20;
+	window_x = window.open(image,\'windowX\',\'width=\'+ width + \', height=\'+ height + \' , resizable=0\');
+}
 //-->
 </script>';
 
+$libpath = api_get_path(LIBRARY_PATH);
+require_once $libpath.'fileManage.lib.php';
+require_once $libpath.'fileUpload.lib.php';
+require_once $libpath.'usermanager.lib.php';
+require_once $libpath.'formvalidator/FormValidator.class.php';
+require_once $libpath.'image.lib.php';
+require_once $libpath.'mail.lib.inc.php';
 
-require_once(api_get_path(LIBRARY_PATH).'fileManage.lib.php');
-require_once(api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
-require_once(api_get_path(LIBRARY_PATH).'usermanager.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-require_once (api_get_path(LIBRARY_PATH).'image.lib.php');
-require_once(api_get_path(INCLUDE_PATH).'lib/mail.lib.inc.php');
-$user_id=isset($_GET['user_id']) ? intval($_GET['user_id']) : intval($_POST['user_id']);
-$noPHP_SELF=true;
-$tool_name=get_lang('ModifyUserInfo');
+$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : intval($_POST['user_id']);
+$noPHP_SELF = true;
+$tool_name = get_lang('ModifyUserInfo');
 
-$interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[]=array('url' => "user_list.php","name" => get_lang('UserList'));
+$interbreadcrumb[] = array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array('url' => "user_list.php","name" => get_lang('UserList'));
 
 $table_user = Database::get_main_table(TABLE_MAIN_USER);
 $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
 $sql = "SELECT u.*, a.user_id AS is_admin FROM $table_user u LEFT JOIN $table_admin a ON a.user_id = u.user_id WHERE u.user_id = '".$user_id."'";
-$res = api_sql_query($sql,__FILE__,__LINE__);
-if(mysql_num_rows($res) != 1)
-{
+$res = Database::query($sql, __FILE__, __LINE__);
+if (Database::num_rows($res) != 1) {
 	header('Location: user_list.php');
 	exit;
 }
-$user_data = mysql_fetch_array($res,MYSQL_ASSOC);
+
+$user_data = Database::fetch_array($res, 'ASSOC');
 $user_data['platform_admin'] = is_null($user_data['is_admin']) ? 0 : 1;
 $user_data['send_mail'] = 0;
 $user_data['old_password'] = $user_data['password'];
 unset($user_data['password']);
 
-$user_data = array_merge($user_data, Usermanager :: get_extra_user_data($user_id,true));
+$user_data = array_merge($user_data, Usermanager :: get_extra_user_data($user_id, true));
 
 // Create the form
-$form = new FormValidator('user_add','post','','',array('style' => 'width: 60%; float: '.($text_dir=='rtl'?'right;':'left;')));
+$form = new FormValidator('user_edit', 'post', '', '', array('style' => 'width: 60%; float: '.($text_dir == 'rtl' ? 'right;' : 'left;')));
 $form->addElement('header', '', $tool_name);
-$form->addElement('hidden','user_id',$user_id);
-
-// Lastname
-$form->addElement('text','lastname',get_lang('LastName'));
-$form->applyFilter('lastname','html_filter');
-$form->applyFilter('lastname','trim');
-$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
-
-// Firstname
-$form->addElement('text','firstname',get_lang('FirstName'));
-$form->applyFilter('firstname','html_filter');
-$form->applyFilter('firstname','trim');
-$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
+$form->addElement('hidden', 'user_id', $user_id);
+
+if (api_is_western_name_order()) {
+	// Firstname
+	$form->addElement('text', 'firstname', get_lang('FirstName'));
+	$form->applyFilter('firstname', 'html_filter');
+	$form->applyFilter('firstname', 'trim');
+	$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
+	// Lastname
+	$form->addElement('text', 'lastname', get_lang('LastName'));
+	$form->applyFilter('lastname', 'html_filter');
+	$form->applyFilter('lastname', 'trim');
+	$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
+} else {
+	// Lastname
+	$form->addElement('text', 'lastname', get_lang('LastName'));
+	$form->applyFilter('lastname', 'html_filter');
+	$form->applyFilter('lastname', 'trim');
+	$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
+	// Firstname
+	$form->addElement('text', 'firstname', get_lang('FirstName'));
+	$form->applyFilter('firstname', 'html_filter');
+	$form->applyFilter('firstname', 'trim');
+	$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
+}
 
 // Official code
-$form->addElement('text', 'official_code', get_lang('OfficialCode'),array('size' => '40'));
-$form->applyFilter('official_code','html_filter');
-$form->applyFilter('official_code','trim');
+$form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => '40'));
+$form->applyFilter('official_code', 'html_filter');
+$form->applyFilter('official_code', 'trim');
 
 // Email
-$form->addElement('text', 'email', get_lang('Email'),array('size' => '40'));
+$form->addElement('text', 'email', get_lang('Email'), array('size' => '40'));
 $form->addRule('email', get_lang('EmailWrong'), 'email');
 $form->addRule('email', get_lang('EmailWrong'), 'required');
 
 // OpenID
-if(api_get_setting('openid_authentication')=='true')
-{
-	$form->addElement('text', 'openid', get_lang('OpenIDURL'),array('size' => '40'));
+if (api_get_setting('openid_authentication') == 'true') {
+	$form->addElement('text', 'openid', get_lang('OpenIDURL'), array('size' => '40'));
 }
 
 // Phone
-$form->addElement('text','phone',get_lang('PhoneNumber'));
+$form->addElement('text', 'phone', get_lang('PhoneNumber'));
 
 // Picture
 $form->addElement('file', 'picture', get_lang('AddPicture'));
 $allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
 $form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
-if (strlen($user_data['picture_uri']) > 0 )
-{
+if (strlen($user_data['picture_uri']) > 0) {
 	$form->addElement('checkbox', 'delete_picture', '', get_lang('DelImage'));
 }
 
 // Username
-$form->addElement('text', 'username', get_lang('LoginName'),array('maxlength'=>20));
+$form->addElement('text', 'username', get_lang('LoginName'), array('maxlength' => USERNAME_MAX_LENGTH));
 $form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule('username', sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH), 'maxlength', USERNAME_MAX_LENGTH);
 $form->addRule('username', get_lang('OnlyLettersAndNumbersAllowed'), 'username');
-$form->addRule('username', '', 'maxlength',20);
 $form->addRule('username', get_lang('UserTaken'), 'username_available', $user_data['username']);
 
 // Password
-$form->addElement('radio','reset_password',get_lang('Password'),get_lang('DontResetPassword'),0);
-if(count($extAuthSource) > 0)
+$form->addElement('radio', 'reset_password', get_lang('Password'), get_lang('DontResetPassword'), 0);
+if (count($extAuthSource) > 0)
 {
-	$group[] =& HTML_QuickForm::createElement('radio','reset_password',null,get_lang('ExternalAuthentication').' ',3);
+	$group[] =& HTML_QuickForm::createElement('radio', 'reset_password', null, get_lang('ExternalAuthentication').' ', 3);
 	$auth_sources = array();
-	foreach($extAuthSource as $key => $info)
-	{
+	foreach($extAuthSource as $key => $info) {
 		$auth_sources[$key] = $key;
 	}
-	$group[] =& HTML_QuickForm::createElement('select','auth_source',null,$auth_sources);
-	$group[] =& HTML_QuickForm::createElement('static','','','<br />');
-	$form->addGroup($group, 'password', null, '',false);
+	$group[] =& HTML_QuickForm::createElement('select', 'auth_source', null, $auth_sources);
+	$group[] =& HTML_QuickForm::createElement('static', '', '', '<br />');
+	$form->addGroup($group, 'password', null, '', false);
 }
-$form->addElement('radio','reset_password',null,get_lang('AutoGeneratePassword'),1);
+$form->addElement('radio', 'reset_password', null, get_lang('AutoGeneratePassword'), 1);
 $group = array();
-$group[] =& HTML_QuickForm::createElement('radio', 'reset_password',null,null,2);
-$group[] =& HTML_QuickForm::createElement('password', 'password',null,null);
-$form->addGroup($group, 'password', null, '',false);
+$group[] =& HTML_QuickForm::createElement('radio', 'reset_password', null, null, 2);
+$group[] =& HTML_QuickForm::createElement('password', 'password', null, array('onkeydown' => 'javascript: password_switch_radio_button();'));
+$form->addGroup($group, 'password', null, '', false);
 
 // Status
 $status = api_get_status_langvars();
-$form->addElement('select','status',get_lang('Status'),$status,'id="status_select" onchange="display_drh_list()"');
+$form->addElement('select', 'status', get_lang('Status'), $status, array('id' => 'status_select', 'onchange' => 'javascript: display_drh_list();'));
 
 //Language
 $form->addElement('select_language', 'language', get_lang('Language'));
 
 $display = $user_data['status'] == STUDENT || $_POST['status'] == STUDENT ? 'block' : 'none';
-$form->addElement('html','<div id="drh_list" style="display:'.$display.';">');
-$drh_select = $form->addElement('select','hr_dept_id',get_lang('Drh'),array(),'id="drh_select"');
-$drh_list = UserManager :: get_user_list(array('status'=>DRH),array('lastname','firstname'));
+$form->addElement('html', '<div id="drh_list" style="display:'.$display.';">');
+$drh_select = $form->addElement('select', 'hr_dept_id', get_lang('Drh'), array(), 'id="drh_select"');
+$drh_list = UserManager :: get_user_list(array('status' => DRH), api_sort_by_first_name() ? array('firstname', 'lastname') : array('lastname', 'firstname'));
 
 if (count($drh_list) == 0) {
-	$drh_select->addOption('- '.get_lang('ThereIsNotStillAResponsible').' -',0);	
+	$drh_select->addOption('- '.get_lang('ThereIsNotStillAResponsible', '').' -', 0);
 } else {
-	$drh_select->addOption('- '.get_lang('SelectAResponsible').' -',0);
+	$drh_select->addOption('- '.get_lang('SelectAResponsible').' -', 0);
 }
 
-foreach($drh_list as $drh)
-{
-	$drh_select->addOption($drh['lastname'].' '.$drh['firstname'],$drh['user_id']);
+foreach($drh_list as $drh) {
+	$drh_select->addOption(api_get_person_name($drh['firstname'], $drh['lastname']), $drh['user_id']);
 }
 $form->addElement('html', '</div>');
 
 // Platform admin
 // Only when changing another user!
-if($user_id != $_SESSION['_uid'])
-{
+if ($user_id != $_SESSION['_uid']) {
 	$group = array();
-	$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin',null,get_lang('Yes'),1);
-	$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin',null,get_lang('No'),0);
-	if ($user_data['status']<>5) {
-		$form->addGroup($group, 'admin', get_lang('PlatformAdmin'), '&nbsp;',false);	
-	} 
-	
+	$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin', null, get_lang('Yes'), 1);
+	$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin', null, get_lang('No'), 0);
+	if ($user_data['status'] <> 5) {
+		$form->addGroup($group, 'admin', get_lang('PlatformAdmin'), '&nbsp;', false);
+	}
 }
 
 // Send email
 $group = array();
-$group[] =& HTML_QuickForm::createElement('radio', 'send_mail',null,get_lang('Yes'),1);
-$group[] =& HTML_QuickForm::createElement('radio', 'send_mail',null,get_lang('No'),0);
-$form->addGroup($group, 'mail', get_lang('SendMailToNewUser'), '&nbsp;',false);
+$group[] =& HTML_QuickForm::createElement('radio', 'send_mail', null, get_lang('Yes'), 1);
+$group[] =& HTML_QuickForm::createElement('radio', 'send_mail', null, get_lang('No'), 0);
+$form->addGroup($group, 'mail', get_lang('SendMailToNewUser'), '&nbsp;', false);
 
 // Registration Date
-$form->addElement('static','registration_date', get_lang('RegistrationDate'), $user_data['registration_date']);
+$form->addElement('static', 'registration_date', get_lang('RegistrationDate'), $user_data['registration_date']);
 
-if(! $user_data['platform_admin'] )
-{
+if (!$user_data['platform_admin']) {
 	// Expiration Date
 	$form->addElement('radio', 'radio_expiration_date', get_lang('ExpirationDate'), get_lang('NeverExpires'), 0);
 	$group = array ();
 	$group[] = & $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
-	$group[] = & $form->createElement('datepicker', 'expiration_date',null, array ('form_name' => $form->getAttribute('name'), 'onChange'=>'enable_expiration_date()'));
+	$group[] = & $form->createElement('datepicker', 'expiration_date', null, array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();'));
 	$form->addGroup($group, 'max_member_group', null, '', false);
 
 	// Active account or inactive account
-	$form->addElement('radio','active',get_lang('ActiveAccount'),get_lang('Active'),1);
-	$form->addElement('radio','active','',get_lang('Inactive'),0);
+	$form->addElement('radio', 'active', get_lang('ActiveAccount'), get_lang('Active'), 1);
+	$form->addElement('radio', 'active', '', get_lang('Inactive'), 0);
 }
 
 
 // EXTRA FIELDS
-$extra = UserManager::get_extra_fields(0,50,5,'ASC');
-foreach($extra as $id => $field_details)
-{
-    if($field_details[6] == 0)
-    {
-        continue;
-    }
-    switch($field_details[2])
-	{
+$extra = UserManager::get_extra_fields(0, 50, 5, 'ASC');
+foreach ($extra as $id => $field_details) {
+	if ($field_details[6] == 0) {
+		continue;
+	}
+	switch ($field_details[2]) {
 		case USER_FIELD_TYPE_TEXT:
 			$form->addElement('text', 'extra_'.$field_details[1], $field_details[3], array('size' => 40));
 			$form->applyFilter('extra_'.$field_details[1], 'stripslashes');
@@ -250,39 +244,36 @@ foreach($extra as $id => $field_details)
 			break;
 		case USER_FIELD_TYPE_RADIO:
 			$group = array();
-			foreach($field_details[9] as $option_id => $option_details)
-			{
+			foreach ($field_details[9] as $option_id => $option_details) {
 				$options[$option_details[1]] = $option_details[2];
-				$group[] =& HTML_QuickForm::createElement('radio', 'extra_'.$field_details[1], $option_details[1],$option_details[2].'<br />',$option_details[1]);
+				$group[] =& HTML_QuickForm::createElement('radio', 'extra_'.$field_details[1], $option_details[1], $option_details[2].'<br />', $option_details[1]);
 			}
 			$form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '');
 			break;
 		case USER_FIELD_TYPE_SELECT:
 			$options = array();
-			foreach($field_details[9] as $option_id => $option_details)
-			{
+			foreach ($field_details[9] as $option_id => $option_details) {
 				$options[$option_details[1]] = $option_details[2];
 			}
-			$form->addElement('select','extra_'.$field_details[1],$field_details[3],$options,'');			
+			$form->addElement('select', 'extra_'.$field_details[1], $field_details[3], $options, '');
 			break;
 		case USER_FIELD_TYPE_SELECT_MULTIPLE:
 			$options = array();
-			foreach($field_details[9] as $option_id => $option_details)
-			{
+			foreach ($field_details[9] as $option_id => $option_details) {
 				$options[$option_details[1]] = $option_details[2];
 			}
-			$form->addElement('select','extra_'.$field_details[1],$field_details[3],$options,array('multiple' => 'multiple'));
+			$form->addElement('select', 'extra_'.$field_details[1], $field_details[3], $options, array('multiple' => 'multiple'));
 			break;
 		case USER_FIELD_TYPE_DATE:
-			$form->addElement('datepickerdate', 'extra_'.$field_details[1], $field_details[3],array('form_name'=>'user_add'));
-			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear',1900);
+			$form->addElement('datepickerdate', 'extra_'.$field_details[1], $field_details[3], array('form_name' => 'user_edit'));
+			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
 			$defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
 			$form -> setDefaults($defaults);
 			$form->applyFilter('theme', 'trim');
 			break;
 		case USER_FIELD_TYPE_DATETIME:
-			$form->addElement('datepicker', 'extra_'.$field_details[1], $field_details[3],array('form_name'=>'user_add'));
-			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear',1900);
+			$form->addElement('datepicker', 'extra_'.$field_details[1], $field_details[3], array('form_name' => 'user_edit'));
+			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
 			$defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
 			$form -> setDefaults($defaults);
 			$form->applyFilter('theme', 'trim');
@@ -290,89 +281,42 @@ foreach($extra as $id => $field_details)
 	}
 }
 
-
 // Submit button
-$form->addElement('style_submit_button', 'submit',get_lang('ModifyInformation'),'class="save"');
-
+$form->addElement('style_submit_button', 'submit', get_lang('ModifyInformation'), 'class="save"');
 
 // Set default values
-$expiration_date=$user_data['expiration_date'];
-if ($expiration_date=='0000-00-00 00:00:00')
-{
-	$user_data['radio_expiration_date']=0;
-	$user_data['expiration_date']=array();
-	$user_data['expiration_date']['d']=date('d');
-	$user_data['expiration_date']['F']=date('m');
-	$user_data['expiration_date']['Y']=date('Y');
-}
-else
-{
-	$user_data['radio_expiration_date']=1;
-	$user_data['expiration_date']=array();
-	$user_data['expiration_date']['d']=substr($expiration_date,8,2);
-	$user_data['expiration_date']['F']=substr($expiration_date,5,2);
-	$user_data['expiration_date']['Y']=substr($expiration_date,0,4);
+$user_data['reset_password'] = 0;
+$expiration_date = $user_data['expiration_date'];
+if ($expiration_date == '0000-00-00 00:00:00') {
+	$user_data['radio_expiration_date'] = 0;
+	$user_data['expiration_date'] = array();
+	$user_data['expiration_date']['d'] = date('d');
+	$user_data['expiration_date']['F'] = date('m');
+	$user_data['expiration_date']['Y'] = date('Y');
+} else {
+	$user_data['radio_expiration_date'] = 1;
+	$user_data['expiration_date'] = array();
+	$user_data['expiration_date']['d'] = substr($expiration_date, 8, 2);
+	$user_data['expiration_date']['F'] = substr($expiration_date, 5, 2);
+	$user_data['expiration_date']['Y'] = substr($expiration_date, 0, 4);
 }
 $form->setDefaults($user_data);
 
-
 // Validate form
-if( $form->validate())
-{
+if ( $form->validate()) {
 	$user = $form->exportValues();
+
 	$picture_element = & $form->getElement('picture');
 	$picture = $picture_element->getValue();
-	$picture_uri = '';
-	
-    //get the picture directory
-    $picture_paths = UserManager::get_user_picture_path_by_id($user_id,'system',true);
-    $picture_location = $picture_paths['dir'];
-    $big_picture_location = $picture_paths['dir'];
-	if (strlen($picture['name']) > 0)
-	{
-		$picture_uri = uniqid('').'_'.replace_dangerous_char($picture['name']);
-        if(!file_exists($picture_location))
-        {
-        	mkpath($picture_location);
-        }
-	    $picture_infos=getimagesize($_FILES['picture']['tmp_name']);
-		$type=$picture_infos[2];
-		$small_temp = UserManager::resize_picture($_FILES['picture']['tmp_name'], 22); //small picture
-		$medium_temp = UserManager::resize_picture($_FILES['picture']['tmp_name'], 85); //medium picture
-		$temp = UserManager::resize_picture($_FILES['picture']['tmp_name'], 200); // normal picture
-		$big_temp = new image($_FILES['picture']['tmp_name']); // original picture
-		
-	    switch (!empty($type)) {
-		    case 2 : 
-		    	$small_temp->send_image('JPG',$picture_location.'small_'.$picture_uri); 
-				$medium_temp->send_image('JPG',$picture_location.'medium_'.$picture_uri);
-	    		$temp->send_image('JPG',$picture_location.$picture_uri);
-	    		$big_temp->send_image('JPG',$picture_location.'big_'.$picture_uri);	    		 
-		    	break;
-		    case 3 :
-		    	$small_temp->send_image('PNG',$picture_location.'small_'.$picture_uri);
-		    	$medium_temp->send_image('PNG',$picture_location.'medium_'.$picture_uri);
-		    	$temp->send_image('PNG',$picture_location.$picture_uri);
-		    	$big_temp->send_image('PNG',$picture_location.'big_'.$picture_uri);
-		    	break;
-		    case 1 :
-		    	$small_temp->send_image('GIF',$picture_location.'small_'.$picture_uri);
-		    	$medium_temp->send_image('GIF',$picture_location.'medium_'.$picture_uri);
-		    	$temp->send_image('GIF',$picture_location.$picture_uri);
-		    	$big_temp->send_image('GIF',$picture_location.'big_'.$picture_uri);	    		 
-		    	break;
-	    }
 
+	$picture_uri = $user_data['picture_uri'];
+	if ($user['delete_picture']) {
+		$picture_uri = UserManager::delete_user_picture($user_id);
+		}
+	elseif (!empty($picture['name'])) {
+		$picture_uri = UserManager::update_user_picture($user_id, $_FILES['picture']['name'], $_FILES['picture']['tmp_name']);
 	}
-	elseif(isset($user['delete_picture']))
-	{
-		@unlink($picture_location.$user_data['picture_uri']);
-	}
-	
-	if (strlen($picture['name']) == 0){
-		$picture_uri = $user_data['picture_uri'];
-	}
-	
+
 	$lastname = $user['lastname'];
 	$firstname = $user['firstname'];
 	$official_code = $user['official_code'];
@@ -380,138 +324,116 @@ if( $form->validate())
 	$phone = $user['phone'];
 	$username = $user['username'];
 	$status = intval($user['status']);
-	$picture = $_FILES['picture'];
 	$platform_admin = intval($user['platform_admin']);
 	$send_mail = intval($user['send_mail']);
 	$reset_password = intval($user['reset_password']);
 	$hr_dept_id = intval($user['hr_dept_id']);
-	$language=$user['language'];
-	if ($user['radio_expiration_date']=='1' && ! $user_data['platform_admin'] )
-	{
+	$language = $user['language'];
+	if ($user['radio_expiration_date'] == '1' && !$user_data['platform_admin']) {
 		$expiration_date=$user['expiration_date'];
-	}
-	else
-	{
+	} else {
 		$expiration_date='0000-00-00 00:00:00';
 	}
 	$active = $user_data['platform_admin'] ? 1 : intval($user['active']);
 
-	if( $reset_password == 0)
-	{
+	if ($reset_password == 0) {
 		$password = null;
 		$auth_source = $user_data['auth_source'];
 	}
-	elseif($reset_password == 1)
-	{
+	elseif($reset_password == 1) {
 		$password = api_generate_password();
 		$auth_source = PLATFORM_AUTH_SOURCE;
 	}
-	elseif($reset_password == 2)
-	{
+	elseif($reset_password == 2) {
 		$password = $user['password'];
 		$auth_source = PLATFORM_AUTH_SOURCE;
 	}
-	elseif($reset_password == 3)
-	{
+	elseif($reset_password == 3) {
 		$password = $user['password'];
-		$auth_source = $user['auth_source'];		
+		$auth_source = $user['auth_source'];
 	}
-	UserManager::update_user($user_id,$firstname,$lastname,$username,$password,$auth_source,$email,$status,$official_code,$phone,$picture_uri,$expiration_date, $active, null, $hr_dept_id,null,$language);
-	if(api_get_setting('openid_authentication')=='true' && !empty($user['openid']))
-	{
+	UserManager::update_user($user_id, $firstname, $lastname, $username, $password, $auth_source, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active, null, $hr_dept_id, null, $language);
+	if (api_get_setting('openid_authentication') == 'true' && !empty($user['openid'])) {
 		$up = UserManager::update_openid($user_id,$user['openid']);
 	}
-	if($user_id != $_SESSION['_uid'])
-	{
-		if($platform_admin == 1)
-		{
+	if ($user_id != $_SESSION['_uid']) {
+		if ($platform_admin == 1) {
 			$sql = "INSERT IGNORE INTO $table_admin SET user_id = '".$user_id."'";
-			api_sql_query($sql,__FILE__,__LINE__);
-		}
-		else
-		{
+			Database::query($sql, __FILE__, __LINE__);
+		} else {
 			$sql = "DELETE FROM $table_admin WHERE user_id = '".$user_id."'";
-			api_sql_query($sql,__FILE__,__LINE__);
+			Database::query($sql, __FILE__, __LINE__);
 		}
 	}
-	
+
 	$extras = array();
-	foreach($user as $key => $value)
-	{
-		if(substr($key,0,6)=='extra_') //an extra field
-		{
-			$myres = UserManager::update_extra_field_value($user_id,substr($key,6),$value);
+	foreach($user as $key => $value) {
+		if(substr($key, 0, 6) == 'extra_') { //an extra field
+			$myres = UserManager::update_extra_field_value($user_id, substr($key, 6), $value);
 		}
 	}
-	
-	if (!empty ($email) && $send_mail)
-	{
-		$recipient_name = $firstname.' '.$lastname;
-		$emailsubject = '['.get_setting('siteName').'] '.get_lang('YourReg').' '.get_setting('siteName');												
-		$sender_name = get_setting('administratorName').' '.get_setting('administratorSurname');
-	    $email_admin = get_setting('emailAdministrator');
-	    
-	    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);					
-				$emailbody=get_lang('Dear')." ".stripslashes("$firstname $lastname").",\n\n".get_lang('YouAreReg')." ". get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". get_setting('siteName') ." ". get_lang('Is') ." : ". $url['url'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".get_setting('administratorName')." ".get_setting('administratorSurname')."\n". get_lang('Manager'). " ".get_setting('siteName')."\nT. ".get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".get_setting('emailAdministrator');
-			}		
+
+	if (!empty ($email) && $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');
+		$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');
+
+		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);
+				$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ". api_get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $url['url'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
+			}
 		}
 		else {
-			$emailbody=get_lang('Dear')." ".stripslashes("$firstname $lastname").",\n\n".get_lang('YouAreReg')." ". get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". get_setting('siteName') ." ". get_lang('Is') ." : ". $_configuration['root_web'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".get_setting('administratorName')." ".get_setting('administratorSurname')."\n". get_lang('Manager'). " ".get_setting('siteName')."\nT. ".get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".get_setting('emailAdministrator');
+			$emailbody=get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ". api_get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $_configuration['root_web'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
 		}
-			
-					
-		$emailbody = get_lang('Dear')." ".stripslashes("$firstname $lastname").",\n\n".get_lang('YouAreReg')." ". get_setting('siteName') ." ".get_lang('Settings')." ". $username;
+
+		$emailbody = get_lang('Dear')." ".stripslashes("$firstname $lastname").",\n\n".get_lang('YouAreReg')." ". api_get_setting('siteName') ." ".get_lang('Settings')." ". $username;
 		// Send password by e-mail if it has been modified, even if encrypted in DB (it doesn't make sense to send an e-mail with login info without the password, even if the password is encrypted)
-		if($reset_password > 0)
-		{
+		if ($reset_password > 0) {
 			$emailbody .= "\n".get_lang('Pass')." : ".stripslashes($password);
 		}
-		@api_mail($recipient_name, $email, $emailsubject, $emailbody, $sender_name,$email_admin);
-			
+		@api_mail($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
 	}
-	$tok = Security::get_token();		
+	$tok = Security::get_token();
 	header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('UserUpdated')).'&sec_token='.$tok);
 	exit();
 }
 
 Display::display_header($tool_name);
 
-//  USER PICTURE
+// USER PICTURE
 $image_path = UserManager::get_user_picture_path_by_id($user_id,'web');
 $image_dir = $image_path['dir'];
 $image = $image_path['file'];
 $image_file = ($image != '' ? $image_dir.$image : api_get_path(WEB_CODE_PATH).'img/unknown.jpg');
-$image_size = @getimagesize(api_url_to_local_path($image_file));
+$image_size = api_getimagesize($image_file);
 
 $img_attributes = 'src="'.$image_file.'?rand='.time().'" '
-    .'alt="'.$user_data['lastname'].' '.$user_data['firstname'].'" '
-    .'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; padding:5px;" ';
+	.'alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" '
+	.'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; padding:5px;" ';
 
-if ($image_size[0] > 300) //limit display width to 300px
-    $img_attributes .= 'width="300" ';
+if ($image_size[0] > 300) { //limit display width to 300px
+	$img_attributes .= 'width="300" ';
+}
 
 // get the path,width and height from original picture
 $big_image = $image_dir.'big_'.$image;
-$big_image_size = @getimagesize(api_url_to_local_path($big_image));
-$big_image_width= $big_image_size[0];
-$big_image_height= $big_image_size[1];
+$big_image_size = api_getimagesize($big_image);
+$big_image_width = $big_image_size[0];
+$big_image_height = $big_image_size[1];
 $url_big_image = $big_image.'?rnd='.time();
-if ($image=='') {
+
+if ($image == '') {
 	echo '<img '.$img_attributes.' />';
 } else {
-	echo '<input type="image" '.$img_attributes.' onclick="return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
+	echo '<input type="image" '.$img_attributes.' onclick="javascript: return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
 }
 
-
 // Display form
 $form->display();
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
+
+// Footer
 Display::display_footer();
-?>

+ 32 - 32
main/admin/user_export.php

@@ -56,19 +56,19 @@ $courses = array ();
 $courses[''] = '--';
 $sql = "SELECT code,visual_code,title FROM $course_table ORDER BY visual_code";
 
-global $_configuration;	
-if ($_configuration['multiple_access_urls']==true) {		
-	$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);	
+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,visual_code,title FROM $course_table as c INNER JOIN $tbl_course_rel_access_url as course_rel_url 		
-		ON (c.code = course_rel_url.course_code)		
+	$sql = "SELECT code,visual_code,title FROM $course_table as c INNER JOIN $tbl_course_rel_access_url as course_rel_url
+		ON (c.code = course_rel_url.course_code)
 		WHERE access_url_id = $access_url_id
-		ORDER BY visual_code";		
+		ORDER BY visual_code";
 	}
 }
-$result = api_sql_query($sql, __FILE__, __LINE__);
-while ($course = mysql_fetch_object($result))
+$result = Database::query($sql, __FILE__, __LINE__);
+while ($course = Database::fetch_object($result))
 {
 	$courses[$course->code] = $course->visual_code.' - '.$course->title;
 }
@@ -84,11 +84,11 @@ $form->setDefaults(array('file_type'=>'csv'));
 if ($form->validate())
 {
 	global $userPasswordCrypted;
-	
+
 	$export = $form->exportValues();
 	$file_type = $export['file_type'];
-	$course_code = $export['course_code'];	
-	$userPasswordCrypted =
+	$course_code = $export['course_code'];
+
 	$sql = "SELECT  u.user_id 	AS UserId,
 					u.lastname 	AS LastName,
 					u.firstname 	AS FirstName,
@@ -102,52 +102,52 @@ if ($form->validate())
 	if (strlen($course_code) > 0) {
 		$sql .= " FROM $user_table u, $course_user_table cu WHERE u.user_id = cu.user_id AND course_code = '$course_code' ORDER BY lastname,firstname";
 		$filename = 'export_users_'.$course_code.'_'.date('Y-m-d_H-i-s');
-	} else {		
-		global $_configuration;	
-		if ($_configuration['multiple_access_urls']==true) {		
-			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
+	} else {
+		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.= " FROM $user_table u INNER JOIN $tbl_user_rel_access_url as user_rel_url 		
-				ON (u.user_id= user_rel_url.user_id)		
+			$sql.= " FROM $user_table u INNER JOIN $tbl_user_rel_access_url as user_rel_url
+				ON (u.user_id= user_rel_url.user_id)
 				WHERE access_url_id = $access_url_id
-				ORDER BY lastname,firstname";		
+				ORDER BY lastname,firstname";
 			}
 		} else {
 			$sql .= " FROM $user_table u ORDER BY lastname,firstname";
-		}		
+		}
 		$filename = 'export_users_'.date('Y-m-d_H-i-s');
 	}
-	require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');	
-	$data = array();	
+	require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
+	$data = array();
 	$extra_fields = Usermanager::get_extra_fields(0, 0, 5, 'ASC',false);
 	if ($export['addcsvheader']=='1' AND $export['file_type']=='csv')
 	{
 		if($userPasswordCrypted!='none') {
 			$data[] = array('UserId', 'LastName', 'FirstName', 'Email', 'UserName', 'AuthSource', 'Status', 'OfficialCode', 'Phone');
 		} else {
-			$data[] = array('UserId', 'LastName', 'FirstName', 'Email', 'UserName','Password',  'AuthSource', 'Status', 'OfficialCode', 'Phone');	
+			$data[] = array('UserId', 'LastName', 'FirstName', 'Email', 'UserName','Password',  'AuthSource', 'Status', 'OfficialCode', 'Phone');
 		}
-		
+
 		foreach($extra_fields as $extra) {
 			$data[0][]=$extra[1];
-		}	
-		
+		}
+
 	}
-	$res = api_sql_query($sql,__FILE__,__LINE__);	
-	while($user = Database::fetch_array($res,'ASSOC')) {		
-		$student_data= UserManager :: get_extra_user_data($user['UserId'],true,false);		
+	$res = Database::query($sql,__FILE__,__LINE__);
+	while($user = Database::fetch_array($res,'ASSOC')) {
+		$student_data= UserManager :: get_extra_user_data($user['UserId'],true,false);
 		foreach($student_data as $key=>$value) {
 			$key= substr($key,6);
-			if (is_array($value)) 
+			if (is_array($value))
 				$user[$key]= $value[$key];
 			else {
 				$user[$key]= $value;
-			}			
+			}
 		}
-		$data[] = $user	;							
+		$data[] = $user	;
 	}
-	
+
 	switch($file_type)
 	{
 		case 'xml':

+ 417 - 417
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);
-	$table->set_header(1, get_lang('FieldLabel'));
-	$table->set_header(2, get_lang('FieldType'));
-	$table->set_header(3, get_lang('FieldTitle'),false);
-	$table->set_header(4, get_lang('FieldDefaultValue'),false);
-	$table->set_header(5, get_lang('FieldOrder'));
-	$table->set_header(6, get_lang('FieldVisibility'));
-	$table->set_header(7, get_lang('FieldChangeability'));
-	$table->set_header(8, get_lang('FieldFilter'));	
-	$table->set_header(9, get_lang('Modify'));
-	$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 = api_sql_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)."'";
-	api_sql_query($sql1,__FILE__,__LINE__);
-	api_sql_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 = api_sql_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 = api_sql_query($sql,__FILE__,__LINE__);
-		
-		// delete the field values
-		$sql = "DELETE FROM $table_user_field_values WHERE field_id = '".Database::escape_string($field_id)."'";
-		$result = api_sql_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 = api_sql_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 = api_sql_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; 
-	}
-}
-?>
+<?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(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;
+	}
+}
+?>

+ 35 - 35
main/admin/user_fields_add.php

@@ -44,44 +44,44 @@ function change_image_user_field (image_value) {
 	if (image_value==1) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_text.png', get_lang('AddUserFields'))."'".');
-			
+
 	} else if (image_value==2) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_text_area.png', get_lang('AddUserFields'))."'".');
-				
+
 	} else if (image_value==3) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('add_user_field_howto.png', get_lang('AddUserFields'))."'".');
-				
+
 	} else if (image_value==4) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_drop_down.png', get_lang('AddUserFields'))."'".');
-				
+
 	} else if (image_value==5) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_multidropdown.png', get_lang('AddUserFields'))."'".');
-				
+
 	} else if (image_value==6) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_data.png', get_lang('AddUserFields'))."'".');
-				
+
 	} else if (image_value==7) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_date_time.png', get_lang('AddUserFields'))."'".');
-				
+
 	} else if (image_value==8) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_doubleselect.png', get_lang('AddUserFields'))."'".');
-				
+
 	} else if (image_value==9) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_divider.png', get_lang('AddUserFields'))."'".');
-				
+
 	}
-}		
-	
-		
-		
+}
+
+
+
 </script>';
 // Database table definitions
 $table_admin	= Database :: get_main_table(TABLE_MAIN_ADMIN);
@@ -96,7 +96,7 @@ if ($_GET['action']<>'edit')
 {
 	$tool_name = get_lang('AddUserFields');
 }
-else 
+else
 {
 	$tool_name = get_lang('EditUserFields');
 }
@@ -149,8 +149,8 @@ if (is_numeric($_GET['field_id']))
 	$defaults['fieldtitle'] = $form_information['field_display_text'];
 	$defaults['fieldlabel'] = $form_information['field_variable'];
 	$defaults['fieldtype'] = $form_information['field_type'];
-	$defaults['fielddefaultvalue'] = $form_information['field_default_value'];									
-	
+	$defaults['fielddefaultvalue'] = $form_information['field_default_value'];
+
 	$count = 0;
 	// we have to concatenate the options
 	if (count($form_information['options'])>0) {
@@ -160,7 +160,7 @@ if (is_numeric($_GET['field_id']))
 			{
 				$defaults['fieldoptions'] = $defaults['fieldoptions'].'; '.$option['option_display_text'];
 			}
-			else 
+			else
 			{
 				$defaults['fieldoptions'] = $option['option_display_text'];
 			}
@@ -174,7 +174,7 @@ $form->setDefaults($defaults);
 		$text=get_lang('buttonEditUserField');
 	} else {
 		$class="add";
-		$text=get_lang('buttonAddUserField'); 
+		$text=get_lang('buttonAddUserField');
 	}
 // Submit button
 $form->addElement('style_submit_button', 'submit',$text, 'class='.$class.'');
@@ -190,13 +190,13 @@ if( $form->validate())
 		$fieldtitle = $field['fieldtitle'];
 		$fielddefault = $field['fielddefaultvalue'];
 		$fieldoptions = $field['fieldoptions']; //comma-separated list of options
-		
+
 		if (is_numeric($field['fieldid']) AND !empty($field['fieldid']))
 		{
 			UserManager:: save_extra_field_changes($field['fieldid'],$fieldlabel,$fieldtype,$fieldtitle,$fielddefault,$fieldoptions);
 			$message = get_lang('FieldEdited');
 		}
-		else 
+		else
 		{
 			$field_id = UserManager::create_extra_field($fieldlabel,$fieldtype,$fieldtitle,$fielddefault,$fieldoptions);
 			$message = get_lang('FieldAdded');
@@ -230,32 +230,32 @@ echo '<div id="id_image_user_field">';
 if(!empty($defaults['fieldtype'])) {
 	$image_value = $defaults['fieldtype'];
 	if ($image_value==1) {
-		echo '<br />'.Display::return_icon('userfield_text.png', get_lang('AddUserFields'));					
+		echo '<br />'.Display::return_icon('userfield_text.png', get_lang('AddUserFields'));
 	} else if ($image_value==2) {
-		echo '<br />'.Display::return_icon('userfield_text_area.png', get_lang('AddUserFields'));						
+		echo '<br />'.Display::return_icon('userfield_text_area.png', get_lang('AddUserFields'));
 	} else if ($image_value==3) {
-		echo '<br />'.Display::return_icon('add_user_field_howto.png', get_lang('AddUserFields'));						
+		echo '<br />'.Display::return_icon('add_user_field_howto.png', get_lang('AddUserFields'));
 	} else if ($image_value==4) {
-		echo '<br />'.Display::return_icon('userfield_drop_down.png', get_lang('AddUserFields'));						
+		echo '<br />'.Display::return_icon('userfield_drop_down.png', get_lang('AddUserFields'));
 	} else if ($image_value==5) {
-		echo '<br />'.Display::return_icon('userfield_multidropdown.png', get_lang('AddUserFields'));								
+		echo '<br />'.Display::return_icon('userfield_multidropdown.png', get_lang('AddUserFields'));
 	} else if ($image_value==6) {
-		echo '<br />'.Display::return_icon('userfield_data.png', get_lang('AddUserFields'));						
+		echo '<br />'.Display::return_icon('userfield_data.png', get_lang('AddUserFields'));
 	} else if ($image_value==7) {
-		echo '<br />'.Display::return_icon('userfield_date_time.png', get_lang('AddUserFields'));								
+		echo '<br />'.Display::return_icon('userfield_date_time.png', get_lang('AddUserFields'));
 	} else if ($image_value==8) {
-		echo '<br />'.Display::return_icon('userfield_doubleselect.png', get_lang('AddUserFields'));									
+		echo '<br />'.Display::return_icon('userfield_doubleselect.png', get_lang('AddUserFields'));
 	} else if ($image_value==9) {
-		echo '<br />'.Display::return_icon('userfield_divider.png', get_lang('AddUserFields'));						
+		echo '<br />'.Display::return_icon('userfield_divider.png', get_lang('AddUserFields'));
 	}
 } else {
-	echo '<br />'.Display::return_icon('userfield_text.png', get_lang('AddUserFields'));	
-}	
-echo '</div>';	
-			
-			
+	echo '<br />'.Display::return_icon('userfield_text.png', get_lang('AddUserFields'));
+}
+echo '</div>';
+
+
+
 
-		
 
 
 // footer

+ 32 - 32
main/admin/user_fields_options.php

@@ -75,7 +75,7 @@ if (isset ($_GET['action']))
 					{
 						Display :: display_confirmation_message(get_lang('FieldOptionMovedUp'));
 					}
-					else 
+					else
 					{
 						Display :: display_error_message(get_lang('CannotMoveFieldOption'));
 					}
@@ -83,17 +83,17 @@ if (isset ($_GET['action']))
 				break;
 			case 'movedown' :
 				if (api_is_platform_admin() && !empty($_GET['option_id']))
-				{					
+				{
 					if (move_user_field_option('movedown', $_GET['option_id']))
 					{
 						Display :: display_confirmation_message(get_lang('FieldOptionMovedDown'));
 					}
-					else 
+					else
 					{
 						Display :: display_error_message(get_lang('CannotMoveFieldOption'));
 					}
-				}				
-				break;			
+				}
+				break;
 		}
 	}
 }
@@ -124,53 +124,53 @@ function get_options_data($from, $number_of_items, $column, $direction)
 {
 	// Database table definition
 	$table_userfields_options 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-	
+
 	// The sql statement
-	$sql = "SELECT 
+	$sql = "SELECT
 				option_order 		AS col0,
-				option_display_text	AS col1,	
+				option_display_text	AS col1,
 				id 					AS col2
 			FROM $table_userfields_options WHERE field_id='".Database::escape_string($_GET['field_id'])."' ORDER BY option_order ASC";
 	$sql .= " LIMIT $from,$number_of_items";
-	$res = api_sql_query($sql, __FILE__, __LINE__);
+	$res = Database::query($sql, __FILE__, __LINE__);
 	$return = array ();
 	while ($option = Database::fetch_row($res))
 	{
 		$return[] = $option;
 	}
-	return $return;	
+	return $return;
 }
 
 function get_number_of_options($from=null, $number_of_items=null, $column=null, $direction=null)
 {
 	// Database table definition
 	$table_userfields_options 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-	
+
 	// The sql statement
 	$sql = "SELECT count(id) as total FROM $table_userfields_options WHERE field_id='".Database::escape_string($_GET['field_id'])."' ";
-	$res = api_sql_query($sql, __FILE__, __LINE__);
+	$res = Database::query($sql, __FILE__, __LINE__);
 	$row = Database::fetch_row($res);
-	return $row[0];	
+	return $row[0];
 }
 
 function actions_filter($option_id,$url_params,$row)
 {
-	global $number_of_options; 
+	global $number_of_options;
 
 	if ($row[0]<>1)
 	{
 		$return .= '<a href="'.api_get_self().'?action=moveup&amp;option_id='.$option_id.'&amp;field_id='.Security::remove_XSS($_GET['field_id']).'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('up.gif', get_lang('Up')).'</a>';
 	}
-	else 
+	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[0]<>$number_of_options)
 	{
 		$return .= '<a href="'.api_get_self().'?action=movedown&amp;option_id='.$option_id.'&amp;field_id='.Security::remove_XSS($_GET['field_id']).'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('down.gif', get_lang('Down')).'</a>';
-	}	
+	}
 	return $return;
 }
 
@@ -179,7 +179,7 @@ function actions_filter($option_id,$url_params,$row)
  *
  * @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
@@ -188,36 +188,36 @@ function move_user_field_option($direction,$option_id)
 {
 	// Database table definition
 	$table_userfields_options 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-	
+
 	// check the parameters
 	if (!in_array($direction,array('moveup','movedown')) OR !is_numeric($option_id))
 	{
-		return false; 
+		return false;
 	}
-	
+
 	// determine the SQL sort direction
 	if ($direction == 'moveup')
 	{
 		$sortdirection = 'DESC';
 	}
-	else 
+	else
 	{
 		$sortdirection = 'ASC';
 	}
-	
-	$found = false; 
-	
+
+	$found = false;
+
 	$sql = "SELECT id, option_order FROM $table_userfields_options  WHERE field_id='".Database::escape_string($_GET['field_id'])."' ORDER BY option_order $sortdirection";
-	$result = api_sql_query($sql,__FILE__,__LINE__);
+	$result = Database::query($sql,__FILE__,__LINE__);
 	while($row = Database::fetch_array($result))
 	{
 		if ($found)
 		{
 			$next_id = $row['id'];
-			$next_order = $row['option_order'];	
+			$next_order = $row['option_order'];
 			break;
 		}
-		
+
 		if ($option_id == $row['id'])
 		{
 			$this_id = $row['id'];
@@ -225,12 +225,12 @@ function move_user_field_option($direction,$option_id)
 			$found = true;
 		}
 	}
-	
+
 	$sql1 = "UPDATE ".$table_userfields_options." SET option_order = '".Database::escape_string($next_order)."' WHERE id =  '".Database::escape_string($this_id)."'";
 	$sql2 = "UPDATE ".$table_userfields_options." SET option_order = '".Database::escape_string($this_order)."' WHERE id =  '".Database::escape_string($next_id)."'";
-	api_sql_query($sql1,__FILE__,__LINE__);
-	api_sql_query($sql2,__FILE__,__LINE__);
-	
+	Database::query($sql1,__FILE__,__LINE__);
+	Database::query($sql2,__FILE__,__LINE__);
+
 	return true;
 }
 ?>

+ 223 - 195
main/admin/user_import.php

@@ -2,68 +2,74 @@
 /* For licensing terms, see /dokeos_license.txt */
 /**
 ==============================================================================
-*   This tool allows platform admins to add users by uploading a CSV or XML file
+* This tool allows platform admins to add users by uploading a CSV or XML file
 * @todo Add some langvars to DLTT
-*	@package dokeos.admin
+* @package dokeos.admin
 ==============================================================================
 */
+
 /**
- * validate the imported data
+ * Validate the imported data.
  */
- 
+
 $language_file = array ('admin', 'registration');
+
+$cidReset = true;
 require '../inc/global.inc.php';
-require_once api_get_path(INCLUDE_PATH).'lib/mail.lib.inc.php'; 
+require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
+
+// Set this option to true to enforce strict purification for usenames.
+$purification_option_for_usernames = false;
 
 function validate_data($users) {
 	global $defined_auth_sources;
-	$errors = array ();
-	$usernames = array ();
+	$errors = array();
+	$usernames = array();
 	foreach ($users as $index => $user) {
-		//1. check if mandatory fields are set	
-		$mandatory_fields = array ('LastName', 'FirstName');
+		// 1. Check if mandatory fields are set.
+		$mandatory_fields = array('LastName', 'FirstName');
 		if (api_get_setting('registration', 'email') == 'true') {
-			$mandatory_fields[] = 'Email';	
+			$mandatory_fields[] = 'Email';
 		}
 		foreach ($mandatory_fields as $key => $field) {
-			if (!isset ($user[$field]) || strlen($user[$field]) == 0) {
+			if (empty($user[$field])) {
 				$user['error'] = get_lang($field.'Mandatory');
 				$errors[] = $user;
 			}
 		}
-		//2. check username
-		if (isset ($user['UserName']) && strlen($user['UserName']) != 0) {
-			//2.1. check if no username was used twice in import file
-			if (isset ($usernames[$user['UserName']])) {
+		// 2. Check username, first, check whether it is empty.
+		if (!UserManager::is_username_empty($user['UserName'])) {
+			// 2.1. Check whether username is too long.
+			if (UserManager::is_username_too_long($user['UserName'])) {
+				$user['error'] = get_lang('UserNameTooLong');
+				$errors[] = $user;
+			}
+			// 2.2. Check whether the username was used twice in import file.
+			if (isset($usernames[$user['UserName']])) {
 				$user['error'] = get_lang('UserNameUsedTwice');
 				$errors[] = $user;
 			}
 			$usernames[$user['UserName']] = 1;
-			//2.2. check if username isn't allready in use in database
-			if (!UserManager :: is_username_available($user['UserName'])) {
+			// 2.3. Check whether username is allready occupied.
+			if (!UserManager::is_username_available($user['UserName'])) {
 				$user['error'] = get_lang('UserNameNotAvailable');
 				$errors[] = $user;
 			}
-			//2.3. check if username isn't longer than the 20 allowed characters
-			if (api_strlen($user['UserName']) > 20) {
-				$user['error'] = get_lang('UserNameTooLong');
-				$errors[] = $user;
-			}
 		}
-		//3. check status
-		if (isset ($user['Status']) && !api_status_exists($user['Status'])) {
+		// 3. Check status.
+		if (isset($user['Status']) && !api_status_exists($user['Status'])) {
 			$user['error'] = get_lang('WrongStatus');
 			$errors[] = $user;
 		}
-		//4. Check classname
-		if (isset ($user['ClassName']) && strlen($user['ClassName']) != 0) {
+		// 4. Check classname
+		if (!empty($user['ClassName'])) {
 			if (!ClassManager :: class_name_exists($user['ClassName'])) {
 				$user['error'] = get_lang('ClassNameNotAvailable');
 				$errors[] = $user;
 			}
 		}
-		//5. Check authentication source
-		if (isset ($user['AuthSource']) && strlen($user['AuthSource']) != 0) {
+		// 5. Check authentication source
+		if (!empty($user['AuthSource'])) {
 			if (!in_array($user['AuthSource'], $defined_auth_sources)) {
 				$user['error'] = get_lang('AuthSourceNotAvailable');
 				$errors[] = $user;
@@ -72,38 +78,33 @@ function validate_data($users) {
 	}
 	return $errors;
 }
+
 /**
- * Add missing user-information (which isn't required, like password, username
- * etc)
+ * Add missing user-information (which isn't required, like password, username etc).
  */
 function complete_missing_data($user) {
-	//1. Create a username if necessary
-	if (!isset ($user['UserName']) || strlen($user['UserName']) == 0) {
-		$username = api_strtolower(api_ereg_replace('[^a-zA-Z]', '', api_substr($user['FirstName'], 0, 3).' '.api_substr($user['LastName'], 0, 4)));
-		if (!UserManager :: is_username_available($username)) {
-			$i = 0;
-			$temp_username = $username.$i;
-			while (!UserManager :: is_username_available($temp_username)) {
-				$temp_username = $username.++$i;
-			}
-			$username = $temp_username;
-		}
-		$user['UserName'] = $username;
+	global $purification_option_for_usernames;
+	// 1. Create a username if necessary.
+	if (UserManager::is_username_empty($user['UserName'])) {
+		$user['UserName'] = UserManager::create_unique_username($user['FirstName'], $user['LastName']);
+	} else {
+		$user['UserName'] = UserManager::purify_username($user['UserName'], $purification_option_for_usernames);
 	}
-	//2. generate a password if necessary
-	if (!isset ($user['Password']) || strlen($user['Password']) == 0) {
+	// 2. Generate a password if necessary.
+	if (empty($user['Password'])) {
 		$user['Password'] = api_generate_password();
 	}
-	//3. set status if not allready set
-	if (!isset ($user['Status']) || strlen($user['Status']) == 0) {
+	// 3. Set status if not allready set.
+	if (empty($user['Status'])) {
 		$user['Status'] = 'user';
 	}
-	//4. set authsource if not allready set
-	if (!isset ($user['AuthSource']) || strlen($user['AuthSource']) == 0) {
+	// 4. Set authsource if not allready set.
+	if (empty($user['AuthSource'])) {
 		$user['AuthSource'] = PLATFORM_AUTH_SOURCE;
 	}
 	return $user;
 }
+
 /**
  * Save the imported data
  * @param   array   List of users
@@ -111,74 +112,76 @@ function complete_missing_data($user) {
  * @uses global variable $inserted_in_course, which returns the list of courses the user was inserted in
  */
 function save_data($users) {
-    global $inserted_in_course;
-    // not all scripts declare the $inserted_in_course array (although they should)
-    if (!isset($inserted_in_course)) { $inserted_in_course = array(); }
-	require_once(api_get_path(INCLUDE_PATH).'lib/mail.lib.inc.php');
+	global $inserted_in_course;
+	// Not all scripts declare the $inserted_in_course array (although they should).
+	if (!isset($inserted_in_course)) {
+		$inserted_in_course = array();
+	}
+	require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
 	$user_table = Database :: get_main_table(TABLE_MAIN_USER);
-	$sendMail = $_POST['sendMail'] ? 1 : 0;
+	$send_mail = $_POST['sendMail'] ? 1 : 0;
 	if (is_array($users)) {
-        foreach ($users as $index => $user)	{
-    		$user = complete_missing_data($user);
-    		
-    		$user['Status'] = api_status_key($user['Status']);
-    		
-    		$user_id = UserManager :: create_user($user['FirstName'], $user['LastName'], $user['Status'], $user['Email'], $user['UserName'], $user['Password'], $user['OfficialCode'], api_get_setting('PlatformLanguage'), $user['PhoneNumber'], '', $user['AuthSource']);
-            if (!is_array($user['Courses']) && !empty($user['Courses'])) {
-            	$user['Courses'] = array($user['Courses']);
-            }
-            if (is_array($user['Courses'])) {
-        		foreach ($user['Courses'] as $index => $course) {
-        			if (CourseManager :: course_exists($course)) {
-        				CourseManager :: subscribe_user($user_id, $course,$user['Status']);
-                        $c_info = CourseManager::get_course_information($course); 
-                        $inserted_in_course[$course] = $c_info['title'];
-                    } 
-                    if (CourseManager :: course_exists($course,true)) {
-                    	// also subscribe to virtual courses through check on visual code
-                        $list = CourseManager :: get_courses_info_from_visual_code($course);
-                        foreach ($list as $vcourse) {
-                        	if ($vcourse['code'] == $course) {
-                        		//ignore, this has already been inserted
-                        	} else {
-                                CourseManager :: subscribe_user($user_id, $vcourse['code'],$user['Status']);                		
-                                $inserted_in_course[$vcourse['code']] = $vcourse['title'];
-                        	}
-                        }
-                    }
-        		}
-            }
-    		if (strlen($user['ClassName']) > 0) {
-    			$class_id = ClassManager :: get_class_id($user['ClassName']);
-    			ClassManager :: add_user($user_id, $class_id);
-    		}
-    		
-    		//saving extra fields
+		foreach ($users as $index => $user)	{
+			$user = complete_missing_data($user);
+
+			$user['Status'] = api_status_key($user['Status']);
+
+			$user_id = UserManager :: create_user($user['FirstName'], $user['LastName'], $user['Status'], $user['Email'], $user['UserName'], $user['Password'], $user['OfficialCode'], api_get_setting('PlatformLanguage'), $user['PhoneNumber'], '', $user['AuthSource']);
+			if (!is_array($user['Courses']) && !empty($user['Courses'])) {
+				$user['Courses'] = array($user['Courses']);
+			}
+			if (is_array($user['Courses'])) {
+				foreach ($user['Courses'] as $index => $course) {
+					if (CourseManager :: course_exists($course)) {
+						CourseManager :: subscribe_user($user_id, $course,$user['Status']);
+						$course_info = CourseManager::get_course_information($course);
+						$inserted_in_course[$course] = $course_info['title'];
+					}
+					if (CourseManager :: course_exists($course, true)) {
+						// Also subscribe to virtual courses through check on visual code.
+						$list = CourseManager :: get_courses_info_from_visual_code($course);
+						foreach ($list as $vcourse) {
+							if ($vcourse['code'] == $course) {
+								// Ignore, this has already been inserted.
+							} else {
+								CourseManager :: subscribe_user($user_id, $vcourse['code'],$user['Status']);
+								$inserted_in_course[$vcourse['code']] = $vcourse['title'];
+							}
+						}
+					}
+				}
+			}
+			if (!empty($user['ClassName'])) {
+				$class_id = ClassManager :: get_class_id($user['ClassName']);
+				ClassManager :: add_user($user_id, $class_id);
+			}
+
+			// Saving extra fields.
 			global $extra_fields;
-			//print_R($user);	
-			//we are sure the extra field exist
-			foreach($extra_fields as $extras) {			
+
+			// We are sure that the extra field exists.
+			foreach($extra_fields as $extras) {
 				if (isset($user[$extras[1]])) {
-						$key 	= $extras[1];					 
-						$value 	= $user[$extras[1]];
-						UserManager::update_extra_field_value($user_id,$key,$value);	
+					$key 	= $extras[1];
+					$value 	= $user[$extras[1]];
+					UserManager::update_extra_field_value($user_id, $key,$value);
 				}
 			}
-		
-    		if ($sendMail) {			
-    			$recipient_name = $user['FirstName'].' '.$user['LastName'];
-    			$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');			
-    			$emailbody = get_lang('Dear').$user['FirstName'].' '.$user['LastName'].",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('Settings')." $user[UserName]\n".get_lang('Pass')." : $user[Password]\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".api_get_path('WEB_PATH')." \n\n".get_lang('Problem')."\n\n".get_lang('Formula').",\n\n".api_get_setting('administratorName')." ".api_get_setting('administratorSurname')."\n".get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email')." : ".api_get_setting('emailAdministrator')."";						
-    			$sender_name = get_setting('administratorName').' '.get_setting('administratorSurname');
-    		    $email_admin = get_setting('emailAdministrator');			
-    			@api_mail($recipient_name, $user['Email'], $emailsubject, $emailbody, $sender_name,$email_admin);
-    		}
-    
-    	}
-    }
+
+			if ($send_mail) {
+				$recipient_name = api_get_person_name($user['FirstName'], $user['LastName'], null, PERSON_NAME_EMAIL_ADDRESS);
+				$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
+				$emailbody = get_lang('Dear').api_get_person_name($user['FirstName'], $user['LastName']).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('Settings')." $user[UserName]\n".get_lang('Pass')." : $user[Password]\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".api_get_path('WEB_PATH')." \n\n".get_lang('Problem')."\n\n".get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email')." : ".api_get_setting('emailAdministrator')."";
+				$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, $user['Email'], $emailsubject, $emailbody, $sender_name, $email_admin);
+			}
+		}
+	}
 }
+
 /**
- * Read the CSV-file 
+ * Read the CSV-file
  * @param string $file Path to the CSV-file
  * @return array All userinformation read from the file
  */
@@ -196,6 +199,7 @@ function parse_csv_data($file) {
  * XML-parser: handle start of element
  */
 function element_start($parser, $data) {
+	$data = api_utf8_decode($data);
 	global $user;
 	global $current_tag;
 	switch ($data) {
@@ -206,22 +210,21 @@ function element_start($parser, $data) {
 			$current_tag = $data;
 	}
 }
+
 /**
  * XML-parser: handle end of element
  */
 function element_end($parser, $data) {
+	$data = api_utf8_decode($data);
 	global $user;
 	global $users;
 	global $current_value;
-	switch ($data)
-	{
+	switch ($data) {
 		case 'Contact' :
-			if ($user['Status'] == '5')
-			{
+			if ($user['Status'] == '5') {
 				$user['Status'] = STUDENT;
 			}
-			if ($user['Status'] == '1')
-			{
+			if ($user['Status'] == '1') {
 				$user['Status'] = COURSEMANAGER;
 			}
 			$users[] = $user;
@@ -231,13 +234,16 @@ function element_end($parser, $data) {
 			break;
 	}
 }
+
 /**
  * XML-parser: handle character data
  */
 function character_data($parser, $data) {
+	$data = trim(api_utf8_decode($data));
 	global $current_value;
 	$current_value = $data;
 }
+
 /**
  * Read the XML-file
  * @param string $file Path to the XML-file
@@ -248,27 +254,24 @@ function parse_xml_data($file) {
 	global $current_value;
 	global $user;
 	global $users;
-	$users = array ();
-	$parser = xml_parser_create();
+	$users = array();
+	$parser = xml_parser_create('UTF-8');
 	xml_set_element_handler($parser, 'element_start', 'element_end');
-	xml_set_character_data_handler($parser, "character_data");
+	xml_set_character_data_handler($parser, 'character_data');
 	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
-	xml_parse($parser, file_get_contents($file));
+	xml_parse($parser, api_utf8_encode_xml(file_get_contents($file)));
 	xml_parser_free($parser);
 	return $users;
 }
-// name of the language file that needs to be included
 
-$cidReset = true;
 $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
-require_once (api_get_path(LIBRARY_PATH).'fileManage.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).'import.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-$formSent = 0;
-$errorMsg = '';
+require_once api_get_path(LIBRARY_PATH).'fileManage.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).'import.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+
 $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
 if (is_array($extAuthSource)) {
 	$defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
@@ -279,123 +282,149 @@ $tool_name = get_lang('ImportUserListXMLCSV');
 $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
 
 set_time_limit(0);
-$extra_fields = Usermanager::get_extra_fields(0, 0, 5, 'ASC',false);
-$user_id_error=array();
+$extra_fields = Usermanager::get_extra_fields(0, 0, 5, 'ASC', false);
+$user_id_error = array();
 if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
 	$file_type = $_POST['file_type'];
-	if (strcmp($file_type,'csv')===0){ //&& strcmp($_FILES['import_file']['type'],'text/'.$file_type.'')===0) {
+	Security::clear_token();
+	$tok = Security::get_token();
+
+	if (strcmp($file_type, 'csv') === 0) { //&& strcmp($_FILES['import_file']['type'],'text/'.$file_type.'')===0) {
 		$users = parse_csv_data($_FILES['import_file']['tmp_name']);
 		$errors = validate_data($users);
-		$error_kind_file=false;
-	} elseif (strcmp($file_type,'xml')===0){// && strcmp($_FILES['import_file']['type'],'text/'.$file_type.'')===0) {
+		$error_kind_file = false;
+	} elseif (strcmp($file_type, 'xml') === 0) { // && strcmp($_FILES['import_file']['type'],'text/'.$file_type.'')===0) {
 		$users = parse_xml_data($_FILES['import_file']['tmp_name']);
 		$errors = validate_data($users);
-		$error_kind_file=false;
+		$error_kind_file = false;
 	} else {
-		$error_kind_file=true;
+		$error_kind_file = true;
 	}
-	
-	//list user id whith error
-	$user_id_error=array();
-	if (is_array($errors)){ 
+
+	// List user id whith error.
+	$user_id_error = array();
+	if (is_array($errors)) {
 		foreach ($errors as $my_errors) {
-			$user_id_error[]=$my_errors['UserName'];
-		}	
+			$user_id_error[] = $my_errors['UserName'];
+		}
 	}
-	if  (is_array($users)) {
+	if (is_array($users)) {
 		foreach ($users as $my_user) {
-		if (!in_array($my_user['UserName'],$user_id_error)) {
-			$users_to_insert[]=$my_user;
-				}
+			if (!in_array($my_user['UserName'], $user_id_error)) {
+				$users_to_insert[] = $my_user;
 			}
 		}
-        $inserted_in_course = array();
-	save_data($users_to_insert);
-	if ( count($errors)>0 ) {
-		$see_message_import=get_lang('FileImportedJustUsersThatAreNotRegistered');
+	}
+
+	$inserted_in_course = array();
+
+	if (strcmp($file_type, 'csv') === 0) // this replace if (strcmp($_FILES['import_file']['type'], 'text/'.$file_type.'') === 0)
+	{
+		save_data($users_to_insert);
+		
+	} elseif (strcmp($file_type, 'xml') === 0) {
+		
+		save_data($users_to_insert);
+		
+	} else {
+		
+		$error_message = get_lang('YouMustImportAFileAccordingToSelectedOption');
+		header('Location: '.api_get_self().'?warn='.urlencode($error_message).'&amp;file_type='.$file_type.'&amp;sec_token='.$tok);
+		exit ();
+	}
+	
+
+	if (count($errors) > 0) {
+		$see_message_import = get_lang('FileImportedJustUsersThatAreNotRegistered');
 	} else {
-		$see_message_import=get_lang('FileImported');
+		$see_message_import = get_lang('FileImported');
+	}
+	$msg2 = '';
+	if (count($inserted_in_course) > 1) {
+		$msg2 .= '<br>'.get_lang('UsersSubscribedToSeveralCoursesBecauseOfVirtualCourses').':';
+		foreach ($inserted_in_course as $course) {
+			$msg2 .= ' '.$course.',';
+		}
+		$msg2 = substr($msg2, 0, -1);
+		$msg2 .= '</br>';
 	}
-        $msg2 = '';
-	if (count($inserted_in_course)>1) {
-        	$msg2 .="<br>".get_lang('UsersSubscribedToSeveralCoursesBecauseOfVirtualCourses').':';
-            foreach ($inserted_in_course as $course) {
-            	$msg2 .= ' '.$course.',';
-            }
-            $msg2 = substr($msg2,0,-1);
-	    $msg2 .= "</br>";
-        }
+
 	if (count($errors) != 0) {
-	$error_message = '<ul>';
-	foreach ($errors as $index => $error_user) {
-	$error_message .= '<li><b>'.$error_user['error'].'</b>: ';
-	$error_message .= $error_user['UserName'].'&nbsp;('.$error_user['FirstName'].' '.$error_user['LastName'].')';
-		$error_message .= '</li>';
+		$error_message = '<ul>';
+		foreach ($errors as $index => $error_user) {
+			$error_message .= '<li><b>'.$error_user['error'].'</b>: ';
+			$error_message .= '<strong>'.$error_user['UserName'].'</strong>&nbsp;('.api_get_person_name($error_user['FirstName'], $error_user['LastName']).')';
+			$error_message .= '</li>';
 		}
 		$error_message .= '</ul>';
 	}
 
-	// if the warning message is too long then we display the warning message trough a session
-	if (strlen($error_message) > 150){
-		$_SESSION['session_message_import_users'] = $error_message;
-		$error_message = 'session_message';
-	}
- 
-        Security::clear_token();
-        $tok = Security::get_token();       
-		header('Location: user_list.php?action=show_message&message='.urlencode($see_message_import).'&warn='.urlencode($error_message).'&sec_token='.$tok);
-		exit ();
+	// if the warning message is too long then we display the warning message trough a session
+	if (api_strlen($error_message) > 150) {
+		$_SESSION['session_message_import_users'] = $error_message;
+		$error_message = 'session_message';
 	}
+	header('Location: user_list.php?action=show_message&message='.urlencode($see_message_import).'&warn='.urlencode($error_message).'&sec_token='.$tok);
+	exit ();
+}
+
 Display :: display_header($tool_name);
 //api_display_tool_title($tool_name);
 
-if($_FILES['import_file']['size'] == 0 AND $_POST) {
+if ($_FILES['import_file']['size'] == 0 AND $_POST) {
 	Display::display_error_message(get_lang('ThisFieldIsRequired'));
 }
 
-if ($error_kind_file===true) {
+if ($error_kind_file === true) {
 	Display :: display_error_message(get_lang('YouMustImportAFileAccordingToSelectedOption'));
+} else if (isset($_GET['warn'])) {
+	$error_message = Security::remove_XSS($_GET['warn']);
+	Display :: display_error_message($error_message);
 }
+
 $form = new FormValidator('user_import');
 $form->addElement('header', '', $tool_name);
 $form->addElement('hidden', 'formSent');
 $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
-$form->addRule('import_file', get_lang('ThisFieldIsRequired'), 'required');
+//$form->addRule('import_file', get_lang('ThisFieldIsRequired'), 'required'); // This rule does not work, probably due to the security mechanism here.
 $allowed_file_types = array ('xml', 'csv');
-$form->addRule('file', get_lang('InvalidExtension').' ('.implode(',', $allowed_file_types).')', 'filetype', $allowed_file_types);
+//$form->addRule('import_file', get_lang('InvalidExtension').' ('.implode(',', $allowed_file_types).')', 'filetype', $allowed_file_types); // This rule does not work, probably due to the security mechanism here.
 $form->addElement('radio', 'file_type', get_lang('FileType'), 'XML (<a href="exemple.xml" target="_blank">'.get_lang('ExampleXMLFile').'</a>)', 'xml');
 $form->addElement('radio', 'file_type', null, 'CSV (<a href="exemple.csv" target="_blank">'.get_lang('ExampleCSVFile').'</a>)', 'csv');
 $form->addElement('radio', 'sendMail', get_lang('SendMailToUsers'), get_lang('Yes'), 1);
 $form->addElement('radio', 'sendMail', null, get_lang('No'), 0);
-$form->addElement('style_submit_button', 'submit',get_lang('Import'),'class="save"');
+$form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
 $defaults['formSent'] = 1;
+$defaults['sendMail'] = 0;
 $defaults['file_type'] = 'xml';
 $form->setDefaults($defaults);
 $form->display();
 
-$list=array();
-$list_reponse=array();
-$result_xml = '' ;
-$i=0;
+$list = array();
+$list_reponse = array();
+$result_xml = '';
+$i = 0;
 $count_fields = count($extra_fields);
 if ($count_fields > 0) {
-	foreach($extra_fields as $extra) {
+	foreach ($extra_fields as $extra) {
 		$list[] = $extra[1];
-		$list_reponse[]='xxx';				
+		$list_reponse[] = 'xxx';
 		$spaces = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
-		$result_xml.=$spaces.'&lt;'.$extra[1].'&gt;xxx&lt;/'.$extra[1].'&gt;';	
-		if ($i!=$count_fields-1)
-			$result_xml.='<br/>';
-		$i++;	
+		$result_xml .= $spaces.'&lt;'.$extra[1].'&gt;xxx&lt;/'.$extra[1].'&gt;';
+		if ($i != $count_fields - 1) {
+			$result_xml .= '<br/>';
+		}
+		$i++;
 	}
 }
+
 ?>
 <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
 
 <blockquote>
 <pre>
-<b>LastName</b>;<b>FirstName</b>;<b>Email</b>;UserName;Password;AuthSource;OfficialCode;PhoneNumber;Status;<font style="color:red;"><?php if(count($list)>0) echo implode(';', $list).';';?></font>Courses;ClassName;
-<b>xxx</b>;<b>xxx</b>;<b>xxx</b>;xxx;xxx;<?php echo implode('/',$defined_auth_sources); ?>;xxx;xxx;user/teacher/drh;<font style="color:red;"><?php if(count($list_reponse)>0) echo implode(';', $list_reponse).';';?></font>xxx1|xxx2|xxx3;xxx;<br />
+<b>LastName</b>;<b>FirstName</b>;<b>Email</b>;UserName;Password;AuthSource;OfficialCode;PhoneNumber;Status;<font style="color:red;"><?php if (count($list) > 0) echo implode(';', $list).';'; ?></font>Courses;ClassName;
+<b>xxx</b>;<b>xxx</b>;<b>xxx</b>;xxx;xxx;<?php echo implode('/', $defined_auth_sources); ?>;xxx;xxx;user/teacher/drh;<font style="color:red;"><?php if (count($list_reponse) > 0) echo implode(';', $list_reponse).';'; ?></font>xxx1|xxx2|xxx3;xxx;<br />
 </pre>
 </blockquote>
 
@@ -403,26 +432,25 @@ if ($count_fields > 0) {
 
 <blockquote>
 <pre>
-&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
+&lt;?xml version=&quot;1.0&quot; encoding=&quot;<?php echo api_refine_encoding_id(api_get_system_encoding()); ?>&quot;?&gt;
 &lt;Contacts&gt;
     &lt;Contact&gt;
         <b>&lt;LastName&gt;xxx&lt;/LastName&gt;</b>
         <b>&lt;FirstName&gt;xxx&lt;/FirstName&gt;</b>
         &lt;UserName&gt;xxx&lt;/UserName&gt;
         &lt;Password&gt;xxx&lt;/Password&gt;
-        &lt;AuthSource&gt;<?php echo implode('/',$defined_auth_sources); ?>&lt;/AuthSource&gt;
+        &lt;AuthSource&gt;<?php echo implode('/', $defined_auth_sources); ?>&lt;/AuthSource&gt;
         <b>&lt;Email&gt;xxx&lt;/Email&gt;</b>
         &lt;OfficialCode&gt;xxx&lt;/OfficialCode&gt;
         &lt;PhoneNumber&gt;xxx&lt;/PhoneNumber&gt;
-        &lt;Status&gt;user/teacher/drh&lt;/Status&gt;         <?php if ($result_xml!='') { echo '<br /><font style="color:red;">',$result_xml;echo '</font>';} ?>        
+        &lt;Status&gt;user/teacher/drh&lt;/Status&gt;         <?php if ($result_xml != '') { echo '<br /><font style="color:red;">', $result_xml; echo '</font>'; } ?>
         &lt;Courses&gt;xxx1|xxx2|xxx3&lt;/Courses&gt;
-        &lt;ClassName&gt;class 1&lt;/ClassName&gt;        
+        &lt;ClassName&gt;class 1&lt;/ClassName&gt;
     &lt;/Contact&gt;
 &lt;/Contacts&gt;
 </pre>
 </blockquote>
 
 <?php
-// footer
 Display :: display_footer();
 ?>

Some files were not shown because too many files changed in this diff